Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Problems Loading Static Files into Django Dev Environment
I am trying to load static files into my Django project and it just isn't working. Inside my settings.py file I have defined the below: STATIC_URL = '/static/' STATICFILE_DIRS = os.path.join(BASE_DIR,'static') This is a screenshot around how my project structure is setup: When the template is rendered only the text shows up - no image. HTML below to show the syntax behind static file loading: <!doctype html> {% load static %} <html class="no-js" lang=""> <head> </head> <body> <h1>Test</h1> <img src="{% static 'test.png' %}" alt=""> </body> </html> Any help is really appreciated -
django python accessing additional fields
I am new to Django and trying to access the custom fields but dont have any luck. Models.py class UserProfile(models.Model): user = models.OneToOneField(User) bio = models.CharField(max_length=400) def __str__(self): return self.user.username forms.py class UserForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput()) bio = forms.CharField(widget=forms.Textarea(attrs={'cols':50, 'rows': 5})) class Meta: model = User fields = ('username', 'email', 'password', 'bio') views.py def register(request): registered = False if request.method == "POST": user_form = UserForm(data=request.POST) if user_form.is_valid(): user = user_form.save() user.set_password(user.password) user.save() registered = True login(request, user) else: print(user_form.errors) else: user_form = UserForm return render(request, 'accounts/register.html', {'user_form':user_form, 'registered': registered}) @login_required def current_user(request): current = request.user # profile = User.objects.get(username=current.username) return render(request,'accounts/profile_detail.html',{"username":current.username, "email":current.email,"id":current.id, "bio":current.bio}) I am trying to access the bio of a user. It keeps saying the field doesnt exist. What I want to do is access bio in the html file: {{ bio }} Not sure what I am missing here. Thanks -
Filter in range of two date fields
I have something like this: class Model(models.Model): start = models.DateTimeField() end = models.DateTimeField() and I want to get all models that follow the following constraints: given two query parameters qstart, qend model.end > qstart model.start < q.end which would give all Model objects that lie between in the range of the two dates. I saw you can do Model.objects.filter(date__range=[qstart, qend]) however, that operates on a single field, where as I need to operate on 2 separate fields. -
How to allow an inactive user to log in and use the /user/ endpoint
I am using rest-auth and I want to allow the users reactivate their accounts by their own. I managed to allow the inactive user to log in by using AllowAllUsersModelBackend in settings.py AUTHENTICATION_BACKENDS = [ "django.contrib.auth.backends.AllowAllUsersModelBackend", ] And then I disallowed rest-auth to check respond with an error message by deleting these lines from the LoginSerializer: if not user.is_active: msg = _('User account is disabled.') raise exceptions.ValidationError(msg) I also customized the UserDetailSerializer to allow deactivation and activation by adding is_active field of the user model. Now I can log in using a deactivated user and it sends me a JWT back, but when I try to use the /user/ endpoint it respond with that error: { "detail": "User account is disabled." } I want to allow them to use this endpoint to reactivate their account but without allowing them to use any other custom endpoint that requires authentication. -
Format a float to justify to the right
I am adding a float value to the template and I am trying to get it to justify to the right. Currently, I am trying {{ float|floatformat:2|rjust }}, but it keeps throwing up a TemplateSyntaxError. Is it even possible to do this via the template system, or will I just have to use some CSS styling for this? -
Referring to forms and models in views.py with variables
When a user signs up on my site, they select a template that they'd like to see as part of the User Profile. In this case, because they want to see the 'green' profile, user.userprofile.color is equal to 1. I've built a specific model (called model1) for the green template as well as a specific form (called form1) for that model. When the user selects 'green' in the UserProfile form and submits the form, an instance of the model1 is assigned to the user automatically Within views.py, I'd like to create a generic view that takes the user.userprofile.color value and uses it to establish a) what form to serve the webpage b) what model the form is based on Rather than hardcoding the form and model value like this: def homepagetemplate(request): if request.method == 'POST': form = form1(request.POST, request.FILES, instance=request.user.model1) if form.is_valid(): form.save() return redirect('/accounts/') else: form = form1(instance=request.user.model1) args = {'form': form} return render(request, 'homepage.html', args) Within the function rather than specifying 'form1' and 'model1', I'd like form and model values to equal to 'form'+i and 'model'+i where i equals the value of user.userprofile.color (i.e. 1). Any help with this would be greatly appreciated! -
Updating email field in both user and custom user models
When creating an account, I have a registration form made of 2 forms, from which email field gets saved in both User and Student models. Now, I made an update account info view. Problem is, I want that email will get updated the same, in both models. But I get error: 'StudentEditForm' object has no attribute 'email' Here is my code: class StudentEditForm(forms.ModelForm): email = forms.EmailField(required=False) name = forms.CharField(max_length=30) surname = forms.CharField(max_length=50) photo = forms.ImageField(required=False) phone = forms.CharField(max_length=15, required=False) class Meta: model = Student fields = ('email', 'name', 'surname', 'phone', 'photo') class User(AbstractUser): pass class Student(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) name = models.CharField(max_length=30, null=True, blank=True, default=None) surname = models.CharField(max_length=50, null=True, blank=True, default=None) email = models.EmailField(unique=True, null=True, blank=True, default=None) student_ID = models.CharField(unique=True, max_length=14, validators=[RegexValidator(regex='^.{14}$', message='The ID needs to be 14 characters long.')], null=True, blank=True, default=None) photo = models.ImageField(upload_to='students_images', null=True, blank=True, default=None) phone = models.CharField(max_length=15, null=True, blank=True, default=None) def __str__(self): return self.surname User.student = property(lambda p: Student.objects.get_or_create(user=p)[0]) def profile_edit(request): user = request.user student = request.user.student if request.method != 'POST': form = StudentEditForm(instance=student) else: form = StudentEditForm(request.POST, instance=student) user.email = form.email form.save() return render(request, 'index.html') context = { "form": form, } return render(request, "registration/profile_edit.html", context) -
Hide password field in GET but not POST in Django REST Framework where depth=1 in serializer
I have 2 models : User & UserSummary. UserSummary has a foreign key to User. I just noticed that if I set depth= 1 within UserSummarySerializer, the password field is included in the output. It's hashed, but it would still be best to exclude this field. To hide the password field, I've just set the user field explicitly in the serializer, just like this : class UserSerializer(serializers.ModelSerializer): """A serializer for our user profile objects.""" class Meta: model = models.User extra_kwargs = {'password': {'write_only': True}} exclude = ('groups', 'last_login', 'is_superuser', 'user_permissions', 'created_at') def create(self, validated_data): """Create and return a new user.""" user = models.User( email = validated_data['email'], firstname = validated_data['firstname'], lastname = validated_data['lastname'], mobile = validated_data['mobile'] ) user.set_password(validated_data['password']) user.save() return user class UserSummarySerializer(serializers.ModelSerializer): user = UserSerializer() class Meta: model = models.UserSummary fields = '__all__' depth = 1 The downside of this way of doing is that, the field password is not available anymore on the POST request when creating a new user. How could I hide the password field on the GET request of UserSummary but display it in the POST request of User ? -
How does the Model Class convert attributes to database columns? DJANGO
Before posting this question, I have read through the Official Django Documentation, scouring it for a comprehensive explanation for beginners. I have read the code of the actual Model Class, and searched around on StackOverflow. When working with databases in Django, you work with classes inheriting from the Model class in the models module. This helps programmers avoid double-typing everything, jumping between database specific syntax and python. As I have read, 'the model class that each model inherits from automatically takes care of translation'. How does this work? How Does the Model Class convert model attributes to database columns? I suppose some methods inherited from the parent Model Class are able to use the variables specified in each new model, but would like a better explanation if possible! Also, why write 'models.Model' if the Model class is within models.base? LINK TO MODEL CLASS: https://docs.djangoproject.com/en/1.11/_modules/django/db/models/base/#Model -
SMTPAuthenticationError in Django
I have a problem like in a subject. I've create the form for sending emails from my project in django. When I set everything the python responde me a error. SMTPAuthenticationError at /kontakt/ (535, b'5.7.8 Username and Password not accepted. Learn more at\n5.7.8 https://support.google.com/mail/?p=BadCredentials g69sm1490980lji.90 - gsmtp') I wanto to say I turn on in lessscureaps and still this same problem. I have no idea where can be a error. In settings.py I have EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = 'mymail@gmail.com' EMAIL_HOST_PASSWORD = '********' EMAIL_PORT = 587 EMAIL_USE_TLS = True In views.py I declared the function : def kontakt(request): sent = False if request.method == 'POST': form = WyslijEmail(request.POST) if form.is_valid(): subject = form.cleaned_data['subject'] from_email = form.cleaned_data['from_email'] message = form.cleaned_data['message'] send_mail(subject, message, from_email,['mymail@gmail.com']) sent = True else: form = WyslijEmail() return render(request,'bajki/kontakt.html', {'form':form, 'sent': sent}) And in kontakt.html I have a code {% if sent %} <h1>Wysłano</h1> {% else %} <h1>Wyslij email</h1> <form action="." method="post"> {% csrf_token %} {{ form.as_p }} <p><input type="submit" value="Wyślij wiadomość"></p> </form> {% endif %} Maybe someone have some ideas how to solve this problem? -
Django 2 paths and urls
I am starting with Django 2 and there is significant change to urls with paths and all that. Does anyone know how to write a path from a template view now? If I previously wrote something like: url(r'^about/$', TemplateView.as_view(template_name='about.html')), Or if I include an app like: url(r'^blog/', include('blog.urls', namespace='blog', app_name='blog')), What would it look like with paths in Django 2? -
TypeError: Object of type 'Decimal' is not JSON serializable
We have a field with JSON (PostgeSQL JSONB) where product prices are stored: {"total": 2400000, "currency": "USD", "per_meter": 3404} When we try to filter this field with NumberFilter with django-filters library we've got an error: TypeError: Object of type 'Decimal' is not JSON serializable https://sentry.io/share/issue/43b4eb682bf64562961f12f60b05f9f6/ django 2.0.1 django-filters 1.1.0 rest_framework 3.7.7 Error query: SELECT "core_properties"."id", "core_properties"."src_id", "core_properties"."is_public", "core_properties"."property_type", "core_properties"."place_id", "core_properties"."place_building_id", "core_properties"."place_section_id", "core_properties"."created_at", "core_properties"."updated_at", "core_properties"."is_for_sale", "core_properties"."s_src_updated_at", "core_properties"."is_for_rent", "core_properties"."r_src_updated_at" FROM "core_properties" INNER JOIN "core_places" ON ("core_properties"."place_id" = "core_places"."id") INNER JOIN "core_places_sites" ON ("core_places"."id" = "core_places_sites"."places_id") INNER JOIN "core_properties_sale" ON ("core_properties"."id" = "core_properties_sale"."property_id") WHERE ("core_properties"."property_type" = 'квартира' AND "core_properties"."is_for_sale" = True AND "core_places_sites"."site_id" = 3 AND ("core_properties_sale"."price_rub" -> 'total') >= <django.contrib.postgres.fields.jsonb.JsonAdapter object at 0x11131b6a0>) -
Django problems with primary keys and data inserts
My console shows this problem when trying to push data into my db invalid literal for int() with base 10: My views.py class: def routineInput(request): if request.method == 'POST': form = CreateRoutine(request.POST) query = request.POST["name_of_routine"] newEntry = Todolist(str(query)) #newEntry.name = () if form.is_valid(): newEntry.save() return HttpResponseRedirect('/todo/saved/') else: form = CreateRoutine() This is my models.py class: class Todolist(models.Model): id = models.AutoField(primary_key=True) name = models.TextField() created_at = models.DateTimeField(default = datetime.now, blank = True) updated_at = models.DateTimeField(default = datetime.now, blank = True) The newEntry = Todolist(str(query)) is my problem. If I change it to newEntry = Todolist(1, str(query)) my code works. But in the last case my code pushes the integer into the "id" field although it should be my auto increment primary key. Without the integer in my function my browser throws me this message: invalid literal for int() with base 10:... -
Django CBV best practice: Setting instance variables
In a class based view, I want to set an instance variable. This variable creates an instance from another class which collects data from other parts of the code to be used in the get_context_data. In this older question, and this newer one, @jpic and @catavaran suggest that the logic of instance variables can be deployed at the dispatch method: ...you could parse the request and set class view instance attributes in an overload of django.views.generic.base.View.dispatch, this is safe according to the source In an October 2013 talk Andrew Pinkham suggests that Overriding dispatch() is appealing (and what I did originally when I presented this talk) because it offers a single simple place to do so, but this defies the logic of dispatch(). Instead, it is best to call set_account() [a method that defines instance variables] in overrides of both get() and post(). At a first glance this is not very DRY. Moreover, the author uses a vague argument to promote it as a better solution, closer to the logic of CBV. Thank you @danielroseman, I fully understood that by overriding the get method, the logic of CBV is purely defied: By overriding get, you've bypassed all the built-in functionality … -
python django number format
I'm trying to format numbers. Examples: 24.324324324324323 18.91891891891892 I want to delete the numbers behind it to be like this 24.3 18.9 what can use django template tags? or using some code? -
Django Python "TypeError: view must be callable or a list/tuple in the case of include()" with urls
I'm getting a "TypeError: view must be callable or a list/tuple in the case of include()" for the subscribe url below for Weather_App/urls.py import signupform.urls import signupform.views as views app_name = "Weather_App" urlpatterns = [ url(r'^admin/', admin.site.urls, name='admin'), url(r'^subscribe/', signupform.urls, name='signup'), ] In my other urls file signupform/urls.py, I had a similar issue but fixed it using a views import from django.conf.urls import url from . import views as Weather_App_views urlpatterns = [ url(r'^$', Weather_App_views.index, name='index'), url(r'confirm/$', Weather_App_views.confirm, name='confirm'), ] -
How to populate django form , based on two ModelForm
I want my app users to be able to edit two forms using one html page , where these two forms will be populated with initial data from two related models,but i am not able to accomplish this result yet, models.py class User(AbstractUser): is_vendor = models.BooleanField(default=False) class Vendor(models.Model): user = models.OneToOneField(User) phone = models.CharField(max_length=15) forms.py class VendorProfileForm(forms.ModelForm): class Meta: model = Vendor fields = ['phone',] class UserForm(forms.ModelForm): class Meta: model = User fields = ['username','email'] views.py def Edit_Vendor_Profile(request, pk): # querying the custom User model . user = User.objects.get(pk=pk) if request.method == "POST": vendor_form = VendorProfileForm(request.POST,request.FILES, instance=user) user_form = UserForm(request.POST, instance=user) if vendor_form.is_valid() and user_form.is_valid(): vendor_form.save() user_form.save() return HttpResponseRedirect('/profile/') else: vendor_form = VendorProfileForm(request.POST,request.FILES, instance=user) user_form = UserForm(instance=user) return render(request, "accounts/update.html", {'vendor_form':vendor_form, 'user_form':user_form}) so the problem is that fields of user model are being populated fine but fields from Vendor model are not.so what that i am doing wrong, thank you very much in advanced . -
Can you save a new object over an existing object?
Let's say I have the following Listing model. I retrieve a listing and store that in old_listing, and set up a new one and store that in new_listing. Now is there some way to save new_listing into old_listing, basically overriding all fields except the auto-incrementing id field? class Listing(models.Model): street = models.CharField(max_length=500) old_listing = Listing.objects.get(id=1) # Assuming this record already exists new_listing = Listing(street='123 Main Street') old_listing.save(new_listing) # This obviously doesn't work -
"to" argument must be a list or tuple in Django
I have a bug like in subject of this question: "to" argument must be a list or tuple I want to create a email form and I can't find a error. Maybe someone help me? My files are: forms.py from django import forms class WyslijEmail(forms.Form): name = forms.CharField(max_length=25) subject = forms.CharField(max_length=255) email = forms.EmailField() message = forms.CharField(required=True, widget=forms.Textarea) views.py from django.shortcuts import render, redirect from django.core.mail import send_mail, BadHeaderError from .forms import WyslijEmail def kontakt(request): if request.method == 'GET': form = WyslijEmail() else: form = WyslijEmail(request.POST) if form.is_valid(): name = form.cleaned_data['name'] subject = form.cleaned_data['subject'] email = form.cleaned_data['email'] message = form.cleaned_data['message'] try: send_mail(name,subject,email,message, ['admin@gmail.com',]) except BadHeaderError: return render('Niewlasciwe cos tam') return redirect('sukces') return render(request,'bajki/kontakt.html', {'form':form}) def sukces(request): return render('Sukces udało sie') kontakt.html <form method="post"> {% csrf_token %} {{ form.as_p }} <p><input type="submit" value="Wyślij wiadomość"></p> </form> What I must define to fix this problem? -
Generic detail view needs object pk or a slug
But I already refer to primary keys, don't I? It says this error relates to: class CommentUpdate(UpdateView): model = Comment fields = ['body'] def form_valid(self, form): film = Film.objects.get(pk=self.kwargs['film_id']) comment = Film.objects.get(pk=self.kwargs['comment_id']) form.instance.user = self.request.user form.instance.film = film form.instance.comment = comment return super(CommentUpdate, self).form_valid(form) I am not sure once this issue is fixed if that code above will work but the view I have to create a comment does: class CommentCreate(CreateView): model = Comment fields = ['body'] def form_valid(self, form): film = Film.objects.get(pk=self.kwargs['film_id']) form.instance.user = self.request.user form.instance.film = film return super(CommentCreate, self).form_valid(form) My urls.py: path('<int:film_id>/comment/', views.CommentCreate.as_view(), name='add_comment'), path('<int:film_id>/comment/<int:comment_id>/', views.CommentUpdate.as_view(), name='update_comment'), model: class Comment(models.Model): # user = models.ForeignKey(User, on_delete=models.CASCADE) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) film = models.ForeignKey(Film, on_delete=models.CASCADE) body = models.CharField(max_length=200) def get_absolute_url(self): return reverse('films:detail', kwargs={'pk': self.film.pk}) And html link I have: <a href="{% url 'films:add_comment' film_id=film.id %}">Leave a comment</a> <a href="{% url 'films:update_comment' film_id=film.id comment_id=comment.id %}">Update</a> -
Many errors on deploying local Django app to Heroku
This is my first time to use Heroku . I have gone through other questions , but I am facing multiple errors , eg. some are related to Procfile not able to get identified (i have done an echo too using other question ) and I am also confused about how my app's structure should be deployed . My Django App structure : Please ignore the /api directory - i am not using it all Current error : I am following these tutorials but I am totally confused about what is my App and what is my Django project . Currently my git repository starts from /wantedly . The project is working fine on local . I need step by step help on how to deploy my local django app to heroku . -
Return particular string from response
I am trying to return a particular string value after getting response from request URL. Ex. response = { 'assets': [ { 'VEG': True, 'CONTACT': '12345', 'CLASS': 'SIX', 'ROLLNO': 'A101', 'CITY': 'CHANDI', } ], "body": "**Trip**: 2017\r\n** Date**: 15th Jan 2015\r\n**Count**: 501\r\n\r\n" } This is the response which i am getting, from this I need only Date: 15th Jan 2015. I am not sure how to do it. Any help would be appreciated. -
What is the right way to create projects in Django ? (Folders)
Sorry for the weird question. I am creating a MMORPG Text browser game, and I feel like my project is wrong. I am creating a new app for everything I need (Account app, Menu app, Fight app). And when I browse Github, people only have like 5/6 folders while I'm at 20 currently. Where should I put my classes/forms/things normally ? Like, where should I have my fight system placed ? Thanks ! (Sorry for bad english) -
UpdateView in Django
I can successfully add a comment with the below code: views.py: class CommentCreate(CreateView): model = Comment fields = ['body'] def form_valid(self, form): film = Film.objects.get(pk=self.kwargs['film_id']) form.instance.user = self.request.user form.instance.film = film return super(CommentCreate, self).form_valid(form) class CommentUpdate(UpdateView): model = Comment fields = ['body'] def form_valid(self, form): film = Film.objects.get(pk=self.kwargs['film_id']) comment = Film.objects.get(pk=self.kwargs['comment_id']) form.instance.user = self.request.user form.instance.film = film form.instance.comment = comment return super(CommentUpdate, self).form_valid(form) urls.py: path('<int:film_id>/comment/', views.CommentCreate.as_view(), name='add_comment'), path('<int:film_id>/comment/', views.CommentUpdate.as_view(), name='update_comment'), models.py: class Comment(models.Model): # user = models.ForeignKey(User, on_delete=models.CASCADE) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) film = models.ForeignKey(Film, on_delete=models.CASCADE) body = models.CharField(max_length=200) def get_absolute_url(self): return reverse('films:detail', kwargs={'pk': self.film.pk}) links in html file: <a href="{% url 'films:add_comment' film_id=film.id %}">Leave a comment</a> <a href="{% url 'films:update_comment' film_id=film.id %}">Update</a> As you can see, I have tried to add update functionality but at the moment when I click the update link and save a comment it creates a new instance rather than amending an existing one. -
ForeignKey admin link name
In my Django model, I have class PhotoComment(AbstractComment): photo = models.ForeignKey(Photo, on_delete=models.PROTECT, related_name='comment') I called it like this to distinguish from a PersonComment class defined in the same project. The URL in the admin page now looks like this: https://xxx.yyy/admin/people/personcomment/ I would love to have https://xxx.yyy/admin/people/comment/ instead. Is it possible?