Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Can I trigger Celery task on table update in Django?
For example, I have a model: class SomeModel(model.Model): is_active = BooleanField(default=False) ... Is it possible to trigger Celery task when is_active changes to True? The most important thing here is that I need to trigger it regardless of the way is_active changed, whether it changed via shell, admin panel, api call etc. The DB I use is psql. -
Is there any way to make a manual join using Django ORM?
lets say I have the following models: class ModelA(models.Model): pass class ModelB(ModelA): pass class ModelC(models.Model): model_a = models.ForeignKey(ModelA) class ModelD(models.Model): model_c = models.ForeingKey(ModelC) And I need to filter all the instances of ModelD that have a relation in ModelB. Is there any way to remove the unnecesary joins in the query that the queryset will produce ? ModelD.objects.filter(model_c__model_a__model_b__id__isnull=False) If there's any way to make a filter like this: ModelD.objects.filter(model_c__model_b__id__isnull=False) I know how to make the query on SQL, but for terms of readabilty and code maintenance I would like to know if there's any way to make the manual join or to remove that intermediate join. Thanks in advance for the replies ! -
Django: list view not recognized
I have to do this project of classified ads for Coursera. Essentially every user can post, update and delete advertisements. The problem is that even if the objects are correctly stored (I checked tables and objects via admin and manually with the command line), the ad list doesn't show up and it tells "There are no ads in the database." even though there are ads. I'm looking everywhere but I cannot find the error. Here's the code: ad_list.html: views.py: from ads.models import Ad from ads.owner import OwnerListView, OwnerDetailView, OwnerCreateView, OwnerUpdateView, OwnerDeleteView class AdListView(OwnerListView): model = Ad class AdDetailView(OwnerDetailView): model = Ad class AdCreateView(OwnerCreateView): model = Ad fields = ['title', 'text', 'price'] class AdUpdateView(OwnerUpdateView): model = Ad fields = ['title', 'text', 'price'] class AdDeleteView(OwnerDeleteView): model = Ad owner.py: from django.views.generic import CreateView, UpdateView, DeleteView, ListView, DetailView from django.contrib.auth.mixins import LoginRequiredMixin class OwnerListView(ListView): """ Sub-class the ListView to pass the request to the form. """ class OwnerDetailView(DetailView): """ Sub-class the DetailView to pass the request to the form. """ class OwnerCreateView(LoginRequiredMixin, CreateView): """ Sub-class of the CreateView to automatically pass the Request to the Form and add the owner to the saved object. """ # Saves the form instance, sets the current … -
Django reCAPTCHA with multiple forms
I have a DJANGO application where I protect forms with reCAPTCHA v2 invisible. I have no issue protecting 1 form, everything works well and I have been using this feature for quite some time. However, if I have 2 forms on the same page, EACH protected with their own captcha, it doesn't work. Here's what happens: OK: both forms have their individual onSubmit_xxxand onSubmit_yyy function (with a different widget uuid) OK: both forms get their "submit" event properly redirected to the verifyCaptcha_xxx or verifyCaptch_yyy function NOK: after grecaptcha.execute(), ALWAYS the onSubmit_xxx function (of the first form) is executed (with the wrong widget uuid) I am using Django 2.1 with Python 3.5 Any hints? Thanks a lot!! -
How to Call a Javascript function onclick event inside jinja template?
{% for person in teacher %} <tr class="bg-gray-100 border-b"> <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900"></td> <td class="p-0 py-4 whitespace-nowrap text-sm font-medium text-gray-900"> <img src="{{person.customuser.profile_pic.url}}" class="rounded-lg w-32" alt="Avatar" /> </td> <td class="text-sm text-gray-900 font-light px-6 py-4 whitespace-nowrap"> <p>{{person.customuser.first_name}} {{person.customuser.last_name}}</p> </td> <td class="text-sm text-gray-900 font-light px-4 py-4 whitespace-nowrap"> {% for item in person.subjects.all %} <p>{{item.name}}</p> {% endfor %} </td> <td class="text-sm text-gray-900 font-light px-4 py-4 whitespace-nowrap"> <div class="flex items-center justify-center"> <div id="btnView" class="inline-flex shadow-md hover:shadow-lg focus:shadow-lg" role="group"> <button type="button" class="rounded-l inline-block px-6 py-2.5 bg-[#4951bf] text-white font-medium text-xs leading-tight uppercase hover:bg-blue-700 focus:bg-blue-700 focus:outline-none focus:ring-0 active:bg-blue-800 transition duration-150 ease-in-out">Edit</button> <button onclick='viewDetails()' type="button" class=" inline-block px-6 py-2.5 bg-[#4951bf] text-white font-medium text-xs leading-tight uppercase hover:bg-green-700 focus:bg-green-700 focus:outline-none focus:ring-0 active:bg-green-800 transition duration-150 ease-in-out">View</button> <button type="button" class=" rounded-r inline-block px-6 py-2.5 bg-[#4951bf] text-white font-medium text-xs leading-tight uppercase hover:bg-red-700 focus:bg-red-700 focus:outline-none focus:ring-0 active:bg-blue-800 transition duration-150 ease-in-out">Delete</button> </div> </div> </td> </tr> {% endfor %} I want to call a javascript function viewDetails({{person.id}}) inside onclick event when the user presses the button.I want the value {{person.id}} to be passed as an argument which is coming from the for loop in jinja tag. Is it possible? -
Django usage of ForeignKey
I have this micro ticket "system" \\models.py class Ticket(models.Model): user = models.ForeignKey( settings.AUTH_USER_MODEL, default=None, null=True, on_delete=models.CASCADE, ) title = models.CharField(max_length=200) description = models.TextField() creator_adress = models.GenericIPAddressField(null=True) start_date = models.DateTimeField(default=timezone.now) ticket_waiting = models.BooleanField(default=True) ticket_solved = models.BooleanField(default=False) reopened_counter = models.IntegerField(default=0) ... Until now, only one message (when the user opens the ticket) can be sent by the user, which will be forwarded to the admin. But the admin and the user can't write any other messages back and forth under the ticket yet. If you use a new model for this, which is connected to every single ticket like so? class TicketMessages(models.Model): ticket = models.ForeignKey(Ticket, on_delete=models.CASCADE) admin_message = models.TextField() user_message = models.TextField() What is the best way to implement this? Thank you very much :> -
Uvicorn async workers are still working synchronously
Question in short I have migrated my project from Django 2.2 to Django 3.2, and now I want to start using the possibility for asynchronous views. I have created an async view, setup asgi configuration, and run gunicorn with a Uvicorn worker. When swarming this server with 10 users concurrently, they are served synchronously. What do I need to configure in order to serve 10 concurrent users an async view? Question in detail This is what I did so far in my local environment: I am working with Django 3.2.10 and Python 3.9. I have installed gunicorn and uvicorn through pip I have created an asgi.py file with the following contents import os from django.core.asgi import get_asgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'MyService.settings.local') application = get_asgi_application() I have created a view with the following implementation, and connected it in urlpatterns: import asyncio import json from django.http import HttpResponse async def async_sleep(request): await asyncio.sleep(1) return HttpResponse(json.dumps({'mode': 'async', 'time': 1).encode()) I run locally a gunicorn server with a Uvicorn worker: gunicorn BudgetService.asgi:application -k uvicorn.workers.UvicornWorker [2022-01-26 14:37:14 +0100] [8732] [INFO] Starting gunicorn 20.1.0 [2022-01-26 14:37:14 +0100] [8732] [INFO] Listening at: http://127.0.0.1:8000 (8732) [2022-01-26 14:37:14 +0100] [8732] [INFO] Using worker: uvicorn.workers.UvicornWorker [2022-01-26 14:37:14 +0100] [8733] [INFO] Booting worker … -
Passing variables to extended template
I'm having templates that later my all other templates extend. Most basic template is base.html. It includes the navigation bar: {% include 'includes/navigation.html' %} Navigation bar should display different titles depending on the role set: {% if role == "admin" %} <p class="title">Welcome to the Administrator Dashboard!</p> {% elif role == "user" %} <p class="title">Welcome to your Dashboard!</p> {% endif %} From base.html a few other layouts extend, for example 2_column.html {% extends "layouts/base.html" %} {% block content %} <div class="block block_main col-md-9"> {% block block_main %}{% endblock block_main %} </div> <div class="block block_side col-md-3"> {% block block_side %}{% endblock block_side %} </div> {% endblock content %} And only from these templates I build all my other html files. For example login.html: {% extends "layouts/2_column.html"%} {% block block_main %} <h3 class="block_title">Login</h3> <form method="post"> <!-- Form --> <div class="input-group"> <label for="file_id">Username</label> <input type="text" id="username"> </div> </form> {% endblock block_main %} I cannot figure out how to pass the role correctly all the way up to the navigation.html. Is that even possible? I've tried to wrap up the whole template in: {% with role="admin" %} {% endwith %} but if {% extends ... %} is inside it tells me that the with … -
submitting a value to Django view through admin SB2 sidebar
I am using the SB admin2 bootstrap dashboard template, and there is a side bar with collapse menus that I am planning on using. I aim to have the user choose one of these 7 options, where each option would have a different value or name and to pass this value/name to a django view called modify once the user clicks on one of the 7 options. HTML: <!-- Nav Item - Pages Collapse Menu --> <li class="nav-item"> <a class="nav-link collapsed" href="#" data-toggle="collapse" data-target="#collapseTwo" aria-expanded="true" aria-controls="collapseTwo"> <i class="fas fa-fw fa-cog"></i> <span>Options</span> </a> <div id="collapseTwo" class="collapse" aria-labelledby="headingTwo" data-parent="#accordionSidebar"> <div class="bg-white py-2 collapse-inner rounded"> <h6 class="collapse-header">Filter Options:</h6> <a class="collapse-item" href="buttons.html">Option1</a> <a class="collapse-item" href="buttons.html">Option2</a> <a class="collapse-item" href="buttons.html">Option3</a> <a class="collapse-item" href="buttons.html">Option4</a> <a class="collapse-item" href="buttons.html">Option5</a> <a class="collapse-item" href="buttons.html">Option6</a> <a class="collapse-item" href="buttons.html">Option7</a> </div> </div> </li> URLS: path('dashboard', modify, name='dashboard'), How can I achieve this without changing the layout of the side bar showed in the image? ( I tried using django forms, but I ended up with a dropdown list with a layout different than this one) -
Django forms not working (the button is doing nothing)
I am new to Django and after I created two forms (TopicForm and EntryForm) only the second one is not working. When I click the button Add Entry, nothing happens. I can't see where the issue actually is, pretty strange because I did almost the same thing for the first form and eveything is good.Tell if I need to share any other files. forms.py: from django import forms from .models import Topic, Entry class TopicForm(forms.ModelForm): class Meta: model = Topic fields = ['text'] labels = {'text': ''} class EntryForm(forms.ModelForm): class Meta: model = Entry fields = ['text'] labels = {'text': 'Entry:'} widgets = {'text': forms.Textarea(attrs={'cols': 80})} urls.py: """Defines URL patterns for learning_logs.""" from django.urls import path from . import views app_name = 'learning_logs' urlpatterns = [ # Home page path('',views.index, name='index'), # Page that shows all topics. path('topics/', views.topics, name='topics'), # Detail page for a single topic. path('topics/<int:topic_id>/', views.topic, name='topic'), # Page for adding a new topic path('new_topic/', views.new_topic, name='new_topic'), # Page for adding a new entry path('new_entry/<int:topic_id>/', views.new_entry, name='new_entry'), ] views.py: from django.shortcuts import render, redirect from .models import Topic from .forms import TopicForm, EntryForm def index(request): """The home page for Learning Log.""" return render(request, 'learning_logs/index.html') def topics(request): """Show … -
Django filtering if multiple foreign key return , display only first foreign key data
I want to get all the quizArchive where qbank, qset match by ID. But only those model that user's first created. I have this model: class QuizArchive(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="quizarchive") questionset = models.ForeignKey( "qbank.QuestionSet", on_delete=models.CASCADE, related_name="qarchive" ) qbank = models.ForeignKey( "qbank.QuestionBank", on_delete=models.CASCADE, null=True, blank=True, related_name="qbank", ) wrong = models.ManyToManyField(Question, related_name="qarchivew", blank=True) skipped = models.ManyToManyField(Question, related_name="qarchivesk", blank=True) right = models.ManyToManyField(Question, related_name="qarchiver", blank=True) selected_answer = models.JSONField(blank=True, null=True) created_time = models.DateTimeField(auto_now_add=True) updated_time = models.DateTimeField(auto_now=True) def __str__(self): return f"{self.user} takes {self.questionset}" Serializer Code: class LeaderboardSerializer(serializers.ModelSerializer): class Meta: model = QuizArchive fields = ["user", "wrong", "right", "skipped", "updated_time","questionset"] def to_representation(self,instance): leaderboard = super().to_representation(instance) return leaderboard API Code: class QSetLeaderBoard(views.APIView): permission_classes = [AllowAny,] def get(self,request,*args, **kwargs): qset = QuestionSet.objects.filter(id=int(kwargs.get("qset"))).first() qbank = QuestionBank.objects.filter(id=int(kwargs.get("qbank"))).first() qarchive = QuizArchive.objects.filter(qbank=qbank,questionset=qset) serializer = LeaderboardSerializer(qarchive,many=True) data = serializer.data return Response(data) Result : [ { "user": 1, "wrong": [], "right": [], "skipped": [ 1 ], "updated_time": "2022-01-26T12:44:12.055967Z", "questionset": 1 }, { "user": 2, "wrong": [ 1 ], "right": [], "skipped": [], "updated_time": "2022-01-26T13:00:27.761721Z", "questionset": 1 }, { "user": 1, "wrong": [ 1 ], "right": [], "skipped": [], "updated_time": "2022-01-26T12:58:52.798367Z", "questionset": 1 }, { "user": 2, "wrong": [], "right": [ 1 ], "skipped": [], "updated_time": "2022-01-26T13:00:47.148016Z", "questionset": 1 } ] But I only … -
Django endpoint executes but never returns Response
The endpoint used to work just fine, but lately as I tested it, it does all the logic it has to do, but when it comes to return the HttpResponse() it never does. I got some logs on my code (the print in this example) and I get to the line before returning the Response but it just doesn't return it, it's like it gets stuck after doing the print(). def endpoint(): # some logic here... print('I got here') return HttpResponse('...', status=200) Also this happens when the "logic" inside it gets a massive amount of data as input, eventhough it executes just fine, it never returns. With smaller data as input it works perfectly and returns. Honestly I've no idea why this is happening since there aren't any errors showing up. -
Error Message: why i am getting "None" although i have add get() at views.py in Django ??? Can anyone help me
This is my Views.py file and in this file I am trying to get the value from HTML from django.shortcuts import render from .models import kitchenData from django.http import HttpResponse def kitchen(request): if request.method == 'POST': table_num = request.POST.get('table_num') full_name = request.POST.get('full_name') qty = request.POST.get('qty') drink_name = request.POST.get('drinks_name') drink_qty = request.POST.get('drinks_qty') message = request.POST.get('message') price = request.POST.get('price') status = request.POST.get('status') print(table_num,full_name,qty,drink_name,drink_qty,message,price,status) return render(request, 'kitchen/kitchen_order.html') else: return render(request, 'kitchen/kitchen_order.html') HTML Photo [![i have attached the output][1]][1] [1]: https://i.stack.imgur.com/y4pYy.png -
Improve db performance in DetailView
I want to improve speed and performance of my blog and avoid the duplicate queries. I'm using the Django debug toolbar for that btw. Note: I'm indexing my models. Here are the models I have: class Post(Model): name ... ... author = ForeignKey(Author..) comments = ManyToManyField(Comment...) ... class Comment(Model): content... ... author = ForeignKey(Author...) replies = ManyToManyField(Reply...) class Reply(Model): content... ... author = ForeignKey(Author...) ... Is there any way to improve the speed of the post detail page, it's above 2 seconds before caching. and 1 second after caching. Here is my try: class PostDetailView(HitCountDetailView): ... def get_queryset(self): return super(PostDetailView, self).get_queryset().select_related().prefetch_related() .... Also I'm using the django-hitcount to track visitors, but it's quite slowy, any fix for that too. -
Automatic Ordinal Number in django queryset ? How to sort this thing in Django?
I have problem to sort such thing as 'Ordinal Number'. For example, I have my Parent Model (Order) and child (Item). I don't know how make Items ID field starting from 1 to N where N is number of items in this particullar Order. It's hard to explain for me , so I put some img with things I want to make and try to explain it by example. My problem on screen And those are my models.py: class Order(models.Model): PENDING = 0 DURING = 1 DONE = 2 STATUS = ( (PENDING, 'Oczekuję'), (DURING, 'W trakcie'), (DONE, 'Zakończone'), ) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='order_user') date_created = models.DateTimeField(auto_now_add=True, null=True) slug = RandomSlugField(length=7, exclude_lower=True, exclude_upper=True, exclude_vowels=True) status = models.SmallIntegerField(choices=STATUS, default=PENDING) class Meta: verbose_name = "zamówienie" verbose_name_plural = "zamówienia" def __str__(self): return "Zamówienie ID#{} z dnia {}".format(self.slug, self.date_created.strftime('%d/%m/%y')) def get_absolute_url(self): return reverse('detail', kwargs={'slug': self.slug}) class Item(models.Model): order = models.ForeignKey(Order, null=True, on_delete=models.SET_NULL) lenght = models.DecimalField(max_digits=4, decimal_places=0) width = models.DecimalField(max_digits=4, decimal_places=0) lenght = models.PositiveSmallIntegerField(blank=False) quantity = models.SmallIntegerField(default=1, blank=False, null=False) description = models.CharField(max_length=255, blank=True, null=True) lenght1 = models.BooleanField(default=False) lenght2 = models.BooleanField(default=False) width1 = models.BooleanField(default=False) width2 = models.BooleanField(default=False) class Meta: verbose_name = "formatka" verbose_name_plural = "formatki" def __str__(self): return "{} x {}".format(self.width, self.lenght) -
Three questions about django-autocomplete-light
I use django-autocomplete-light in my Django project. I build create new article for list articles. And with this third application, I want to use for autocomplete and create new one form for name of the Journal, Journal years and volume and issue. For example, in my models, the main model is Article with the field: journal, journal year, volume and issue. This field has a foreign key in its model. Also, in template I use depends on dropdown. name of the journal -> year journal -> volume and issue How does it work? If the user would like to add his article to the site. He select name of the journal, journal year and volume and issue. If it does not have information in foreign key, he can create new information about it. I could build it but I have some problem. Depends on dropdown work good, but If I use create new one, I want to assign it to a foreign key. For example, the User created journal, year, volume and issue, and then when other user want to add in the same journal, year, volume and issue they can do it. Now new Foreign key to create in … -
Uncaught SyntaxError: Unexpected token ':' on django channels
messages.js let loc = window.location let wsStart = 'ws://' if (loc.protocol == 'https') { wsStart = 'wsss://' } let endpoint = wsStart + loc.host + loc.pathname varsocket = new WebSocket(endpoint) socket.onopen = async function(e: Event) { //-----------------> Eroor comes here e: Event) { console.log('open', e) } socket.onmessage = async function(e: MessageEvent) { console.log('message', e) } socket.onerror = async function(e: Event) { console.log('error', e) } socket.onclose = async function(e: CloseEvent) { console.log('close', e) } error: Uncaught SyntaxError: Unexpected token : on django channels please help me what is the error how to solve this -
Unable to retrieve API data using axios
I'm trying to build a simple login using an API but keep facing errors import React from "react"; import { useState } from "react"; import axios from "axios"; import { useNavigate } from "react-router-dom"; export default function Login() { const navigate = useNavigate(); const [formData, setFormData] = useState({ uid: "", password: "", blocked: 0 }); const handleSubmit = (e) => { e.preventDefault(); console.log(formData); const data = JSON.stringify(formData); console.log(data); axios .post("https://myphysio.digitaldarwin.in/api/login/", data) .then(function (response) { console.log(response); console.log("Successfully Logged in "); navigate("/success"); }) .catch(function (error) { console.log(error); }); }; return ( <form onSubmit={handleSubmit}> <h3>Login</h3> <div className="form-group"> <label>uid Name</label> <input name="uid" className="form-control" placeholder="Enter your uid Name" value={formData.uid} onChange={(e) => setFormData({ ...formData, uid: e.target.value })} /> </div> <div className="form-group"> <label>Password</label> <input type="password" name="password" className="form-control" placeholder="Enter password" value={formData.password} onChange={(e) => setFormData({ ...formData, password: e.target.value }) } /> </div> <button type="submit" className="btn btn-primary btn-block"> Submit </button> </form> ); } The error I keep facing is console log of error POST https://myphysio.digitaldarwin.in/api/login/ 500 (Internal Server Error) Error: Network Error at createError (createError.js:16:1) at XMLHttpRequest.handleError (xhr.js:117:1) POST https://myphysio.digitaldarwin.in/api/login/ net::ERR_CONTENT_LENGTH_MISMATCH 500 (Internal Server Error) -
In PyCharm I can run the configuration of the project but can't debug the project
I'm getting trouble with debugging a Django 4.0 application with Pycharm 2021.2 (Professiontal Edition). I have configured the Run/Debug Configurations with the right Python Interpreter. It's the basic configurations. Running with Shift + F10 runs the project, but debugging (Shift + F9) gives the error message: Connected to pydev debugger (build 212.4746.96) <dir>/env/bin/python /opt/pycharm-2021.2/plugins/python/helpers/pydev/pydevd.py --multiproc --qt-support=auto --client 127.0.0.1 --port 46579 --file /home/caco/Workspace/CodeChallenges/desafio-dev-system/desafio-dev/manage.py runserver 8000 <dir>/env/bin/python: can't find '__main__' module in '' Process finished with exit code 1 In other project the debugging mode is runnig accordingly. I already destroyed .idea dir and closed and opened Pycharm again, but the problem persists. -
Update Nested User Serializer With Image avatar
I want to add an avatar image to my profile serializer which is nested in the User Serializer as a one-to-one field. Im having issues getting the file to upload on the front end and I want to make sure I have everything correct in my backend Django DRF. I am using Djoser for the urls with DRF API. Please take a look and let me know if there is anything I might be missing. I have no errors with the "put" request on the frontend but the file is not being uploaded to my avatar file path and obviously not saving in the nested user object neither. I can update the avatar from the DRF with no issues as well. Model.py class Profile(models.Model): user = models.OneToOneField(User, primary_key=True, on_delete=models.CASCADE) name = models.CharField(max_length=100, blank=True, null=True) occupation = models.CharField(max_length=100, blank=True, null=True) residence = models.CharField(max_length=100, blank=True, null=True) email = models.CharField(max_length=100, blank=True, null=True) active_id = models.BooleanField(default=True) avatar = models.ImageField(null=True, blank=True, upload_to ='uploads/profile_pics',default='uploads/default.jpg') def __str__(self): return self.user.username # def get_image(self): # return self.avatar.path def save(self, *args, **kwargs): super(Profile, self).save(*args, **kwargs) img = Image.open(self.avatar.path) if img.height > 300 or img.width > 300: output_size = (300, 300) img.thumbnail(output_size) img.save(self.avatar.path) Serializers.py class ProfileSerializer(serializers.ModelSerializer): user = serializers.StringRelatedField(read_only=True) class Meta: … -
How to update Celery tasks in production?
I have a Django application and some scheduled tasks handled by Celery. I use RabbitMQ as a message broker. Locally, everything works as supposed, but in production, celery worker runs old tasks that don't even exist anymore. I've tried adding worker restart to my celery worker Kubernetes-deployment -file, but that didn't make any difference. Here's what I tried: spec: containers: - name: celery-worker command: ["/bin/sh"] args: - -c - >- celery -A project_name -b 10.0.240.179 worker -l info && celery restart -A project_name -b 10.0.240.179 worker -l info This runs the worker pod without errors but it still uses the old, already deleted tasks. Is there a way how I could get updated tasks from Django's settings.py? -
How to solve error message: no such column: auctions_auction.image_url
I'm creating an aunction website where users will submit a form with the link to an image when creating a new listing. This link/url will then be converted and displayed as an image on the website. I keep getting this error when I upload the details of the form including the link to the image - ""OperationalError at /create/ no such column: auctions_auction.image_url."" How can I clear this error? VIEWS.PY from django.shortcuts import render, redirect from .forms import AuctionForm def create_listing(request): form = AuctionForm() if request.method == 'POST': form = AuctionForm(request.POST, request.FILES) if form.is_valid: form.save() return redirect('index') else: form = AuctionForm() context = {'form': form} return render(request, 'auctions/create-listing.html', context) FORMS.PY from .models import Auction from django import forms from django.forms import fields class AuctionForm(forms.ModelForm): class Meta: model = Auction fields = ['title', 'description', 'current_bid', 'image_url'] MODELS.PY from django.db import models from django.core.files import File from urllib.request import urlopen from tempfile import NamedTemporaryFile class Auction(models.Model): title = models.CharField(max_length=25) description = models.TextField() current_bid = models.IntegerField(null=False, blank=False) users_bid = models.IntegerField(null=False, blank=False) image_upload = models.ImageField(upload_to='images/') image_url = models.URLField(verbose_name="URL", max_length=255, unique=True) created_at = models.DateTimeField(auto_now_add=True) def save(self, *args, **kwargs): if self.image_url and not self.image_upload: img_temp = NamedTemporaryFile(delete=True) img_temp.write(urlopen(self.image_url).read()) img_temp.flush() self.image_upload.save(f"image_{self.pk}", File(img_temp)) super(self).save(*args, **kwargs) def __str__(self): return … -
ImportError: Failed to import test module: Django Tests
I have written some tests for model, views and serializer. All tests are running fine except for the serializer tests. Creating test database for alias 'default'... System check identified no issues (0 silenced). ........E ====================================================================== ERROR: testapp.tests.test_serializers (unittest.loader._FailedTest) ---------------------------------------------------------------------- ImportError: Failed to import test module: testapp.tests.test_serializers Traceback (most recent call last): File "C:\Python310\lib\unittest\loader.py", line 436, in _find_test_path module = self._get_module_from_name(name) File "C:\Python310\lib\unittest\loader.py", line 377, in _get_module_from_name __import__(name) File "F:\Python\django-advanced\testproj\testapp\tests\test_serializers.py", line 19, in <module> AutoSlugField(), from_field(SlugField()) File "C:\Python310\lib\site-packages\django_extensions\db\fields\__init__.py", line 155, in __init__ raise ValueError("missing 'populate_from' argument") ValueError: missing 'populate_from' argument ---------------------------------------------------------------------- Ran 9 tests in 0.034s FAILED (errors=1) Destroying test database for alias 'default'... I am getting the above error when I run python manage.py test Here is my file tree - My project name - testproj My app name - testapp testproj/ ┣ .hypothesis/ ┃ ┣ examples/ ┃ ┃ ┣ 89906a9970b0f6fa/ ┃ ┃ ┃ ┗ 7210af19145ec2a8 ┃ ┃ ┗ f79909d6c0990774/ ┃ ┃ ┗ 7210af19145ec2a8 ┃ ┗ unicode_data/ ┃ ┗ 13.0.0/ ┃ ┃ ┗ charmap.json.gz ┣ testapp/ ┃ ┣ migrations/ ┃ ┃ ┣ __pycache__/ ┃ ┃ ┃ ┣ 0001_initial.cpython-310.pyc ┃ ┃ ┃ ┣ 0002_alter_tag_name.cpython-310.pyc ┃ ┃ ┃ ┣ __init__.cpython-310.pyc ┃ ┃ ┃ ┗ __init__.cpython-38.pyc ┃ ┃ ┣ 0001_initial.py ┃ ┃ ┣ … -
How can I filter users as a choice in a foreign key django forms?
I'm stuck with a problem to filter project managers from a foreign key field in django forms. I want to exclude superusers and other user roles except project manager. Models.py class Projects(models.Model): id=models.AutoField(primary_key=True) project_name=models.CharField(max_length=255) project_manager=models.ForeignKey(CustomUser,on_delete=models.CASCADE, limit_choices_to={'is_project_manager__eq : 1 '}) client_name=models.ForeignKey(Clients,on_delete=models.CASCADE, null=True) project_pic=models.ImageField(upload_to='static/website/project-images') project_start_date=models.DateField(null=True) project_end_date=models.DateField(null=True) project_description=models.TextField(null=True) created_at=models.DateTimeField(auto_now_add=True) updated_at=models.DateTimeField(auto_now=True) is_draft = models.BooleanField(default=True) objects=models.Manager() class Meta: verbose_name_plural = 'Project' def __str__(self): return f'{self.project_name}' Forms.py class ProjectForm(forms.ModelForm): class Meta: model = Projects fields = ['project_name', 'project_manager', 'client_name', 'project_pic', 'project_start_date', 'project_end_date', 'project_description'] Views.py def project_list(request): projects = Projects.objects.all() if request.method == 'POST': form = ProjectForm(request.POST, request.FILES) if form.is_valid(): form.save() project_name = form.cleaned_data.get('project_name') messages.success(request, f'{project_name} has been successfully added.') return redirect('project_list') else: form = ProjectForm() context = { 'projects' : projects, 'form' : form, } template_name ='project-admin/project-list.html' return render(request, template_name, context) CustomUser/Models.py Here is their own roles to set them as a project manager, inventory admin, and client class CustomUser(AbstractUser): is_inventory_admin = models.BooleanField('Is Inventory Admin', default=False) is_project_manager = models.BooleanField('Is Project Manager', default=False) is_client = models.BooleanField('Is Client', default=False) class Meta: db_table = 'auth_user' -
Django: Display the same form multiple times in the same view
I need to open the same form multiple times while looping trough some items. This is the form: class CancelRefundForm(forms.forms.Form): cancel = forms.BooleanField(label='Check to cancel the refund', required=True ,widget=forms.CheckboxInput(attrs={ 'class': 'hidden-checkbox', 'name': 'hiddenCheckBoxName' } )) item = forms.IntegerField( required=True, widget=forms.NumberInput(attrs={ 'class': 'cancel-item-input', 'value': '', 'type': 'hidden' }), ) This is the HTML: <div class="order-items-display"> {% for item in order.orderitem_set.all %} <div class="single-order-item"> <span > <a href="{{ item.item.get_absolute_url }}"> <img src="../../../media/{{ item.item.main_image }}" alt="{{ item.item.title }} image"> </a> </span> <span class="order-item-details"> <h3><a href="{{ item.item.get_absolute_url }}"> {{ item.item.title }} {% if item.replica %} <small>(Replica)</small> {% endif %} </a></h3> <p><strong>Price: </strong>{{ item.old_price }}€</p> {% if item.quantity > 1 %} <p><strong>Quantity: </strong>{{ item.quantity }}</p> <p><strong>Total: </strong>{{ item.get_old_total_price }}€</p> {% endif %} {% if order.refund_deadline > nowDate %} <p><b>The deadline for requesting a refund ends in {{ order.refund_deadline }}(30 days)</b></p> {% else %} <p><b>The deadline for requesting a refund ended in {{ order.refund_deadline }}.</b></p> {% endif %} <button class="myBtnPri update-cart" data-product="{{item.id}}" data-action="add"> <a class="mySecLink" href="#"> Buy Again </a> </button> {% if item.refund_requested %} <p><b>Refund requested: </b> {{ item.refund_requested }}</p> <p><b>Refund granted: </b> {{ item.refund_granted }}</p> <form action="{% url 'order-details' order.slug %}" method="POST" class="cancel-form"> {% csrf_token %} {{ cancelForm.item }} <label for="{{ cancelForm.cancel.id_for_label }}" class="myCheckbox"> {{ …