Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Celery Error when applying a task "'NoneType' object has no attribute 'top'"
Since last week we are seeing a lot of errors on our production server, Specifically when calling Celery 4.47 (python 2.7) apply_async on tasks that were working for a long time, seems the request stack is null. python2.7/site-packages/celery/app/task.py line 1023 in _get_request args locals req = self.request_stack.top AttributeError: 'NoneType' object has no attribute 'top' Would appriciate your kind help -
Different permission for different type of user
I work on my project and i want create 3 type of user include Admin(user and second user with different premission). I want ask which method i should use to do it ? I read a bit about AbstractUser, create group and "flag's" -
foreign key change depending on previous selection Django
Hello i have quick question with something i am having trouble with. i have these two model which use foreign keys. but i want one of the foreign keys options to change depending on what you selected in the previous fk. Here is the code. class Customer(models.Model): company_name = models.CharField(max_length=255) contact_person = models.CharField(max_length=255) email = models.EmailField() phone = models.IntegerField() active = models.CharField(choices=yesno, max_length=200) submitted_date_time = models.DateTimeField(default=timezone.now) def __str__(self): return self.company_name class Connections(models.Model): company = models.ForeignKey(Customer, on_delete=models.CASCADE) customerVlan = models.ForeignKey(CustomerVlan, on_delete=models.CASCADE) switch_port_number = models.IntegerField(default=0) duplex = models.CharField(choices=duplex, max_length=200) voice_vlan_number = models.IntegerField(default=0) phone_mac_address = models.CharField(max_length=200) phone_extension = models.CharField(max_length=200) purpose = models.TextField() sticky_port = models.CharField(choices=yesno, max_length=200) additional_configuration = models.TextField() remark = models.TextField() actual_user = models.CharField(max_length=200) status = models.CharField(choices= status, max_length=200) connection_date = models.DateField(default=timezone.now) disconnection_date = models.DateField(default=timezone.now) def __str__(self): return self.actual_user class WorkOrder(models.Model): work_order_date = models.DateTimeField(default=timezone.now) request_date = models.DateField(default=timezone.now) company_id = models.ForeignKey(Customer, on_delete=models.CASCADE) connections= models.ForeignKey(Connections, on_delete=models.CASCADE, blank=True, null=True) service_desk_ticket_number = models.CharField(max_length=200) request_type = models.CharField(choices=requestType, max_length=200) request_description = models.TextField() configuration_remark = models.TextField() comment = models.TextField() engineer_assigned = models.CharField(max_length=200) vlan_number = models.ForeignKey(CustomerVlan, on_delete=models.CASCADE) submitted_date_time = models.DateTimeField(default=timezone.now) as you can see in the image when i select a company_id i want only connections with that company to show up and not everything in the database because there … -
ModuleNotFoundError: No module named 'jet'
im trying to run a project at https://github.com/VladKha/MovieNet but i keep getting the error even after pip install jet multiple times Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\rajan\AppData\Local\Programs\Python\Python310\lib\threading.py", line 1009, in _bootstrap_inner self.run() File "C:\Users\rajan\AppData\Local\Programs\Python\Python310\lib\threading.py", line 946, in run self._target(*self._args, **self._kwargs) File "C:\Users\rajan\venv\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\rajan\venv\lib\site-packages\django\core\management\commands\runserver.py", line 125, in inner_run autoreload.raise_last_exception() File "C:\Users\rajan\venv\lib\site-packages\django\utils\autoreload.py", line 87, in raise_last_exception raise _exception[1] File "C:\Users\rajan\venv\lib\site-packages\django\core\management_init_.py", line 398, in execute autoreload.check_errors(django.setup)() File "C:\Users\rajan\venv\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\rajan\venv\lib\site-packages\django_init_.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\rajan\venv\lib\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "C:\Users\rajan\venv\lib\site-packages\django\apps\config.py", line 228, in create import_module(entry) File "C:\Users\rajan\AppData\Local\Programs\Python\Python310\lib\importlib_init_.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "", line 1050, in _gcd_import File "", line 1027, in _find_and_load File "", line 992, in _find_and_load_unlocked File "", line 241, in _call_with_frames_removed File "", line 1050, in _gcd_import File "", line 1027, in _find_and_load File "", line 1004, in _find_and_load_unlocked ModuleNotFoundError: No module named 'jet' -
How to store multiple objects as a list in Django model fields?
I am trying to create a simple e-auction platform. I have models for customers where i want to store a list of all the items they have bid on and the exact amount they have bid on. class Company(models.Model): name = models.CharField(max_length=256) contact_person_name = models.CharField(max_length=256) contact_no = PhoneNumberField() class Customer(models.Model): name = models.CharField(max_length=256) company_name = models.ForeignKey(Company, on_delete=models.CASCADE) And then i have a model for my catalogue where i wish to store a list of bidders on a particular catalog and their current bid. class Catalogue(models.Model): name = models.CharField(max_length=512) owner = models.ForeignKey(Customer, on_delete=models.CASCADE) start_date = models.DateTimeField() end_date = models.DateTimeField() start_price = models.PositiveIntegerField() bidders = models.ManytoManyField(Customer) But how do i store the exact amount a customer has bid on a catalogue item? -
Django - Javascript : How can i dinamically display those files on this iframe
I'm getting started on learning the Django Framework for my project. I'm currently trying to get this new functionnality to work. I know what i need to do but i don't know how to do it. Display image (the iframe src is empty so that's why the firefox error message I'm creating ,for each element of an array, a button. Each of those elements have a txt file that i want to display on this iframe (below the buttons). This image shows, in this case, three buttons ( 3 elements in the array). What i want to do is ,when i click on one of those buttons, it will change the src of the iframe to match the current index of the array. It will then show the content of the txt file on the iframe. JS: function createHeader() { let iframe = document.getElementById("iframe-overplot") let buttons = document.querySelectorAll("div > div > div > button"); console.log(buttons); for (let i = 0; i < spectra_list.length; i++) { // the array let button = document.createElement("button"); button.innerText = " "; button.style.backgroundColor = colors[i]; button.classList.add("h-10", "py-1", "text-xl", "text-gray-100", "font-medium", "transition-colors", "hover:text-gray-900", "focus:outline-none", "display:inline-block", "flex-row", "w-1/2"); div_header.appendChild(button); button.addEventListener("click", function (){ // change the iframe src to … -
Django migrations.RenameField creating new field instead of renaming existing one
I edited a fresh migration file to instead of adding a new field, just rename a field that already exists on the Django Model This was the only change on this field migrations.RenameField( model_name='my_field', old_name='field_old_name', new_name='field_new_name', ), But after running manage.py migrate, I notice that a new field was added (with a default field value) and the old one still there And when running manage.py makemigrations again, it creates a migration to remove the old field What I can't do, because I would lose the data Steps: new fields added to model (without removing old one to not break code) manage.py makemigrations code changed to use new field migration file edited to use migrations.RenameField manage.py migrate -
How to filter JSONField by key value in Django to retrieve similar values using MySQL/MariaDB database
I am trying to retrieve similar values to a specific key value from a JSONField using a MySQL database. I have used 3 different options as listed for views.py all of which do not work. According to Django documentation (https://docs.djangoproject.com/en/3.1/topics/db/queries/#containment-and-key-lookups) this can be done with an exact match to the key value, yet I would like to filter with the value only being similar and not exact. There is an example for using KeyTextTransform or KeyTransform (https://code.djangoproject.com/ticket/27205) but this is used with PostgreSQL only. Is there another way of doing this with a MySQL or MariaDB database? A post request is made to the following end-point with parameter name description as follows: http://localhost/get_meta/?description=text Data Example: { "meta": { "description": "The description text.", "field": 1 } } models.py class Model(models.Model): meta = models.JSONField(default=dict) views.py Option 1: def get_meta(self, request): queryset = Model.objects.filter(meta__contains=request.GET.get('description') or "") serializer_class = ModelSerializer(queryset, many=True) data = {'data': serializer_class.data} return Response(data) Option 2: def get_meta(self, request): queryset = Model.objects.filter(meta__description__contains=request.GET.get('description') or "") serializer_class = ModelSerializer(queryset, many=True) data = {'data': serializer_class.data} return Response(data) Option 3: def get_meta(self, request): queryset = Model.objects.filter(meta__contains={'description':request.GET.get('description') or ""}) serializer_class = ModelSerializer(queryset, many=True) data = {'data': serializer_class.data} return Response(data) -
Cannot assign "<QuerySet [<Profile: admin>, <Profile: test>]>": "Notifications.user" must be a "User" instance
when i get the user followers i got this err Cannot assign "<QuerySet [<Profile: admin>, <Profile: test>]>": "Notifications.user" must be a "User" instance. my code is #fun in models def user_add_post(sender, instance, *args, **kwargs): post = instance user = Profile.objects.filter(following=post.author.user) profile = Profile.objects.all() sender = post.author.user text_preview = post.title[:50] notify = Notifications(post=post, sender= sender, user = user, text_preview=text_preview, notifications_type=1 ) notify.save() post_save.connect(Post.user_add_post, sender=Post) how to fix this err -
Nested Admin files access forbidden on server
I have implemented NestedModelAdmin in my model in Django Admin panel. I have done this in order to add/edit/delete child objects of a model. The code is working fine on my local machine, but I am getting following error on the server, which is preventing me from perform CRUD operations in my modal in the admin panel. GET https://amazonaws.com/static/nested_admin/dist/nested_admin.min.css net::ERR_ABORTED 403 (Forbidden) GET https://amazonaws.com/static/nested_admin/dist/nested_admin.min.js net::ERR_ABORTED 403 (Forbidden) Any idea why this error might be occurring? -
Using Subquery to annotate Count of an unrelated model
This can be a duplicated of this question but I didn't understand if it is possible or not. I have two models that are unrelated (or have a nested nested relation) class Cycle(models.Model): start_date = models.DateField() end_date = models.DateField() class Event(models.Model) created_at = models.DateField() What I want is filter the current Cycle and to annotate the number of Events that were created between the Cycle's start_date and end_date, all in one query. What I have so far: now = timezone.now() number_events = Event.objects\ .filter(created_at__gte=OuterRef('start_date'), created_at__lte=OuterRef('end_date')) cycle = Cycle.objects \ .filter(start_date__lte=now, end_date__gte=now) \ .annotate(number_events=Count(number_events)) \ .first() This creates an invalid syntax, saying subquery must return only one column If I add values("id") in the number_events query, it raises more than one row returned by a subquery used as an expression If I add values("id")[:1] it works, but only counts one Event And if I try to do the query in SQL I can retrieve data SELECT *, (select COUNT(*) AS "number_events" FROM "events_event" U0 WHERE (U0."created_at" >= "cycles_cycle"."start_date" AND U0."created_at" <= "cycles_cycle"."valid_until")) FROM "cycles_cycle" WHERE ("cycles_cycle"."start_date" <= '2022-06-01' AND "cycles_cycle"."end_date" >= '2022-06-01') GROUP BY "cycles_cycle"."id" limit 1; Is there a way to create this query in django, or is it impossible … -
OSError: [WinError 123] The filename, directory name, or volume label syntax is incorrect - DJANGO
so i was trying get files what i was upload it to html. but when i run the code, the web got error message : ModuleNotFoundError: No module named 'audio' OSError: [WinError 123] The filename, directory name, or volume label syntax is incorrect: 'F:\KULIAH\SEMESTER8\SKRIPSI\MusicLockApp\' maybe i was made mistake from syntax. please help me to check it! #html {% for record in audio %} <audio controls="controls"> <source src="{{record.audio}}" type="audio/mp3"> </audio> {% endfor %} #urls urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^decode/$', views.decode), url(r'^$', views.homepage), url(r'^$', include('audio.urls')), path('audio', views.Audio_store), ] #models fs = FileSystemStorage(location='media/mp3') fss = FileSystemStorage(location='media/txt') class Audio_store(models.Model): password=models.FileField(storage=fss, null=True) audio=models.FileField(storage=fs, null=True) def __str__(self): return self.audio #views def homepage(request): form = AudioForm() audio = Audio_store.objects.all() if request.method == "POST": form = AudioForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect("homepage") context={'form':form, 'audio':audio} return render(request, "homepage.html", context=context) -
Deleting an Item from the cart on Django not working
My "Remove" button to remove an item from cart is not working. My views.py file: from urllib.request import Request from django.contrib import messages from django.contrib.auth.decorators import login_required from django.shortcuts import render, redirect, get_object_or_404 from django.urls import reverse_lazy from django.views.decorators.http import require_POST from requests import request from courses.models import Course from udemy.models import Enroll from .cart import Cart @require_POST def cart_add(request, slug): cart = Cart(request) # create a new cart object passing it the request object course = get_object_or_404(Course, slug=slug) cart.add(course=course, quantity=1, update_quantity=False) return redirect('cart:cart_detail') def cart_remove(request, slug): cart = Cart(request) course = get_object_or_404(Course, slug=slug) cart.remove(course) return redirect('cart:cart_detail') def cart_detail(request): cart = Cart(request) return render(request, 'cart/detail.html', {'cart': cart}) @login_required(login_url='/login') def cart_checkout(request): carts = Cart(request) for cart in carts: course = cart['course'] # course = get_object_or_404(Course, slug=course.slug) Enroll.objects.create(course=course, user_id=request.user.id) messages.success(request, 'Successfully checked out!') carts.clear() return redirect(reverse_lazy('cart:cart_detail')) My cart.html file: <div class="move-remove"> <div> <form action="" method="post"> {% csrf_token %} <input type="hidden" value="{{ course.slug }}"> <input type="submit" class="btn-success" value="Remove",name="Remove"> </form> </div> When I press the remove button it won't delete. I don't know why it is happening. whats wrong? Do I have to change in views or in my html file? -
Django - get objects from one table who belong to another objects in other table
I have a project to do which consists to creating a note manager in Django. So I created my tables in sql with foreign keys. And I have been facing a problem for several days. I have a page that lists all the students in the database, and I would like by clicking on a link, to be able to display all the notes belonging to each student. Here's my SQL tables (étudiants = students / Notes = grades) : sql students table / sql grade table models.py : class Etudiants(models.Model): numeroetudiant = models.BigIntegerField(db_column='numeroEtudiant', blank=True, null=True) # Field name made lowercase. nom = models.CharField(max_length=255, blank=True, null=True) prenom = models.CharField(max_length=255, blank=True, null=True) groupe = models.BigIntegerField(blank=True, null=True) photo = models.TextField(blank=True, null=True) email = models.CharField(max_length=255, blank=True, null=True) class Meta: managed = False db_table = 'etudiants' def __str__(self): return self.nom + " " + self.prenom class Notes(models.Model): examens = models.ForeignKey(Examens, models.DO_NOTHING, db_column='examens', blank=True, null=True) etudiant = models.ForeignKey(Etudiants, models.DO_NOTHING, db_column='etudiant', blank=True, null=True) note = models.BigIntegerField(blank=True, null=True) appreciation = models.TextField(blank=True, null=True) class Meta: managed = False db_table = 'notes' def __str__(self): return "Note de " + self.etudiant.nom + " " + self.etudiant.prenom + " à l'examen de " + self.examens.titre -
How can I generate and excel output from django python
Given a query set from my database, I am trying to output the results into an excel file. I have tried two versions of code... the code executes properly without outputting any error messages, but the excel file is not outputted, any suggestions on where I went wrong. import pandas as pd import csv, io, xlsxwriter from django.http import HttpResponseRedirect, HttpResponse, JsonResponse, FileResponse def print_excel(request) products = Product.objects.all() df = pd.DataFrame(list(products.values())) excel_file = io.BytesIO() xlwriter = pd.ExcelWriter(excel_file, engine='xlsxwriter') df.to_excel(xlwriter, 'sheetname') xlwriter.save() #xlwriter.close() excel_file.seek(0) response = HttpResponse(excel_file.read(), content_type='application/ms-excel vnd.openxmlformats-officedocument.spreadsheetml.sheet') # set the file name in the Content-Disposition header response['Content-Disposition'] = 'attachment; filename=myfile.xls' return response I also tried the below approached where I tried to output an excel with the string rows import pandas as pd import csv, io, xlsxwriter from django.http import HttpResponseRedirect, HttpResponse, JsonResponse, FileResponse def print_excel(request) buffer = io.BytesIO() workbook = xlsxwriter.Workbook(buffer) worksheet = workbook.add_worksheet() worksheet.write('A1', "rows") workbook.close() buffer.seek(0) return FileResponse(buffer, as_attachment=True, filename='myfile.xlsx') The two codes executes properly but I cant locate the excel file created. -
Adding a comment section with django
as title suggests I am trying to add a comment section to my website using the following code under movies app models.py class Movie(models.Model): title = models.CharField(max_length=100) description = models.TextField(max_length=1000) image = models.ImageField(upload_to='movies') banner = models.ImageField(upload_to='movies_banner') category = models.CharField(choices=CATEGORY_CHOICES, max_length=10) language = models.CharField(choices=LANGUAGE_CHOICES, max_length=10) status = models.CharField(choices=STATUS_CHOICES, max_length=2) cast = models.CharField(max_length=100) year_of_production = models.DateField() views_count = models.IntegerField(default=0) movie_trailer = models.URLField() created = models.DateTimeField(blank=True, default=timezone.now) slug = models.SlugField(blank=True, null=True) name = models.CharField(max_length=200, null=False, blank=False) class Comment(models.Model): movie = models.ForeignKey(Movie, related_name="comments", on_delete=models.CASCADE) commentor_name = models.CharField(max_length=200) comment_body = models.TextField() date_added = models.DateTimeField(auto_now=True) def __str__(self): return '%s - %s' % (self.movie.name, self.commentor_name) admin.py from django.contrib import admin from .models import Movie, MovieLinks, Comment admin.site.register(Movie) admin.site.register(MovieLinks) admin.site.register(Comment) under admin page I am able to add a comment https://i.stack.imgur.com/Tc5pp.png So up until now everything is configured correctly. the problem comes when I try to add it to the HTML using logic currently what we're looking to edit is line 70 - 82 but i've pasted the whole HTML as i have a feeling it'll be needed :) {% extends 'base.html' %} {% block body %} <script src="https://kit.fontawesome.com/a076d05399.js" crossorigin="anonymous"></script> <main class="content"> <div class="single"> <section class="trailer"> <h3>Trailer</h3> <div class="trailer_frame"> <iframe width="560" height="315" src="{{object.movie_trailer}}" frameborder="0" allowfullscreen></iframe> </div> </section> <section … -
REACT + DJANGO app, uploading excel files into the backend, Django returns empty dictionary
So I have been trying to upload a excel file from the frontend using a post request to a Django backend, however whatever I do the request[FILES] python dictionary is empty. Does anyone have an idea of why this would happen? This is my POST view from the Django views.py file @api_view(["POST"]) @csrf_exempt def processFile(request, *args, **kwargs): data = request.data print(data.items()) print(str(data.get('file0'))) if len(request.FILES) == 0 : print("empty files") print(request.FILES) return Response("ok") And now the way I am making the POST request in the frontend. const fileList = async (actualFiles) => { var dataForm = new FormData(); console.log(actualFiles) for(let i=0;i<actualFiles.length;i++) { const id = 'file' + i; console.log("appending file" + i) dataForm.append(id, actualFiles[i]) } const res = await fetch(`http://localhost:8000/process-file/`, { method: 'POST', headers: { 'Content-Type': 'multipart/form-data; boundary=----somefixedboundary' }, body : dataForm, }) const data = await res.json() console.log("Data:" + data) } Worth mentioning: I have been trying for a while thinking the problem is in the request, however in the network tab on the browser I can see that it is all alright. I am adding the content type and boundary because according to Django documentation if you do not add those the server will not be able to process … -
'<' not supported between instances of 'int' and 'str' django Overlapping check
When I am checking overlapping in Django forms with this code i could not check the overlapping, geting the error of tuples How i can solve this error, form.py record=[] if count > 1: for i in range(count): start_run = self.data.get(f'runningdefinition_set-{i}-start_run',[]) end_run = self.data.get(f'runningdefinition_set-{i}-end_run',[]) application_run =self.data.getlist(f'runningdefinition_set-{i}-application_run',[]) record.append((i, start_run, end_run, application_run)) first_value=[] for j in record: first_value.append(j[0]) last_value=[] for k in record: last_value.append(k[1]) if first_value[0] < last_value[-1]: raise ValidationError("overlap not allowed") -
How can I automatically fill in the ModelChoiceFields?
I have three models. The model is as follows. models.py class Post(models.Model): title = models.CharField(max_length=50) content = models.TextField() category = models.ForeignKey(Category, null=True, blank=True, on_delete=models.SET_NULL) subject = models.ForeignKey(Subject, null=True, blank=True, on_delete=models.SET_NULL) class Category(models.Model): name = models.CharField(max_length=30, unique=True) slug = models.SlugField(max_length=20, unique=True, allow_unicode=True) subject = models.ForeignKey(Subject, null=True, blank=False, on_delete=models.SET_NULL) class Subject(models.Model): name = models.CharField(max_length=10, unique=True) slug = models.SlugField(max_length=20, unique=True, allow_unicode=True) forms.py class PostForm(forms.ModelForm): class Meta: model = Post fields = ['title', 'category', 'subject', 'content'] widgets = { 'content': SummernoteWidget() } def __init__(self, *args, **kwargs): super(PostForm, self).__init__(*args, **kwargs) self.fields['title'].widget.attrs.update({'class': 'textInput form-control form_title', 'placeholder': '제목을 입력하세요'}) self.fields['category'].widget.attrs.update({'class': 'form-select form-control form_category'}) self.fields['subject'].widget.attrs.update({'class': 'form-select form-control form_subject'}) category = forms.ModelChoiceField(queryset=Category.objects.all(), empty_label='카테고리를 선택하세요') In forms, 'subject' fields is ModelChoiceField and I want the 'subject' field to be automatically selected according to the value selected in 'category' -
How to add +/- button to a displayed Object list in django to increase or decrease object value
I'm new to Django and I want to display the items in my database and have a button next to each row that will add or decrease the value. I know how to do this in a form for single item, but not with them listed. Table with button to add and decrease -
{"non_field_errors":["Invalid data. Expected a dictionary, but got Company."]}
file company.py(models) from django.db import models COMPANY_TYPE = [('ИП', 'ИП'), ('АО', 'АО'), ('ТОО', 'ТОО')] class Company(models.Model): name = models.CharField(blank=False, max_length=255) company_type = models.CharField(blank=False, max_length=10, choices=COMPANY_TYPE, default='ИП') logo = models.CharField(blank=False, max_length=255) owner = models.ForeignKey('user.User', on_delete=models.CASCADE, related_name='companies') average_review = models.FloatField(blank=True, default=0, editable=True) count_of_review = models.IntegerField(blank=True, default=0, editable=True) created_date = models.DateTimeField(blank=False, auto_now_add=True) last_change_date = models.DateTimeField(blank=False, auto_now=True) def __str__(self): return self.name views.py class CompanyDetailView(APIView): permission_classes = [IsAuthenticated] def get(self, request, company_id): data = get_object_or_404(Company, id=company_id) payload = CompanyDetailSerializer(data=data) payload.is_valid(raise_exception=True) return Response(payload.data) serializers.py class CompanyDetailSerializer(serializers.ModelSerializer): class Meta: model = Company fields = ('id', 'name', 'company_type', 'logo', 'owner', 'average_review', 'count_of_review', 'created_date', 'last_change_date') But it returns data {"non_field_errors":["Invalid data. Expected a dictionary, but got Company."]} I could not find any solutions, I am only started coding in rest framework) -
How to fix an error with related models, which serializers have HyperlinkedIdentityField?
I'm getting the next error when I try to perform GET request to /api/dishes-types/ page in my web app: ImproperlyConfigured at /api/dishes-types/ Could not resolve URL for hyperlinked relationship using view name "category-detail". You may have failed to include the related model in your API, or incorrectly configured the lookup_field attribute on this field. I've tried to apply to my code all the solutions from this page, but nothing worked for me. How to solve this error ? I'm really got stuck... And here is my code. models.py: *I've replaced metaclasses and magic __str__ methods that are intended to admin panel from django.db import models class Category(models.Model): name = models.CharField(max_length=30, unique=True) class DishesType(models.Model): name = models.CharField(max_length=30, unique=True) category = models.ForeignKey(Category, on_delete=models.CASCADE) class Dish(models.Model): name = models.CharField(max_length=64, unique=True) type_of_food = models.ForeignKey(DishesType, on_delete=models.CASCADE) description = models.CharField(max_length=1000) prices = models.JSONField() serializers.py: from rest_framework.exceptions import ValidationError from rest_framework.fields import SerializerMethodField from rest_framework.relations import HyperlinkedIdentityField from rest_framework.serializers import HyperlinkedModelSerializer from Pub.models import Category, DishesType, Dish class BaseSerializerMixin(HyperlinkedModelSerializer): @staticmethod def validate_name(name): if not name.replace(" ", "").isalnum(): raise ValidationError( "'name' field may contain only letters, numbers and spaces. Change it, please !" ) return name # # DISH SERIALIZERS # class DishSerializerMixin(BaseSerializerMixin): dish_url = HyperlinkedIdentityField(view_name="dish-detail", lookup_field="name") class … -
How can I access the result of an asynchronous task in asyncio python using the task name?
I have been wanting to calculate the progress of an asynchronous task. So, I have created another async function "progress" that I am awaiting from the for loop inside the original function after every n iterations. Now, I created an async django view where I want to access the result of the task(progress function) with the name I set, and return that as HttpResponse. My Django View async def get_progress(request, job_id): task = get_the_task(name=job_id) return task.result Working Function of which I want to calculate the progress async def working_function(request, job_id): for i in range(x): after_every_n_iterations: await asyncio.create_task(progress(i, x), name=job_id) This is my progress function async def progress(work_till_done, total_work): return work_till_done/total_work*100 I don't know where to go from here. Kindly help me. -
Using create_user() method in django
I'm using Django 1.11.10. I want to create a login page with just one username and password. However when I try to use create user I take an Attribute error. How can I use this method? models.py class UserProfile(models.Model): user = models.OneToOneField(User) user = User.create_user(username='username',email=None,password='testpassword') def __str__(self): return self.user.username -
Django file not showing input data on website
So I had a similar issue earlier with the code not iterating correctly to get my table output to work but now i'm trying a description list and it is not showing any of my input data. Any help would be greatly appreciated! Views.py from django.shortcuts import render from django.http import HttpResponse from .models import products, typeWork def hello(request): context = typeWork.objects.all() context2 = {'context':context} return render(request, 'products/index.html', context2) def detail(request, product_id): context3 = typeWork.objects.get(id=product_id) context4 = {'context3':context3} return render(request, 'products/detail.html', context4) Detail.html {% extends 'base.html' %} {% block content %} <dl> <dt>Work</dt> <dd>{{context4.work}}</dd> <dt>Type of Work</dt> <dd>{{context4.genre}}</dd> </dl> {% endblock %} Working code for the table(like it shows input data on the table just adding to see if it may provide any insight on why the detail.html isn't showing the input data index.html {% extends 'base.html' %} {% block content %} <table class="table table-bordered table-hover"> <thead> <tr> <th>Work</th> <th>Type of Work</th> <th>Hours needed</th> </tr> </thead> <tbody> {% for context2 in context%} <tr> <td>{{context2.work}}</td> <td>{{context2.genre}}</td> <td>{{context2.hoursWorked}}</td> </tr> {% endfor %} </tbody> </table> {% endblock %} Picture of my actual issue Working table picture