Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django forms with variable user entries
I want to create a django form that captures user entry such as name, address, age. For this type of information I can create a model such as class GeneralInfoPremium(models.Model): state = models.CharField(max_length = 2, choices = STATE_choices) class_code = models.CharField(max_length = 4) manual_premium = models.DecimalField(decimal_places = 2, max_digits = 10) class GeneralUserInfo(models.Model): firstname = models.CharField() lastname = models.CharField() address = models.CharField() # etc.... However, I also want to capture maybe some information like their class schedule or family information. class UserSchedule(models.Model): course_number = model.IntegerField() course_name = model.CharField() # etc.... class FamilyInfo(models.Model): family_member_type = models.CharField(choices = MEMBER_CHOICES) # mother, father, sibling family_member_name = models.CharField() # jon doe # etc.... where by each user, the number of courses and number of family members could vary. I would like the form to look something like below with a simple submit button to send things off to be saved. My question is, how should I structure the form template considering there are multiple models? -
Misunderstanding about Django collectstatic
I'm currently getting my Django website ready for production and have run into a small hitch. I've looked at the page https://docs.djangoproject.com/en/2.2/ref/contrib/staticfiles/, and it seems I need to run the collectstatic command to process all my static files and put them in one directory. The problem is that I have about 80GB worth of static files, and to copy them into a new STATIC_ROOT takes up a large amount of redundant hard drive space. Is there any way to keep this large set of datafiles in a file structure outside of the django website, and to serve them from there? -
I am trying to create a registration form to add data to 2 tables simultaneously. But I am not sure what to write after the POST method
I want to create a user into auth_user. And use its id(primary key) to fill in an entry into User_Profile to take it as a Foreign key. Models.py: class User_Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) contact_number = models.IntegerField() birth_date = models.DateField(null=False) address = models.CharField(max_length=200) role = models.ForeignKey(Role, on_delete=models.CASCADE) Forms.py: class UserForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput) class Meta: model = User fields = ['username', 'email', 'password'] class UserProfileForm(forms.ModelForm): class Meta: model = User_Profile fields = [ 'contact_number', 'birth_date', 'address', 'role'] Views.py: def registration_view(request): form = UserForm(request.POST) form2 = UserProfileForm(request.POST) else: context = { 'form': form, 'form2': form2 } return render(request, 'Schoool/registration_form.html', context) -
How can I send a notification on creating a new post using django-webpush?
I need to add a web push notification on creating a post but it does not work. I have tried following this documentations, https://www.digitalocean.com/community/tutorials/how-to-send-web-push-notifications-from-django-applications#conclusion Added this to my CreatePost View at Views.py self.object.save() for user in User.objects.all(): user_id = self.object.user.pk user_site = get_object_or_404(User, pk=user_id) payload = {'head': self.object.group, 'body': str(self.object.user)+' Uploaded a post.'} try: send_user_notification( user=user_site, payload=payload, ttl=1000) print('Success!') except: print("Fail") return super().form_valid(form) I expect it to send a push notification to all users in my site. -
How to edit django form data before cleaning/validation?
How can I edit the value returned by a django form field before it is validated or saved? For example, If I have: from django import forms class ContactForm(forms.Form): # Everything as before. ... def clean(self): # the widget returns user.id's (django-select2 ModelSelect2MultipleWidget recipient_ids = self.data['recipients'] # need to convert IDs to usernames usernames = User.objects.filter(id=recipient_ids).values_list(username, flat=True) # now I have a list of usernames, I need to put those back into the data to finish cleaning etc: self.data['recipients'] = usernames # error, data isn't mutable... return super().clean() How can I modify the form data self.data['recipients'] = usernames before it gets sent for cleaning? Side note on why I need to do this: I am trying to use Django-select2 ModelSelect2MultipleWidget (which returns pks) for the Django-postman recipients field, but recipients in Django postman can't be ids, it has to be username or some other field (I tried setting POSTNAME_NAME_USER_AS='pk' but postman doesn't accept that, so I'm just using the default which is 'username') -
Raise exception in django authentication backend instead of return none
In my django project, i implement a custom authentication backend and i want to raise several exceptions in authenticate method and handle these exceptions in login view. below line is from Django doc: Either way, authenticate() should check the credentials it gets and return a user object that matches those credentials if the credentials are valid. If they’re not valid, it should return None. Is there any problem with raising exception in authentication backend? -
django channel cannot create new instance of an object using html input in otree
I am programming in otree for an online asset market with double auction, where each subject can both sell and buy, and all their orders are public to everyone in the market. I am using WebSocket to make orders visible in one page in the browser after subjects submit an order. My problem is that it seems that data from input submission can be received, but it cannot be used to create new instance of an object from the info shown in console, and I don't get any other error messages. Here is the code I tried. In consumer.py def receive(self, text=None, bytes=None, **kwargs): self.clean_kwargs() msg = text player = self.get_player() group = self.get_group() if msg['action'] == 'new_order': if msg['order_type'] == 'Buy': try: bid = player.bids.create(price_buy=msg['price_buy'], quantity_buy=msg['quantity_buy']) except NotEnoughFunds: logger.warning('not enough funds') elif msg['order_type'] == 'Sell': try: ask = player.asks.create(price_sell=msg['price_sell'], quantity_sell=msg['quantity_sell']) except NotEnoughSharesToSell: logger.warning('not enough shares to sell') player.save() for p in group.get_players(): self.group_send(p.get_personal_channel_name(), {'asks': p.get_asks_html(), 'bids': p.get_bids_html()}) In JS $form_container.on('click', 'button#submit_order', function () { ...some variable declared... if (order_type == 'Sell' && price_sell > 0) { var msg = { ...some message content... }; if (socket.readyState === WebSocket.OPEN) { socket.send(JSON.stringify(msg)); console.log(msg); }; } else if (order_type == 'Buy' && … -
Obtaining data from user
How do I obtain the field data from a User auth query within a class View. It's on the django framework. This code works just fine... from django.contrib.auth.models import User class PaymentsReportView(ListView): template_name = 'payments/Payment_list.html' userid = 'James' queryset = Payment.objects.filter(Landlord_FK__User_id=userid) but this doesn't... class PaymentsReportView(ListView): template_name = 'payments/Payment_list.html' userid = User.username # where the username is James queryset = Payment.objects.filter(Landlord_FK__User_id=userid) How can I check the output of User.username to see if it's valid? What am I missing to get the data? -
Bootstrap collapse expanding all cards when one is clicked
Hi I am trying to use bootstrap collapse for a part of my django application. This is my implementation so far: {% extends 'base.html' %} {% block content %} <div class="container"> <div class="row"> <div class="col-6"> <div class="card"> <h1 class="text-center">Recent reports</h1> <div class="accordion" id="accordionExample"> {% for report in reports %} <div class="card"> <div class="card-header" id="report_{{ loop.counter }}"> <h2 class="mb-0"> {% if loop.counter == 1 %} <button class="btn btn-link" type="button" data-toggle="collapse" data-target="#collapse{{ loop.counter }}" aria-expanded="true" aria-controls="collapse{{ loop.counter }}"> Report #{{ report.report_number }} </button> {% else %} <button class="btn btn-link collapsed" type="button" data-toggle="collapse" data-target="#collapse{{ loop.counter }}" aria-expanded="false" aria-controls="collapse{{ loop.counter }}"> Report #{{ report.report_number }} </button> {% endif %} </h2> </div> <div id="collapse{{ loop.counter }}" class="collapse" aria-labelledby="report_{{ loop.counter }}" data-parent="#accordionExample"> <div class="card-body"> <table class="table"> <tbody> <tr> <th scope="row">Date</th> <td>{{ report.datetime_submitted }}</td> </tr> <tr> <th scope="row">XYZ</th> <td>{{ report.xyz }}</td> </tr> ..... </tbody> </table> </div> </div> </div> {% endfor %} </div> </div> </div> </div> </div> {% endblock %} I am facing an issue where when I click on the card-header card, all the collapse card-body class elements expand opposed to just the related one(which is the desired behaviour). Any guidance on how to solve this will be appreciated. -
How can you show more than just the foreign key of an object when listing something in Django Rest Framework?
I'm working on a problem in one class called Tour, which includes an Artist foreign key. I need to show more than just its foreign key. How can I do that while keeping all of CRUD functional? I tried to add depth = 1 to the Meta class in the serializers. That works, but upon attempting to create a new object, I get the error NOT_NULL CONSTRAINT FAILED. Then I got rid of that and instead added artist = ArtistSerializer to the TourSerializer, but that still doesn't do it, even though I've seen it work in a tutorial. The issue with using artist=ArtistSerializer() is that when I try to create the object, I pass the foreign key, but it doesn't seem to recognize it as a valid field. It's like I didn't type anything at all into the field. Every time I get it to properly list it, the creation doesn't work as intended. Here's how my code looks right now: class TourSerializer(ModelSerializer): artist = ArtistSerializer() class Meta: model = Tour fields = ['artist', 'start', 'end', 'country', 'id', 'created_at', 'updated_at'] read_only_fields = ['id', 'created_at', 'updated_at'] The models for Tour and Artist are as follows: class Tour(models.Model): artist = models.ForeignKey('core.Artist', on_delete=models.PROTECT) … -
How can I display some specific column?
I have this problem : I have this following form using Django : class Test(forms.Form): name = forms.CharField( label=_('Name'), ) price = forms.IntegerField( label=_('Price'), required=False, ) year = forms.IntegerField( label=_('year'), required=False, ) And then to display the labels with the entries I did this : {% if form %} {{ form.as_p }} But I just want to display the label 'name' with entry and the label 'price' with entry and to give a default value to year. Could you help me please ? Thank you very much ! PS : I tried to use this editable:False but I got an unexepected keyword argument 'editable' -
Django : how to use modified queryset in templates without saving modification
In my views.py, I do: context_data = {} all_answers = Answer.objects.all() for i in range(0, len(all_answers)) : all_answers[i].text = modify_text(all_answers[i].text, request) context_data ["all_answers"] = all_answers print(context_data ["all_answers"][0].text) #Check that it was modified return render(request, 'template.html', context_data) And in my templates I have like : {% for answer in all_answers.all %} {{ answer.text}} {% endfor %} The check shows that the modification is made, yet it my template the answer.text is the unmodified data from the database. I saw that the type of the context_data ["all_answers"] is a queryset, that I guess is triggered during the template rendering, making any unsaved changes useless, how to make my changes show in the template ? I have tried : context_data ["all_answers"] = list(all_answers) To load the queryset. The check works but then nothing show in the template (1) An error arise during the template render when I used this function to load the queryset into a list of dict. I also saw a [linked question without answer].3 I don't want to save the changes as they are customized for each request (for each user basically). TLDR : How to see my modifications in the templates without saving the changes into the database ? … -
NOT NULL constraint failed for Django Forms when extending Custom Model mid-project
I'm trying to mimic this project with the Profile one-to-one model: https://ruddra.com/posts/django-custom-user-migration-mid-phase-project/ Django version 2.2.3. The difficulty is that it's allowing only one user model any user model after the first one created. I create a super user and then cannot register any other users. I've been working on extending the base model for a week. I'm getting the Null Constraint error: views.py def payments(request): if request.user.is_authenticated: return redirect('login') else: if request.method == "POST": form = CustomUserCreationForm(request.POST) if form.is_valid(): profile = form.save(commit=False) profile.user = request.user profile.key = "".join(random.choice(string.digits) for i in range(20)) profile.save() Profile = Profile.get_or_create( user = request.user, key=profile.key, first_name=form.cleaned_data['first_name'] ) Profile.save() auth_login(request, form.get_user()) messages.success(request, f'Your account has been created! Please proceed to agreements and payment.') return redirect('agreements_page') else: raise ValidationError("Form is not valid. Try Again.") else: form = CustomUserCreationForm() return render(request, 'premium/payments.html', {'form': form}) models.py I'm relying on both the default base model, which is what this saves to. I then create the profile model via the Django form. Once one is created, it does not allow me to create another user. class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) key = models.CharField(max_length=25, null=True, blank=True) first_name = models.CharField(max_length=25) last_name = models.CharField(max_length=25) address1 = models.CharField(null=True, max_length=100, blank=True) address2 = models.CharField(null=True, max_length=100, … -
How do I make a list of field values on annotated Django queryset results?
This may be out there somewhere, but not quite sure how to ask it. Hopefully it will be a quick one. Say I have a table like the following: name count site Guy Man 2 ABC Guy Man 3 BCD Guy Man 4 CDE Girl Woman 2 ABC Girl Woman 2 BCD Girl Woman 3 CDE I would like to annotate these, so that I get a name, total count, and list of sites. So given the data above, I'd get the following. [ { "name": "Guy Man", "count_total": 9, "site_list": "ABC, BCD, CDE" }, { "name": "Girl Woman", "count_total": 7, "site_list": "ABC, BCD, CDE" } ] I understand how to get count_total, but I'm not sure how to get site_list. Any ideas? -
Django expire reservation
Hello I'm writing a simple app for reserving and buying the tickets in in cinema, one of the task is to reserve a ticket for some time (ex. 1 hour) its then in pending status and can be paid withing this period. Do you have any recommendation how to achieve expiration time? I have a field in Model storing the date that can be used. -
Is it required to compare social access token with Social Email ID in Social Auth?
When using Social Auth, Email ID is auto validate with Social(Google, FB) account. But I want to develop api for social auth.Mobile developer are using GOOGLE/FB SDK and provide me email. Issue: Is Social access token require, so comparing it with email ID received and then process the data if social access token received from social auth matched with Email? -
Django - Join on specific column
I have a model, let's call it Notification. A notification has a from_user, and a to_user among other fields which are not important right now. class Notification(models.Model): from_user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='from_user' ) to_user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='to_user' ) read = models.BooleanField(default=False) ... What I want to achieve is, in theory, very simple, but I can not get it to work. I would like to get the count of unread notifications for every user. The following Django ORM expression: User.objects.annotate( notification_count=Count('notification', filter=(Q(notification__read=False))) ).values('notification_count') Produces the following SQL: SELECT COUNT("notification"."id") FILTER (WHERE "notification"."read" = False) AS "notification_count" FROM "account" LEFT OUTER JOIN "notification" ON ("account"."id" = "notification"."from_user_id") GROUP BY "account"."id" ORDER BY "account"."member_since" DESC But this is not what I want. I want the LEFT_OUTER_JOIN to be done on the to_user column, not the from_user column. How can I achieve this using the Django ORM? -
How to create SaaS application with Python and Django 2019
Can you give me some examples of saas applications (free code), I'm already in the devepment phase but I don't have a clear model data to work with de multi tenancy -
Using pagination with django-filters
I want to add the pagination alongside with django-filters in the template. What should I write in pagination and how should I loop over my list of filtered vehicles? I've written the pagination in the HTML template, but it doesn't work with filtered results. When I go to the next page, I get all the vehicles (not filtered) again and again. class VehicleFilter(django_filters.FilterSet): model = django_filters.CharFilter(lookup_expr='icontains') year = django_filters.RangeFilter() mileage = django_filters.RangeFilter() price = django_filters.RangeFilter() class Meta: model = Vehicle fields = ['brand', 'model', 'year', 'mileage', 'price', ] def search(request): vehicle_list = Vehicle.objects.all() vehicle_filter = VehicleFilter(request.GET, queryset=vehicle_list) paginator = Paginator(vehicle_filter.qs, 1) page = request.GET.get('page') try: vehicles = paginator.page(page) except PageNotAnInteger: vehicles = paginator.page(1) except EmptyPage: vehicles = paginator.page(paginator.num_pages) return render(request, 'sale/vehicle_list.html', { 'vehicles': vehicles, 'page': page, 'vehicle_filter': vehicle_filter, }) <div class="pagination"> {% if vehicles.has_previous %} <a href="?page=1">&laquo; first</a> <a href="?page={{ vehicles.previous_page_number }}{% if request.GET.q %}&q={{ request.GET.q }}{% endif %}">previous</a> {% endif %} <a href="#" class="active">Page {{ vehicles.number }} of {{ vehicles.paginator.num_pages }}</a> {% if vehicles.has_next %} <a href="?page={{ vehicles.next_page_number }}{% if request.GET.q %}&q={{ request.GET.q }}{% endif %}">next</a> <a href="?page={{ vehicles.paginator.num_pages }}{% if request.GET.q %}&q={{ request.GET.q }}{% endif %}">last &raquo;</a> {% endif %} </div> Could you help me with the pagination … -
How to create Django model from MySQL table on-fly?
I have a DB with tables created on the fly. (via the 'pandas' module: ds.to_mysql ('BACTH_INPUT_XXX') I plan to use a dynamic model to display tables using 'django-datatables-views'.) How to create a Django model on the fly? I find: def create_batch_input_model(batch_id): name = "BatchInput{}".format(batch_id) fields = { 'first_name': models.CharField(max_length=255), 'last_name': models.CharField(max_length=255), } model = create_model(name, fields, app_label='dynamic', module='core.batchs',) return model How to populate model fields from MySQL table? -
Prefetch related with a filter that contains a field of the original model
If I have Model A with a ForeignKey to Model B, how can I prefetch Model A from Model B using some criteria in Model B? This is something what I would want (OuterRef obviously only works in a SubQuery, but this is basically the functionality I need): class ModelA(models.Model): somecriteria = models.CharField() class ModelB(models.Model): somerelation = models.ForeignKey(ModelA) someattribute = models.CharField() qs = ModelA.objects.all() qs = qs.prefetch_related( Prefetch( 'modelb_set', queryset=ModelB.objects.filter(someattribute=OuterRef('somecriteria')), to_attr='some_attr' ), ) The query is supposed to do the following (in less queries): for obj in qs: # Change this to new_qs = obj.some_attr if prefetch is working. newqs = obj.modelb_set.filter(someattribute=obj.somecriteria) if newqs.exists(): # Do something -
Use of if condition in get_absolute_url
I've developed a solution for put offline a post if it is a draft or a scheduled post. Now, that I want do is allow to see this type of post only if the user is_staff, then I try to use this: models.py class BlogPost(models.Model): title = models.CharField(max_length=70) slug_post = models.SlugField(max_length=70) publishing_date = models.DateTimeField() draft = models.BooleanField(default=False) category = models.ForeignKey(..) def __str__(self): return self.title @property def is_future(self): if self.publishing_date > datetime.datetime.now(): return True return False @property def is_draft(self): if self.draft == True: return True return False def get_absolute_url(self): if self.is_draft or self.is_future: return reverse("adminblogpost_preview", kwargs={"slug_post": self.slug_post}) else: return reverse("single_blogpost", kwargs={ "slug_post": self.slug_post, "slug_category": self.category.slug_category, }) decorators.py def staff_only(function=None, redirect_field_name=REDIRECT_FIELD_NAME, login_url='login'): actual_decorator = user_passes_test( lambda u: u.is_active and u.is_staff, login_url=login_url, redirect_field_name=redirect_field_name ) if function: return actual_decorator(function) return actual_decorator views.py def singlePost(request, slug_post, slug_category): category = get_object_or_404(BlogCategory, slug_category=slug_category) blogpost = get_object_or_404(BlogPost, slug_post=slug_post, draft=False, publishing_date__lte=timezone.now()) category_blogpost = BlogPost.objects.filter(category=category) context = { "category": category, "blogpost": blogpost, "category_blogpost": category_blogpost } return render(request, "blog/reading/single_post.html", context) @staff_only def singleOfflinePost(request, slug_post): status = BlogPost.objects.filter(draft=True, publishing_date__gte=timezone.now()) blogpost = get_object_or_404(status, slug_post=slug_post) context = {"blogpost": blogpost} return render(request, "blog/reading/single_post.html", context) urls.py path("<slug:slug_category>/<slug:slug_post>/", views.singlePost, name='single_blogpost'), path("preview/", views.singleOfflinePost, name='adminblogpost_preview'), If I use this solution I see this error message: NoReverseMatch at /backend/blog-posts/ Reverse … -
NoReverseMatch with arguments '(",)' in Django
I keep getting the NoReverseMatch error although I have checked numerous times to see if I have entered the code as instructed, and it seems I did, yet the webpage won't load properly. Because I have a few files and I don't know which one has the error (it should be urls.py but I just don't see where the error is located) I will post a link to my GitHub repository where I have uploaded all relevant files and a screenshot of the error message I've been getting. Sorry for not posting any code but I think it would make it very messy posting all the code here. Also, I saw a lot of similar questions but none of them solved my problem and none of them are with these exact arguments. GitHub repo: https://github.com/DjoleRkc/Python-Crash-Course-error-p.435.git -
Authenticate an API call correctly with requests and sessions
I want to call my own API in a custom view I wrote. Normally I use JWT authentication with my API calls. In this specific view though, I'd like to use a different authentication. I want to enable logged in users to make a successful get call (without a token). Not logged in users should not be able to make that call. I tried this with Basic Authentication and Session Authentication but don't really get it tow work. Here is my view that makes the API call: def visualize_buildings(request, id): passed_id = id endpoint = 'linktomyendpoint' + str(passed_id) response = requests.get(endpoint) building_group_data = response.json() # print(building_group_data) if 'buildings' in building_group_data: building_data = building_group_data['buildings'] context = {'building' : building_data} return render(request, 'building_group_visualize_api.html', context) else: return HttpResponseNotFound("Ups. We are sorry but no Building Group was found with that id") Here my API view: class BuildingGroupRetrieveAPIView(RetrieveAPIView): authentication_classes = [JSONWebTokenAuthentication, SessionAuthentication, BasicAuthentication] serializer_class = BuildingGroupSerializer queryset = BuildingGroup.objects.all() The view works with if I send a token in the headers. But how can I use Session Authentication with that? I tried getting username and password from the request and then pass it to the API call. But that doesn't work because I can't decode … -
Failed to Build mysqlclient ,Wheel cannot build. pip install mysqlclient not working
The problem have been faced by many including myself. You cannot use the command pip install mysqlclient directly for the latest build for python 3.7.4 or any 3.7.X . It is mentioned on the PyPI website that new wheels are not given the latest release of mysqlclient.