Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
wagtail how to JSON serialize RichText field in ListBlock
Error: Object of type RichText is not JSON serializable. My code: class AvvisiBlock(blocks.StructBlock): avvisi = blocks.ListBlock( blocks.StructBlock( [ ("title", blocks.CharBlock(classname="full title", icon="title", required=True)), ("text", blocks.RichTextBlock(icon="pilcrow", required=True)), ] ) ) def get_api_representation(self, value, context=None): dict_list = [] for item in value["avvisi"]: print(item) temp_dict = { 'title': item.get("title"), 'text': item.get("text"), } dict_list.append(temp_dict) return dict_list item in value: StructValue([('title', 'avvisi importanti 1'), ('text', <wagtail.core.rich_text.RichText object at 0x000001F73FCDE988>)]) how can serialize the object? -
Importing users in Django
I try to import some users from a csv file. I'm using the import-export module into the original User model. If I upload the file that I made it imports one user but with blank fields except date_joined, is_staff, is_active, is_superuser. The other fields like username, password, first and last name are empty. Focus on the last user, others added before with a registration form. What am I doing wrong? views.py from tablib import Dataset from .resources import UserResource def simple_upload(request): if request.method == 'POST': person_resource = UserResource() dataset = Dataset() new_users = request.FILES['myfile'] imported_data = dataset.load(new_users.read().decode(), format='csv', headers=False) result = person_resource.import_data(dataset, dry_run=True) # Test the data import if not result.has_errors(): person_resource.import_data(dataset, dry_run=False) # Actually import now return render(request, 'stressz/simple_upload.html') resources.py from import_export import resources from django.contrib.auth.models import User class UserResource(resources.ModelResource): class Meta: model = User html <form method="post" enctype="multipart/form-data"> {% csrf_token %} <input type="file" name="myfile"> <button type="submit">Upload</button> </form> new_persons.csv - comma separated but it look better here on this way -
How can I pass string from HTML file to view in django?
I'm new in django and i have this input in HTML,and i nedd to get the string typed from the user and send for my views.py: <form id="username_exists_form" method='GET'> Name: <input type="username" name="username" /> <button type='submit'> Check </button> </form> That's my view.py, i nedd the string replace "username": template_name = 'Exames.html' def get_context_data(self,**kwargs): context = super(ShowExames, self).get_context_data(**kwargs) exames = Examlabs.objects.filter(id_atendimento = username) context.update({'exames': exames}) return context def get_queryset(self): return Examlabs.objects.all()``` -
failed (13: Permission denied) nginx server with Django
I am getting permission denied error on nginx server, for CACHE folder created by django compressor, the error is "/home/xxxx/myproject/static/CACHE/js/output.dabd456b15d4.js" failed (13: Permission denied), client: 112.196.162.182, server: example.com, request: "GET /static/CACHE/js/output.dabd456b15d4.js HTTP/1.1", host: "abc.example.com", referrer: "https://abc.example.com/member/dashboard/" the permissions are shown as follows drwxrwxr-x 26 xxxx xxxx 4096 Oct 8 05:44 . drwxrwxr-x 14 xxxx xxxx 4096 Oct 26 13:49 .. drwxr-xr-x 4 xxxx www-data 4096 Oct 26 13:54 CACHE drwxrwxr-x 7 xxxx xxxx 4096 May 11 04:02 admin drwxrwxr-x 7 xxxx xxxx 4096 Feb 4 2021 assets drwxrwxr-x 2 xxxx xxxx 4096 Sep 24 2020 autocomplete_light drwxrwxr-x 5 xxxx xxxx 4096 Sep 9 2020 ckeditor drwxrwxr-x 5 xxxx xxxx 4096 Oct 23 2020 client_admin drwxrwxr-x 5 xxxx xxxx 4096 Sep 24 2020 client_admin_new drwxrwxr-x 3 xxxx xxxx 4096 May 28 04:41 client_members drwxrwxr-x 3 xxxx xxxx 4096 Sep 3 2020 clients drwxrwxr-x 3 xxxx xxxx 4096 Nov 23 2020 css drwxrwxr-x 2 xxxx xxxx 4096 Sep 23 2020 data_table xxxx is the user, how can it be solved, seeking advice, thank you -
How to save form instance in looping python django
i've tried to save the form instance by looping. i've created assignment-control and workplace models. the user in assignment-control is foreign key, i decided to create a views that save all user by making them as a list views.py def create_job(request): emp = EmployeeManagement.objects.filter(is_employee=True, is_supervisor=False) form = CreateEmployeeJob() if request.method == 'POST': form = CreateEmployeeJob(request.POST or None, request.FILES or None) emp_list = request.POST.getlist('emp') print(emp_list) // ['1', '2'] if form.is_valid(): if emp_list: for employee in emp_list: form.instance.worker_id = int(employee) form.save() context = { 'employee': emp, 'form': form, } return render(request, 'd/form.html', context) the views that i create is only save the last index of the list meanwhile in form.html <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} {% if employee %} {% for emp in employee %} <input type="checkbox" id="emp" name="emp" value="{{emp.id}}"> {{ emp }} <br> {% endfor %} {% endif %} <br> <button>Save</button> </form> there is any mistakes in my models.py class WorkPlace(models.Model): buildings = models.CharField(max_length=255, verbose_name='Nama Gedung : ') tower_name = models.CharField(max_length=255, verbose_name='Nama Tower : ') ground_name = models.CharField(max_length=255, verbose_name='Nama Lantai : ') job_area = models.CharField(max_length=255, verbose_name='Zona Kerja : ') qr_code = models.TextField(verbose_name='unique code QR', default=generate_code()) qr_img = models.FileField(verbose_name='QR Code Image', upload_to='qr/', blank=True, null=True) class AssignmentControl(models.Model): assignment = … -
I want to create app for previous data update
I has a member list. There have been a edit button beside member name, When Member click the edit button, A form will open a bootstrap form (previous data must non editable from inspect eliminate) with 2 input field for email and phone number. After member put his email and phone, member list will be update and show updated info. Please give a nice resource or code to done it in one day. N.B. I'm new in Django and python. -
command line login to using django user name and password
I have a command-line application and I would like to connect it to a Django Web application. Any ideas about how the user can log in using their Django user name and password from the terminal application? -
how to print this model data in template djnago?
i have a model named item as follows: class Item(models.Model): title = models.CharField(max_length=100) price = models.FloatField() bargainprice = models.FloatField(default=0) discount_price = models.FloatField(blank=True, null=True) category = models.CharField(choices=CATEGORY_CHOICES, max_length=2) label = models.CharField(choices=LABEL_CHOICES, max_length=1) slug = models.SlugField() description = models.TextField() image = models.ImageField() i have a model named as Bargain as follows: class Bargain(models.Model): user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE ) item = models.ForeignKey( Item, on_delete=models.CASCADE ) bprice = models.FloatField() class Meta: constraints = [ models.UniqueConstraint( fields=['item', 'user'], name='unique_user_item') ] and i am passing this model data in the template "product.html" as follows; class ItemDetailView(DetailView): model = Item template_name = "product.html" def get_bargain(self, request): if request.user.is_authenticated(): print("this is the user ", self.user.pk) return Bargain.objects.filter(item=self.object, user=request.user).first() and i want to access the "bprice" in the template "product.html" so i am doing this on template : This is the Bprice :{{ view.get_bargain.bprice }} but **it shows nothing ** and i also have one object in bargain model named "Bargain object(3) with all neccesory values example : user: admin item:mattalicdot bprice:1799 and i am logined with user admin . can anyone tell me that what is the issue? -
Execute javascript code present inside child template after the main template is rendered
I've a base template which serves as a common structure for child templates. Inside this base template, I've the jQuery library included right before the closing body tag. base template <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> . . </head> <body> {% block content %} {% endblock %} <script src="path/to/jQuery/library"></script> </body> </html> Now my child template has the following code child template {% extends 'base_template.html' %} {% block content %} <h1>How you doing?</h1> <script type="text/javascript"> // this code is specific to this template, may not be used in another template // but can't use jQuery here since the library hasn't loaded yet </script> {% endblock %} So how would I go about running javascript code inside child template only after the base template has finished loading the jQuery library? -
Is it possible to remove CommonPasswordValidator when you register an account in Django?
When a password is too common, Django raises the "The password is too common" error. I wanna remove this validation. Is it possible? And how to do it? -
Footballer(model name) matching query does not exist
views.py from django.shortcuts import render from .models import Footballer from django.http import JsonResponse import json def madrid_list(request): player = Footballer.objects.all().order_by('name') return render(request, "players/madrid_list.html", {"players":player}) def madrid_detail(request,slug): players = Footballer.objects.get(slug=slug) return render(request, "players/madrid_detail.html", {"players": players}) def json(request): data = list(Footballer.objects.values()) return JsonResponse(data, safe=False) why it's not showing me the JSON path when I put it in my server? -
How to pass a constructed payload to a ModelViewSet create method
I have a ModelViewSet, of which I have overriden the create function like below - class BookViewSet(viewsets.ModelViewSet): queryset = Book.objects.all() serializer_class = BookSerializer def create(self, request, *args, *kwargs): req_data = json.loads(request.body) x = req_data.get('x') response = super().create(request, *args, **kwargs) book_id = response.data['id'] do_foo(book_id, n=x) return response Now in another function I am trying to call this ViewSet's create function. @api_view(['POST',]) def bar(request, *args, **kwargs): req_data = request.data rf = RequestFactory() payload = {'name': "Book1", 'author': "Helen"} mock_req = rf.post('/book', json.dumps(payload), content_type='application/json') vs = BookViewSet() return vs.create(mock_req) This is giving me an error - AttributeError: 'WSGIRequest' object has not attribute 'data' at this line - response = super().create(request, *args, **kwargs) -
How can I Display data of Model field last_bid(Foreign Key) to template
I am working on an Auction website using Django. I am trying to display data of the Last_bid field which is connected to Bid table with a foreign key. I tried many ways but nothing worked out. The models.py file is: from django.contrib.auth.models import AbstractUser from django.db import models from django.db.models.base import Model from django.db.models.deletion import CASCADE from django.db.models.fields import CharField from django.utils import timezone class User(AbstractUser): pass class Category(models.Model): category = models.CharField(max_length=64) def __str__(self): return f'{self.category}' class AuctionListing(models.Model): item_name = models.CharField(max_length=100) item_image = models.ImageField(upload_to="products", null=True, blank=True) detail = models.TextField() price = models.IntegerField() last_bid = models.ForeignKey('Bid', on_delete=models.CASCADE, blank=True, null=True, related_name='lst') user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='publisher_listing', null=True, blank=True) watchers = models.ManyToManyField(User, blank=True, related_name='watched_list') pub_date = models.DateTimeField(auto_now=True, null=True) deadline = models.DateTimeField(null=True) list_category = models.ForeignKey(Category, on_delete=models.CASCADE, null=True, related_name='sortion') closed = models.BooleanField(default=False) def __str__(self): return f'{self.item_name} - {self.price}' class Bid(models.Model): bid = models.IntegerField() user = models.ForeignKey(User, on_delete=CASCADE) auction = models.ForeignKey(AuctionListing, on_delete=CASCADE) bid_date = models.DateTimeField(auto_now=True) def __str__(self): return f'{self.bid}-{self.auction}' class Comment(models.Model): user = models.ForeignKey(User, on_delete=CASCADE) com = models.TextField() pub_date = models.DateField() com_item = models.ForeignKey(AuctionListing, on_delete=models.CASCADE, related_name='get_comment') def __str__(self): return f'{self.user} - {self.pub_date}' Views.py: from django.contrib.auth import authenticate, login, logout # from django.contrib.auth.decorators import login_required from django.db import IntegrityError, reset_queries from django.http import HttpResponse, HttpResponseRedirect from … -
add filed automatically to form in dajngo CreateView
I have Major model and Course model. when I add course to the course model using ModelForm and CreatView class, I want to add the field automatically. I tried to use form_valid method but it get me this Error: NOT NULL constraint failed: quizes_course.major_id this is the major model: class Major(models.Model): name = models.CharField(max_length=50) years = models.IntegerField(validators=[minMaxVal]) def __str__(self): return self.name def get_absolute_url(self): return reverse("majors") class Meta: verbose_name_plural = "1. Majors" and this is the course model: class Course(models.Model): major = models.ForeignKey(Major, on_delete=models.CASCADE) year = models.IntegerField(validators=[minMaxVal]) name = models.CharField(max_length=100) def __str__(self): return f'{self.major.name}_{self.year}_{self.name}' def get_absolute_url(self): return reverse("courses", kwargs={"pk": self.major.pk}) class Meta: verbose_name_plural = "2. Courses" and this is the view: class CreateCourse(CreateView): model = Course form_class = CourseCreateForm template_name = 'quizes/create.html' def form_valid(self, form): form.save(commit=False) major = get_object_or_404(Major, id=self.kwargs['pk']) form.major = major.id return super().form_valid(form) -
Set initial values in form passing parameters (kwargs) with view
I want to prefill a form with values taken in a table. First I pass the PK relative to the line where I wan't to get values and build the kwargs list: views.py def NavetteToFicheCreateView(request, pk): navette = Navette.objects.get(id=pk) ref = navette.id attribute_set = navette.famille.pk cost = navette.cost qty = navette.qty etat = navette.etat etat_ebay = navette.etat.etat_ebay ean = get_last_ean() form = NavetteToFicheForm( request.POST, ref=ref, attribute_set=attribute_set, cost=cost, qty=qty, etat=etat, etat_ebay=etat_ebay, ean=ean, ) [...] then I retrieve the kwargs in the form.py and setup my initial values class NavetteToFicheForm(forms.ModelForm): def __init__(self, *args, **kwargs): self.ref = kwargs.pop('ref', 'noref') self.attribute_set = kwargs.pop('attribute_set', 9999) self.cost = kwargs.pop('cost', 0) self.qty = kwargs.pop('qty', 0) self.etat = kwargs.pop('etat', 0) self.etat_ebay = kwargs.pop('etat_ebay', 9999) self.ean = kwargs.pop('ean', 9999) super(NavetteToFicheForm, self).__init__(*args, **kwargs) self.fields['ref'].initial = self.ref self.fields['attribute_set'].initial = self.attribute_set self.fields['cost'].initial = self.cost self.fields['qty'].initial = self.qty self.fields['etat'].initial = self.etat self.fields['etat_ebay'].initial = self.etat_ebay self.fields['ean'].initial = self.ean [...] My problem : some fields like "ref" or "attribute_set" are foreignKeys and are not transmitted when i display the form. For checking my values : print(self.ref) print(self.attribute_set) output 34 2 noref 9999 questions : Why does the "print" displays 2 couples of values ? This looks like as if the "noref" and "999" are taken … -
How to jump to a related model object via Django admin's list_display?
I do have a model Comment that relates to the model Poller via FK relationship. Is there any way I can jump to this related object via the Django admin interface from the Comment's overview? # Models.py class Comment(models.Model): """ A Class for comments made by users to a specific Poller """ poller = models.ForeignKey(Poller, on_delete=models.CASCADE, related_name='PollerComment') user = models.ForeignKey(Account, on_delete=models.CASCADE) vote = models.ForeignKey(Vote, on_delete=models.CASCADE) # Admin.py @admin.register(Comment) class PollerCommentAdmin(admin.ModelAdmin): list_display = ('user', 'created_on', 'poller', 'comment', 'flag_count', 'upvote_count', 'downvote_count', 'is_public', 'is_removed') Now I would like to make the 'poller' column clickable which will then redirect me to this poller object in the admin. -
update in serializer: django rest framework
I have a doubt, how to use update() in serializer? serializers.py def update(self, instance, validated_data): instance.name = validated_data.get('name', instance.name) instance.description = validated_data.get('description', instance.description) instance.is_free = validated_data.get('is_free', instance.is_free) instance.keyarea = validated_data.get('keyarea', instance.keyarea) instance.subject = validated_data.get('subject', instance.subject) beneficiary_data = validated_data.get('beneficiary', instance.beneficiary) instance.beneficiary.set(*[beneficiary_data]) section_data = validated_data.get('section', instance.section) instance.section.set(*[section_data]) instance.image = validated_data.get('image', instance.image) instance.instructor = validated_data.get('instructor', instance.instructor) instance.relevance = validated_data.get('relevance', instance.relevance) instance.difficulty = validated_data.get('difficulty', instance.difficulty) instance.contributor = validated_data.get('contributor', instance.contributor) instance.general_status = validated_data.get('general_status', instance.general_status) instance.review_status = validated_data.get('review_status', instance.review_status) instance.save() return instance I use a lot of lines here to update the course model, is there any other way to simplify this? -
upload multiple files into media-library in django/mezzanine
I'm newbie with mezzanine and I was told to fix the media-library upload problem met by our customers. In the production site of the django-1.8/mezzanine-4.2 application it is possible to upload just one file at time, meanwhile in the developemnt side I can upload as many as I want to. Just noticed that the working development side has a multiple attribute within the input-tag whereas production side doesn't have. Can it be the reason for this and could there be means to fix it be changing configuration ? <div class="file-input-wrapper"> <div class="file-input-result"> <div class="progress hide show-in-progress show-done"> <div class="progress-inner"></div> </div> <div class="button button-error cancel-button hide show-selected"> Remove </div> <span class="status hide show-selected show-in-progress show-done"></span> </div> <label class="button hide-in-progress hide-done"> Browse <input name="Filedata" type="file" multiple /> </label> </div> -
Django - Ordered ManyToManyField
I have 2 models in my Django app: Operation and Job. Job model has a many-to-many relationship with Operation model. I use Job model to run multiple Operations in one go. But I need those Operations to be executed in a specific order. I can use JSONField to store foreign keys in specific order to do this, but is there a better solution for this? Here are my models: class Operation(models.Model): name=models.CharField(verbose_name='Operation name',max_length=50) merger_operation=models.BooleanField(verbose_name='Merger operation',default=False) parser_action=models.ForeignKey(ParserAction,on_delete=models.CASCADE,verbose_name='Parser action') class Job(models.Model): name=models.CharField(verbose_name='Job name',max_length=50) operations=models.ManyToManyField(Operation,verbose_name='Pre-request operations') -
How to print values of model joined through foreign key in django?
I have one Model named as item as follows: class Item(models.Model): title = models.CharField(max_length=100) price = models.FloatField() bargainprice = models.FloatField(default=0) discount_price = models.FloatField(blank=True, null=True) category = models.CharField(choices=CATEGORY_CHOICES, max_length=2) label = models.CharField(choices=LABEL_CHOICES, max_length=1) slug = models.SlugField() description = models.TextField() image = models.ImageField() and have a product page called " product.html" which shows the current product information as shown in image :the product page image and i am getting all this data on product.html by the view as follows : class ItemDetailView(DetailView): model = Item template_name = "product.html" and on product.html i am getting data by syntax : <span class="mr-1"> <del>₹ {{ object.price }}</del> </span> <span>₹ {{ object.discount_price }}</span> this is the one story which is working fine no issues till there **problem starts when i create this Bargain model below ** class Bargain(models.Model): user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE ) item = models.ForeignKey( Item, on_delete=models.CASCADE ) bprice = models.FloatField() class Meta: constraints = [ models.UniqueConstraint( fields=['item', 'user'], name='unique_user_item') ] *let me explain the purpose of this bargain model. actually this model used to bargain the price of the product and it takes input price from user and updates to the bargain model with the following values User, Item and "bprice" which is … -
Psycopg2 can't adapt type 'tuple' issue occurring intermittently
Recently we upgraded Django & Python version to following Python 3.9.5, Django 3.2, Psycopg2 2.9.1, Httpd 2,4.2, Postgres 12.8 Observed that the Application was failing intermittently with psycopg2.ProgrammingError: can't adapt type 'tuple' error Below are the Query and Params logged before the cursor.execute() is executed {'employer_id': 200176, 'approximate_age_band': ('30-39', '50-59') SELECT month_key as cadence_val, sum(eligible_count) as eligible FROM xyz_table_name WHERE employer_id = %(employer_id)s AND approximate_age_band IN %(approximate_age_band)s GROUP BY 1 ORDER BY 1; Below is complete stacktrace 2021-10-27 05:00:52,280 [ERROR] django.request: Internal Server Error: mobile_report/reports Traceback (most recent call last): File "/var/www/pulse_preprod/service/venv/lib/python3.9/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) psycopg2.ProgrammingError: can't adapt type 'tuple' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/var/www/service_rest/service/api/views.py", line 375, in mobile_visits data = get_report_data(request, "VisitsReport", src_employer_id) File "/var/www/service_rest/service/api/views.py", line 453, in get_report_data data = get_data(src_employer_id, filter_params, report_key, **params) File "/var/www/service_rest/service/api/views.py", line 466, in get_data data = report_obj.get_data(employer, filter_values, **params) File "/var/www/service_rest/service/reports/pulse/mobile.py", line 49, in get_data rows1, cadence_list = self.get_rows_from_query(cursor, sql1, employer_id, table_name, File "/var/www/service_rest/service/reports/__init__.py", line 1415, in get_rows_from_query cursor.execute(sql, params) File "/var/www/pulse_preprod/service/venv/lib/python3.9/site-packages/django/db/backends/utils.py", line 66, in execute return self._execute_with_wrappers(sql, params, many=False, executor=self._execute) File "/var/www/pulse_preprod/service/venv/lib/python3.9/site-packages/django/db/backends/utils.py", line 75, in _execute_with_wrappers return executor(sql, params, many, context) File "/var/www/pulse_preprod/service/venv/lib/python3.9/site-packages/django/db/backends/utils.py", line … -
Django Admin query with postgres
I have model class TmaskMda02(models.Model): ... class Meta: managed = False db_table = 'public.tmask_mda02' And reponse http ProgrammingError at /admin/rest_app/tmaskmda02/ relation "public.tmask_mda02" does not exist LINE 1: SELECT COUNT(*) AS "__count" FROM "public.tmask_mda02" ^ Request Method: GET In PGadmin ERROR: relation "public.tmask_mda02" does not exist LINE 1: SELECT COUNT(*) AS "__count" FROM "public.tmask_mda02" ^ SQL state: 42P01 Character: 35 but if I use this select in PGadmin but without "" resonse is OK SELECT COUNT(*) AS "__count" FROM public.tmask_mda02 -
Django inlineformset - NOT NULL constraint failed: forecasting_forecast.forecast_cost
I have a CreateView with an inline formset that has a forecast_month & forecast_cost for each month of the year, I want it to save all 12 forecasts for each month but I keep getting this error. Ideally it should save 12 Forecast's one for each month Error: NOT NULL constraint failed: forecasting_forecast.forecast_cost (I have deleted & rerun migration) Models.py class Forecast(models.Model): project = models.ForeignKey(Project, on_delete=models.CASCADE) forecast_month = models.CharField(verbose_name="Month", max_length=200) forecast_cost = models.DecimalField(verbose_name="Forecast", decimal_places=0, max_digits=11) Views.py class ForecastCreateView(LoginRequiredMixin, CreateView): model = Forecast fields = ["project"] login_url = "/login/" success_url = '' def get_context_data(self, **kwargs): financialYears = ["July", "August", "September", "October", "November", "December", "January", "February", "March", "April", "May", "June"] initial = [{'forecast_month': forecast} for forecast in financialYears] ForecastChildFormset = inlineformset_factory( Project, Forecast, fields=('project', 'forecast_month', 'forecast_cost'), can_delete=False, extra=len(financialYears), widgets={'forecast_month': forms.Select(attrs={'disabled': True})}, ) data = super().get_context_data(**kwargs) if self.request.POST: data['forecast'] = ForecastChildFormset(self.request.POST, initial=initial) else: data['forecast'] = ForecastChildFormset(initial=initial) return data def form_valid(self, form): context = self.get_context_data() forecast = context["forecast"] form.instance.creator = self.request.user if forecast.is_valid(): self.object = form.save() forecast.instance = self.object forecast.save() else: return self.form_invalid(form) return super(ForecastCreateView, self).form_valid(form) -
Django + Postgresql, new instance of a model rewrites previous
I have Order model and OrderDetails model which represents product related to the order. One Order can have many OrderDetails. So I create new order and press button to add new product and this button redirects me to the 'Add product' page powered by OrderDetailsCreateView. I fill form with desired product and press 'add', success.. But not so fast. Now if I check database it has new OrderDetails row related to my order. When I add another product I assume that it must create another row, because primary key is order_id + product_id, but instead it overwrites previous row. I want it to add new rows and not touch previous. OrderDetails model class OrderDetails(models.Model): order = models.OneToOneField('Orders', models.DO_NOTHING, primary_key=True) product = models.ForeignKey('products.Products', models.DO_NOTHING, primary_key=True) unit_price = models.FloatField() quantity = models.SmallIntegerField() discount = models.FloatField() class Meta: managed = False db_table = 'order_details' unique_together = (('order', 'product'),) def get_absolute_url(self): return u'/orders/%d' % self.order.pk OrderDetails form class OrderDetailCreateOrUpdateForm(forms.ModelForm): def __init__(self, already_selected_products, *args, **kwargs): super(OrderDetailCreateOrUpdateForm, self).__init__(*args, **kwargs) self.fields['product'].queryset = self.fields['product'].queryset.exclude(id__in=already_selected_products) class Meta: model = OrderDetails fields = ['product', 'unit_price', 'quantity', 'discount'] OrderDetailsCreateView class OrderDetailsCreateView(LoginRequiredMixin, CreateView): model = OrderDetails template_name = 'orders/orderdetails_create.html' form_class = OrderDetailCreateOrUpdateForm def get_form_kwargs(self, **kwargs): form_kwargs = super(OrderDetailsCreateView, self).get_form_kwargs(**kwargs) emp = get_current_users_employee(self.request.user) … -
django async if else use a thread or sync_to_async
I don't know where the error is if data['msg']: print('in') model = await DB.Myself.filter_data(name__contains='') print('ok') else: print('else') model = await DB.Myself.filter_data(name__contains='') print(model, 'model') In if log in ok In else log else You cannot call this from an async context - use a thread or sync_to_async. Why? Can you help me?