Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django view template responsiveness
I am trying to work on the responsiveness of my django application on mobile view. So here is our it looks on a smaller screen size So I want to remove all the white space that I have marked in blue, which is supposed to separate one post from the next. Here is the code snippet associated with that section <section class="category-section"> <div class="container" data-aos="fade-up"> <div class="section-header d-flex justify-content-between align-items-center mb-5"> <h2>Politics</h2> <div><a href="politics" class="more">See All Politics</a></div> </div> <div class="row"> {% for politic in politics%} {% if forloop.counter < 11 %} <div class="post-entry-1 col-lg-2 col-md-6 col-xs-12 mx-1"> <a href="/politicalpost/{{politic.id}}"><img src="{{politic.image.url}}" alt="" class="post_img img-fluid"></a> <div class="post-meta float-right"> <span class="date">{{politic.category}}</span> <span class="mx-1">&bullet;</span> <span>{{politic.created_at}}</span> </div> <h2 class="mb-2"><a href="/politicalpost/{{politic.id}}">{{politic.title}}</a></h2> <span class="author mb-3 d-block">Ole Pundit</span> <p class="mb-4 d-block">{{politic.body| safe | truncatewords:15}}</p> </div> {% endif %} {% endfor %} </div> </div> </section> And here are some of the css style classes that are at play .post-entry-1 { margin-bottom: 30px; } .post-entry-1 img { margin-bottom: 30px; } .post-entry-1 h2 { margin-bottom: 20px; font-size: 20px; font-weight: 500; line-height: 1.2; font-weight: 500; } .post-entry-1 h2 a { color: var(--color-black); } .post-entry-1.lg h2 { font-size: 40px; line-height: 1; } .post-meta { font-size: 11px; letter-spacing: 0.07rem; text-transform: uppercase; font-weight: 600; font-family: … -
ManyToMany in Django Admin as Muti Select CheckBox
i'm using python 3.9 with django 4.1. I have list of apartments and list of their commodities, each apartment can have zero or more commodities. the modes are created as such: class Commodities(models.Model): name_en = models.CharField(verbose_name=_('English Name'), unique=True, blank=True, null=True, max_length=200) name_he = models.CharField(verbose_name=_('Hebrew Name'), unique=True, blank=True, null=True, max_length=200) name_fr = models.CharField(verbose_name=_('French Name'), unique=True, blank=True, null=True, max_length=200) class Meta: constraints = [ models.CheckConstraint( check=Q(name_en__isnull=False) | Q(name_he__isnull=False) | Q(name_fr__isnull=False), name='not_all_null_commodities' ) ] def __str__(self): return getattr(self, 'name_' + get_2l_lang()) class Apartment(models.Model): address = models.ForeignKey(Address, verbose_name=_('Apartment Address'), on_delete=models.CASCADE) floor = models.IntegerField(verbose_name=_('Floor'), null=True, blank=True) apartment = models.CharField(verbose_name=_('Apartment'), null=True, blank=True, max_length=10) def __str__(self): return self.address.__str__() + \ (' ' + _('Entrance') + ' ' + self.address.entrance if self.address.entrance else '') + \ (' ' + _('Floor') + ' ' + str(self.floor) if self.floor else '') + \ (' ' + _('Apartment') + ' ' + self.apartment if self.apartment else '') class ApartmentCommodities(models.Model): apartment = models.ForeignKey(Apartment, on_delete=models.CASCADE, verbose_name=_('Apartment')) commodity = models.ForeignKey(Commodities, on_delete=models.CASCADE) def __str__(self): return self.apartment.__str__() + ' - ' + getattr(self.commodity, 'name_' + get_2l_lang()) I want in the admin page, when I add or modify an apartment, to see the commodities as multi-checkbox instead of selecting adding and removing each commodity line by line. … -
User creation on registrations Django
In my app, I want the user to register this code is showing no error but it is not saving in the database; if guys have any suggestions that would be very helpful. The reason I'm creating in this method because I have lots of other user groups because of that reason I wanna create the database model, form and views in this manner Thanks in advance Models.py class User(AbstractUser): ADDCHKS_ID=models.CharField(max_length=16,null=True) is_active=models.BooleanField(default=False) class justforfun(models.Model): Name=models.CharField(max_length=100,null=True) Roll_no=models.CharField(max_length=100,null=True) User=models.ForeignKey(User,on_delete=models.CASCADE) Forms.py class just(forms.Form): Name = forms.CharField( label='Name', widget=forms.TextInput(attrs={ 'class': 'form-control', 'placeholder': 'Name', 'rows':1 }) ) Roll_no = forms.CharField( label='Roll-no', widget=forms.TextInput(attrs={ 'class': 'form-control', 'placeholder': 'Roll_no', 'rows':1 }) ) views.py def test2(request): form=just() if request.method=='POST': if form.is_valid(): user21=User.ojects.create( username=form.data["Name"], password=str(random.random(000000000000,999999999999)) ) user21.save() just_data=justforfun.objects.create( user=user21, Name=form.data["Name"], Roll_no=form.data["Roll_no"] ) just_data.save() context={ "form":form } return render(request, "just.html", context) -
Django v3.1 gets django_admin_bootstrapped exception saying "'future' is not a registered tag library"
We have upgraded an old project from Python v2.7 + Django v1.8 to Python v3.7 + Django v3.1 and fixed some compatibility issues during the change. As a result, the project works as expected in most parts. However, we noticed an exception when logging out of the admin console, saying 'future' is not a registered tag library. We are new to this area and highly appreciate any hints or suggestions. Exception details: TemplateSyntaxError at /api/admin/logout/ 'future' is not a registered tag library. Must be one of: admin_list admin_modify admin_urls app_tags bootstrapped_goodies_tags cache humanize i18n l10n log rest_framework static tz Request Method: GET Request URL: http://test.local/api/admin/logout/ Django Version: 3.1.4 Exception Type: TemplateSyntaxError Exception Value: 'future' is not a registered tag library. Must be one of: admin_list admin_modify admin_urls app_tags bootstrapped_goodies_tags cache humanize i18n l10n log rest_framework static tz Exception Location: /data/app/venv3.7/lib/python3.7/site-packages/django/template/defaulttags.py, line 1038, in find_library Python Executable: /data/app/venv3.7/bin/python Python Version: 3.7.9 Python Path: ['/data/app/APPLICATION', '/data/app/APPLICATION', '/var/lib/snapd/snap/pycharm-professional/297/plugins/python/helpers/pycharm_display', '/usr/local/lib/python37.zip', '/usr/local/lib/python3.7', '/usr/local/lib/python3.7/lib-dynload', '/data/app/venv3.7/lib/python3.7/site-packages', '/var/lib/snapd/snap/pycharm-professional/297/plugins/python/helpers/pycharm_matplotlib_backend'] Server time: Mon, 15 Aug 2022 14:56:10 -0600 Error during template rendering In template /data/app/APPLICATION/django_admin_bootstrapped/templates/registration/logged_out.html, error at line 2 'future' is not a registered tag library. Must be one of: admin_list admin_modify admin_urls app_tags bootstrapped_goodies_tags cache humanize i18n l10n log … -
IntegrityError at /auth/userreg/ (1048, "Column 'user_id' cannot be null")
I am a newbie in django, I am at learning stage I am creating a project appointment system where user and doctor can login . I want to register them as multiuser type for that I have extended abstract class and given one to one relation to other tables but when The code is execute and I click submit This error appears. all fields are correct there is no error in the code everything is working correct just this integrity error is not getting solved. I have not created any foriegn key just trying to create user at of the user registration . authenticate.models from django.db import models from django.contrib.auth.models import AbstractUser from django.contrib.auth.models import User # Create your models here. class User(AbstractUser): is_user = models.BooleanField('user', default=False) is_doctor = models.BooleanField('doctor', default=False) first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) class User_reg(models.Model): user = models.OneToOneField('User',on_delete=models.CASCADE, primary_key=True) fname = models.CharField(max_length=50,blank=False) lname = models.CharField(max_length=50,blank=False) email = models.EmailField(max_length=100,blank=False) address = models.TextField(max_length=500,blank=False) gender = models.CharField(max_length=7, blank=False) phone = models.CharField(max_length=12,unique=True,blank=False) Username = models.CharField(max_length=100,blank=False,unique=True) Userpassword = models.CharField(max_length=100,blank=False) views.py from django.shortcuts import render from django.contrib import messages # from django.contrib.auth.models import get_user_model from django.contrib.auth.models import User from authenticate_me.models import User_reg, dr_reg def login(request): return render(request, 'user/login.html') def register(request): if request.method … -
Get specific uuid object in view from model in django
I have django app in which user can upload files in course with 3 editable fields. models.py class Course(models.Model): course_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False, unique=True) title = models.CharField(max_length=20) thumbnail = models.ImageField(upload_to='thumbnails', null=False, default='default.jpg') videofile = models.FileField(validators=[FileExtensionValidator], upload_to='videos') def path(self): return self.url I have view to display those the thumbnails of all courses and when user click on thumbnail it redirects him to course detail page. urls.py path('course/<uuid:course_id>/', views.course_detail, name='course-detail') So my question is how can I get information about fields of model Course in my html file to display them. views.py def course_detail(request, *args, **kwargs): course = models.Course.objects.get() context = { 'course': course, } return render(request, 'courses/info_course_view.html', context) Without uuid i would just write pk=pk in brackets but since i use uuid i don't know how to make it work. template <div class="container"> {{ course.title }} </div> Thank you all for help! -
How to iterate django template variable in the jQuery selected element?
I am working on a chat system in which I can open multiple chat of users (just like facebook). When the user clicks on the username that is in the contact list, a chat popup gets open. Following is the snippet from my models.py, class ThreadManager(models.Manager): def by_user(self, **kwargs): user = kwargs.get('user') lookup = Q(first_person=user) | Q(second_person=user) qs = self.get_queryset().filter(lookup).distinct() return qs class Thread(models.Model): first_person = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True, related_name='thread_first_person') second_person = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True, related_name='thread_second_person') updated = models.DateTimeField(auto_now=True) timestamp = models.DateTimeField(auto_now_add=True) objects = ThreadManager() class Meta: unique_together = ['first_person', 'second_person'] class ChatMessage(models.Model): thread = models.ForeignKey(Thread, null=True, blank=True, on_delete=models.CASCADE, related_name='chatmessage_thread') user = models.ForeignKey(User, on_delete=models.CASCADE) message = models.TextField() timestamp = models.DateTimeField(auto_now_add=True) Following is a query that I pass from views.py to my html template, threads = Thread.objects.by_user(user=request.user).prefetch_related('chatmessage_thread') Following is the html code, <div class="chat_box"> <div class="chat_header" > <h1 class="chat_heading">(6) Contacts</h1> </div> <hr> <div class="chat_content" style="display: none;"> {% for thread in Threads %} <div class="user" id="{{ thread.second_person.id }}" thread-id = "{{thread.id}}" chat-id="chat_{{ thread.id }}"> <img id="my_img" src="{{user_personal.picture.url}}" class="user_icon"> {% if thread.first_person == user %} <h3 class="username">{{ thread.second_person.first_name }} {{ thread.second_person.last_name }}</h3> {% else %} <h3 class="username">{{ thread.first_person.first_name }} {{ thread.first_person.last_name }}</h3> {% endif %} <i class="fa fa-circle"></i> </div> {% endfor … -
Django Rest Framework transforming my APIView into a ModelViewSet
I have the following model, class Schema(models.Model): week = models.PositiveIntegerField(validators=[MinValueValidator(1), MaxValueValidator(53)]) users = models.ManyToManyField(MyUser, related_name="users") class Meta: ordering = ('week',) The model holds a week number and list of users related to that week number. I have then created an APIView where the GET request fetches all the Schemas (my model), and the POST request does the following, if the week number is not in the database then it simply creates a row in the database for the given week number and the given users. If the week number is already present in the database then I simply overwrite the users related to that week number with the newly given users, the view looks like this, class SchemaView(APIView): permission_classes = (SchemaPermissions,) def get(self, request): schemas = Schema.objects.all() serializer = SchemaSerializer(schemas, many=True) return Response(serializer.data) def post(self, request): data = request.data serializer = SchemaSerializer(data=data) if serializer.is_valid(): input_data = serializer.validated_data week = input_data.get('week') user_ids = input_data.get('user_ids') if Schema.objects.filter(week = week).count() > 0: schema = Schema.objects.get(week = week).first() else: schema = Schema.objects.create(week = week) schema.users.set(user_ids) schema.save() return Response(SchemaSerializer(schema).data, status=status.HTTP_200_OK) else: return Response(status = status.HTTP_400_BAD_REQUEST) Now this works as expected, however now comes my problem. This only works for a single "Schema" (my model) on … -
Highlighting the first repeating loop element in django
Please tell me how to select only the first repeating element of the cycle in Jinja django? <table id="{{el.slug}}_table" class="table table-striped table-bordered table-sm " cellspacing="0" width="100%" > <thead> <tr> <th>expand</th> <th>Тип алерта </th> <th>hostname</th> <th>username</th> <th>message</th> <th>Actions</th> </tr> </thead> <tbody> {% regroup alerts|dictsort:"username" by username as alrt %} {% for all in alrt %} {% for ell in all.list %} {% if el.title == ell.title %} {% if forloop.first %} <tr class="table-primary"> <td class="row1">+</td> <td class="{{ rowcolors }}">{{ell.title}}</td> <td>{{ell.hostname}}</td> <td>{{ell.username}}</td> <td>{{ell.message}}</td> <td><a href="#"><i class="fa fa-eye" aria-hidden="true"></i></a> <a href="#"><i class="fa fa-user-plus" aria-hidden="true"></i></a> <a href="#"><i class="fa fa-paper-plane-o" aria-hidden="true"></i></a> <a href="#"><i class="fa fa-bug" aria-hidden="true"></i></a> <a href="#"><i class="fa fa-times-circle" aria-hidden="true"></i></i></a></td> </tr> {% else %} <tr class="table-light"> <td class="row2">+</td> <td class="{{ rowcolors }}">{{ell.title}}</td> <td>{{ell.hostname}}</td> <td>{{ell.username}}</td> <td>{{ell.message}}</td> <td><a href="#"><i class="fa fa-eye" aria-hidden="true"></i></a> <a href="#"><i class="fa fa-user-plus" aria-hidden="true"></i></a> <a href="#"><i class="fa fa-paper-plane-o" aria-hidden="true"></i></a> <a href="#"><i class="fa fa-bug" aria-hidden="true"></i></a> <a href="#"><i class="fa fa-times-circle" aria-hidden="true"></i></i></a></td> </tr> {% endif %} {% endif %} {% endfor %} {% endfor %} </tbody> </table> At the moment, it turned out to select only the first element in the loop, and you need the first repeating one -
Get user's information from Google Sign Up using Django?
I have added the "Continue with Google" button in my HTML code and all of that works and after the user has gone through that process it sends a POST request to my backend with the variables "credential" and "g_csrf_token". I want to know how to handle this information and get the user's name, email, profile picture, etc. This is the HTML code that sends the request: <script src="https://accounts.google.com/gsi/client" async defer></script> <div id="g_id_onload" data-client_id="188921335755-m1v9q2v7lghon45rlp89qq2rm7f4ko9c.apps.googleusercontent.com" data-login_uri="http://localhost:8000/accounts/signup/continue-with-google/" data-auto_prompt="false"> </div> <div id="continueWithGoogleButton" class="g_id_signin" data-type="standard" data-size="large" data-theme="outline" data-text="continue_with" data-shape="pill" data-logo_alignment="left" data-width="300"> </div> -
Heroku deploy Django application
I'm trying to launch my Django application with Heroku but when I execute the command "Heroku local" I get the following error .... Anyone can explain why? Before writing this post I tried to make various changes and read up on the official website but it didn't work. To run heroku in local I ran Heroku local in my main directory, with gunicorn everything was fine but apparently with heroku I'm doing something wrong. I've also created a Procfile with the following line inside of it: web: gunicorn social_site.wsgi where social_site is the name of the app. -
Django datetime returning negative value even though the date is not over
I have this issue with date time, I don't understand the datetime module and django dates either, what I am trying to achieve is get the difference days between a constant datetime saved in the database and current date. See, the problem is even though today is not over I am getting negative -1 day and the day is not over yet. from django.utils.timezone import now class ExamplModel(models.Model): due_date = models.DateTimeField() # model method def get_due_date(self): days_left = due_date - now() return days_left if due_date is today a couple of hours ago, example I get result like this -1 day, 18:54:04.590519 instead of 0 day, 18:54:04.590519 How can I solve this. -
Django : Change data when model become a choice field
I have a form where I ask people's hobbies. It was a Charfield in my form. I transformed this field with multiple CHOICES. For my old datas, I would like to update their values: for example if they had entered: "football", "skiing", it would have to change to 'sport'. abstract_models.py class ReferencesProfileBase(models.Model, UsernameNaturalKeyMixin): HOBBY_CHOICES = ('sport', ('sport')), ('music', ('music')), ('travel', ('travel')), ('other', ('other')), ) customer = models.OneToOneField( 'customers.CustomerProfile', verbose_name=_('Customer'), related_name='referencesprofile', on_delete=models.CASCADE, ) hobby = models.CharField( ('Hobby'), max_length=250, choices=HOBBY_CHOICES, blank=True, null=True, ) what I want on my old data done automatically : sport = ["skiing", "football"] if hobby in sport : hobby = "sport" else : hobby = "other" return hobby but I don't know in which function to write this code -
KeyError: 'skip_checks on heroku run python manage.py migrate_schemas
After deployment in Heroku a Django app, I run a command as follows: heroku python manage.py migrate_schemas and throws this error: File "/app/.heroku/python/lib/python3.10/site-packages/tenant_schemas/migration_executors/base.py", line 58, in run_migrations run_migrations(self.args, self.options, self.codename, public_schema_name) File "/app/.heroku/python/lib/python3.10/site-packages/tenant_schemas/migration_executors/base.py", line 31, in run_migrations MigrateCommand(stdout=stdout, stderr=stderr).execute(*args, **options) File "/app/.heroku/python/lib/python3.10/site-packages/django/core/management/base.py", line 365, in execute if self.requires_system_checks and not options['skip_checks']: KeyError: 'skip_checks' Any idea of how fix this error? -
Django Form Post but doesn't display data
I'm working on a project but I'm kind of stuck on a problem. My Django post form doesn't have any bug but every time I submit a form, it redirects as it should but doesn't display anything. And I have 5 forms of the same type but it's only one of them that does it. Code Snippet Below View.py ########################## PRESCRIPTION ##################################################### def patients_list(request): context = {'patients_list': Prescription.objects.all()} return render(request, 'dashboard/patients_list.html', context) def patients_form(request, id=0): if request.method == 'GET': if id == 0: pform = PatientsForm() else: prescription = Prescription.objects.get(pk=id) pform = PatientsForm(instance=prescription) return render(request, 'dashboard/patients_form.html', {'pform': pform}) else: if id == 0: pform = PatientsForm(request.POST) else: prescription = Prescription.objects.get(pk=id) pform = PatientsForm(request.POST, instance=prescription) if pform.is_valid(): pform.save() return redirect('/list') urls.py ########################## PRESCRIPTION ##################################################### path('form', views.patients_form, name='patients_form'), path('list', views.patients_list, name='patients_list'), path('update_patient/<str:id>/', views.patients_form, name="update_patient"), path('patients_delete/<str:id>/', views.patients_delete, name="patients_delete"), ########################## END PRESCRIPTION ##################################################### patients_form.html <form action="" method="POST"> {% csrf_token %} <div class="form-group"> {{pform.first_name|as_crispy_field}} </div> <div class="form-group"> {{pform.last_name|as_crispy_field}} </div> <div class="form-group"> {{pform.CNI|as_crispy_field}} </div> <div class="form-group"> {{pform.gender|as_crispy_field}} </div> <div class="form-group"> {{pform.marital_status|as_crispy_field}} </div> <div class="form-group"> {{pform.telephone1|as_crispy_field}} </div> <div class="form-group"> {{pform.telephone2|as_crispy_field}} </div> <div class="form-group"> {{pform.town|as_crispy_field}} </div> <div class="form-group"> {{pform.address|as_crispy_field}} </div> <div class="form-group"> {{pform.occupation|as_crispy_field}} </div> <div class="form-group"> {{pform.status|as_crispy_field}} </div> <div class="row"> <div class="col md 6"> <button class="btn btn-success my-4" … -
Traverse m2m,filter and aggregate data in django
Currently, I'm developing a CRM system for collecting/aggregating data about female models I got 3 DB models that interact with each other: class User(AbstractBaseUser, PermissionsMixin): """ User class """ email = models.EmailField( max_length=128, unique=True, null=False, blank=False) is_active = models.BooleanField(default=True) staff_type = models.CharField( max_length=128, choices=STAFF_TYPES, null=False, blank=False) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) created_at = models.DateTimeField(default=timezone.now, editable=False) updated_at = models.DateTimeField(default=timezone.now, editable=False) USERNAME_FIELD = ("email") objects = UserManager() def __str__(self): return f'{self.email} - {self.staff_type}' class OnlyFansModel(models.Model): """ Class(Model) storing data for OnlyFans models""" username = models.CharField( max_length=128, unique=True, null=False, blank=False) plan = models.IntegerField() # Filters experience = models.CharField( max_length=128, choices=EXPERIENCE_TYPE, blank=False, null=False, default=EXPERIENCE_TYPE[0]) type = models.CharField( max_length=128, choices=TYPES, blank=False, null=False ) teamlead = models.ForeignKey(User, on_delete=models.SET_NULL, related_name="teamleads", default=1, blank=True, null=True,) client_manager = models.ForeignKey( User, on_delete=models.SET_NULL, related_name="clientmanagers", default=1, blank=True, null=True) marketer = models.ForeignKey(User, on_delete=models.SET_NULL, related_name="marketers", default=1, blank=True, null=True) created_at = models.DateTimeField(default=timezone.now) updated_at = models.DateTimeField(default=timezone.now) def __str__(self): return f'{self.username}' class Record(models.Model): """ Storing data """ ofmodel = models.ForeignKey( OnlyFansModel, on_delete=models.CASCADE, related_name='records') fact = models.IntegerField(blank=False, null=False) fact_percentage = models.DecimalField( max_digits=8, decimal_places=2, blank=True, null=True) run_rate = models.DecimalField( max_digits=8, decimal_places=1, blank=True, null=True) run_rate_percentage = models.DecimalField( max_digits=8, decimal_places=2, blank=True, null=True) lfl_sales = models.DecimalField( max_digits=6, decimal_places=2, blank=True, null=True, default=100.0) average_sales_per_model = models.DecimalField( max_digits=9, decimal_places=2, blank=True, null=True) all_fans_start = models.IntegerField(blank=False, null=False) … -
working with multi language data (translations) in db using django models
I'm using Python 3.9 with Django 4.1 and I want to store data in my database in 3 languages, English, French and Hebrew. currently I work on addresses so for country, city and street i have columns name_en, name_fr and name_he. I have country, city and street tables, and also relation tables CountryCity that contains country id and city id and CountryCityStreet that contains countryCityId and streetId. i can get the current used language using translation.get_language() and i can take only the first 2 characters to get the desired result (en, fr or he). so I created a service function to get the first characters: def get_2l_lang(): lang = translation.get_language() return lang[0:lang.find("-")] and I created the models for that: class Country(models.Model): class Meta: verbose_name_plural = "Countries" name_en = models.CharField(unique=True, verbose_name="English Country Name", max_length=100) name_fr = models.CharField(unique=True, verbose_name="French Country Name", max_length=100) name_he = models.CharField(unique=True, verbose_name="Hebrew Country Name", max_length=100) def __str__(self): return getattr(self, 'name_' + get_2l_lang()) class City(models.Model): class Meta: verbose_name_plural = "Cities" name_en = models.CharField(unique=True, verbose_name="English City Name", max_length=100) name_fr = models.CharField(unique=True, verbose_name="French City Name", max_length=100) name_he = models.CharField(unique=True, verbose_name="Hebrew City Name", max_length=100) def __str__(self): return getattr(self, 'name_' + get_2l_lang()) class Street(models.Model): name_en = models.CharField(unique=True, verbose_name="English Street Name", max_length=100) name_fr = … -
DJANGO Templates dont share static files
I have a currently have a problem. I got two django templates:cart.html and index.html. In the cart.html there is a javascript file linked. Both of these files should acces the static files in the static folder. The problem now is that, when I try to acces the static files from the linked cart.html javascript file it gives me this error: [15/Aug/2022 20:14:40] "GET /cart/images/fruits/Kornknacker.jpg HTTP/1.1" 404 2419 These are my settings: STATIC_URL = 'static/' STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'),) Here is the project structure: Project Here is the javascript file: {% load static %} function loadCart() { let productsSection = document.getElementById("products_section"); productsSection.innerHTML = ''; let productHTML = ''; let totalPrice = 0; let cartItems = JSON.parse(localStorage.getItem('cart')); if (cartItems && cartItems.length > 0) { for (let item of cartItems) { totalPrice = totalPrice + (item.quantity * item.price); productHTML = productHTML + ` <div class="product-card" data-name="${item.itemName}" data-price="${item.price}" data-id="${item.itemId}"> <div> <img src="{%static '/images/fruits/${item.itemName}.jpg'%}" alt="FRUIT" width="180"> </div> <h3> ${item.itemName} </h3> <div> Anzahl: ${item.quantity} </div> <div> Preis: ${item.quantity * item.price}€ </div> </div> `; } document.getElementById("total_price_container").style.display = 'block'; document.getElementById("total_price").innerHTML = totalPrice; document.getElementById("no-products_section").style.display = 'none'; document.getElementById("checkout-section").style.display = 'flex'; document.getElementById("order-process_section").style.display = 'none'; productsSection.innerHTML = productHTML; } else { document.getElementById("no-products_section").style.display = 'block'; document.getElementById("checkout-section").style.display = 'none'; document.getElementById("total_price_container").style.display = 'none'; } }; … -
Cannot login to django admin panel after changing password
I hope you are fine. I have a superuser in django admin and the problem is that when this superuser changes his password, he will be redirected to the django admin login page and when the superuser enters correct username and password in the admin login page, it gives an error that is “Please enter the correct username and password for a staff account. Note that both fields may be case-sensitive.”, but I am sure that both of the username and password fields are filled correctly; I will thank if anyone help me to solve this problem. Thanks. -
Creating a form with input for 2 models django
I have create 2 models, models.py class Integrations(models.Model): subscription_id = models.UUIDField( primary_key=True, default=uuid.uuid4, unique=True, editable=False ) subscription_name = models.CharField(max_length=256) subscription_type = models.CharField( max_length=256, choices=SUBSCRIPTION_TYPE, default="mqtt" ) def __str__(self): return self.subscription_name class Meta: ordering = ["subscription_name"] verbose_name = "Integration" verbose_name_plural = "Integrations" class Subscription(models.Model): url = models.CharField(max_length=256) port = models.IntegerField() username = models.CharField(max_length=256) password = models.CharField(max_length=256) topics = ArrayField(models.CharField(max_length=256)) subscription_id = models.ForeignKey(Integrations, default=None, on_delete=models.CASCADE) admin.py class MQTTSubscriptionAdmin(admin.ModelAdmin): fields = [ 'subscription_id', 'mqtt_url', 'port', 'username', 'password', 'subscribed_topics'] add_form = NewMQTTCreationForm fieldsets = None add_form_template = 'integrations/add_new_integration.html' add_fieldsets = ( (None, { 'classes': ('wide',), 'fields': ('subscription_id', 'subscription_name', 'subscription_type'), }), ) forms.py from django import forms from django.core.exceptions import ValidationError class NewMQTTCreationForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(NewMQTTCreationForm, self).__init__(*args, **kwargs) self.fields['url'].required = True self.fields['port'].required = True self.fields['username'].required = False self.fields['password'].required = False self.fields['subscription_id'].required = True self.fields['subscribed_topics'].required = False add_new_integration.html {% extends "admin/change_form.html" %} {% load i18n admin_urls static admin_modify jazzmin %} {% get_jazzmin_settings request as jazzmin_settings %} {% block form_top %} <!-- empty block to remove default user create text --> {% endblock %} {% block field_sets %} <div class="col-12 col-lg-9"> <div class="card"> <div class="card-body"> {% get_changeform_template adminform as changeform_template %} {% include changeform_template %} </div> </div> </div> {% endblock %} Here I want to … -
space in url Django
I am creating a search bar on my site, everything is fine if I pass the names without spaces, being that I pass the word of the search bar directly in the url, as you can imagine the problem arises when the user enters words with space. I also convert the url into utf-8, but I think django does it automatically because even without the conversion in the url if you pass the space it appears at its post% 20, I wanted to clarify that the problem persists if you enter characters like:! ?can someone help me? Thanks in advance. urls.py: from django.urls import path from dac import views from django.conf.urls.static import static from django.conf import settings from django.urls import re_path #include from django.contrib import admin app_name = 'dac' urlpatterns = [ path('admin/', admin.site.urls), path('', views.index, name='index'), path('doctors/<slug:slug>', views.doctor, name='doctors'), path('doctors/search/<slug:slug>/<slug:slug2>', views.doctor_search, name='doctors_search'), re_path(r'^doctors_search/search/(?P<slug>.)/(?P<slug2>\d+)$', views.doctor_search, name='doctors_search'), path('<slug:slug>', views.doctor_detail, name='doctor_detail'), path('signup/', views.sign_up, name="sign_up"), path('login/', views.log_in, name='log_in'), path('logout/', views.log_out, name='log_out'), path('reports/', views.reports, name='reports'), ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) views.py: def doctor(request, slug): print("slug: ",slug) if request.method == 'POST': print("slug: ",slug) risposta=request.POST.get("textAnswer") risposta=risposta.upper() risposta_list=risposta.rsplit() print(risposta_list) actual_url=request.build_absolute_uri() url=re.sub("\d+$", "search/%s/1"%(risposta), actual_url) return HttpResponseRedirect(url.encode('utf-8')) slug=int(slug) max_slug=int(round(doctors.objects.count()/28,0)) if slug==1: prew_slug=slug else: prew_slug=slug-1 if slug==max_slug: nxt_slug=max_slug else: nxt_slug=slug+1 … -
Filtering pages by fields of child pages of the nested level in Wagtail
There is the following page structure: ServiceCategoryPage -> ServicePage -> TariffPage and TariffPagePrices(Orderable): page = ParentalKey(TariffPage, on_delete=models.CASCADE, related_name='tariff_prices') .... How to filter the results of page ServiceCategoryPage on page ServicePage by the properties of model TariffPagePrices? -
Django Model Field to Count Other Field
I have these models class HatchingBatch(models.Model): hatch_date = models.DateField() incubator = models.CharField(max_length=32) rhode_island_red = models.IntegerField(default=0) barred_plymouth_rock = models.IntegerField(default=0) black_australorp = models.IntegerField(default=0) class Reservations(models.Model): date = models.DateField() hatch = models.ForeignKey(HatchingBatch, related_name="reservation", on_delete=models.CASCADE) is_done = models.BooleanField() is_delivery = models.BooleanField() shipping_fee = models.IntegerField() amount = models.IntegerField() class Stocks(models.Model): hatch = models.OneToOneField(HatchingBatch, on_delete=models.CASCADE, related_name="stock") I want to add a field to the Stocks model that would be the number of the reserved chicks (easily done through ForeignKey) however, I also want to add a "sold" field that would correspond to the sum of the Reservations with "is_done" : True -
Uncaught SyntaxError: Expected property name or '}' in JSON at position 1 at JSON.parse (<anonymous>)
Hi Im trying to execute python from javascript .So I'm trying to use the below code example views.py from django.shortcuts import render from json import dumps def send_dictionary(request): # create data dictionary dataDictionary = { 'hello': 'World', 'geeks': 'forgeeks', 'ABC': 123, 456: 'abc', 14000605: 1, 'list': ['geeks', 4, 'geeks'], 'dictionary': {'you': 'can', 'send': 'anything', 3: 1} } dataJSON = dumps(dataDictionary) return render(request, 'main / landing.html', {'data': dataJSON}) landing.html <!DOCTYPE html> <body> <div style="width: 40%; border: 1px solid black; background-color: lightcyan; font-family: Helvetica, sans-serif;"> <div style="margin: 5%;"> <h2> <u>Data</u> </h2> <h4 id='data'></h4> </div> </div> </body> </html> <script> var data = JSON.parse('{{data|escapejs}}') var dataNode = document.getElementById('data'); for(var x in data){ dataNode.innerHTML+=x+' : '+data[x]+'<br><br>'; } </script> When I try to run ,I got this syntax error but doesn't really seem to be a syntax error. Uncaught SyntaxError: Expected property name or '}' in JSON at position 1 at JSON.parse () Im referring to the example in the below link. https://www.geeksforgeeks.org/how-to-pass-data-to-javascript-in-django-framework/ -
Ajax call run by form submission and will pass data to a separate views.py template
I am building a web application using Django. I have a search function on my index page. When a user submits the form an AJAX call should be executed. This AJAX call should take all the needed data from the form and pass it over to a completely separate views.py template that will make API GET requests using that data and build a new page using that separate template. As of right now it is not loading the separate views.py template, I am unsure if I am passing the data correctly however I do see /searchresults?searchType=data1&amp;executeLocation=data2 in my console because my AJAX call is returning on success currently. It is safe to assume that I have all the data needed in the data1 and data2 variables, I just need help redirecting to the new page and passing the data along with the redirect. My code: urls.py # The home page path('', views.index, name='home'), # Search results page path('searchresults', views.search_results, name='searchresults'), AJAX function getSearchResults(searchType,executeLocation,csrf_token) { $.ajax( { type: $(this).attr('method'), url: "searchresults", //The URL you defined in urls.py data : { searchType: searchType, executeLocation: executeLocation, csrfmiddlewaretoken: csrf_token }, dataType: 'text', success: function(response) // currently executes success (but not correct outcome) { console.log(response); …