I was working on a django project. I made a userprofiles app to manage(create, update) user's profile in my website, but it is not working properly. I am getting 'This field is required' &
'no file chosen' while making profile as a user and if I do blank=True in models profile_picture user pictures are not saving in the media url.
I have tried so many tips from stackoverflow but they are not working.
here is my code:
# settings.py
MEDIA_URL = '/media/'
MEDIA_ROOT = str(BASE_DIR.joinpath('media'))
# models.py
from django.db import models
from django.contrib.auth import get_user_model
import uuid
class UserProfile(models.Model):
author = models.OneToOneField(get_user_model(), on_delete=models.CASCADE)
profile_picture = models.ImageField(upload_to='images/')
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
bio = models.TextField(blank=True)
occupation = models.CharField(max_length=100)
hobbies = models.TextField(blank=True)
date_of_birth = models.TimeField()
def __str__(self):
return self.author.username + ("'s profile")
# views.py
from django.views.generic import CreateView
from .forms import CustomUserCreationForm
from django.urls import reverse_lazy
class SignUpView(CreateView):
form_class = CustomUserCreationForm
template_name = "registration/signup.html"
success_url = reverse_lazy("profile_create")
# project-level urls.py
from django.contrib import admin
from django.conf import settings
from django.urls import path, include
from django.conf.urls.static import static
from django.views.generic.base import TemplateView
urlpatterns = [
path('admin/', admin.site.urls),
path("accounts/", include("accounts.urls")),
path("accounts/", include("django.contrib.auth.urls")),
path("profile/", include("userprofiles.urls")),
path("", TemplateView.as_view(template_name="home.html"), name="home"),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
# app-level urls.py
from django.urls import path
from .views import ProfileCreateView
urlpatterns = [
path("create/", ProfileCreateView.as_view(), name="profile_create")
]
# profile_create.html
{% extends 'base.html' %}
{% block title %}Create Your Profile{% endblock title %}
{% block content %}
<h2>Create Your Profile</h2>
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Create my profile</button>
</form>
{% endblock content %}
tell me what is the problem with it, I am stucked out of it, Thank you
I believe you missed enctype in html form,
enctype="multipart/form-data"
from docs,
Note that request.FILES will only contain data if the request method
was POST, at least one file field was actually posted, and the
that posted the request has the attribute
enctype="multipart/form-data". Otherwise, request.FILES will be empty.
HTML form should be,
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Create my profile</button>
</form>
Related
I am attempting to set up dependent dropdown lists in a Django 3.1 site. The lists are populated via another app (Django-Machina) DB tables. I attempted to adapt the example here. However I am new to Django and Python and so far, I am not able to get this to work.
My files are as follows:
models.py
from django.contrib.auth.models import AbstractUser
from django.db import models
from machina.core.db.models import get_model
from django.db.models import Q
Forum = get_model("forum", "Forum")
class CustomUser(AbstractUser):
age = models.PositiveIntegerField(null=True, blank=True)
business_location_state = models.ForeignKey(Forum, null=True, on_delete=models.SET_NULL, limit_choices_to={"lft":1})
business_location_county = models.ForeignKey(Forum, null=True, on_delete=models.SET_NULL, related_name='county', limit_choices_to=(~Q(lft__in = (1,2))))
views.py
from django.urls import reverse_lazy
from django.views.generic import CreateView
from .forms import CustomUserCreationForm
from .models import CustomUser
from django.shortcuts import render
from machina.core.db.models import get_model
from django.db.models import Q
Forum = get_model("forum", "Forum")
class SignUpView(CreateView):
form_class = CustomUserCreationForm
success_url = reverse_lazy('login')
template_name = 'registration/signup.html'
def load_counties(request):
parent_id = request.GET.get('business_location_state')
counties = Forum.objects.filter(parent_id=parent_id).order_by('name')
return render(request, 'hr/county_dropdown_list_options.html', {'counties': counties})
accounts/urls.py
# accounts/urls.py
from django.urls import path
from .views import SignUpView
from . import views
urlpatterns = [
path('signup/', SignUpView.as_view(), name='signup'),
path('ajax/load-counties/', views.load_counties, name='ajax_load_counties'), # ajax to load counties
]
forms.py
from django import forms
from django.contrib.auth.forms import UserCreationForm, UserChangeForm
from .models import CustomUser
class CustomUserCreationForm(UserCreationForm):
class Meta(UserCreationForm):
model = CustomUser
fields = UserCreationForm.Meta.fields + ('username', 'email', 'age', 'business_location_state', 'business_location_county')
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['business_location_county'].queryset = CustomUser.objects.none()
class CustomUserChangeForm(UserChangeForm):
class Meta:
model = CustomUser
fields = ('username', 'email', 'age','business_location_state', 'business_location_county')
count_dropdown_list_options.html
<!-- templates/hr/county_dropdown_list_options.html -->
<option value="">---------</option>
{% for county in counties %}
<option value="{{ business_location_county.pk }}">{{ business_location_county.name }}</option>
{% endfor %}
signup.html
<!-- templates/registration/signup.html -->
{% extends 'base.html' %}
{% block title %}
Sign Up
{% endblock title %}
{% block content %}
<h2>Sign up</h2>
<form method="post" id=signupForm data-counties-url="{% url 'ajax_load_counties' %}" novalidate>
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Sign Up</button>
</form>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script>
$("#id_business_location_state").change(function () {
var url = $("#signupForm").attr("data-counties-url"); // get the url of the `load_cities` view
var stateId = $(this).val(); // get the selected country ID from the HTML input
$.ajax({ // initialize an AJAX request
url: url, // set the url of the request (= localhost:8000/hr/ajax/load-cities/)
data: {
'business_location_state': stateId // add the state id to the GET parameters
},
success: function (data) { // `data` is the return of the `load_cities` view function
$("#id_county").html(data); // replace the contents of the city input with the data that came from the server
}
});
});
</script>
{% endblock content %}
I am not currently seeing any errors but the counties list is not changing based on the "Business location state" choice. Any ideas about what is going wrong?
i'm creating a 'create an account view ' which the user can store his image, name ,lastname ....
on my database the name,lastname... are registred but the image is not stored.why?
in models.py:
from django.db import models
class information(models.Model):
name=models.CharField(max_length=50)
lastname=models.CharField(max_length=50)
email=models.CharField(max_length=50)
password=models.CharField(max_length=50)
img=models.ImageField(upload_to='media',blank=True)
in forms.py:
from app1.models import information
from django import forms
class create_form(forms.ModelForm):
class Meta:
model=information
fields=[
'name',
'lastname',
'email',
'password',
'img'
]
in views.py:
def create_view(request,*args,**kwargs):
my_form=create_form(request.POST or None)
if my_form.is_valid():
my_form.save()
print(my_form.cleaned_data['img'])**#########print :None**
context={"form":my_form}
return render(request,'first create.html',context )
in templates:
<main>
<section>
<form action="" method="Post"> {% csrf_token %}
{{form.as_p}}
<input type="submit" value="save"/>
</form>
</section>
</main>
url.py
from django.contrib import admin
from django.urls import path
from app1 import views
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path('home/', views.firstview, name='home'),
path('Create/', views.create_view, name='create'),
path('home/main/', views.homeview, name='main')
]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
You made two mistakes here. First of all, you need to pass request.FILES to the form:
from django.shortcuts import redirect
def create_view(request,*args,**kwargs):
if request.method == 'POST':
my_form=create_form(request.POST, request.FILES)
if my_form.is_valid():
my_form.save()
return redirect('some-view')
else:
my_form = create_form()
context={'form': my_form}
return render(request,'first create.html', context)
and furthermore you need to specify enctype="multipart/form-data" in your <form> tag:
<main>
<section>
<form action="" method="Post" enctype="multipart/form-data">
{% csrf_token %}
{{form.as_p}}
<input type="submit" value="save"/>
</form>
</section>
</main>
Note that you better implement the Post/Redirect/Get pattern [wiki] and thus make a redirect(..) [Django-doc] in case of a succesful POST request.
I've been banging my head about this for a week or so in my spare time, I currently have in my model
import recurrence.fields
.
.
.
course_recurring = recurrence.fields.RecurrenceField(null=True)
I can add recurrences and retrieve them in the admin console, but this in the template: {{ course.course_recurrence.rrules }} returns nothing.
I was suffering from the same problem, but I solved it.
Please try below steps:
1) Include {{form.media}} in your html head tag.
2) Please include the following before urlpatterns =[...]
-js_info_dict = {'packages': ('recurrence', ),}
3) Then add this url in the urls.py which includes your template:
-url(r'^jsi18n/$', django.views.i18n.javascript_catalog, js_info_dict)
Note: You need to import django library by including following line in your same urls.py file
-import django
This configuration works well for the new Django:
urls.py
from django.conf import settings
from django.conf.urls.static import static
from django.contrib import admin
from django.urls import path, include
from django.views.i18n import JavaScriptCatalog
urlpatterns = [
path('admin/', admin.site.urls),
# ...
path('jsi18n/', JavaScriptCatalog.as_view(packages=['recurrence']), name='javascript-catalog'),
]
# Connect static files
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
course_form.html
<html>
<head>
<script type="text/javascript" src="{% url 'javascript-catalog' %}">
</script>
</head>
<body>
<form method="post" class="post-form">
{% csrf_token %}
{{ form.media }}
{{ form }}
<button type="submit">Submit</button>
</form>
</body>
</html>
views.py
class CourseCreateView(CreateView):
model = Course
fields = ['title', 'price', 'recurrences']
success_url = reverse_lazy('course-list')
forms.py
from django import forms
from .models import Course
class CourseForm(forms.ModelForm):
class Meta:
model = Course
fields = ('title', 'price', 'recurrences', )
models.py
from django.db import models
from recurrence.fields import RecurrenceField
class Course(models.Model):
title = models.CharField(max_length=255)
price = models.PositiveSmallIntegerField()
recurrences = RecurrenceField()
def __str__(self):
return self.title
class Meta:
verbose_name = 'Course'
verbose_name_plural = 'Courses'
I am trying to build a simple landing page in Django that will allow users to sign up for an email newsletter. I am using this cookie cutter template - https://github.com/Parbhat/cookiecutter-django-foundation - because it integrates Foundation 6 from the jump.
The challenge is that the form fields are not showing in the template. Any help would be appreciated.
My models.py is:
class Subscribe(models.Model):
email = models.EmailField()
subscription_status = models.BooleanField(default=True)
create_date = models.DateTimeField(auto_now_add = True, auto_now = False)
update_date = models.DateTimeField(auto_now_add = False, auto_now = True)
def __unicode__(self):
return self.email
My forms.py is:
from django import forms
from .models import Subscribe
class SubscribeForm(forms.ModelForm):
class Meta:
model = Subscribe
fields = ('email',)
My views.py is:
from django.shortcuts import render
from subscribers.forms import EmailForm, SubscribeForm
from .models import Subscribe
def home(request):
form = SubscribeForm(request.POST or None)
if form.is_valid():
new_join = form.save(commit=False)
#we might need to do something here.
email = form.cleaned_data['email']
new_join_old, created = Subscribe.objects.get_or_create(email=email)
#new_join.save()
context = {"form": form}
template = "pages/home.html"
return render(request, template, context)
And my template is:
{% extends "base.html" %}
{% load foundation_formtags %}
{% block content %}
<section class="hero">
<!-- HERO SECTION -->
<div class="homebox">
<div class="wrap">
<p>Lorem Ipsum</p>
<form class="form" method="post" action=""> {% csrf_token %}
{{ form|as_foundation }}
<input type='submit' value='Subscribe' class='btn' />
</form>
</div>
</div>
</section>
My urls.py is:
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from django.conf.urls import url
from . import views
from subscribes.views import home
urlpatterns = [
url(r'^$', home, name='home'),
]
Thanks!
I'd like to add Imageform to my form to allow all users to add a photo.
I've read this https://docs.djangoproject.com/en/dev/ref/forms/fields/#imagefield
and this https://docs.djangoproject.com/en/dev/ref/forms/api/#binding-uploaded-files
but still I'm confused about how to achieve that. How can I change my codes to allow users to add a photo from their own folders?Here's my codes and I also attached the ideal form I'd like to create.
[My ideal form]
models.py
from django.db import models
from django.forms import ModelForm
class Sell(models.Model):
subject = models.CharField(max_length=100)
price = models.CharField(max_length=100)
condition = models.CharField(max_length=100)
photo = models.ImageField(upload_to="media")
email = models.EmailField()
body = models.CharField(max_length=200)
forms.py
from django.forms import ModelForm
from uasite1.models import Sell
class SellForm(ModelForm):
class Meta:
model = Sell
views.py
from django.shortcuts import render_to_response,get_object_or_404
from django.http import HttpResponseRedirect
from uasite1.forms import SellForm
from uasite1.models import Sell
from django.template import RequestContext
def sell_create(request):
context = {}
if request.method == 'POST':
form = SellForm(request.POST)
if form.is_valid():
new_sell = form.save()
return HttpResponseRedirect('/sechand/%d/' % new_sell.pk)
else:
form = SellForm()
context['form'] = form
return render_to_response('sell.html',context,context_instance = RequestContext(request))
sell.html
{% extends 'base.html' %}
{% block extrahead %}
{% endblock %}
{% block content %}
<form enctype="multipart/form-data" action = "/sechand/" method = "post">
{% csrf_token %}
{{ form.as_p }}
<input type = "submit" value="Submit" />
</form>
{% endblock%}
sell_display.html (this is the template where the submitted information would show up.)
{% extends 'base.html' %}
{% block content %}
<div id = 'sell'>
<h3> Product Name : [ {{ sell.subject }}]</h3>
<p>Photo{{ sell.photo }}</p>
<p>Price: [ {{ sell.price }} ]</p>
<p>Condition: [ {{ sell.condition }} ]</p>
<p>Comments: [ {{sell.body}} ]</p>
<p>Contact Email:[ {{ sell.email }} ]</p>
</div>
{% endblock %}
urls.py
from django.conf.urls import patterns, include, url
from django.conf.urls.static import static
from django.conf import settings
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^sechand/$','uasite1.views.sell_create'),
url(r'^sechand/(?P<pk>\d+)/$', 'uasite1.views.sell_detail'),
url(r'^products/electronics/$', 'uasite1.views.Electronics'),
url(r'^products/$', 'uasite1.views.ProductsAll'),
url(r'^admin/', include(admin.site.urls)),
)+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
I did not go through your entire code but I can notice 1 important mistake, view should have the following:
form = SellForm(request.POST, request.FILES)
Also, this line:
<p>Photo{{ sell.photo }}</p>
I don't think that's the way to show a photo, I would put a link to the photo doing:
<p>Photo{{ sell.photo.url }}</p>
And finally, for development environments you may want to serve media files so just add this line to your main urls.py file:
from django.conf.urls.static import static
from django.conf import settings
urlpatterns = patterns('',
# your url patterns in here
) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
editing:
Serving media files. That link should give you a good overview, it's confusing I know, so I am going to give you an example, just like I do in my projects. First the way I do it in settings.py:
#settings.py
from os.path import dirname, join, realpath
# have in mind that I have settings.py under project_root/project/settings.py
# so you probably want to check your path to your project root folder first
ROOT_DIR = realpath(join(dirname(__file__), '..'))
MEDIA_ROOT = realpath(join(ROOT_DIR, 'media'))
MEDIA_URL = '/media/'
STATIC_URL = '/static/'
STATICFILES_DIRS = (
join(ROOT_DIR, "static"),
)
That's the way I do it, you could find many ways that also work. To give you a better clue my folders look like this:
project_root/
media/
static/
project/
settings.py