Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Add help_text to UserCreationForm
I'm using UserCreationForm in Django and I'm trying add help_text to the email field. Here's the forms.py code: from django.contrib.auth import get_user_model from django.contrib.auth.forms import UserCreationForm, UserChangeForm class CustomUserCreationForm(UserCreationForm): class Meta(UserCreationForm): model = get_user_model() fields = ('email','username',) help_texts = { 'email': 'Use your work email', } I'm using Crispy Forms to render it and it isn't rendering the help_text. As another approach, I tried adding this to the class: def __init__(self, *args, **kwargs): super(CustomUserCreationForm, self).__init__(*args, **kwargs) self.fields['email'].help_text = 'hello' But it didn't work either. What am I missing? -
How to add custom class and id to UserCreationForm fields?
So,I have fields from the default UserCreationForm. Now, I want to add bootstrap class and id to those fields. How do I do this? I don't wanna install third-party packages(yet).My code -
Django 'dict' object has no attribute 'META' error when using an API
I am trying to get some data from an API but have been getting the error 'dict' object has no attribute 'META' when I try to print it. I am using Requests module for this. Here is the code: url = "https://coronavirus-map.p.rapidapi.com/v1/summary/region" querystring = {"region":"Bangladesh"} headers = { 'x-rapidapi-host': "coronavirus-map.p.rapidapi.com", 'x-rapidapi-key': "leaving this out :P" } request = requests.get(url, headers=headers, params=querystring).json() print(request.text) Everything works on Postman. Can anyone help? -
How to get html form input and save as variable in Python Django
I'm trying to get a simple input(which would be an integer) from the user, and use it as a variable in the next python function. But whenever I try to print the input it prints out "None". Here's my code HTML <form action="/./" method="POST">{% csrf_token %} <input type="text" name="quantity" placeholder="Repeat" size=2> <input type="submit" value="Save!"> </form> Python Django (This is just part of the function.) def saveCriteria(request): title = request.POST.get('quantity') context = {} print(title) return render(request, "home.html", context) Any help or advice would be greatly appreciated! -
How to display category list at django template
I want to display list of category at main(base) page. (mysite is here. http://jgahn.pythonanywhere.com/) When I click the 'Chemistry' category, It took me post list with 'Chemistry' category and display list of category(right side, sky-blue color, chemistry and physics). This is my problem, category list is displayed only when I access some category. I want to display always without any access at category (like sidebar). Here is my view.py from .models import Post, Comment, Category def list_of_post_by_category(request, category_slug): categories = Category.objects.all() posts = Post.objects.filter(published_date__lte=timezone.now()).order_by('-published_date') if category_slug: category = get_object_or_404(Category, slug=category_slug) posts = posts.filter(category=category) template = 'myblog/list_of_post_by_category.html' context = {'categories': categories, 'posts': posts, 'category': category,} return render(request, template, context) This is my main_page.html <p class="taglist"><a href="{% url 'list_of_post_by_category' category.slug %}">{{ category }}</a></p> {% endfor %} list_of_post_by_category.html {% extends 'myblog/main_page.html' %} {% block content %} <h4><span style="color: #ab4a67; font-weight: bold;">{{category.name}}</span> category</h4> <hr> <!--<button class="btn-tag">{{ category.name }}</button>--> {% for post in posts %} <div class="list"> <h6><a href="{% url 'post_detail' pk=post.pk %}" style="text-decoration:none;"> &gt; &nbsp; {{ post.title }}</a> &nbsp; &nbsp; <span class="small">{{ post.published_date|date }} {% if user.is_superuser %} {% if post.comments.count >= 1 %} &nbsp; {{ post.comments.count }} Comments {% endif %} {% endif %} &nbsp; <button class="btn-tag">{{ tag }}</button> </span> </h6> </div> {% … -
How can I resolve the infinite check_resolver loop from the Django resolvers.py when trying to follow the step-by-step polls tutorial?
Hello everyone! I am trying to build my first Django application using the "Writing your first Django app" tutorial, which can be found on the following link: "https://docs.djangoproject.com/en/3.0/intro/tutorial01/". The problem is that when I follow the step-by-step to run the server, i.e. creating the urls.py and views.py and executing the "python manage.py runserver" on the command prompt, the code gets stuck in a infinite loop involving the Django built-in application resolvers.py and my urls.py, which gives me the following error: File "C:\ProgramData\Anaconda3\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver return check_method() File "C:\ProgramData\Anaconda3\lib\site-packages\django\urls\resolvers.py", line 408, in check messages.extend(check_resolver(pattern)) RecursionError: maximum recursion depth exceeded I could not find any kind of answer in the tutorial, neither at others stackoverflow questions. Hope someone can help me and thanks in advance to everyone! -
Graphene Django email scalar in arguments
How to force user to enter correct email? I tried to make a user in GraphQL interface but it allows to enter every string. -
Django models uppercase
i'm a Django site building beginner, i wanna convert an input of my models to uppercase before it's registered in the db. so it's shows in uppercase in administration site, as also in the db. -
How we can make filtered query in schema.py in graphene-django project without using Relay feature?
i am new to back-end programming especially in graphene-django. my question is how can we create filtered query in schema.py in graphene-django project without using Relay feature? i saw this before but i don't want to use Relay feature. rather than i want use a filter, but i don't know how?? now my models.py and schema.py look-like these: *models.py # shoes_store/ingredients/models.py from django.db import models class Category(models.Model): name = models.CharField(max_length=50) notes = models.TextField(default='') def __str__(self): return self.name class Product(models.Model): name = models.CharField(max_length=300) descreption = models.TextField(default='') price = models.CharField(max_length=50, default='') imageURL = models.TextField(default='') category= models.ForeignKey(Category,on_delete=models.CASCADE) def __str__(self): return self.name and schema.py: import graphene from graphene_django.types import DjangoObjectType from shoes_store.ingredients.models import Category, Product class CategoryType(DjangoObjectType): class Meta: model = Category class ProductType(DjangoObjectType): class Meta: model = Product class Query: #=========================== # product products = graphene.List(ProductType) product = graphene.Field(ProductType,product_id=graphene.ID()) def resolve_products(self, info, **kwargs): # Querying a list return Product.objects.all() def resolve_product(self, info, product_id): # Querying a single user return Product.objects.get(pk=product_id) #=========================== # product_category categories = graphene.List(CategoryType) category = graphene.Field(CategoryType,category_id=graphene.ID()) def resolve_categories(self, info, **kwargs): # Querying a list return Category.objects.all() def resolve_category(self, info, category_id): # Querying a single user return Category.objects.get(pk=category_id) -
Django: modalbox with javascript
in my Django Website in the user page there's a list of the items the user added. Next to each of 'em there's a 'Delete' button. When pressed it shows a modal box as confirmation. The problem is that just the first modal box it's shown and not the others. How can it be? thanks a lot! html template: <!-- Inserire il database dell'utente registrato --> {% if object_list %} {% for o in object_list %} <div class="container_band"> <div class=album_band> <!-- insert an image --> {%if o.cover%} <img src= "{{o.cover.url}}" width="100%"> {%endif%} </div> <div class="info_band"> <!-- insert table info --> <table> <tr><th colspan=2><h3>{{o.band}}</h3></th></tr> <tr><td> Anno: </td><td> {{o.anno}} </td></tr> <tr><td> Disco: </td><td> {{o.disco}} </td></tr> <tr><td> Etichetta: </td><td> {{o.etichetta_d}} </td></tr> <tr><td> Matrice: </td><td> {{o.matrice}} </td></tr> </table> </div> <div class="mod"> <table> <tr> <td> <a href="{% url 'edit_info' id=o.id %}"><button type="button" class=" btn btn-default"> UPDATE </button></a> </td> </tr> <tr> <td> <button id="modalBtn" class="button">delete</button> <!--<a href="{% url 'delete_info' id=o.id %}"><button id="modal-btn" type="button" class=" btn btn-default"> DELETE</button></a>--> </td> </tr> </table> <div id="simpleModal" class="modal"> <div class="modal-content"> <span id="close" class="closeBtn">&times;</span> <p> prova modal box </p> </div> </div> </div> </div> {% endfor %} {%endif%} </div> <div class="pagination"> <span class="step-links"> {% if page_obj.has_previous %} <a href="?page=1">&laquo; first</a> <a href="?page={{ page_obj.previous_page_number … -
Handling CRUD models with one to many relation DRF
I appreciate your help I have 2 models with a realation one to many like this class Header(models.Model): title = models.CharField(max_length=35) class Detail(models.Model): header = models.ForeignKey(Header, related_name='details', on_delete=models.PROTECT) description = models.CharField(max_length=35) I would like to know if exist some package that handle internally the CRUD of the details within the header CRUD, for example: If I make a POST to app/header with this JSON: { "title": "title 1" "details":[ { "description": "detail number 1" }, { "description": "detail number 2" } ] } the app should create the header with id = 1 and then the 2 details with ids = 1,2 in the database If I make a PUT to app/header/1 with this JSON: { "id": 1, "title": "title 1 updated" "details":[ { "id": 1, "description": "detail number 1 with a change" }, { "id": 2, "description": "detail number 2" } ] } the app should update the title of the header and the description of the detail with id=1 Then if I make a PUT to app/header/1 with this JSON: { "id": 1, "title": "title 1 updated" "details":[ { "id": 2, "description": "detail number 2" } ] } the app should delete only the detail with id=1 And … -
return to function from another function
i have a table which include all users and two columns at the end (Edit,Delete) and i just enabled the delete column, the issue is when i click on the delete icon the record will be deleted but the url will stuck on the delete function even if i used return render(request,'getUsersInfo.html') which is get all records function Model Name: Users urls: from django.urls import path from django.conf.urls import url from . import views urlpatterns = [ path('signup.html',views.signup,name=''), path('getUsersInfo.html',views.getAllUsers,name=''), url(r'^deleteUser/(?P<fullname>\D+)/$',views.deleteUser, name='deleteUser'), # this is how to call a function without parameters url(r'^deleteUser/$',views.deleteUser, name='deleteUser'), in the same view i have 3 functions (singup "add user", getAllUsers "get all the records to the table,deleteUser) views: def getAllUsers(request): print("getAllUsers") thesearchValue = '' if 'SearchValue' in request.GET: thesearchValue = request.GET['SearchValue'] print(request.GET['SearchValue']) allUsers = User.objects.filter(fullname__icontains=thesearchValue)#all() # return render(request,'getUsersInfo.html',{'allUsers':allUsers}) return render(request,'getUsersInfo.html',{'allUsers':allUsers}) else: print("Empty") allUsers = User.objects.all() return render(request,'getUsersInfo.html',{'allUsers':allUsers}) def deleteUser(request,fullname): print('delete the user') todelete = User.objects.filter(fullname=fullname) todelete.delete() return render(request,'getUsersInfo.html') Notice that i used return render(request,'getUsersInfo.html') which should call getAllUsers(request): but the url stuck on http://127.0.0.1:8000/deleteUser/John/ -
Dynamic form choices not being displayed: DJANGO
I am trying to dynamically add form choices based on a session variable. I have a views.py with a choice form that redirects to my second form (which isn't displaying my choices) views.py: def teacher(request): if request.method == 'GET': form = TeacherForm() else: form = TeacherForm(request.POST) if form.is_valid(): date_list = [] if form.cleaned_data['teacher'] == 'No Preference': for i in Availability.objects.all(): date_list.append(str(i.dates)) request.session['choices'] = tuple(date_list) return redirect('book-appt') context = { 'form': form, } return render(request, 'main/booktchr.html', context) after successful submission of the above view user is sent to another view with another form. On that second view, in the following form's init I try to populate the choices with the stores in the session variable above. forms.py: class BookingForm(forms.Form): def __init__(self,request,*args,**kwargs): super (BookingForm,self).__init__(*args,**kwargs) self.fields['booking_date'].choices = request.session['choices'] booking_date = forms.CharField(widget=forms.Select(attrs={'class': 'form-control'})) However the form is rendered and the choicefield is empty. Any help is much appreciated. I'm not entirely sure this is the best way to achieve what I'm trying to achieve so any other methods are welcome, basically what I am trying to do is set the booking_date choices dynamically based on what is set in the request.session['choices'] variable in the view. thanks -
Duplicate celery tasks
I have an issue with celery task, app is Deployed on Heroku. When i create task, using eta, I getting many duplicated tasks, i think this realated to redis restarted on heroku, and then task will duplicated. Thanks for you answers! $ celery inspect scheduled -> celery@78640d9a-168a-43c4-88f9-8cd4c81ca8b4: OK * {'eta': '2020-04-16T10:21:00+00:00', 'priority': 6, 'request': {'id': '5ea46d5e-a6b3-43bc-9228-73833624e8b2', 'name': 'task_module.tasks.send_reminder', 'args': [41407234, '8'], 'kwargs': {}, 'type': 'task_module.tasks.send_reminder', 'hostname': 'celery@78640d9a-168a-43c4-88f9-8cd4c81ca8b4', 'time_start': None, 'acknowledged': False, 'delivery_info': {'exchange': '', 'routing_key': 'celery', 'priority': 0, 'redelivered': None}, 'worker_pid': None}} * {'eta': '2020-04-16T10:21:00+00:00', 'priority': 6, 'request': {'id': '5ea46d5e-a6b3-43bc-9228-73833624e8b2', 'name': 'task_module.tasks.send_reminder', 'args': [41407234, '8'], 'kwargs': {}, 'type': 'task_module.tasks.send_reminder', 'hostname': 'celery@78640d9a-168a-43c4-88f9-8cd4c81ca8b4', 'time_start': None, 'acknowledged': False, 'delivery_info': {'exchange': '', 'routing_key': 'celery', 'priority': 0, 'redelivered': None}, 'worker_pid': None}} * {'eta': '2020-04-16T10:21:00+00:00', 'priority': 6, 'request': {'id': '5ea46d5e-a6b3-43bc-9228-73833624e8b2', 'name': 'task_module.tasks.send_reminder', 'args': [41407234, '8'], 'kwargs': {}, 'type': 'task_module.tasks.send_reminder', 'hostname': 'celery@78640d9a-168a-43c4-88f9-8cd4c81ca8b4', 'time_start': None, 'acknowledged': False, 'delivery_info': {'exchange': '', 'routing_key': 'celery', 'priority': 0, 'redelivered': None}, 'worker_pid': None}} * {'eta': '2020-04-16T10:21:00+00:00', 'priority': 6, 'request': {'id': '5ea46d5e-a6b3-43bc-9228-73833624e8b2', 'name': 'task_module.tasks.send_reminder', 'args': [41407234, '8'], 'kwargs': {}, 'type': 'task_module.tasks.send_reminder', 'hostname': 'celery@78640d9a-168a-43c4-88f9-8cd4c81ca8b4', 'time_start': None, 'acknowledged': False, 'delivery_info': {'exchange': '', 'routing_key': 'celery', 'priority': 0, 'redelivered': None}, 'worker_pid': None}} * {'eta': '2020-04-16T10:21:00+00:00', 'priority': 6, 'request': {'id': '5ea46d5e-a6b3-43bc-9228-73833624e8b2', 'name': 'task_module.tasks.send_reminder', 'args': [41407234, '8'], 'kwargs': {}, 'type': … -
Issue with redirect in the Django Application
I am pretty new to Django framework. Kindly apologize my ignorance. I am trying to set the language preference on my web-application using the URL: WebURL/home?_lang=fr I am using the following code snippet for the doing the same: if request.GET.get('_lang'): set_the_language_pref(request) print("Redirect to same page") redirect('/home') However, the redirect('/home') does not redirect to the same page. Any idea, if I am missing anything here? -
How do I bring full html code from Django database to template?
so I have a full html code-from !Doctype to -stored in my Django database. I was hoping I could bring them as template, NOT as the raw content displayed on the screen. Here's my models.py class NewsLetter(models.Model): title = CharField(max_length=10) content = TextField() And in the content field, I have stored full html code. In my views.py, from .models import NewsLetter def letter(request, id): thisLetter = NewsLetter.objects.get(pk=id) return render(request, 'letter.html', {'thisLetter' : thisLetter} and finally in my letter.html, {{thisLetter.content}} I do understand why it displays the full html code, not the content. But I have no idea on how to display content instead of raw html code. I very much appreciate your help :) -
how to configure different request body for post and put call for same end point in django-rest-framework
I am using django-rest-framework and for an endpoint (i.e) api/v1/accounts for post-call I need all data should be sent mandatorily and for put call, not all fields are needed only the field that needs to be updated is alone, how can I configure serializer for this, or should I use different serializer for post and put call? -
I need help about Django models' field
In my get_total_cost() function below in the end of Order model what is this self.items, where is it coming from?, we usually give an iterable collection in list comprehensions but I didn't create this anywhere. Here is my models.py from django.db import models from shop.models import Product class Order(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) email = models.EmailField() address = models.CharField(max_length=250) postal_code = model.CharField(max_length=20) city = models.CharField(max_length=100) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) paid = models.BooleanField(default=False) class Meta: ordering = ('-created',) def __str__(self): return 'Order {}'.format(self.id) def get_total_cost(self): return sum(item.get_cost() for item in self.items.all()) class OrderItem(models.Model): order = models.ForeignKey(Order, related_name='items', on_delete=models.CASCADE) product = models.ForeignKey(Product, related_name='order_items', on_delete=modesl.CASCADE) price = models.DecimalField(max_digits=10, decimal_places=2) quantity = models.PositiveIntegerField(default=1) def __str__(self): return '{}'.format(self.id) def get_cost(self): return self.price * self.quantity -
Override django admin model saving action
I have two django models. If i add an entry via django admin to modelA and I save it, then I would like to add the value of modelB-s total field. (total = total + amount) Is there a way to override the save method of django admin? Thx for your further answer! class modelA(models.Model): amount = models.IntegerField(default=0) class modelB(models.Model): total = models.IntegerField(default=0) -
Get data from json form-data and store in database in django
My JSON file : (It's a file) { "user-id": 10009, "rating": 3, "movie_id": 9823 } I need to get the each data separately.so I can store them in database. the JSON file is a form-data. I tried: def post(self, request): data = request.FILES['json_file'] # a = data.read().decode('utf-8') a = json.loads(data) x = a['user-id'] print(x) return Response(x, status=status.HTTP_201_CREATED) The above code is not working and giving me error: the JSON object must be str, not 'InMemoryUploadedFile' How can i get data from JSON file(form-data) and store it's content in database? -
Django For Loop Ajax issue
I want to "div" from one page to another. but only one line appears due to the for loop. i use this code ; <script type="text/javascript"> window.setTimeout(ajaxCall); function ajaxCall() { $.ajax({ cache: true, url: "poll/daily", dataType: "html", success: function (data) { var html2 = $(data).find(".takeleft").html(); $(".pastedivhere").html(html2); }, error: function (request, ajaxOptions, thrownError) { } }); } </script> and my daily.html file {% for polls in poll %} <div class="copythisdiv" id="copythisdiv"> <ul> <li> {{ polls.title }} </li> </ul> </div> {% endfor %} and my index.html page; <div class="pastedivhere"> </div> pastedivhere show only one line. but i go poll/daily.html there are a lot of lines. i think for loop is not working using ajax. How can I transfer all loop information? -
Django container is not entirely waiting for a new postgres container
Ok, so, I'm trying to start a project using Django and docker. The first step is simple, I just want to launch a default django app in container and see the django starting screen in my browser. I also want to hook up a simplest postgres container to run along with it. Everything great. I created a simple image for my app, nothing fancy: FROM python:3.7 RUN mkdir /app COPY requirements.txt /app/ WORKDIR /app RUN pip install -r requirements.txt COPY . /code/ And a docker-compose.yml: version: '3' services: python: build: context: . dockerfile: docker/python/Dockerfile volumes: - .:/app ports: - "8000:8000" depends_on: - db restart: always db: image: postgres:9.5 environment: POSTGRES_USER: cards POSTGRES_DB: cards POSTGRES_PASSWORD: cards As you can see, I'm not even copying any source code into the docker image, I'm mounting a volume for django to read it from host. The problem is when I start the containers, the django server is starting too soon for the postgres to be ready, and psycopg2 throws an OperationalError. Here are the logs, when I start fresh containers: Creating network "backend_default" with the default driver Creating backend_db_1 ... done Creating python ... done Attaching to backend_db_1, python db_1 | The files belonging … -
How to enable CORS for django project in EC2 aws instance?
How to enable CORS in Amazon AWS EC2 instance for Django project. I have developed the project using Docker which I can run in two modes. Developed modes: Development mode: It runs Django's built in server for project and media/staticfiles delivery Production mode: It runs NGINX for project and media/staticfiles delivery I have used CORS_ORIGIN_ALLOW_ALL = True for first option, but I still have following issue Access to XMLHttpRequest at 'http://ec2-18-191-33-108.us-east 2.compute.amazonaws.com:8000/api/achievements/list/' from origin 'http://localhost:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. And I have used following nginx.conf for production mode. # # Wide-open CORS config for nginx # 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; if ($request_method = 'OPTIONS') { add_header 'Access-Control-Allow-Origin' '*'; add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS'; # # Custom headers and headers various browsers *should* be OK with but aren't # add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If- Modified-Since,Cache-Control,Content-Type,Range'; # # Tell client that this pre-flight info is valid for 20 days # add_header 'Access-Control-Max-Age' 1728000; add_header 'Content-Type' 'text/plain; charset=utf-8'; add_header 'Content-Length' 0; return 204; } if ($request_method = 'POST') { add_header 'Access-Control-Allow-Origin' '*'; add_header 'Access-Control-Allow-Methods' 'GET, … -
Check login without refreshing
how I can modify my code that be check login&password without refreshing? Ajax call function in django to check login and password then send .json with result. Next one I want display error in js if result is failed or play animation if it's true. js code: function CheckBeforeSend() { var LoginInput = document.getElementById('flogin'); if(LoginInput.value.match(/^[a-zA-Z]+['.']+[a-zA-Z]+[0-9]+$/) == null) { if(document.getElementById('Windows').childElementCount > 2) { document.getElementById('Windows').children[0].remove(); } AddPicture("paperJsConn"); } else { document.getElementById("button").type = "submit"; $.ajax({ url: 'http://127.0.0.1:8000/', data: $('#login_form').serialize(), type: "POST", async:false, success: function(response) { var CheckingCorrect = response['result']; //if checkingcorrect play func animation. }, error: function(error){ alert('No Connection!'); } }); } } $('#login_form').submit(function(e){ e.preventDefault(); $.post('view-url', $(this).serialize()); }); // this event dont work. views.py: def Logget(request): if request.method == 'POST': login = request.POST.get('flogin') response_data = {} response_data['result'] = 'Failed' lengthBase = UsersLog.objects.count() for i in range(lengthBase): if login == str(UsersLog.objects.get(id=i+1)): password = request.POST.get('lpass', False) if str(password) == str(UsersLog.objects.get(id=i+1).password): response_data['result'] = 'Succes' break return JsonResponse(response_data) return render(request, 'index.html') -
I want to save textarea in Django with space characters
I want to save textarea in Django with space characters. for example I want to be saved like this 1. A BC D E 2. 1000 2000 The result is saved and viewed 1. A BC D E 2. 1000 2000 The source code above is my form. class createPlanForm(forms.ModelForm): class Meta: model = plan_models.Plan fields = [ "title_for_plan", "contents_for_plan", ] widgets = { "title_for_plan": forms.TextInput(attrs={"placeholder": "title"}), "contents_for_plan": forms.Textarea(attrs={"placeholder": "contents"}), } If you have any additional things you need to do in Django, please let me know. I wish you could let me know if there is a way:)