Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django dynamic url redirecting to 404
I'm trying to create a dynamic URL pattern where there's an ID passed into the URL and used the retrieve a piece of information from the database. Here's the definition of the pattern: urlpatterns = [ path('',views.index,name='index'), path('<int:question_id/>', views.detail,name='detail'), path('<int:question_id>/results/',views.results,name='results'), path('<int:question_id>/vote/',views.vote,name='vote') ] and here's the piece of code used to retrieve the information: def detail(request, question_id): question = get_object_or_404(Questions, pk = question_id) return render(request, 'polls/detail.html', {'question': question}) the user seems to be redirected to a 404 page no matter what id is passed in the url. -
nested serializer filed TypeError: Object of type QuerySet is not JSON serializable
I have two serilizers like this : class UsersInfoSeriliazerByUsers(serializers.ModelSerializer): class Meta: model = FreeTime fields = '__all__' class SetTimeZoneSerializer(serializers.Serializer): TIMEZONES = tuple(zip(pytz.all_timezones, pytz.all_timezones)) meeting_date = serializers.DateField(format="%d-%m-%Y", input_formats= ['%d-%m-%Y', 'iso-8601']) time_zone_destination = serializers.ChoiceField( choices = TIMEZONES) time_table = UsersInfoSeriliazerByUsers(many=True,read_only=True) in views.py i need to get data from freetime model and send it to SetTimeZoneSerializer again(i need to serialize the queryfilter results and it is a nested field ) : @action(detail=False, methods=['post']) def common(self,request): serializer = SetTimeZoneSerializer(data = request.data) if serializer.is_valid(): j={} j['meeting_date']=serializer.data['meeting_date'] j['time_zone_destination']=serializer.data['time_zone_destination'] j['time_table'] = FreeTime.objects.all().values() json_string = json.dumps(j) serializer = SetTimeZoneSerializer(json_string, many=True) and i got this error : Internal Server Error: /api/time/common/ Traceback (most recent call last): File "/home/admin1/envs/myvenv/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/home/admin1/envs/myvenv/lib/python3.8/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/admin1/envs/myvenv/lib/python3.8/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/home/admin1/envs/myvenv/lib/python3.8/site-packages/rest_framework/viewsets.py", line 125, in view return self.dispatch(request, *args, **kwargs) File "/home/admin1/envs/myvenv/lib/python3.8/site-packages/rest_framework/views.py", line 509, in dispatch response = self.handle_exception(exc) File "/home/admin1/envs/myvenv/lib/python3.8/site-packages/rest_framework/views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "/home/admin1/envs/myvenv/lib/python3.8/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception raise exc File "/home/admin1/envs/myvenv/lib/python3.8/site-packages/rest_framework/views.py", line 506, in dispatch response = handler(request, *args, **kwargs) File "/home/admin1/mizbanproject/time-algorithm/time_algorithm_api/api/views.py", line 114, in common json_string = json.dumps(j) File "/usr/lib/python3.8/json/__init__.py", line 231, in dumps return _default_encoder.encode(obj) File "/usr/lib/python3.8/json/encoder.py", … -
How to add many objects to the database in Django TabularInLine?
Currently I have a need to add a lot of objects to a punch-through table using a python manage.py shell. I will describe the models here in a nutshell, I will not litter with unnecessary fields. So I have a model Product: class Product(models.Model): name = models.CharField(max_length=200, db_index=True, unique=True) slug = models.SlugField(max_length=200, db_index=True, unique=True) I have a model Shop: class Shop(models.Model): name = models.CharField(max_length=200, db_index=True) slug = models.SlugField(max_length=200, db_index=True) I have model ShopQuantity: class ShopQuantity(models.Model): shop = models.ForeignKey(Shop, blank=True, on_delete=models.CASCADE, null=True, related_name='product_list') product = models.ForeignKey(Product, blank=True, on_delete=models.CASCADE, null=True, related_name='shop_list') price = models.DecimalField(max_digits=10, decimal_places=2, default='0') quantity = models.IntegerField(blank=True, null=True, default='0') In admin.py: class ShopQuantityInline(admin.TabularInline): model = ShopQuantity extra = 0 @admin.register(Shop) class ShopAdmin(admin.ModelAdmin): fields = ['name', 'slug'] list_display = ['name'] inlines = [ShopQuantityInline] @admin.register(Product) class ProductAdmin(admin.ModelAdmin): fields = ['name', 'slug'] list_display = ['name'] inlines = [ShopQuantityInline] Suppose I already have 1000 items of goods in my database. Please tell me how I can put these 1000 products inside the store inside the Shop table. I know it's possible using manage.py shell but I do not understand how it can be done. If anyone came across this and solved this problem, please help. -
Update Stock value after product invoice in Django
I am working on a project on Pharmacy inventory management. I two models Medicine and Medicine Sale, code is mentioned below. I want to update the stock value inventory of each medicine when I generate a sale.e:g If I sell 3 quantities of a product, that quantity should be removed from the stock value of that product. Can anyone guide me? Here is the models.py file which has both classes of Medicine and Medicine Sale class Medicine(models.Model): medicine_choices = ( ('Tablet', 'Tablet'), ('Syrup', 'Syrup'), ('Granules', 'Granules'), ('Capsules', 'Capsules'), ('Injection', 'Injection'), ('Supplements', 'Suplements'), ) year_choices = ( ('2021', '2021'), ('2022', '2022'), ('2023', '2023'), ('2024', '2024'), ('2025', '2025'), ('2026', '2026'), ) medicine_name = models.CharField(max_length=255) medicine_type = models.CharField(choices=medicine_choices, max_length=100) stock_value = models.IntegerField() price = models.IntegerField() expiry_date = models.CharField(choices=year_choices, max_length=100) def __str__(self): return self.medicine_name class MedicineSale(models.Model): medicine1 = models.ForeignKey(Medicine, related_name = 'first_medicine', on_delete=CASCADE) qty_no_1 = models.FloatField() price_no_1 = models.FloatField() total_amt1 = models.FloatField(editable=False, default=0) medicine2 = models.ForeignKey(Medicine, related_name = 'second_medicine', on_delete=CASCADE, blank=True) qty_no_2 = models.FloatField() price_no_2 = models.FloatField() total_amt2 = models.FloatField(editable=False, default=0) medicine3 = models.ForeignKey(Medicine, related_name = 'third_medicine', on_delete=CASCADE, blank=True) qty_no_3 = models.FloatField() price_no_3 = models.FloatField() total_amt3 = models.FloatField(editable=False, default=0) medicine4 = models.ForeignKey(Medicine, related_name = 'fourth_medicine', on_delete=CASCADE, blank=True) qty_no_4 = models.FloatField() price_no_4 = models.FloatField() total_amt4 … -
Unable to see pie chart in template using django and chart js
I want to count the number of companies in companytype model and show that in pie chart. The count should by the name field in company table. eg: If Company Type is medical and there are 4 companies in that category then i want to show its count on pie chart. models.py class CompanyType(models.Model): company_type = models.CharField(max_length=100) is_active = models.BooleanField(default=True) created_at = models.DateField(auto_now_add=True) updated_at = models.DateField(auto_now=True) class Company(models.Model): name = models.CharField(max_length=100) address = models.TextField() company_type = models.ForeignKey(CompanyType,on_delete=models.CASCADE) is_active = models.BooleanField(default=True) views.py def index(request): labels = [] data = [] queryset = Company.objects.values('company_type__company_type').annotate(company_type_sum=Count('name')).order_by('-company_type_sum') for entry in queryset: labels.append(entry['company_type__company_type']) data.append(entry['company_type_sum']) context = { 'labels':labels, 'data':data, } return render(request,'index.html',context) I have taken Chartjs code from index.html file if there is something wrong. index.html <script> var ctx = document.getElementById('myChart').getContext('2d'); var myChart = new Chart(ctx, { type: 'pie', data: { labels: [data.labels], datasets: [{ label: 'Companies in Particular Section', data: [data.data], backgroundColor: [ 'rgba(255, 99, 132, 0.2)', 'rgba(54, 162, 235, 0.2)', 'rgba(255, 206, 86, 0.2)', 'rgba(75, 192, 192, 0.2)', 'rgba(153, 102, 255, 0.2)', 'rgba(255, 159, 64, 0.2)' ], borderColor: [ 'rgba(255, 99, 132, 1)', 'rgba(54, 162, 235, 1)', 'rgba(255, 206, 86, 1)', 'rgba(75, 192, 192, 1)', 'rgba(153, 102, 255, 1)', 'rgba(255, 159, 64, 1)' ], … -
Filter for slug, title not working in Django rest Framework
I am trying to make a dynamic search but cant seem to filter queryset by slug. I have tried just about everything and went through stackoverflow questions and nothing seems to solve it. I have tried changing the keyword to "id" and "category" and I get a result but not on slug. Here is the error/no queryset I received. This is the filter I made for authors which seems to work. Here is the code, Please inform if I need to provide more code to understand the problem as this is my first question here. Thanks! blog_api/views.py from rest_framework import generics from blog.models import Post from .serializers import PostSerializer from rest_framework.permissions import SAFE_METHODS, IsAuthenticated, IsAuthenticatedOrReadOnly, BasePermission, IsAdminUser, DjangoModelPermissions from rest_framework import viewsets from rest_framework import filters from django.shortcuts import get_object_or_404 from rest_framework.response import Response class PostUserWritePermission(BasePermission): message = 'Editing posts is restricted to the author only.' def has_object_permission(self, request, view, obj): if request.method in SAFE_METHODS: return True return obj.author == request.user class PostList(generics.ListAPIView): permission_classes = [IsAuthenticated] # queryset = Post.objects.all() serializer_class = PostSerializer def get_queryset(self): user = self.request.user return Post.objects.filter(author=user) class PostDetail(generics.RetrieveAPIView, PostUserWritePermission): # permission_classes = [PostUserWritePermission] queryset = Post.objects.all() serializer_class = PostSerializer def get_queryset(self): item = self.kwargs["pk"] print(item) return … -
values duplicating for no reason in Django
I am getting this error on my model save, i don't understand why is it duplicating when I am only inserting value once if request.method == 'POST': gender = request.POST.get('gender') email = request.POST['email'] first_name = request.POST['first_name'] last_name = request.POST['last_name'] date_of_birth = request.POST.get('date_of_birth') contact_no = request.POST['contact_no'] password = request.POST.get('password') user_type = request.POST.get('user_type') user = User( gender=gender, email=email, first_name=first_name, last_name=last_name, date_of_birth=date_of_birth, contact_no=contact_no, user_type=user_type ) user.set_password(password) user.save() city = request.POST.getlist('city') state = request.POST.getlist('state') zip_code = request.POST.getlist('zip_code') address_street = request.POST.getlist('address_street') address_obj_list = [] for index,value in enumerate(address_street): address_obj_list.append(Address( user = user, street = value, city= city[index], state = state[index], zip_code =zip_code[index] ) ) my error IntegrityError at /reg/ duplicate key value violates unique constraint "manageusers_user_username_key" DETAIL: Key (username)=(zahidmala32) already exists. i have this method on my Model user which seems to give me error def save(self, *args, **kwargs): if self.email != None: self.username = self.email.split('@')[0] super().save(*args, **kwargs) -
How can I override Django Model's save() method
I have a model which looks like this. import uuid from django.db import models class TemplateId(models.Model): id = models.SmallAutoField(primary_key=True, serialize=False, verbose_name='ID') template_name = models.CharField(max_length=255, default="") template_id = models.UUIDField(max_length=255, default=uuid.UUID, unique=True) def __str__(self): return str(self.template_name) class Meta: ordering = ('-id',) I have another function/code where I'm calling an API to fetch the template_name and template_id and store it in dB. But every time when I get a response from the API, I want to override the the whole table (everytime deleting old record and then adding the new records) currently I'm doing this: def fetch_template_id(): api_response = # calling the API for template_id in api_response: temp_name = template_id["name"] obj = TemplateId(template_id=template_id["id"], template_name=template_id["name"]) obj.save() In order to override, I tried overriding the save method in my TemplateId model as below but it didn't work def save(self, *args, **kwargs): super(TemplateId, self).save(*args, **kwargs) Since the data gets saved in the model fields by getting the API response, next time when same data is received from the API response, it throws an duplicate data error in the dB. How do I override all the every with each API call? -
Get notification on React-Native when app is closed (with websockets if possible)
I have an app whose back-end is build using django rest(DRF) and for real time changes I use channels and on front end I use websockets, but I want to create a notification for the user when a new message is created(I have completed the back-end part of it), but now I want to get the user notified on front end, but without using 3rd part libraries like firebase (just an example, nothing against it) or other ones. -
Filter Queries which sum of their amount field are greater or lesser than a number
let's say this is my model : class Item(models.Model): user = models.ForeignKey(User, on_delete=models.DO_NOTHING) price = models.DecimalField(max_digits=23, decimal_places=8, null=True, blank=True) amount = models.DecimalField(max_digits=23, decimal_places=8) i'm trying to get all the records which sum of their amount will be lesser than any integer i give. for example from 20 records that exists , it returns first 5 records which sum of their amount is 1000 . it is like having these values : 100,400,300,100,100 . the sum is 1000 so it returns them as queryset. it is possible to implement it with loops but i'm trying to handle it with django orm . can anyone help me with this ? -
SQL Concatenation // Incorrect syntax near Inner// Python & MSSQL
I am currently concatenating an MSSQL statement in my python web app , as per the below code : baseSelectMonth = 'SELECT '+ opetion2 + option1 + ' Debit , Credit FROM PostGL AS genLedger ' baseTRBMonth = 'Inner JOIN Accounts '\ 'on Accounts.AccountLink = genLedger.AccountLink '\ 'Inner JOIN _etblGLAccountTypes as AccountTypes '\ 'on Accounts.iAccountType = AccountTypes.idGLAccountType '\ 'WHERE genLedger.AccountLink not in (161,162,163,164,165,166,167,168,122) '\ 'AND genLedger.TxDate > ? ' xtrbMonth = baseSelectMonth + baseTRBMonth + option3 all the options (option1, 2 and 3) are determined by if statements in the python code that just add an additional sting value to the statement if needed. When I execute this statement I get the above mentioned error, does anyone know why this could be happening as I cant seem to find any errors here. I have read other articles and most of the time it is incorrect spacing or repeating of words that cause this error. Please see the below full error message for your consideration: ProgrammingError at /accConnect/printReports/8 ('42000', "[42000] [Microsoft][ODBC SQL Server Driver][SQL Server]Incorrect syntax near the keyword 'Inner'. (156) (SQLExecDirectW); [42000] [Microsoft][ODBC SQL Server Driver][SQL Server]Statement(s) could not be prepared. (8180)") Request Method: GET Request URL: http://localhost:8000/accConnect/printReports/8 Django Version: … -
Annotation grouping in a queryset
order_list = Order.objects.filter( is_deleted=0, order_status__in=[4], order_type=0) order_list_data = order_list.annotate( customer_gross_sum=F('invoice__original_amount') - F('invoice__discount_amount')+F('invoice__tax_amount'), dcount=Count('user_id'),customer_transactions=F('invoice__transaction_invoice__transaction_amount')) print(order_list_data.values()) from the table above, the customer_transactions in the queryset is called in the column payment in the table. The second and third in the table is of the same bill with two transactions. Is it possible to bring that under one data. -
How can I get date,year and month from this created_date: "2021-09-27T06:10:07.972531Z" in react js?
I'am getting response from backend with date in this fromat created_date: "2021-09-27T06:10:07.972531Z", but I want to show such as 31 December,2020 in the UI. So is there any way to get only year,month and the day? -
Django - Does Django know the number of instances of each model?
everybody. I was wondering... Since Django does not execute the query to the database until the Queryset is evaluated : QuerySets are lazy – the act of creating a QuerySet doesn’t involve any database activity. You can stack filters together all day long, and Django won’t actually run the query until the QuerySet is evaluated. Then how MODEL.objects.get(pk=1), for example, raises DoesNotExist exception when there is no MODEL instance with pk=1, even if I stored it in a variable without printing it for example ? -
conversion of python dictionary to json types in django rest framework
This is a question of comprehension rather than code issue. I am using DRF for a year. When I learnt about serializers, it says there are two steps. For get request what serializer class do is: Converting complex datatypes like queryset into python datatype like the dictionary. Converting dictionary into json format which is sent to the api as response. I use print commands to see everything what is happening or using the shell. I can see the first step happening ie I can see the complex queryset and after serialization can see the dictionary of the queryset. But nowhere in the code I can see the second step happening. Although the json format isnt very different from the python dictionary. The only difference I see is the double quotes instead of single quote in json. But still, the conversion needs to happen. Is it happening automatically or am I missing something here?? My snippet: My prints of the queryset and serialized data: Here, the email printed is the complex data. After serialization it is converted to python dictionary. However, the JSON data coming into postman is like this. -
How to distribute self-created ads onto the django project?
In this project, I am trying to create an advertisement distribution website where users can upload their advertisements and after uploading, the back-end architecture will distribute the ads onto the website(the user does not need to do anything, automatically the ads will be distributed). I have created ad spaces in the HTML templates as you can see below. And I have stored sample ads to the table( refer Model Ad ). My question is how could I distribute those ads, saved in the table with target_url, into the ads spaces onto the whole project. I am working in Python with Django . Any suggestions would be appreciated. Thank You Below I have attached the code. HTML: <!-- Advanced CSS for displaying Ads --> <div style="background: #FFA92F; color: white; font-size: 14px; height: 75px; width: 300px;"> <marquee behavior="alternate" direction="left" scrollamount="2"><span style="float: left; font-family: Oswald, Arial; padding: 0 0 0 2px;">Order your dream blog or website design</span> </marquee> <marquee behavior="alternate" direction="right" scrollamount="2"><span style="float: right; padding: 0 2px 0 0;"> <a href="https://www.techprevue.com">CLICK HERE</a></span></marquee> <span style="background: #FFF; color: #ffa92f; float: left;">Order Now: +91-876567XXXX</span> <div style="float: right; font-size: xx-small;"> Ads by <span style="background: #FFF; color: #ffa92f;">techPrevue</span></div> </div> <br><br><br> <!-- Normalized CSS for displaying Ads --> <div … -
how to upload recorded audio by flutter_sound package to server using Dio in flutter?
I am building a chat application in Django and it has a mobile app (using Flutter) as well which consumes the RESTFUL API of the web app. The web app is completed but stuck with sending recorded audio by flutter_sound package to the server using Dio. -
django autocomplete returning empty for linked data
In my django admin app, I have a Site table with references to Countries, and to specific Regions(provinces/states). Currently, when trying to add a Site entry, the dropdown menus for countries and regions display all possible objects. I would like for the region dropdown to display only objects possible according to the previously selected Country option. For example, selecting Canada in the Country dropdown should result in only Canadian provinces being shown in the Region dropdown. To do this, I've tried the django-autocomplete-light library, according to the basic tutorials. Unfortunately, the Regions dropdown now shows the following error. Here are my model.py, form.py, and admin.py files. class Country(models.Model): country = models.CharField(max_length=200) class Region(models.Model): region = models.CharField(max_length=200) country = models.ForeignKey(Country, models.CASCADE, null=True, blank=True) class Site(models.Model): country = models.ForeignKey(Country, models.CASCADE, null=True, blank=True) region = models.ForeignKey(Region, models.CASCADE, null=True, blank=True) class TestForm(forms.ModelForm): class Meta: model = Site fields = '__all__' widgets = { 'region': autocomplete.ModelSelect2(url='sites/site', forward=('country',)) } @admin.register(Site) class SiteAdmin(autocomplete.Select2QuerySetView): form = TestForm -
How to process multiple objects at once in views.py
I'm making a function that adds the current user name by selecting the checkbox in the last column of each row and clicking the "Add Teacher" button. The code below works when only one checkbox is checked. How do I select multiple checkboxes? urls.py path('student/add_teacher/<int:id>/', views.add_teacher, name='add_teacher') views.py def add_teacher(request, id): student = Student.objects.get(pk=id) student.teacher = request.user.name student.save() return HttpResponseRedirect(f'/student_list/') student_list.html <table id="student-list" class="maintable"> <thead> <tr> <th>Name</th> <th>Age</th> <th>Sex</th> <th>Select</th> </tr> </thead> <tbody> {% for student in students %} <tr class="student"> <td>{{ student.name }}</td> <td>{{ student.age }}</td> <td>{{ student.sex }}</td> <td><input type="checkbox"></td> </tr> {% endfor %} </tbody> </table> <button type="button" class="btn btn-secondary addteacher">Update Teacher</button> student_list.js $('button.addteacher').click(function (e) { var elem = $(".maintable input:checked").parents("tr"); var studentID = elem.attr('student-id'); var updateTeacher = confirm("will you update?"); if (updateTeacher) { window.location.href = '/student/add_teacher/' + studentID + '/'; } }); The way I thought of is to create a list of selected ids with ajax and pass it to views.py . However, views.py cannot handle multiple objects because it uses object.get() . Through long-time search, we have confirmed that multiple objects can be processed at once by using a transaction. Can I use transactions? Haven't been able to fix it for several days. Please help. … -
Get the default value from a list django
I have a website with a list of status, how do I only retrieve the steps 1 when my form is submitted and store into the database? models.py class Photo(models.Model): STEP1 = "step 1" STEP2 = "step 2" STEP3 = "step 3" STEP4 = "step 4" STATUS = ( (STEP1, 'Received'), (STEP2, 'Cleaning'), (STEP3, 'Leak '), (STEP4, 'Loss Pressure Test'), ) Datetime = models.DateTimeField(auto_now_add=True) serialno = models.TextField() # serialno stand for serial number partno = models.TextField() # partno stand for part number reception = models.TextField() Customername = models.TextField() def __str__(self): return self.reception forms.py class AddForm(forms.Form): reception = forms.CharField(label='', widget=forms.TextInput( attrs={"class": 'form-control', 'placeholder': 'Enter reception number'})) partno = forms.CharField(label='', widget=forms.TextInput( attrs={"class": 'form-control', 'placeholder': 'Enter part number'})) serialno = forms.CharField(label='', widget=forms.TextInput( attrs={"class": 'form-control', 'placeholder': 'Enter Serial Number'})) Customername = forms.CharField(label='', widget=forms.TextInput( attrs={"class": 'form-control', 'placeholder': 'Enter customer name'})) class meta: model = Photo fields = ('reception', 'partno', 'serialno', 'Customername') views.py def addPhoto(request): msg = None if request.method == 'POST': form = AddForm(request.POST) if form.is_valid(): Datetime = datetime.now() reception = form.cleaned_data['reception'] partno = form.cleaned_data['partno'] serialno = form.cleaned_data['serialno'] Customername = form.cleaned_data['Customername'] # create a new MCO object with the form data form = Photo(Datetime=Datetime, reception=reception, partno=partno, serialno=serialno, Customername=Customername) form.save() context = {'form': form} return redirect('/gallery', … -
zombie django qcluster shows up as soon as I start redis broker
I am using redis request broker with django. When I run "$ python manage.py qinfo" I see a Cluster is running but Idle. I did not start this cluster. When I start a cluster I run "$ python manage.py qcluster" and I see 2 clusters with qinfo. I can kill the cluster I started with Ctrl+C but the zombie cluster remains. Power cycling dosn't help since the zombie cluster comes back to life as soon as I start redis. Any idea on how to kill the zombie cluster or remove it from redis memory so it does't come back to life? -
Is it possible to use subprocess to execute uploaded python file in django?
I want to allow my company users to upload a python script and execute it. I am using subprocess to execute script but I am getting errors saying "expected str, bytes or os.PathLike object, not InMemoryUploadedFile" def execute(request) if request.method == 'POST': if request.FILES.get('document'): file = request.FILES['document'] subprocess.run(['python', file], stdout=True) -
How to make forms to not be widespreaded in django?
I have been editing my forms, and like the idea of widget_tweaks, so tried few and like this one. But I got that my forms are widespread, apart from this I like it how it turned up. Can I make them not to be widespread? {% extends "base.html" %} {% load widget_tweaks %} {% block content %} <br/> <form method="post" novalidate> {% csrf_token %} {% for hidden_field in form.hidden_fields %} {{ hidden_field }} {% endfor %} {% if form.non_field_errors %} <div class="alert alert-danger" role="alert"> {% for error in form.non_field_errors %} {{ error }} {% endfor %} </div> {% endif %} {% for field in form.visible_fields %} <div class="form-group"> {{ field.label_tag }} {% if form.is_bound %} {% if field.errors %} {% render_field field class="form-control is-invalid" %} {% for error in field.errors %} <div class="invalid-feedback"> {{ error }} </div> {% endfor %} {% else %} {% render_field field class="form-control is-valid" %} {% endif %} {% else %} {% render_field field class="form-control" %} {% endif %} {% if field.help_text %} <small class="form-text text-muted">{{ field.help_text }}</small> {% endif %} </div> {% endfor %} <button type="submit" class="btn btn-primary">Download your template!</button> </form> <br/> {% endblock content %} -
Django IntegrityError at /accounts/signup/: NOT NULL constraint failed: accounts_subject.gender
Basically I am trying to create a user registration form with a few more fields than the default User model apparently brings. So I created another model with a 1 to 1 relationship with the Model User and this works (in django admin I can create Subjects (that's what I call this class "extended") related to some user). When I use my registration form, the idea is that a User is created (with its usual attributes: username, email, password) and also a Subject related to that User that has the rest of the attributes that I want to save (gender, level of studies, year of birth, etc) But, when using it only the User is saved in the database (the Subject is not saved) and I get the following error: IntegrityError at /accounts/signup/ NOT NULL constraint failed: accounts_subject.gender Here is my code: models.py: from django.db import models import uuid from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver class Subject(models.Model): GENDER_CHOICES = ( ('M', 'Masculino'), ('F', 'Femenina'), ) EDUCATIONLEVEL_CHOICES = ( ('P', 'Primaria'), ('S', 'Secundaria'), ('T', 'Terciaria'), ('U', 'Universitaria'), ) id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=True) user = models.OneToOneField(User, on_delete=models.CASCADE) gender = models.CharField(max_length=20, choices=GENDER_CHOICES, default=None) education_level = models.CharField(max_length=20, … -
How to get the IP address from Channels (Django)?
I use Channels 3.0.4 and I use AsyncWebsocketConsumer from channels.generic.websocket import AsyncWebsocketConsumer class consumer (AsyncWebsocketConsumer): async def connect(self): ... async def disconnect(self, code): ... async def receive(self, text_data): ... How can I get the IP address in the connect function or disconnect function or receive function?