Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
mutiple time data saving problem in django sqllite3
i using django with sqllite i create a survey form with the help of django model and django forms but when i hit submit i see sometime data save twice in my database is it happen normally or something wrong with my code from django.shortcuts import render, redirect from django.contrib import messages from django.template.response import TemplateResponse from .forms import SurveyForm # Create your views here. def index(request): if request.method == 'POST': form = SurveyForm(request.POST) if form.is_valid(): form.save() return TemplateResponse(request, 'thankyou.html') else: return messages.error(request, 'Please fill the form to continue') else: form = SurveyForm() return render(request, 'learnersform.html', {'form': form}) -
Use object variable in base.html of Django
I come from Ruby on Rails and I am trying to learn Django. There are multiple things that puzzle me when it comes to how to solve simple things. I have a sidebar in which I would like to have a link to a random item. My first thought was to use: <a href="{% url 'headline_detail' Headline.objects.order_by('?')[0].id %}">Random headline</a> Although it works perfectly fine to run Headline.objects.order_by('?')[0].id in the shell, this causes an error in Django: Could not parse the remainder: '('?')[0].id' from 'Headline.objects.order_by('?')[0].id' which I find very weird since 'Headline.objects.order_by('?')[0].id' creates a number (id) and if I put the same number in as <a href="{% url 'headline_detail' 123 %}">Random headline</a> it works perfectly fine. Another option would be to create this previously in the template, like {% rand_id = Headline.objects.order_by('?')[0].id %} <a href="{% url 'headline_detail' Headline.objects.order_by('?')[0].id %}">Random headline</a> which is I would hotfix it in Rails - but this doesn't work. The third option (which is better than the 2nd) is to put the variable in the view. However, this is not really viable since this code is in the sidebar and I cannot pass this in every view (DRY!). So, I figure out I should use context templates, … -
Tutorial for browser-sync setup for Wagtail
I am new to python world and finished Codeforeveryone Wagtail videos. I have wireframe website that I have added to Wagtail but could not figure out how to get browser-sync to work. Could anyone suggest what I need to do to get this browser-sync setup working so that html, css, scss update automatically after I hit the save button? -
DRF: Need Guidance to perform a task
I need to create an API to book a call with an advisor Endpoint: /user/<user_id>/advisor/<advisor_id>/ for this used path('user/<int:user_id>/advisor/<int:advisor_id>') in urls.py but the problem is I have to request a Booking time(a DateTime sting) when I make a request to that link which I can perform via PostMan In serilaizer.py I used: class BookingSerializer(serializers.ModelSerializer): class Meta: model = models.Booking fields = '__all__' def create(self, validated_data): user = models.Booking.objects.create( user=validated_data['user'], advisor=validated_data['advisor'], time=validated_data['time']) user.save() return user In this i have pass everything via the body in postman but I want to use the user_id and advisor_id from the url and just want to provide DateTime string via body in PostMan -
Django form field has initial value and is disabled, but not being submitted
tldr I'm having a problem that seems like it's fairly basic, but I can't figure it out. It seems that if a form field is disabled, and that field is instantiated with an initial value, the initial value correctly displays in a rendered template, but that field does not get submitted with the POST payload, which I would expect. Details In my Django application I have: a form with two required fields, field1 amd field2. a template that displays the form and allows submission a view that On a GET, renders the template with the form unbound On a POST, validates the data and either does something (if valid) or renders the template with the bound form if the submission had errors. Desired behavior On a GET, have the view provide an initial value for field1 That value needs to be set dynamically, so I can't just set a default on the field Have the value be visible, but not editable, by the user Have the value submitted with the form on a POST My attempt What I expected to work was: Render the unbound form by passing initial= Set the form field to disabled=True. Reproducible example This is on … -
Why does my Submit button renders a page that is blank when it is supposed to contain the data that was just updated?
I'm trying to update the values of my database using a HTML Form. When I Click Edit it brings me to the edit the values above. However as I am clicking the submit button, it returns me a database but with no other values. Is there anyone that can help me understand what I did wrong and point me to the right documentation (if any) editclaims.html: <div class="arrange2"> <h1>Edit Claim Form - #{{claims.id}} </h1> </div> <form method="POST" action="/update/{{claims.id}}"> {% csrf_token %} views.py: def editclaims(request,id): context = initialize_context(request) user = context['user'] claims = SaveClaimForm.objects.get(id=id) return render(request, "Login/editclaims.html",{'claims':claims, 'user':user}) def updateclaims(request, id): context = initialize_context(request) user = context['user'] claims = SaveClaimForm.objects.get(id=id) form=reclaims(request.POST, request.FILES, instance=claims) if form.is_valid(): form.save() messages.success(request,"The Claim has been updated successfully.") return render(request, "Login/existingclaims.html", {'SaveClaimForm':claims, 'user':user}) urls.py: urlpatterns = [ path('existingclaims/', views.viewclaims, name='existingclaims'), path('editclaims/<int:id>', views.editclaims, name='editclaims'), path('update/<int:id>', views.updateclaims, name='updateclaims'), ] -
Hide buttons if user doesn't belong to any of Django groups
My problem is that I want to hide the button from all users who are not in group1 and group2 or in both groups. I did the following thing but it seems doesn't work at all. My views.py: def is_group1(user): return user.groups.filter(name='Group1').exists() def is_group2(user): return user.groups.filter(name='Group2').exists() def employee_list(request): groups = [g.name for g in request.user.groups.filter(name__in=['Group1', 'Group2'])] context = {'employee_list': Employee.objects.filter(dept__in=groups)} return render(request, 'employee_register/employee_list.html', context) My little example of employee_list.html: <form> {% if user.is_group1 %} <button formaction="{% url 'employee_insert' %}">Add</button> {% if user.is_group2%} <button formaction="{% url 'employee_insert' %}">Add</button> {% else %} <p>You are not logged</p> {% endif %} </form> Any thoughts how I can implement this ? -
"ConnectionAbortedError: [WinError 10053] An established connection was aborted by the software in your host machine" when i tried to add image in db
# Create your models here. from django.contrib.auth.models import AbstractUser, BaseUserManager from django.db import models from django.contrib.auth.models import User from django.utils.translation import ugettext_lazy as _ import uuid from django.db.models.signals import post_save, post_delete from django.utils.timezone import now class UserManager(BaseUserManager): """Define a model manager for User model with no username field.""" use_in_migrations = True def _create_user(self, email,username, first_name, last_name, password, **extra_fields): """Create and save a User with the given email and password.""" if not email: raise ValueError('The given email must be set') email = self.normalize_email(email) user = self.model(email=email,username=username,first_name=first_name,last_name=last_name, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, password=None, **extra_fields): """Create and save a regular User with the given email and password.""" extra_fields.setdefault('is_staff', False) extra_fields.setdefault('is_superuser', False) return self._create_user(email, password, **extra_fields) def create_superuser(self, email, password, **extra_fields): """Create and save a SuperUser with the given email and password.""" extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) if extra_fields.get('is_staff') is not True: raise ValueError('Superuser must have is_staff=True.') if extra_fields.get('is_superuser') is not True: raise ValueError('Superuser must have is_superuser=True.') return self._create_user(email, password, **extra_fields) class User(AbstractUser): """User model.""" username = models.CharField(max_length=200, null=True) first_name = models.CharField(max_length=200, null=True) last_name = models.CharField(max_length=200, null=True) email = models.EmailField(('email address'), unique=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = UserManager() class Post(models.Model): """post model""" id = models.UUIDField(primary_key=True,default=uuid.uuid4,editable=False) name = models.CharField(max_length=100,null=False) picture … -
Select a valid choice while selecting Foreignkey in django admin mongodb
database in MongoDB (djongo) I have registered a model in admin.py admin.site.register(Media) models.py class Media(BaseModel): _id = models.ObjectIdField(primary_key=True) url = models.URLField() media_type = models.CharField(max_length=100) user = models.ForeignKey(User, db_column="user", on_delete=models.CASCADE) post = models.ForeignKey(Post, db_column="post", on_delete=models.CASCADE) group = models.ForeignKey(Group, db_column="group", on_delete=models.CASCADE) class Meta: db_table = "media" while changing values using the admin site I got these errors. can you help me to solve this error? django==3.0.5 djongo==1.3.4 -
Multiple Django admin site on same server ,login abnormal
I deploy serveral django web sites on windows with IIS on same server,such as A,B,C. Each site works,but when I login django admin on site A,the login of django admin on site B and C will logout and each operation need relogin. Browser is chrome. I want these sites don't interfere each other. Is there lack of django configuration? -
Rendering a dictionary in a template
While rendering values of a dictionary in a template, some values are showed outside the html table. I cant realize why. Any ideas? Thanks in advance, #This is how the dictionary is printed in console [{'socio': 'Randazzo Walter Ariel 25', 'enero': 'P', 'febrero': 'P', 'marzo': 'P', 'abril': 'P', 'mayo': 'P', 'junio': 'P', 'julio': 'P', 'agosto': 'P', 'septiembre': 'P', 'octubre': 'P', 'noviembre': 'P', 'diciembre': 'P'}, {'socio': 'Silvi Edgardo Marcelo 31', 'enero': 'P', 'febrero': 'P', 'marzo': 'P', 'abril': 'P', 'mayo': 'P', 'junio': 'P', 'julio': '-', 'agosto': '-', 'septiembre': '-', 'octubre': '-', 'noviembre': '-', 'diciembre': '-'}] #this is how the template is rendered #Template: <table class="table" style="width: 100%;"> <thead> <tr style="border: 1px solid black;"> <th style="width: 30%; text-align: center;">SOCIO</th> <th style="width: 25%; text-align: center;">ENE</th> <th style="width: 25%; text-align: center;">FEB</th> <th style="width: 25%; text-align: center;">MAR</th> <th style="width: 25%; text-align: center;">ABR</th> <th style="width: 25%; text-align: center;">MAY</th> <th style="width: 25%; text-align: center;">JUN</th> <th style="width: 25%; text-align: center;">JUL</th> <th style="width: 25%; text-align: center;">AGO</th> <th style="width: 25%; text-align: center;">SEP</th> <th style="width: 25%; text-align: center;">OCT</th> <th style="width: 25%; text-align: center;">NOV</th> <th style="width: 25%; text-align: center;">DIC</th> </tr> </thead> <tbody> {% for pago in pagos %} <tr {% if forloop.first %}style="padding-top: 3px;" {% endif %}> <td class="text-center">{{ pago.socio }}</td> <td class="text-center">{{ … -
How to check if session is expired in Django views?
I am using Django session framework for login and logout functionality in my application. I do have multiple Django views as per business requirements. I have login view where I call authenticate() function to start the session for a user. But,I want to know how do I check whether session is valid when user calls different views. I am planning to implement using following code snippet. Can I someone tell me if this is the correct way of checking whether session is active or expired? def login(request): body_unicode = request.body.decode('utf-8') body = json.loads(body_unicode) user_name = body['user_name'] password = body['password'] user = authenticate(user_name,password) if user is None: ... else: ... return JsonResponse(...) def view_1(request): body_unicode = request.body.decode('utf-8') body = json.loads(body_unicode) user_name = body['user_name'] session_key = body['session_key'] # is below code a correct way to validate for user session if request.session['user_name'] == user_name and request.session.session_key == session_key: print('session active') else: print('session expired') -
Modifying django-allauth library
GitHub library: https://github.com/pennersr/django-allauth Package installed using pipenv. I have installed this library and made the settings so that the authentication is working fine. How do I make changes to login and signup html files as I have to add lots more html content on those pages? These files are in the allauth module which is not visible under my project directory as I installed it using pipenv. -
ModuleNotFoundError: "No module named <mymodule>", when deploying to Heroku from Django
When deploying my Django app to Heroku, I get a ModuleNotFoundError that states "no module named 'RealisticEstate'". RealisticEstate is the name of my Django project. The program builds no problem, but when I try to deploy I get the following errors: [2021-05-13 21:35:45 -0400] [15610] [INFO] Starting gunicorn 20.1.0 9:35:45 PM web.1 | [2021-05-13 21:35:45 -0400] [15610] [INFO] Listening at: http://0.0.0.0:5000 (15610) 9:35:45 PM web.1 | [2021-05-13 21:35:45 -0400] [15610] [INFO] Using worker: sync 9:35:45 PM web.1 | [2021-05-13 21:35:45 -0400] [15613] [INFO] Booting worker with pid: 15613 9:35:45 PM web.1 | [2021-05-13 21:35:45 -0400] [15613] [ERROR] Exception in worker process 9:35:45 PM web.1 | Traceback (most recent call last): 9:35:45 PM web.1 | File "/Users/<user>/RealisticEstate/venv/lib/python3.9/site- packages/gunicorn/arbiter.py", line 589, in spawn_worker 9:35:45 PM web.1 | worker.init_process() 9:35:45 PM web.1 | File "/Users/<user>/RealisticEstate/venv/lib/python3.9/site-packages/gunicorn/workers/base.py", line 134, in init_process 9:35:45 PM web.1 | self.load_wsgi() 9:35:45 PM web.1 | File "/Users/<user>/RealisticEstate/venv/lib/python3.9/site-packages/gunicorn/workers/base.py", line 146, in load_wsgi 9:35:45 PM web.1 | self.wsgi = self.app.wsgi() 9:35:45 PM web.1 | File "/Users/<user>/RealisticEstate/venv/lib/python3.9/site-packages/gunicorn/app/base.py", line 67, in wsgi 9:35:45 PM web.1 | self.callable = self.load() 9:35:45 PM web.1 | File "/Users/<user>/RealisticEstate/venv/lib/python3.9/site-packages/gunicorn/app/wsgiapp.py", line 58, in load 9:35:45 PM web.1 | return self.load_wsgiapp() 9:35:45 PM web.1 | File "/Users/<user>/RealisticEstate/venv/lib/python3.9/site-packages/gunicorn/app/wsgiapp.py", line 48, in … -
How can I change a string on swagger url
This String in particular [string to change][1] [1]: https://i.stack.imgur.com/3xn3s.png Class View class ServiceProviderBaseUnityAvaliationsView( mixins.ListModelMixin, mixins.CreateModelMixin, viewsets.GenericViewSet): permission_classes = [permissions.IsAdminUser, ] pagination_class = PageNumberPagination serializer_class = ServiceProviderBaseUnityAvaliationSerializer queryset = ServiceProviderBaseUnityAvaliation.objects.all() def get(self, request, *args, **kwargs): return self.list(request, *args, **kwargs) def post(self, request, *args, **kwargs): return self.create(request, *args, **kwargs) -
Django and JavaScript pagination for SPA - possible to make this without repeating myself?
My website is single page application, 3 different pages. 3 JavaScript functions. 3 Methods in the Django backend ( 1 for each JavaScript function ) My backend methods return paginated posts, each JavaScript function uses fetch from a different URL that works with a different method in the backend I'm trying to add paginate buttons on the frontend, say I've added divs for the buttons, now I'm stuck with solving the problem that how when I click for example on the "next" button to fetch from the right URL again without needing to make a pagination frontend function for each JavaScript with a different fetch URL? I'm trying to do this without repeating myself in more than 1 function. views.py def show_all_web_posts(request): """ Method to return all posts in the database. """ all_web_posts = NewPost.objects.all() all_web_posts = all_web_posts.order_by("-date_added").all() page_number = request.GET.get('page', 1) paginator = Paginator(all_web_posts, 10) current_page_posts = paginator.page(page_number) posts_paginated = current_page_posts.object_list return JsonResponse({ "posts": [website_post.serialize() for website_post in posts_paginated] }, safe=False) def display_profile_posts(request, profile_name): """ Method to return all posts that is related to specific profile. """ try: profile = User.objects.get(username=profile_name) profile_posts = NewPost.objects.filter(poster=profile.id) profile_posts = profile_posts.order_by("-date_added").all() page_number = request.GET.get('page', 1) paginator = Paginator(profile_posts, 10) current_page_posts = paginator.page(page_number) profile_posts_paginated … -
automatic Image resizing for every uploaded images by users
I have a web application that allows user to upload tons of images, My goal is to reduce the hosting fees AWS are going to charge me by shrink the image size users uploaded, Currently i set the limit to 1MB using simple Js, I am not really a frontend developer, So How hard it is to create a javascript solution that automatically shrinks the image size? Is this can be done easily? If not, then my other two options are Django and AWS UI, the backend is Django, But Django can only process the image once it reaches the backend, So if this happens, Would my aws cost increase? Finally it's the AWS solution, I don't know how to do it yet, Maybe using something called lambda? Is it completely free? If it keeps my cost down and easy to set up then this is it? Or would it be wise just to use simple javascript? is this can be easily implemented? like copy and paste code less than 50lines of code then it's automatically solved? -
Djnago reads images without defining MEDIA_URL
I'm new to Django, I know that to display an image I should define MEDIA_URL in the settings but when I tried to remove it and use the {{ img.url }} and still the images are readable and the browser can see it and display it, the question is does this mean that the MEDIA_URL does not import in displaying images -
Django Models: Setting up daily time slots
I’ve been thinking about this for a while, and not getting anywhere. Using Django, I’m trying to set up a time slot reservation web app, but I’m getting hung up on how to set up the models. Essentially, every day of the week would have time slots offered like: 09:00, 09:10, 09:20, 09:30, 09:40, etc. And each of those time slots would include the specified time, date, and count of people. My first try... I was initially thinking I’d make records for every time slot, for every day of the week; then I could query that to display available time slots on the website. That seems really inefficient though, because I’d have to create around 70 entries for each day of the week. My Second Try... Then I was thinking I’d just lay out all of the time slots on the website itself, then when someone reserves one of the slots, save that to the database. However, doing that, I’m not sure how I would then NOT display that time slot on the site. I included a rough mockup below to describe what I'm trying to accomplish. Any ideas that would lead me the right direction would be great. Thanks! … -
When i try to iterate over a RawQuerySet object in django i get "django.db.utils.ProgrammingError: can't adapt type 'dict'"
for example lets say books.objects.raw(....) the (...) are a representation of the sql parameters for example as seen in the django docs https://docs.djangoproject.com/en/3.2/topics/db/sql/#:~:text=Django%20gives%20you%20two%20ways,ORM%20before%20using%20raw%20SQL! when i try to iterate through the above oject like so [print(x) for x in books.ojects.raw(...)] I get this from my logs below django.db.utils.ProgrammingError: can't adapt type 'dict' -
can I use the value of the arguments more than once
My problem is in python/django I want to use the value of my argument entry before passing it on to my function util.get_entry Below is my original code: def display_entry(request, entry): entry = util.get_entry(entry) markdowner = Markdown() context = {'entry': markdowner.convert(entry)} return render(request, "my_app/entry.html", context) I have tried to do: def display_entry(request, entry): title = entry entry = util.get_entry(entry) markdowner = Markdown() context = {'entry': markdowner.convert(entry)} return render(request, "my_app/entry.html", context, title) The goal is to be able to render the title of my page dynamically but it produces unexpected results. I am sure it is something very simple but currently I am not seeing it. Thank you for looking into it. -
Change save method at Admin panel Django
This is my models.py from django.db import models class Post(models.Model): html = models.TextField(editable=False) thumbnail = models.TextField(editable=False) url = models.TextField() This is admin.py from django.contrib import admin from .models import Post class PostAdmin(admin.ModelAdmin): def save_model(self, request, obj, form, change): print("Not working") othermethod() obj.html = "html" obj.save() super().save_model(request, obj, form, change) def othermethod(): print("Not working") admin.site.register(Post) How can I call a function that do something before I save a Post through Django admin panel, this is what I've been trying so far, but doesn't work at all, Post object is saving at the database without 'html' field and "othermethod() function isn't been called". -
How to have pre/post populated id field in django form submissiob
What I am trying to achieve is to have my "student_id" auto-generated field to be part of the form submission in the sense that the "student_id" field does not have to be manually input in form submission: The "student_id" field needs to be either pre-generated upon displaying the form or to be generated upon form submission. I have tried and currently facing error when submitting form as bellow: KeyError at 'student_id' Exception Value: 'student_id' Removing the "student_id = form.cleaned_data['student_id']" syntax in views.py does not help either. I have the following model, which generates an auto "student_id" field class Student(models.Model): student_id = models.AutoField(primary_key=True,unique=True, max_length=10, blank=False) name = models.CharField(max_length=200, blank=False) first_name = models.CharField(max_length=100, blank=True) last_name = models.CharField(max_length=100, blank=True) def __str__(self): return self.name and my forms.py look as bellow: Class StudentForm(forms.ModelForm): class Meta: model = Student fields = [ 'student_id','name', 'first_name', 'last_name' ] And my views.py look as bellow def index(request): if request.method == 'POST': form = StudentForm(request.POST, or None) if form.is_valid(): student_id = form.cleaned_data['student_id'] form.save() else: FormError = StudentForm.errors return redirect(f'/card/{student_id}') else: form = StudentForm() template_name = 'index.html' context = { 'form' : form, } return render(request, template_name, context) {% csrf_token %} <div class="form-group"> {{ form | crispy }} </div> <input type="submit" … -
Mantener un input en todos los Templates
Estoy haciendo la parte de búsqueda para una venta de repuestos. El problema es que no sé como pasar el input entre las direcciones. En views.py tengo ésto: dev home(request): formulario_busqueda=Formulario() // Creo un formulario de 1 sólo input valor=request.GET.get("search") // obtengo el valor que se ingresó al formulario if valor: comp=spare.objects.filter(engine_info__engine_ide__icontains=valor) // Creo un query con todos los repuestos que tengan ese código return(request,"Repuestosapp/home.html",{"form":formulario_busqueda,"spare":comp}) def brand(request,val): test=val brand_id=spare.objects.filter(spare_brand__icontains=test) return render(request,"Repuestosapp/brand.html",{"brand_id":brand_id}) En base.html simplemente tengo: <div class="contform"> <h1>Buscador de repuestos</h1> <form action="" method="GET"> <!-- {% csrf_token %} --> <div class="maintable">{{formulariop.as_table}}</div> <button type="submit" value="enviar">Buscar</button> </form> </div> En home.html tengo un link para redirigir a la marca si deseo clickearla, así: <table> <tr> <th>Code</th> <th>Brand</th> <th>Type</th> <th>Car</th> </tr> {% for spares in spare %} <tr> <th><a href="">{{spares.spare_code}}</a></th> <th><a href="{% url 'brand' spares.spare_brand %}">{{spares.spare_brand}}</a></th> <!-- <th><a name="brand_id" href="brand?brand_id">{{spares.spare_brand}}</a></th> --> <th><a href="">{{spares.spare_name}}</a></th> <th><a href="">{{spares.car_info.car_manufacturer}}</a></th> </tr> {% endfor %} </table> El problema, es que cuando renderiza brand.html, el formulario se pierde, porque en la función en views.py no estoy pasando el formulario. En realidad tengo 2 formularios, pero sólo estoy preguntando por ése. También debo crearle un hyperlink a tipo de repuesto y para eso debo crear otro html. Pero no sé como pasar esos … -
Models are'nt loaded yet error when trying to get object of a model by it's ForeignKey
i have two models like this : class Author(models.Model): name = models.CharField(max_length=100,) code = models.IntegerField(unique = True) class Book(models.Model): title = models.CharField(max_length=100,) author = models.ForeignKey(Author, on_delete=models.PROTECT) And i want to list some Book with specific author and use them in another model like below: class SomeBook(models.Model): books = Book.objects.all().values('title').filter(author__code=20) text = models.TextField(default=books) But i receive the "Models aren't loaded yet" Error. i also tried to use the serializers to get the object in josn format But still the same error appears. I also look at the similar question in here but nothings helped How i can fix this error.