Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Basic Django POST not creating model with sqlite
When I click the submit button, it redirects me to the create model (in this case create record) page, and does not actually create a new model, it doesn't appear in the main page which shows all models that were created. I tried following this tutorial: Link I feel like I did mostly the same things as him, and yet my form submission button does not create my post. The differences between our programs is simply the naming and the number of fields in my model. The user registration form works, but that is using a function based view, this is using a class based view (should still work as far as I know), and there are barely any differences between the model creation html and the user registration html. Here's the model creation form, record_form.html: {% extends "catalog/base.html" %} {% block content %} <h1 class="text py-3 pt-4">Create a Record!</h1> <style> .text { font-size: 40px; font-weight: bold; color: #060007; } </style> <div class="shadow p-3 mb-3 bg-light rounded"> <form class="form" method="POST" action="/catalog/"> {% csrf_token %} <p> <label for="name">Name:</label> {{ form.name }} </p> <p> <label for="description">Description:</label> </p> <p> {{ form.description }} </p> <p> <label for="date_start">Date start:</label> {{ form.date_start }} </p> <p> <label … -
ValueError: "<User: >" needs to have a value for field "id" before this many-to-many relationship can be used?
I haved created customize User model. class User(AbstractUser): mobile = models.CharField(validators=[RegexValidator(regex="^\d{11}$", message="Length has to be 11", code="nomatch")], max_length=11) After the user who’s is_superuser is 0 and is_staff is 1 logs in, when this user who has permission to add users performs the operation of adding a user, the following error occurred. ValueError: "<User: >" needs to have a value for field "id" before this many-to-many relationship can be used. I just created the user model and start django, and don't know what happened, the version of django is 3.0.6 and the xadmin's version is 2.0.1. Later I performed the above operation when django's version is 1.11.11 and xadmin's version is 0.6.1, the operation adding a user is normal executed. please help me to solve this problem, thanks very much! -
How can i to create base class for extend to another class?
How can i to create base class for extend to another class class BaseCustomModelAdmin(admin.ModelAdmin): model = None list_display = [field.name for field in model._meta.get_fields()] search_fields = [field.name for field in model._meta.get_fields()] use like this class BaseCustomModelAdmin(BaseCustomModelAdmin): model = Person -
The view HomePage.views.signin didn't return an HttpResponse object. It returned None instead
this is my views.py file where the signin page is not getting loaded and showing the error while am clicking on signin "The view HomePage.views.signin didn't return an HttpResponse object. It returned None instead." could any one place help me out from django.shortcuts import render from. models import student from django.contrib.auth import authenticate from django.shortcuts import redirect # Create your views here. def HomePage(request): return render(request,'index.html',{'link':"https://cloudbinary.io/"}) def signup(request): return render(request,'signup.html') def register(request): if request.method == 'POST': name =request.POST["name"] email =request.POST["email"] mobile =request.POST["mobile"] Password=request.POST["password"] course =request.POST["course"] if student.objects.filter(Email=email).exists(): messages.info(request,'email already in use') return redirect('signup') else: Student =student(Name=name,Email=email,phone=mobile,Course=course,Password=Password) Student.save() print("user created") return render(request,'signup.html') def signin(request): if request.method=='POST': email1=request.POST['email1'] Password1=request.POST['Password1'] stud=auth.authenticate(Email=email1,Password=Password1) if stud is None: auth.login(request,stud) return redirect("/signin/") else: messages.info(request,'invalid credentials') return redirect('login.html') -
Django: How to Add Default Location for Forms.ImageField
I am changing my models to forms so that I can use a placeholder for my textboxes. In doing so, I am having difficulty changing the ImageField because it is providing me with an error that it recieved ``an unexpected keyword: default``` Here are my models.py: class Project(forms.Form): name = forms.CharField(max_length=30) #owner = models.ForeignKey(User, on_delete=models.CASCADE, null = True) bPic = forms.ImageField(default='defaultproban.jpg', upload_to='project_banner') logo = forms.ImageField(default='defaultlogo.jpg', upload_to='project_logo') dep_choice1 = ( ('Behavioral Sciences and Leadership', ('Behavioral Sciences and Leadership')), ('Chemistry and Life Science', ('Chemistry and Life Science')), ('Civil and Mechanical Engineering', ('Civil and Mechanical Engineering')), ('Electrical Engineering and Comptuer Science', ('Electrical Engineering and Comptuer Science')), ('English and Philosophy', ('English and Philosophy')), ('Foreign Languages', ('Foreign Languages')), ('Geography and Environmental Engineering', ('Geography and Environmental Engineering')), ('History', ('History')), ('Law', ('Law')), ('Mathematical Sciences', ('Mathematical Sciences')), ('Physics and Nuclear Engineering', ('Physics and Nuclear Engineering')), ('Social Sciences', ('Social Sciences')), ('Systems Engineering', ('Systems Engineering')), ('Independent', ('Independent')), ) department = forms.CharField( max_length=50, choices=dep_choice1, default='Independent', ) purpose = forms.CharField(max_length=50, null = True, widget=forms.TextInput(attrs={'placeholder':'Write Your Mission Statement'})) description=forms.TextField(widget=forms.TextInput(attrs={'placeholder':'Briefly Describe Your Project, Progress, Goals, and Your Team!'})) tag_choice = ( ('Data Analysis' , ('Data Analysis')), ('3D Printing' , ('3D Printing')), ('Robotics' , ('Robotics')), ('Coding' , ('Coding')), ('Science' , ('Science')), ('Drones' , ('Drones')), ('Math' … -
DRF get field from other serizalizer
I'm trying to solve my previous question : drf ordering by custom field and add ranking in to_representation My idea now is create an nullable field in model (db), so that I could try to store the custom field into the nuallable field and then sort it by nullable field in viewset not serizalizer. However how could I pass the value to this nullable empty field in serizalizer? the nullable field I define is weekly_score and here is the code: def get_weekly_score(self,instance): data = super().to_representation(instance) rankings = data.pop('rankings', None) result=0 if rankings: popscore_sum = 0 counter = 0 for value in rankings: for key, value in rankings[counter].items(): isFloat = isinstance(value, float) if isFloat: popscore_sum += value counter += 1 result = popscore_sum / counter return result However it give error Django:“RuntimeError: maximum recursion depth exceeded” -
Is something wrong with the password change page on Django admin?
Using Django 3.16, going into the admin console and managing a user (admin/auth/user/412/change/ in the example of user id 412), I attempt to change the user password by clicking on the link "you can change the password using this form". But when I click on the link I get the error "User with ID "412/password". It's like the URL settings aren't pulling the PK/ID out of the URL properly. (You'll see I'm using the Grappelli styling for the admin console. I've tested it without Grappelli and I get the same errors.) My urls.py has the usual line path('admin/', admin.site.urls). Is there some reason why this might be happening, or something I can do about it? thanks John -
Django custon form with validate
I have some problem with the form and Django. I would like to do a custom (in column and with style) form from a model. But after few hours to try I thinks it's not possible. So I decide to create not a forms.ModelForm but a forms.Form, in order to custom my form. But in this way i can't keep the validations... And last thing I try, it in the template file to write a validation manually, it's work but when I submit my form with error, and when it's refresh, all the data are loose, and I see just the error message... So it make me crazy... I just would like to do a nice form with django... Thanks in advance forms.py class PatienceForm(forms.ModelForm): class Meta: model = Patience fields = ('nom', 'prenom', 'age', 'email') template.html <form method="POST" accept-charset="utf-8"> {% csrf_token %} <p><label for="id_nom">Nom :</label> <input type="text" name="nom" maxlength="200" required id="id_nom"></p> <p><label for="id_prenom">Prenom :</label> <input type="text" name="prenom" maxlength="200" required id="id_prenom"></p> <p><label for="id_age">Age :</label> <input type="number" name="age" required id="id_age"></p> <p><label for="id_email">Email :</label> <input type="email" name="email" maxlength="254" required id="id_email"></p> {% for err in form.email.errors %} {{err}} {% endfor %} <button type="submit" class="save btn btn-default">Save</button> view.py def post_essaie(request): if request.method == "POST": … -
django class ListView is not displaying and data
I wanted to see how ListView class is working, but I couldn't display any data. I checked everything multiple times, but I can find my mistake. Any help is appreciated. view: class ViewListView(LoginRequiredMixin, ListView): template_name = 'realestateads.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['latest_realestate_ads'] = AdRealEstate.objects.order_by('-publish_date')[:5] return context HTML: {% if latest_realestate_ads %} {% for ad in latest_realestate_ads %} <!-- BLOCK POST --> <div id="div_block"> <a href="#" class = "post_hover" style = "width:100%;"> <div id="estate-posts-block"> <div class="estate-post-block-content"> <table> <tr> <td>Title</td> <td class = "par_space"><span>{{ ad.title }}</span></td> </tr> <tr> <td>Location</td> <td class = "par_space"><i class="fas fa-map-marker-alt"></i>&nbsp;<span class = "cont_space">{{ ad.address }}</span></td> </tr> <tr> <td>Contact</td> <td class = "par_space"><i class="fas fa-bed"></i><span class = "cont_space">{{ ad.phone}}</span></td> </tr> <tr> <td>Type</td> <td class = "par_space"><i class="fas fa-city">&nbsp;</i><span class = "cont_space">On Sale</span></td> </tr> </table> </div> </div> </a> </div> <!-- END BLOCK POST--> {% endfor %} {% else %} <p>No data</p> {% endif %} -
How to pass Django DateTimeField inside POST method of contact form
I create an contact-form using Django models. I added DateTimeField in my models.py file so that I can see the date-time when the contact-form was submitted. After added DateTimeField in my models.py. I am getting this error in admin panel when click on contact model: NOT NULL constraint failed: contact_contact.current_time and getting this error when clicking submit button: ['“” value has an invalid format. It must be in YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format.'] I run makemigrations and migrate after adding the DateTimeField in models.py and didn't get any error massage while running makemigrations and migrate. >>python manage.py makemigrations No changes detected >> python manage.py migrate Operations to perform: Apply all migrations: admin, auth, contenttypes, sessions Running migrations: No migrations to apply. #my models.py file from django.db import models import datetime # Create your models here. class Contact(models.Model): current_time = models.DateTimeField(blank=True, null=True,default=datetime.date.today) name =models.CharField(max_length=100) email =models.EmailField(max_length=100) message = models.TextField(max_length=2000) #my forms.py file from django.forms import ModelForm from .models import Contact class ContactForm(ModelForm): class Meta: model = Contact fields = ['name','email','message',] def clean(self): # data from the form is fetched using super function super(ContactForm, self).clean() # extract the username and text field from the data name = self.cleaned_data.get('name') if len(name) < 5: self._errors['username'] = … -
PWA - Cannot log out
I am unable to logout in a web application due to caching via service worker, how may I solve this? I have tried ignoring certain pages for caching but that does not seem to work. I am not sure what to do. -
How can I run an async function from a django view to run in the background while I process requests in the main loop?
As I said in the title, I want a task to run in the background processing a large database query while I handle requests from my frontend. Can I even do that with async/asyncio? I was told it was possible... For the purpose of context, I would like to do something like the following. Note also that I don't really need the function to tell me when it's done (though I'd sure like to know if it's possible) since I just check if the .json file was finally written. def post_data_view(request): if request.method == 'POST': ... do_long_query_in_the_background(some_data) return HttpResponse('Received. Ask me in a while if I finished.') def is_it_done_view(request): if request.method == 'GET': data = find_json() if data: return JsonResponse(data) else: return HttpResponse('Not yet dude...') async def do_long_query_in_the_background(data): # do some long processing... # dump the result to a result.json return I was told this was possible with async but I really find it hard to understand. For context, I tried to simplify this a lot, and even then I found I didn't quite understand what was happening: async def f(): while True: print(0) await asyncio.sleep(2) asyncio.create_task(f()) even this code I tried fails sys:1: RuntimeWarning: coroutine 'f' was never awaited, … -
python socketio - open packet not returned by the server
I am trying to connect to a socket server (node.js) say http://localhost:4300. On the server side it has been successfully connected, on my server's log client connected {client_id} but on my client side (python-socketio client) it returns exceptions OPEN Packet not returned by the server Could anyone please help me explain why I got this exceptions? I have been doing what the docs said. -
" Django " category in div id
Hi I have to use Python and Django for our application. I get categories slugs for div id but not working What do you think? I put the required code at the bottom. view.py def my_grouper(n, iterable): args = [iter(iterable)] * n return ([e for e in t if e is not None] for t in itertools.zip_longest(*args)) def home_page(request): sliders = Sliders.objects.get_active_slider().first() projects = Projects.objects.get_active_projects() projects_category = ProjectsCategory.objects.get_active_projects_category() grouped_projects = list(my_grouper(4, projects)) context = { 'slider': sliders, 'projects': grouped_projects, 'projects_category': projects_category } return render(request, 'tarahan/home-page.html', context) list category template {% for category in projects_category %} <li class="p-tab-btn" data-tab="#{{ category.slug }}">{{ category.title }}</li> {% endfor %} for loop for get item {% for project_list in projects %} <div class="p-tab" id="{% for project in project_list %}{{ project.categories.first.slug }}{% endfor %}"> <div class="project-carousel owl-theme owl-carousel"> <!--Gallery Item--> {% for project in project_list %} <div class="gallery-item"> <div class="inner-box"> <figure class="image-box"><img src="{{ project.image.url }}" alt="{{ project.categories.first.slug }}"> </figure> <!--Overlay Box--> <div class="overlay-box"> <div class="overlay-inner"> <div class="content"> <a href="{{ project.image.url }}" class="lightbox-image image-link" data-fancybox-group="example-gallery" title=""><span class="icon fa fa-expand"></span></a> <a href="{{ project.get_url }}" class="image-link"><span class="icon fa fa-link"></span></a> </div> </div> </div> </div> </div> {% endfor %} </div> </div> {% endfor %} thanks -
i am getting a Python Error: list index out of range
i am trying to loop through a 2d array to append the first item to a different list. When i try to loop through and append it gives an error. error: list index out of range here is the code #there is a loop that creates a 2d array that goes like this [[object, int], [object, int], [object, int]] sorted_list = sorted(temp_list, key=lambda x: x[1], reverse=True) #the above code sorts this list by the second value in the inner arrays of the 2d array for x in sorted_list: y = x[0] post_list.append(y) #the above code loops through the sorted list and should append the first value of each inner list #to the list post_list note that if i change the loop to: for x in sorted_list: print(x[0]) then it doesn't give an error, it just outputs this object object object why am i getting the out of range error? -
REST API versioning pattern guide
I am writing huge Rest API, to make it easily discoverable, i am making the pattern like this way. http://127.0.0.1:8000/membership/api/v1/make-a-payment But i notice poeple used to make the pattern like this way: http://127.0.0.1:8000/ap/v1/blabla Can you anyone tell me what is the best practice? is it ok writing pattern like this way? http://127.0.0.1:8000/membership/api/v1/make-a-payment ? I just trying to make it easily discoverable by swegger docs. What is your opinion? -
DRF Update price of a product via Viewset Interface
My model for this is straight simple, but I fail to create a "handsome" interface on the ViewSet Template: class Product(models.Model): id = models.PositiveIntegerField(unique = True) price = models.DecimalField(Price, default = 0) name = models.CharField("name", max_length = 128) I created a serializer: class ProductSerializer(serializers.ModelSerializer): class Meta: model = Product fields = ["id", "name", "price"] and I added a ViewSet: class LoadPageViewSet(viewsets.ViewSet): serializer_class = ProductSerializer http_methods = ["get", "put"] def list(self, request): query = Product.objects.all() results = ProductSerializer(data = query, many = True) results.is_valid() return Response(data = results.data, status = status.HTTP_200_OK) def put(self, request): serializer = LoadPageSerializer(data = request.data) if serializer.is_valid(): P = Product.objects.get(id = request.data["id"]) P.price = request.data["price"] P.save() return Response(serializer.data, status = status.HTTP_200_OK) return return Response(serializer.data, status = status.HTTP_400_BAD_REQUEST) If I execute this, when I choose a new price I run into the unique constraint of the id field: product with this id already exists.. -
Setting Djando field default value based on another field
I am creating a Django model where: expirationTimeStamp field's default value is based on creationTimeStamp isLive boolean field value is based on expirationTimeStamp I have written the following functions expirationTimeCalculation and postLiveStatus and assigned them as default values to the fields but I am getting error. I have also tried to assign to respective fields through property(function) yet I am still getting error. One of the functionality that I need to implement is that user can send custom expirationTimeStamp as well that would override default value, therefore, I believe property(function) assignment is not ideal for expirationTimeStamp field. Is there any other way that I can go about to set the expirationTimeStamp field value based on creationTimeStamp field? Any feedback is appreciated! class Posts(models.Model): def expirationTimeCalculation(self): EXPIRATION_DURATION = 86400 #time in seconds expirationTime = self.creationTimestamp + timedelta(seconds = EXPIRATION_DURATION) return expirationTime def postLiveStatus(self): return (self.expirationTimestamp > timezone.now) message = models.TextField() creationTimestamp = models.DateTimeField(default=timezone.now) expirationTimestamp = models.DateTimeField(default=expirationTimeCalculation) isLive = models.BooleanField(default=postLiveStatus) -
testdriven.io Tutorial broke: Dockerizing Django with Postgres, Gunicorn, and Nginx
https://testdriven.io/blog/dockerizing-django-with-postgres-gunicorn-and-nginx/ Learning Fullstack. Have done a little Docker, a lot of python, but no NGINX stuff. 60% through this tutorial I am failing at the end of NGINX section. The Nginx container builds and starts with the other two but stops immediately. And I of'course get a 404 on the localhost and port specified. Just to eliminate any screwy localhost issues on my Mac, I ran an Nginx container directly from the Docker command.... docker run -p 80:80 nginx It ran fine. No so with my tutorial project. The project is literally bog standard from the tut, but here are some specifics. docker-compose.prod.yml: version: '3.7' services: web: build: context: ./app dockerfile: Dockerfile.prod command: gunicorn hello_django.wsgi:application --bind 0.0.0.0:8000 expose: - 8000 env_file: - ./.env.prod depends_on: - db nginx: build: ./nginx ports: - 1337:80 depends_on: - web db: image: postgres:12.0-alpine volumes: - postgres_data:/var/lib/postgresql/data/ env_file: - ./.env.prod.db volumes: postgres_data: nginx/Dockerfile - FROM nginx:1.19.0-alpine RUN rm /etc/nginx/conf.d/default.conf COPY nginx.conf /etc/nginx/conf.d nginx/nginx.conf upstream hello_django { server web:8000; } server { listen 80; location / { proxy_pass http://hello_django; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; } } -
DRF ViewSet: Change appearance of field
I have a model like this: ## model: class Product(models.Model): id = models.PositiveIntegerField(unique = True) price = models.ForeignKey(Price, on_delete = models.CASCADE, null = True, blank = True) ## serializer: class ProductSerializer(serializers.ModelSerializer): class Meta: model = Product fields = ["id", "price",] which shows up in the template of the API like this: I get, this is because of the nature of the model field type. Two questions here: Can I get rid of the little arrows somehow and make a normal field? Could I somehow return a list of all Product ids like for the price? Something like ids = Product.objects.values_list("id", flat = True) or so? -
Django Blog, Only Update Publish Date if not Already Published
So I've built a very basic blog in Django. I have been working on adding a new feature allowing me to save a new post as a draft to publish later, or to unpublish an already published post. I'm fairly new to Django/Python, so perhaps I'm making a novice mistake here. To achieve this, I've added two fields to my Post model. A BooleanField named published and a DateTimeField named publish_date. I only ever want publish_date to update when publish is set to True & was previously False. The approach I've taken is to override the save() method of my Post model. Within the method, I am either setting publish_date to None (if published is unchecked on the form) or I am setting publish_date to timezone.now() (if published is checked on the form). This approach is okay, although publish_date will be updated everytime the post is updated, even if it has not been unpublished/republished. This cannot happen. I'm still learning about the interactions between views, models, and forms, so I really appreciate any guidance. Please take a look at all relevant code and let me know of a better approach to solving this. Thank you for your help! models.py class … -
'str' object has no attribute 'match_key' when sorting dictionary
Full error: 'str' object has no attribute 'match_key' I am trying to sort a dictionary by the values of one of the keys in the objects but I am running into errors whem doing so. What is the best way to do this kind of sort? Code: x = { 'id': f'{item.id}', 'post': item, 'match_key': match_percentage } temp_dict.update(x) sorted_dict = sorted(temp_dict, key=operator.attrgetter('match_key')) -
How do you add a text placeholder without changing the model to a form?
So this this post shows how you would use a placeholder for a textfield if you wanted to change the model to a form. But if I want to keep the model as a model so that I don't need to write a form, how can I add a placeholder in the textbox that disappears when the user clicks it? Here's my current model: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) firstName = models.CharField(max_length = 25, null=False, blank=False, default="Enter your first name") I want to switch default to blank and add "Enter your first name" as a placeholder so the user doesn't need to delete the text when he or she wants to fill in the information. However, I don't want to turn it into a form. -
How can I automatically add a Django command to each log?
Right now I have a Django command named log_test. class Command(BaseCommand): help = '' def handle(self, *args, **options): logging.info("This is a log test") My log formatter looks like this 'formatters': { 'standard': { 'format': '%(message)s [%(request_id)s]{%(user_id)s}' }, }, So when I run python manage.py log_test the above function will log This is a log test [abc]{12} I would like to update this so that the log reads This is a log test [abc]{12} script=log_test Is there an easy way to do this using Django? In summary want each log that originated from a Django command to also log the name of the Django command. -
Django forgot password email giving invalid token on Mac and iPad
I have a Django application running on a Windows server. I have used the "Forgot Password" option numerous times without a problem. A user complained that on a Mac using Firefox, she got an invalid token when she clicked on the link in the password reset email. I could not duplicate it on my Windows PC using Chrome or Firefox. However, I tried it on an iPad, and I got the same behavior as she (I don't have a Mac to try). I tried it several times with the same result. The link in the email that I send looks like this: https://{{ domain }}{% url 'password_reset_confirm' uidb64=uid token=token %} I opened the same email from my Windows PC, and that link in my password reset email worked without a hitch (it generates a reset page with the address "https://myserver.com/reset/MTE/set-password/"). My ipad gets to the same page, but with an invalid token. Does anyone know what might be going on here and how to fix it? Thanks-- Al