Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Web Design Tool Assets
How do copyright laws apply to the assets (pictures, html,css, etc) that are used in various web design tools that WordPress or GoDaddy provide? I have been using a tool of that nature to design a website but I would like to take all the assets that the tools have provided and host them elsewhere with a django server. Is this something that falls under fair use or open source policies? -
I am missing something with Django's url paths
I have an app in django that has a webpage with buttons to travel to another page via a menu and 8 hrefs. When I travel to the first page and try to click on another, I will encounter a 404 error. Page not found (404) http://127.0.0.1:8000/index.html/contact Here is my url.py urlpatterns = [ path('index.html/', views.homepage), path('contact.html/', views.contact), path('about.html/', views.about), ] Views as well def customers(request): return render(request, 'customers.html') def about(request): return render(request, 'about.html') def contact(request): form_class = ContactForm return render(request, 'contact.html', { 'form': form_class, }) I do not want http://127.0.0.1:8000/index.html/contact I want http://127.0.0.1:8000/index or http://127.0.0.1:8000/contact How do I keep my URLs basic? -
Wagtail vs Mezzanine, which is better for building a customised CMS?
Wagtail and Mezzanine are good open source CMS platforms. But, which one is better to be extended and used to build a Django web app with CMS included? -
Dropbox API with Django - Authentication
I'm trying to learn Dropbox API and want to use OAuth 2 for authorization. I'm getting following error: dropbox_auth_start() missing 1 required positional argument: 'request' Here is my code: Views.py from dropbox import DropboxOAuth2Flow from django.shortcuts import redirect def get_dropbox_auth_flow(web_app_session): redirect_uri = "https://www.my-dummy-url.com" APP_KEY = 'my-app-key' APP_SECRET = 'my-app-secret' return DropboxOAuth2Flow( APP_KEY, APP_SECRET, redirect_uri, web_app_session, "dropbox-auth-csrf-token") def dropbox_auth_start(web_app_session, request): if request.method == 'GET': authorize_url = get_dropbox_auth_flow(web_app_session).start() return redirect(authorize_url) urls.py urlpatterns = [ path('dropbox/', views.dropbox_auth_start, name='dropbox') ] -
Why is extending the user model causing an http 400 error?
I followed the Django documentation to try to extend my user model to add a field called authentication_key. It is resulting in an HTTP 400 error when I test the site locally. My models: class AuthenticationKey(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) authentication_key = models.CharField(max_length=100) My Admin: class AuthenticationKeyInline(admin.StackedInline): model = AuthenticationKey can_delete = False verbose_name_plural = 'AuthenticationKey' # Defines a new User admin class UserAdmin(BaseUserAdmin): inlines = (AuthenticationKeyInline, ) # Re-register UserAdmin admin.site.unregister(User) admin.site.register(User, UserAdmin) And how I'm referring to the field in my views.py @login_required(login_url='/login/') def home_page(request): u_id = request.user.authenticationkey I'm thinking the error may be how I'm referring to the field in views but I can't figure out quite what's wrong. -
How to use the OAuth2 toolkit with the Django REST framework with class-based views?
I'm trying to add an API using the Django REST framework to an existing codebase which uses the Django OAuth2 toolkit. The existing views make use of the fact that the OAuth2 toolkit's backend modifies the behavior of Django's login_required decorator so that it uses OAuth2 authentication. The function-based views look similar to the one in the tutorial example: from django.contrib.auth.decorators import login_required from django.http.response import HttpResponse @login_required() def secret_page(request, *args, **kwargs): return HttpResponse('Secret contents!', status=200) I'm trying to adapt the example given on https://django-oauth-toolkit.readthedocs.io/en/latest/rest-framework/getting_started.html to my situation, but I'm finding it's not an exact correspondence, because the example uses the DRF's ModelViewSet classes whereas my current view uses a (less-integrated) generic class-based view: from rest_framework import generics from ..models import Session from ..serializers import SessionSerializer class SessionDetail(generics.UpdateAPIView): queryset = Session.objects.all() serializer_class = SessionSerializer where I've set the default permission class to IsAuthenticated in settings.py: REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAuthenticated', ], } This should allow a Session object to be updated using PATCH requests, but it appears to return a 403 Forbidden response for use cases similar to the ones for the current views decorated with login_required. How can I update the SessionDetail view so that it behaves the … -
Access to model field through connected one
I have two models class Category(models.Model): name = models.CharField("category", max_length=200, null=True) discount = models.PositiveIntegerField(null=True) class Product(models.Model): name = models.CharField("product", max_length=200) price = models.DecimalField(max_digits=10, decimal_places=2) category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name="products", verbose_name="category") How to show discount value in admin panel? class ProductAdmin(admin.ModelAdmin): list_display = ['name', 'category', 'price', 'discount'] # not works list_filter = ['category', 'price'] list_editable = ['price'] -
Django pagination URL
I can get pagination to work at http://127.0.0.1:8000/ using the below code: {% if is_paginated %} <div class="pagination"> <span class="page-links"> {% if page_obj.has_previous %} <a href="/?page={{ page_obj.previous_page_number }}">previous</a> {% endif %} <span class="page-current"> Page {{ page_obj.number }} of {{ page_obj.paginator.num_pages }}. </span> {% if page_obj.has_next %} <a href="/?page={{ page_obj.next_page_number }}">next</a> {% endif %} </span> </div> {% endif %} I would like to paginate a bunch of comments at http://127.0.0.1:8000/film id which is like a details page for each film. I think I just need to change these urls for it to work: <a href="/films?page={{ page_obj.previous_page_number }}">previous</a> <a href="/films?page={{ page_obj.next_page_number }}">next</a> But so far have not been able to do so. My hrefs are usually like <a href="{% url 'films:add_comment' film_id=film.id %}">Leave a comment</a> but I am not fussed how it is wrote as long as it works. -
Using JS to render Django form
I'm learning to utilize pure JS in Django projects. Being a server-side developer the concepts are relatively new for me, so need a hand. Imagine a form where a user can post text, and/or upload an image. Think of it as a simple Django form like so: class PostForm(forms.Form): image = forms.ImageField(required=False) reply = forms.CharField(required=False, widget=forms.Textarea(attrs={'cols':30,'rows':3,'class': 'cxl','autocomplete': 'off','autofocus': 'autofocus'})) def __init__(self,*args,**kwargs): super(PostForm, self).__init__(*args,**kwargs) self.fields['image'].widget.attrs['id'] = 'browse_image_btn' def clean(self): data = self.cleaned_data # perform cleaning return data If I were to render this form in HTML, something like the following would do: <form action="{% url 'post_content' %}" method="POST" enctype="multipart/form-data"> {% csrf_token %} {{ post_form.reply }}<br> {{ post_form.image }} <label for="browse_image_btn" style="cursor: pointer;"><img alt="Select photo" src="{{ STATIC_URL }}img/upload.svg" width="70" height="70"></label> <input type="submit" value="submit"> </form> But how do I create this HTML solely via JS? Use-case: imagine a page that contains a long list of content, with a reply button under each. The form above only appears under specific content once the user has pressed the reply button. Moreover, pressing the same button toggles it off too. I can't seem to wrap my head around solving a problem like that. Please advise, preferably with an illustrative example. I'd prefer to understand the most … -
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'), ]