Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to add a progress bar which keeps track of student completion of courses in a Django LMS
I'm new to Django and have a running e-learning(Learning Management System) website in Django where students can view contents uploaded by Instructors but i would like to add a progress bar which keeps track of the modules completed by students in the form of checkboxes and automatic checking of boxes if the student spends more than a minimum number of minutes (if possible). Models.py file with course and modules model Views.py file from the students app Student Course Detail Template -
Save two model (One contains foreign key) data from a single template
I'm pretty new to django and working on a blog based project where user can add ratings to specific type of review post.For example giving stars are enabled for restaurant but not for tech stores. I have created two different form for "review" and "star" model. I want to rate the restaurant using the model named "star" and do it in same template.But I'm having difficulties to do that. my review model kinda looks like this (Removed other attributes which aren't related to this problem): class Review(models.Model): review_title = models.CharField(verbose_name='Title', max_length=100) review_body = models.TextField() author = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE) restaurant_or_techstore = models.CharField(verbose_name='Foods or Travel',max_length=20) slug = models.SlugField(null=False,unique=True,max_length = 300) My rating model looks like this: class Star(models.Model): post_id = models.ForeignKey(Review, on_delete = models.CASCADE ) food = models.FloatField(verbose_name='Food',null=False) service = models.FloatField(verbose_name='Food',null=False) cleanliness = models.FloatField(verbose_name='Food',null=False) and my view : def CreateReview(request): ImageFormSet = modelformset_factory(Image,form=ImageForm,extra=5) if request.method == 'POST': reviewForm = ReviewForm(request.POST) formset = ImageFormSet(request.POST,request.FILES,queryset=Image.objects.none()) starsForm = StarsrForm(request.POST) if reviewForm.is_valid() and formset.is_valid() and starsForm.is_valid(): review_form = reviewForm.save(commit=False) review_form.author = request.user review_form.post_or_discussion = 1 review_form.food_or_travel = 'Foods' review_form.save() reviewForm.save_m2m() starsForm.save() for form in formset.cleaned_data: if form: image = form['image'] photo = Image(review=review_form,image=image) photo.save() messages.success(request,'Image Uploaded Successfully') return HttpResponseRedirect("/") else: print(reviewForm.errors, formset.errors) else: reviewForm = ReviewForm() formset … -
Where the Http404 and PermissionDenied are handled exactly in django?
Where and how do the Http404 or PermissionDenied are handled exactly in django? I could not find functions or methods to catch these exceptions. -
ImportError: cannot import name 'ORDER_PATTERN' from 'django.db.models.sql.constants'
I want to add SearchFilter to the filte_backends but every time I imported rest_framework.filters I get this error -
Compare list with string in Python and highligth matches
I'm trying to compare a python list with a string and highlight matches with mark inside a new string. But it won't work. Following example: string = 'This is my string where i would find matches of my List' list = ['This is', 'would find', 'bla', 'of my List'] result_that_i_need = '<mark>This is</mark> my string where i <mark>would find</mark> matches <mark>of my List</mark>' Has anybody any idea how to solve this? Can somebody help me please? -
Django 2.2 -> 3.1 Upgrade: TypeError: the JSON object must be str, bytes or bytearray, not dict
After upgrading from Django 2.2 to 3.1 I'm getting this on every one of my views with no clear traceback: TypeError: the JSON object must be str, bytes or bytearray, not dict Has anyone else run into this? I am using the older, now deprecated django.contrib.postgres.fields.JSONField in a few models, and planned to do this until it's removal in 4.0 (since it said it wasn't being removed). Do I actually have to migrate all of my django.contrib.postgres.fields.JSONFields to a django.db.models.JSONField? Or is not the cause? It doesn't mention in the documentation that these fields don't work anymore. I don't have any other relevant code to share– it's happening on all views that load this model, and there isn't any clear traceback. Anyone else run into this? -
Django - MAX ... GROUP BY on ForeignKey to itself
I have a model similar to this: class Tree(models.Model): description = models.CharField(max_length = 255, null = False, blank = False) parent = models.ForeignKey("Tree", null = True, blank = True, on_delete = models.CASCADE) I need to find the latest record for each parent. I tried with this: latests = Tree.objects.values("parent").annotate(Max("pk")) The result is not correct because the SQL query is: select parent_id, max(id) from tree group by id The ORM translates the foreign key to the source and does not use the value inside the field. Is there a way not to "follow" the foreign key and to use instead the value of the field? -
Change value of a model based on value of other model Django
I have a models Wallet and StudentPayment. Every time I add or update StudentPayment, the Wallet balance should change based on the added or updated StudentPayment. class Wallet(models.Model): ... balance = models.DecimalField(decimal_places=2, max_digits=100, default=0.00) ... class StudentPayment(models.Model): ... wallet = models.ForeignKey( Wallet, on_delete=models.SET_NULL, null=True, related_name='students_payment') amount = models.DecimalField(decimal_places=2, max_digits=100) ... For Example: if I add payment with 1000 amount, the wallet balance should change to 1000 too, I know how to do this, but don't know how to deal with the update, ex: if I change the payment amount to 900, the wallet balance should also change. Appreciate any help) I tried to implement with overriding save() method, but nothing works -
How to use same field in again and again in forms Django Framework
I want to add a subject and mark multiple in the same form. Now as I am only filling one time only. But unable to find how to use the field again and again in the form. I want to add the option add another inform when the user clicks on add another the user will get two extra fields of subject and marks again and again. I tried a lot and search a lot, but unable to find how to do this. Anybody will please help me. )------- Thanks models.py class Courses(models.Model): name = models.CharField(max_length=254) price = models.IntegerField(default=False) def __str__(self): return self.name class CourseSubject(models.Model): course = models.ForeignKey('Courses', on_delete=models.CASCADE) name = models.CharField(max_length=254) def __str__(self): return self.name class Exam_result(models.Model): student = models.ForeignKey('student.Student',on_delete=models.CASCADE, default=False) course = models.ForeignKey('student.Courses', on_delete=models.CASCADE, default=False) subject = models.ForeignKey('student.Subject', on_delete=models.CASCADE, default=False) marks = models.IntegerField() def __str__(self): return str(self.student) forms.py class ExamResult(forms.ModelForm): class Meta: model = Exam_result fields = "__all__" widgets = { 'student' : forms.Select(attrs={'class': 'form-control'}), 'course' : forms.Select(attrs={'class': 'form-control'}), 'subject' : forms.Select(attrs={'class': 'form-control'}), 'marks' : forms.TextInput(attrs={'class': 'form-control', 'placeholder': ' Enter Student marks'}) } views.py def exam_result(request): forms = ExamResult() if request.method == 'POST': forms = ExamResult(data=request.POST.getlist) if forms.is_valid(): forms.save() return redirect('/panel/exam/result/list/') return render(request, 'exam/exam_result.html', {'forms' :forms}) -
TypeError at /accounts/register/
Error Page's Picture enter image description here If doesn't work https://hizliresim.com/AaNt5f -
My Django Python code is not changing the database record
I'm creating an auction site and I want to be able to change the data in a table to change the price to the new bid. I'm kind of new to Django and Python so I must be missing something. Right now I'm not getting any errors - it's just not changing the data in the DB. Does anyone see the issue? Here is my HTML and Python code (the relevant parts): views.py: def bid(request, username): price = request.POST.get("price") itemID = request.POST.get("itemID") newBid = request.POST.get("newBid") title = request.POST.get("title") query = Bid.objects.filter(itemID = itemID).first() print(query) if(newBid > price and username != query.highestBidder): query2 = NewPost.objects.filter(title = title).first().update(price = newBid) new = Bid.objects.create(itemID = itemID, newBid = newBid, highestBidder = username) new.save() return render(request, "auctions/post.html") models.py: class Bid(models.Model): itemID = models.CharField(max_length=64) newBid = models.IntegerField() highestBidder = models.CharField(max_length=64) post.html: {% extends "auctions/layout.html" %} {% block body %} <h2>{{ p.title }} - Category: {{ p.category }}</h2> <p>Price = ${{ p.price }}</p> <div> {% if user.is_authenticated %} <form name="bid" action="/post/{{p.title}}{{p.price}}" method="post" > {% csrf_token %} <input autofocus class="form-control" type="text" name="newBid" placeholder="Enter New Bid"> <input autofocus class="form-control" type="hidden" name="itemID" value={{p.title}}{{p.price}}> <input autofocus class="form-control" type="hidden" name="price" value={{p.price}}> <input autofocus class="form-control" type="hidden" name="title" value={{p.title}}> <input class="btn btn-primary" type="submit" … -
Problems with Django Rest Framework-filters
I'm new in django rest and i'm trying build filters for my apps. Looking at the documentation https://github.com/philipn/django-rest-framework-filters I followed all the implementation steps, but when I try to filter my search by username, nothing works settings.py INSTALLED_APPS = [ 'general', 'suprimentos', 'corsheaders', 'django.contrib.auth', 'django.contrib.admin', 'django.contrib.messages', 'django.contrib.sessions', 'django.contrib.staticfiles', 'django.contrib.contenttypes', 'simple_history', 'django_filters', 'rest_framework_filters', 'django_dbconn_retry', 'rest_framework' ] REST_FRAMEWORK = { 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination', 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_simplejwt.authentication.JWTAuthentication', ), 'DEFAULT_FILTER_BACKENDS': ( 'rest_framework_filters.backends.RestFrameworkFilterBackend', ) } views.py import django_filters.rest_framework from rest_framework import viewsets from rest_framework import filters import rest_framework_filters as filters from rest_framework_filters import backends class UsernameFilter(filters.FilterSet): username = filters.AllLookupsFilter(name='username') class TrackUserView(viewsets.ModelViewSet): model = TrackUser queryset = TrackUser.objects.all() serializer_class = TrackUserSerializer filter_backends = [backends.RestFrameworkFilterBackend] filter_class = UsernameFilter def get(self, request): track = UserLoginActivity.objects.all() serializer = UserLoginActivitySerializer(track, many=True) data = serializer.data return Response({'result':data}) def post(self, request): url = request.data['page'] ip_client = request.META.get('HTTP_IP_CLIENT') if ip_client: ip = ip_client.split(',')[0] else: ip = request.META.get('REMOTE_ADDR') username = request.user.username user_agent_info = request.META.get('HTTP_USER_AGENT', '<unknown>')[:255] hour = datetime.datetime.now() model = TrackUser.objects.create(url=url, ip=ip, username=username, user_agent_info=user_agent_info, datetime=hour) return Response(status=status.HTTP_200_OK) urls.py path('trackuser/',TrackPagesView.as_view({'get':'get','post':'post'}), name='trackuser') I don't know if something is missing or I put something wrong in somewhere, but I can't find the error or syntax problem that's causing it. -
How to keep a form from submitting when creating a Django model object with many-to-many field selection that is doesn't exist in the related model?
I'm using Django to create a web app. I have multiple Django models with relationships between each other. One of my models is called "Type" and another is called "TestEquipment". The Type model has a many-to-many relationship with TestEquipment. To allow the user to create a new Type, I have an html form and to select which TestEquipment will be associated with that Type I have am using searchable dropdown with "chips" (javascript) which loads all TestEquipment and allows you to search and select multiple objects to add. When the user submits the form, the selected TestEquipment is added. Everything works great other than when the user enters text and presses enter, instead of selecting from the dropdown, a chip is added with that text. When the form submits it tries to add a TestEquipment that doesn't exists. I would like to find a way to either not allow adding an objects that doesn't exist or throw an alert "must select from existing test equipment"; somehow I have to ensure that the form does not submit to my constructor and create the new Type if text is added to the field. I've tried to find an answer to this and … -
\copy in Postgres/Docker: No such file or directory
I have de Django app using postgresql that is "dockerized" I try to import data using psql commande \copy table1 (id,name) FROM '/home/docker/Apps/data.csv' WITH CSV HEADER DELIMITER ',' QUOTE '"'; /home/docker/Apps/data.csv: No such file or directory I wonder if it is because I add this files after I build my image is it possible? for other reasons, I do not manage to rebuild... -
python-crontab IOError Read crontab ubuntu: must be privileged to use -u
I have a Ubuntu server with Apache and a django web app running. I am using python-crontab to create cronjob's based on selections by a user. This worked fine on my dev server :8000. However, when I moved it over to production I got this error: IOError: Read crontab ubuntu: must be privileged to use -u This is linked to this code: cron = CronTab(user=True) This is where the error is. I have tried with no user, with my root user, pretty much anything. Any advice on how to solve this would be greatly appreciated -
Got AttributeError when attempting to get a value for field `Name` on serializer `UserSerializer`
I got the following error: Got AttributeError when attempting to get a value for field Name on serializer UserSerializer. The serializer field might be named incorrectly and not match any attribute or key on the User instance. Original exception text was: 'User' object has no attribute 'Name'. Why do I get an error? Here is my code: views.py from .serializers import UserSerializer from rest_framework import viewsets, status from django.contrib.auth.models import User class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer serializers.py from django.contrib.auth.models import User from rest_framework import serializers from .models import Profile from rest_framework.authtoken.models import Token class UserSerializer(serializers.ModelSerializer): class Meta: model = Profile fields = ('id', 'Name', 'secondName', 'user', 'nickName', 'phoneNumber') """extra_kwargs = {'password': {'write_only': True, 'required': True}}""" def create(self, validated_data): user = User.objects.create_user(**validated_data) token = Token.objects.create(user=user) print('Loogg') return user models.py from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver """Define Profile Fields""" class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, default=None) Name = models.CharField(max_length=32) secondName = models.CharField(max_length=32) nickName = models.CharField(max_length=32) phoneNumber = models.IntegerField(max_length=32) def __str__(self): return self.user.username class Meta: verbose_name = 'Profile' verbose_name_plural = 'profiles' urls.py from django.contrib import admin from django.urls import path from django.conf.urls import include from rest_framework import routers from .views … -
Compiling django files to pyc
I would to compile a python file in my django application, using: python --OO -m compileall *.py For example in app blog with structure: blog\ ... admin.py apps.py forms.py ... I want django to see __pycache__/admin.pyc as admin.py and so on. After compilation, I will delete all *.py files. Is there a way to linking some_file.pyc as to some_file.py for dajngo interpreter? -
enabling AVX2,AVx512 flags for tensorflow in server
Iam trying to load models that are trained in google colab in the backend of django website. the hosting service has no gpu support so i need to enable AVX2,AVX512 flags for cpu execution of tensorflow models.I gone through the process of enabling them .but every process includes installation of bazel .How is it possible for me to install bazel in the backend and execute it to set up my tensorflow with flags in hosting environment.here is my error with using tensorflow cpu. I tensorflow/core/platform/cpu_feature_guard.cc:142] This TensorFlow binary is optimized with oneAPI Deep Neural Network Library (oneDNN)to use the following CPU instructions in performance-critical operations: AVX2 AVX512F FMA#012To enable them in other operations, rebuild TensorFlow with the appropriate compiler flags. I wonder if there is command using pip that installs tensorflow with required flags AVX2.AVx512fetc.please help -
i am a newbie to django, and am getting error when am trying to the runserver
Traceback (most recent call last): File "c:\users\iam-korede\appdata\local\programs\python\python38-32\lib\runpy. py", line 194, in run_module_as_main return run_code(code, main_globals, None, File "c:\users\iam-korede\appdata\local\programs\python\python38-32\lib\runpy. py", line 87, in run_code exec(code, run_globals) File "C:\Users\iam-korede\AppData\Local\Programs\Python\Python38-32\Scripts\dj ango-admin.exe_main.py", line 7, in File "c:\users\iam-korede\appdata\local\programs\python\python38-32\lib\site-p ackages\django\core\management_init.py", line 401, in execute_from_command_l ine utility.execute() File "c:\users\iam-korede\appdata\local\programs\python\python38-32\lib\site-p ackages\django\core\management_init.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "c:\users\iam-korede\appdata\local\programs\python\python38-32\lib\site-p ackages\django\core\management\base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "c:\users\iam-korede\appdata\local\programs\python\python38-32\lib\site-p ackages\django\core\management\commands\runserver.py", line 61, in execute super().execute(*args, **options) File "c:\users\iam-korede\appdata\local\programs\python\python38-32\lib\site-p ackages\django\core\management\base.py", line 371, in execute output = self.handle(*args, **options) File "c:\users\iam-korede\appdata\local\programs\python\python38-32\lib\site-p ackages\django\core\management\commands\runserver.py", line 68, in handle if not settings.DEBUG and not settings.ALLOWED_HOSTS: File "c:\users\iam-korede\appdata\local\programs\python\python38-32\lib\site-p ackages\django\conf_init_.py", line 83, in getattr self.setup(name) File "c:\users\iam-korede\appdata\local\programs\python\python38-32\lib\site-p ackages\django\conf_init.py", line 64, in _setup raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: Requested setting DEBUG, but settin gs are not configured. You must either define the environment variable DJANGO_SE TTINGS_MODULE or call settings.configure() before accessing settings. -
Convert QueryDict to key-value pair dictionary
I have a QueryDict that I get from request.POST in this format: <QueryDict: {'name': ['John'], 'urls': ['google.com/\r\nbing.com/\r\naskjeeves.com/'], 'user_email': ['john.smith@gmail.com']}> Why are the values all in lists? I did dict(request.POST) I got {'name': ['John'], 'urls': ['google.com/\r\nbing.com/\r\naskjeeves.com/'], 'user_email': ['john.smith@gmail.com']} How can I get?: {'name': 'John', 'urls': 'google.com/\r\nbing.com/\r\naskjeeves.com/'`, 'user_email': 'john.smith@gmail.com'} -
When should I use a lazy function in Django
I am starting out with django and I have come across functions like reverse_lazy instead of reverse and gettext_lazy instead of gettext for translation. From the information, I could get online, it seems that these lazy functions only call the original functions when they are to be used and not immediately they are declared. What exactly does this mean and in what real life coding senerios should I use the lazy version as against the original function. Thanks a lot in advance -
Django drf-writable-nested not calling create method
I am using drf-writable-nested and overriding the create method of the serializer but it is not executing. I have tried the below code. Any help would be appreciated. models.py class Product(models.Model): name= models.CharField(max_length=500, unique=True, null=True) price = models.FloatField(null=True) description = models.CharField(max_length=100, null=True, blank=True) date_created = models.DateTimeField(auto_now_add=True, null=True) class ProductImage(models.Model): product = models.ForeignKey(Product, related_name="productImage", null=True,on_delete=models.SET_NULL) product_image = models.ImageField(max_length=255, null=True,blank=True) def __str__(self): return self.product_image.name serializers.py from rest_framework import serializers from drf_writable_nested.serializers import WritableNestedModelSerializer from API.serializers.productImageserializers import ProductImageSerializer class ProductsSerializer(WritableNestedModelSerializer): productImage = ProductImageSerializer(many=True) class Meta: model = Product fields = '__all__' def create(self, validated_data): image_data = validated_data.pop('productImage') product = Product.objects.create(**validated_data) for attached_file in image_data: ProductImage.objects.create(**attached_file) return product Api views.py @api_view(['GET','POST']) @permission_classes([IsAdminUser]) def products(request): productsserializer = ProductsSerializer(data=request.data) if productsserializer.is_valid(): productsserializer.save() return Response(productsserializer.data, status=status.HTTP_201_CREATED) return Response(productsserializer.errors, status=status.HTTP_400_BAD_REQUEST) I am submitting a post request to add the details. The request also contains image files. I want to create a new product which will have an images. I have installed the drf-writable-nested library which will do the nested writables without calling the create function. I have tried without using the create method and also later overriding the create method but it was showing the below error. { "productImage": [ "This field is required." ] } -
Form not passing is_valid() check when trying to use form data from another form
I have two forms in two separate models: Trainer and User. The Trainer form has one field called price_for_trainer that I need to pull into the User form. It's getting pulled in with the default value of 0 but I need the price for the trainer, like $5000, which would have been entered by the trainer. I'm using the prefix keyword (see code below) as described in this example: django: add form field to generated form from another table But when I debug my code trainer_form.is_valid() inside of if request.method == "POST": returns False, so my code block doesn't get executed. Also, when debugging I'm printing the form errors for Trainer and they say field is required. I should also mention that I'm using forms.ModelForms for both my Trainer and User. Here's what I've tried. I've tried using the prefix keyword in my User view (see code below) which pulls in the price_for_trainer field from the Trainer form but sets the field to the default value of 0 Here's my code: User views.py def user(request): if request.method == "POST": user_form = UserForm(request.POST, prefix="user") trainer_form = TrainerForm(request.POST, prefix="trainer") if user_form.is_valid() and trainer_form.is_valid(): user = user_form.save() trainer = trainer_form.save(commit=False) trainer.user=user trainer.save() return … -
Django admin actions based on custom conditions
I have a user model with fields like user_name, email and created_on. I tried the following code to export the user data into csv format Using the following code I am able to download the selected user data. Is it possible to download the user list on the basis of the time period by making use of this function ? def export_as_csv(self, request, queryset): meta = self.model._meta field_names = [field.name for field in meta.fields] response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename={}.csv'.format(meta) writer = csv.writer(response) writer.writerow(["first_name", "email", "created_on"]) for obj in queryset: row = writer.writerow([obj.first_name, obj.email, obj.created_on) return response class UserAdmin(admin.ModelAdmin): actions = [export_as_csv] list_display = ('created_on','email', 'first_name') -
Django filter local folders
I have a templatetag function that returns a Collapse menu with all folders, subfolders and images in a root directory but now I want to be able to filter which folders I get, the templatetag function recives one parameter, the root directory, and I know it should recibe a second parameter with the folder I want to get but I'm confused in this part. in my settings.py I have this: STATICFILES_DIRS = [ BASE_DIR / 'static', 'D:/Users/my_user/Documents/Luis/results', ] in my templatetag.py I have this: from django import template from django.utils.safestring import mark_safe import os register = template.Library() @register.simple_tag def my_tag(path): html='' for file in os.listdir(path): rel = os.path.join(path, file) if os.path.isdir(rel): html += f"""<button type="button" class="collapsible">{file}</button>""" html +='<div class="content"><div class="row mt-2">' html += my_tag(rel) html += '</div></div>' else: html +=f'<div class="col-md-6 d-flex align-items-stretch"><picture>' x=str(rel)[43:] print(x) html += """<img src="/static"""+"""/%s" """%(x) html += """ class="lazy card-img-top" width="500" height="400" """ html += """alt="/static"""+"""/%s" """%(x) html +='></picture></div>' return mark_safe(html) and in my template.html I have this: {% load static files %} <style> .collapsible { background-color: #F8F8F8; color: #858E9B; cursor: pointer; padding: 18px; width: 100%; border: none; text-align: left; outline: none; font-size: 15px; } /* .active, .collapsible:hover { background-color: #555; }*/ .content { padding: …