Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Use AWS S3 as django storage backend partially
Is there any way to upload some of my DJango media files to AWS S3? Yes, I am aware of the django-storages library but that sets my default storage location to S3. I want to accomplish a hybrid of both S3 and local storage. Is it possible? -
Django request.user will return wrong results when many people use my website at the same time
I'm using Django 3.1, now I'm facing a problem that when many people use my website at the same time, request.user will return wrong results sometimes, but when you clicked next page it will return normal, which is very strange. I guess there'are something wrong in sessions. I have already checked the documents but I don't know what to do :( -
ConnectionResetError: [Errno 54] Connection reset by peer in Django
I am running my django site still on my development folder. I have started getting this error. Which I am not sure what the cause is. The site does load with all the images and styling but I can't get rid of this. I am not sure if this is causing more issues in my site. This is the error in the terminal Settings.py file Debug set to True -
Need help in django project
I have developed a student website using django which includes a database(MySQL), so now I want to run this django project in another system, so how can I run this django project in another system including the database(that is MySQL) -
Got AttributeError when attempting to get a value for field `text` on serializer `CommentSerializer`
I am using Django Rest Framework to make a Blog API. But I have been getting this error when I search for individual comments under each post. The model, serializers and views for Comments is given below: Models.py class Comment(models.Model) : text = models.TextField( validators=[MinLengthValidator(3, "Comment must be greater than 3 characters")] ) post = models.ForeignKey(Post, on_delete=models.CASCADE) owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) # Shows up in the admin list def __str__(self): return (self.post.title) Serializers.py class CommentSerializer(serializers.ModelSerializer): owner = serializers.StringRelatedField() post = serializers.StringRelatedField() class Meta: model = Comment fields = ['text', 'created_at', 'post', 'owner'] Views.py class CommentViewSet(viewsets.ModelViewSet): serializer_class = CommentSerializer permission_classes = [permissions.IsAuthenticatedOrReadOnly] def get_object(self, queryset = None, **kwargs): item = self.kwargs.get('pk') return get_list_or_404(Comment, post = item) def get_queryset(self): return Comment.objects.all() Whenever I go to http://localhost:8000/api/comments/1/ this is what happens. Got AttributeError when attempting to get a value for field `text` on serializer `CommentSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `list` instance. Original exception text was: 'list' object has no attribute 'text'. -
Django AWS MySQL
I tried to deploy my application on AWS, but I'm having problems! First, when trying to put MySQL data in settings.py, a problem appears: "Unknown MySQL server host 'myapp.us-east-1.rds.amazonaws.com' I tried with other databases (Postgresql and Oracle) and they worked, but mysql did not. Does anyone know how to solve? I would be grateful. Gratitude. -
how do i fix django Password reset error 200 1903 & 302 0
It gives me the following error and shuts down the program. [05/Feb/2021 19:41:25] "GET / HTTP/1.1" 200 25 [05/Feb/2021 19:41:35] "GET /reset_password/ HTTP/1.1" 200 1903 [05/Feb/2021 19:41:41] "POST /reset_password/ HTTP/1.1" 302 0 My URLS: path('reset_password/', auth_views.PasswordResetView.as_view(), name="reset_password"), path('reset_password_sent/', auth_views.PasswordResetDoneView.as_view(), name="password_reset_done"), path('reset/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(), name="password_reset_confirm"), path('reset_password_complete/', auth_views.PasswordResetCompleteView.as_view(), name="password_reset_complete") and setting.py EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = '****@gmail.com' EMAIL_HOST_PASSWORD = '********' I have allowed less secure apps on Gmail, but it still gives this error! -
Django query with inner join
With these models: class Categoria(models.Model): titolo=models.CharField(max_length=128, default="unavailable") class Oggetto(models.Model): titolo=models.CharField(max_length=128) desc=models.TextField() url_img=models.URLField() id_categoria=models.ForeignKey(Categoria,on_delete=models.CASCADE,related_name="categoria", default=False) I try this : qs=Oggetto.objects.filter(id=12).select_related().values() to have a SQL : SELECT Oggetto.*,Categoria.titolo FROM Oggetto INNER JOIN Categoria ON (Oggetto.id_categoria=Categoria.id) WHERE Oggetto.id=12 The output (wrong) is : QuerySet [{'id': 12, 'titolo': 'abc', 'desc': 'abc', 'url_img': '', 'id_categoria_id': 1}] -
post to django API returns 403 (Forbidden) when authenticated, but able post when not authenticated
I'm building an app that works as follows: Users fill out data on an html form and submit. the data is posted onto the API (via Fetch). This app uses django, django rest frame work with plain html and vanilla jav My issue is that when the user is authenticated on the API/backend, I cannot post. It returns 403. However, when I am not authenticated I can post data from the form. Here is the JS on the form.html that posts data into the API: <script> console.log('js linked') function getCookie(name) { var cookieValue = null; if (document.cookie && document.cookie !== '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = cookies[i].trim(); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } var csrftoken = getCookie('csrftoken'); console.log(csrftoken) function post_report(event) { event.preventDefault(); var contact_email = document.getElementById("contact_email").value var contact_number = document.getElementById("contact_number").value var date_time = document.getElementById("date_time").value var location = document.getElementById("location").value var description = document.getElementById("description").value console.log(contact_email + ' ' + description) fetch("http://127.0.0.1:8000/api/Flight_Safety_Reports/",{ method: "POST", mode: 'same-origin', headers:{ "Accept": "application/json", 'Content-Type':'application/json', 'X-CSRFToken': csrftoken }, … -
Django cannot read data from MySQL database after moving it to another VPS
I'm writing as I'm stuck with a task that's keeping me busy for a long time now. Basically I have a Django app hosted at Pythonanywhere, and I would like to move it to DigitalOcean VPS. I've set up the APP on Digital Ocean and it works correctly, static files are loaded and I can see it if I visit the new IP. What I'm stuck at is when I need to move the data in MySQL from Pythonanywhere to DigitalOcean. Django is not reading the data and my app is empty. Here's what I've done: Did a mysqldump on the DB on Pythonanywhere Used the backup to create the same tables and same data in the new DB on DigitalOcean Checked that the tables are correctly present in the new VPS's MySQL. Here's the tables on DigitalOcean: +----------------------------+ | Tables_in_mysitedb | +----------------------------+ | auth_group | | auth_group_permissions | | auth_permission | | auth_user | | auth_user_groups | | auth_user_user_permissions | | blog_category | | blog_post | | blog_post_productos | | django_admin_log | | django_content_type | | django_migrations | | django_redirect | | django_session | | django_site | | pages_homepage | | productos_product | | productos_product_tags | | productos_tag | … -
Both buttons are appearing when only one is supposed to
So it is supposed to show remove from cart when user has that item in their cart and add to cart when they don't, I am trying to use django template language for this but both buttons are appearing anyway, home function handles the page i am talking about, It passes all the variables to home.html. home.html <h1>Here are products</h1> <h1>{{ error }}</h1> <h1>Your cart currently costs ${{ price }}</h1> {% for book in books %} <h3>{{ book.name }}</h3> <img src= "/media/{{ book.image }}" alt=""> <p>{{ book.description }}</p> {% for usercart in cart %} {% if book == usercart.book %} <form method="POST" action="/removefromcartforhome/"> {% csrf_token %} <button type="submit" name="removeid" value="{{ book.id }}">remove item from cart</button> </form> {% else %} <form method="POST" action="/addtocartforhome/"> {% csrf_token %} <button type="submit" name="bookid" value="{{ book.id }}">Add to cart</button> </form> {% endif %} {% endfor %} {% endfor %} views.py from django.shortcuts import render, redirect from django.contrib.auth.forms import UserCreationForm, AuthenticationForm from django.contrib.auth.models import User from django.contrib.auth import login, logout, authenticate from django.db import IntegrityError from .models import Book, CartItem, OrderItem from django.contrib.auth.decorators import login_required from .forms import BookForm from django.core.exceptions import ObjectDoesNotExist import random # Create your views here. removederror = '' def calculate(request): oof = … -
How to add another field if some choice is taken in django?
I've problem I'm stuck for month. I have a field like this problem_choice = ( ("a", 'A'), ("a", 'B'), ) group = models.CharField(choices=problem_choice, on_delete=models.CASCADE) If "A" is choosen, I want to have field of something chosen_a = models.Charfield(choices=a_choices) and If user choosen choice"B" I dont want to have that any another field. I've already ask similar problem with no reply How can i add choice if some choice is choosen in django? I'm still stuck. Thank you for your help. -
I am not able to get data from Form (DJANGO)
I am not able to get data from forms the code is in python and im using django framework i just want to get data from form when submited FORMS.py from django import forms class NewProject(forms.Form): project = forms.CharField(label='New Project') url = forms.CharField(label='Project url') description = forms.CharField(label='Description') ADD.html <form action='{% url "home" %}' method='POST'> {% csrf_token %} {{form.as_p }} <input type='submit'> </form> VIEWS.py from .forms import NewProject def Add(request): if request.method == 'POST': form = NewProject(request.POST) if form.is_valid(): url = form.cleaned_data['url'] description = form.cleaned_data['description'] print(url,description) return HttpResponse(name) else: return render(request,'tasks/add.html',{ "form":form }) return render(request,'base/add.html',{ 'form':NewProject(), }) -
How to use <int:pk> in class-based general views
bookinstance_form.html {% extends "catalog/base_generic.html" %} {% block content %} <form action="" method="post"> {% csrf_token %} <table> {{ form.as_table }} </table> <input type="submit" value="Submit" /> </form> {% endblock %} urls.py path('bookinstance/create/', views.BookInstanceCreate.as_view(), name='bookinstance_create'), path('bookinstance/<uuid:pk>/update/', views.BookInstanceUpdate.as_view(), name='bookinstance_update'), path('bookinstance/<uuid:pk>/delete/', views.BookInstanceDelete.as_view(), name='bookinstance_delete'), views.py class BookInstanceCreate(CreateView): model = BookInstance fields = '__all__' class BookInstanceUpdate(UpdateView): model = BookInstance fields = '__all__' class BookInstanceDelete(DeleteView): model = BookInstance success_url = reverse_lazy('catalog:books') https://developer.mozilla.org/zh-CN/docs/Learn/Server-side/Django/Forms has all course How to use int:pk in class-based general views, adding bookinstance needs to be associated with Book, so I need to know book.id, but I don't know how to write it in views.BookInstanceCreate. -
Override Django (DRF) Serializer object GET
I'm trying to "inject" some raw sql into my DRF nested Serializer: # SERIALIZERS class CarSerializer(serializers.ModelSerializer): class Meta: model = Car fields = '__all__' class DriverSerializer(serializers.ModelSerializer): car = CarSerializer() # <--- here I don't want to get the Car object but rather inject a raw sql. class Meta: model = Driver fields = '__all__' The SQL injection is needed to request for a specific version of the data since I'm using MariaDB versioning tables but this is not relevant. How do I override the method that gets the object from CarSerializer? Thank you. -
Access django model, in diferrent app, which uses different router?
I have 2 apps, each using a different schema, the schema being specified with a router : ex: DATABASES = { 'DB1': { 'OPTIONS': { 'options': '-c search_path=schema1' }, }, 'DB2': { 'OPTIONS': { 'options': '-c search_path=schema2' }, }, } DATABASE_ROUTERS = [ 'database_routers.router.Router1', 'database_routers.router.Router2', ] If I try to access a model in app2 from app1 I get relation "schemaname.tablename" does not exist. If I create tablename in schema1 I don't get the error. So I assume app1 searches in it's own schema. How can I specify the model is in a different schema ? -
I want to add product in cart without refreshing page with AJAX and Django
Nothing will ne happened when I submit product in the the cart. I want to use AJAX without refreshing page. When I submit the console message will be displayed. I'm trying to use AJAX first. Trying to add product in the cart without refreshing page. I need help please :) Views Django def add_cart(request, product_id): cart = Cart(request) product = get_object_or_404(Product, id=product_id) form = CartProductForm(request.POST) if form.is_valid(): cd = form.cleaned_data cart.add(product=product, quantity=cd['quantity'], update_quantity=cd['update_qt'] ) return JsonResponse({'status': 'success'}) Form from django import forms from django.core.validators import MinValueValidator, MaxValueValidator class CartProductForm(forms.Form): quantity = forms.IntegerField(initial=1) update_qt = forms.BooleanField(required=False, initial=False, widget=forms.HiddenInput) HTML Code <form action="{% url "..." %}" method="post" data-id="{{ ... }}" class="form-order" id="form"> {{ cart_product_form }} {% csrf_token %} <a data-id="{{ ... }}" class="buy-product"><button>BUY</button></a> </form> JS Code $(".buy-product").on('click', function(){ var product_id = $(this).attr('data-id') var quantity = 1 console.log(product_id) console.log(quantity) data = { 'product_id': product_id, 'quantity': quantity } var point='/cart/add/'+product_id+'/' $.ajax({ headers:{ 'Content-Type':'application/json', 'X-CSRFToken':csrftoken, }, url: point, type: 'POST', data: data, success: function(data){ console.log('success') console.log(csrftoken) } }) }) -
Django sending emails with links is not working
I am trying to send a mail with an attached link in Django. my views.py: def mail_report(request, pk): admin_objs = Admin.objects.order_by() Report_obj = Report.objects.filter(pk=pk).first() to = [] for i in admin_objs: to.append(i.email) mail_report_dict = { 'report' : Report_obj, } html_content = render_to_string("app/mail_report.html", mail_report_dict) text_content = strip_tags(html_content) email = EmailMultiAlternatives( "Industry Inspection Report from Project Surokkha", text_content, settings.EMAIL_HOST_USER, to ) email.send() return redirect('app:index') my template: <!DOCTYPE html> {% load static %} <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> </head> <body> <h3>Hello Admin,</h3> <p> Inspection Report of {{ report.name }} </p> <p> Please check the report: <a href="https://html2canvas.hertzen.com/configuration" style="color: skyblue;"> report link </a> </p> </body> </html> But when The mail received, there is no hyperlink present with the word report link. N.B.: I check the mail_report.html in my browser also, that contains the link perfectly. How can I fix this? -
Cant filter objects with uuid foreign key Django
I have two models class MixCompetitionTag(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) mixCompetitionId = models.ForeignKey(MixCompetition, models.CASCADE, db_column='mix_competition_id') mixId = models.ForeignKey(Mix, models.CASCADE, db_column='mix_id') win_place = models.IntegerField() class MixCompetitionTagLike(models.Model): userId = models.ForeignKey(Useremail, models.CASCADE, db_column='user_id') mixCompetitionId = models.ForeignKey(MixCompetitionTag, models.CASCADE, db_column='mix_competition_id') And when I try to count second model instances, like that: tagId = MixCompetitionTag.objects.get(mixId_id=mix['id'], mixCompetitionId_id=competId) mix['likeCount'] = MixCompetitionTagLike.objects.filter(mixCompetitionId=tagId).count() It gives me error operator does not exist: integer = uuid LINE 1: ...bacos_mixcompetitiontaglike"."mix_competition_id" = 'f0ac09b... ^ HINT: No operator matches the given name and argument types. You might need to add explicit type casts. I can see Django transforming it into ('SELECT COUNT(*) AS "__count" FROM "brandstobacos_mixcompetitiontaglike" ' 'WHERE "brandstobacos_mixcompetitiontaglike"."mix_competition_id" = %s') I tried to make first table Id to be int, but it didn't help. How do I solve that or what am I doing wrong? -
"NoReverseMatch at /user/" but for an other url path called '"restaurant_detail' with keyword arguments "{'pk'}"
My page was nearly finished to be ready for an alpha phase but then I got this Error "NoReverseMatch at /user/". This normally means that There is something wrong with the path from the urls.py directing to the page a user was linked to. But in this case I open up the page /user/ and get the error for /restaurant_detail/int:pk. I show you all the details. Don't wonder. HTML elements are in german. : ) The link that was clicked: <a href="{% url 'user' %}">Profil</a> The path in urls.py: path('user/', views.user, name='user'), The path the error is referring to: path('restaurant_detail/<str:pk>/', views.restaurant_detail, name='restaurant_detail'), path('restaurant_detail/<str:pk>/<int:underpage>', views.restaurant_detail, name='restaurant_detail'), Not part of this problem I think but here is the view of the user page in views.py: @login_required(login_url='login') def user(request): currentUser = request.user comments = Comment.objects.filter(account=request.user) liked = Restaurant.objects.filter(likes=currentUser) foods = Food.objects.all() if request.method == 'POST': #comment_form = CreateCommentForm(request.POST or None) userForm = UserUpdateForm(request.POST, instance=currentUser) pictureForm = PictureUpdateForm(request.POST, request.FILES, instance=currentUser) if userForm.is_valid(): userForm.save() pictureForm.save() messages.success(request, f'Your account hast been updated') return redirect('user') else: userForm = UserUpdateForm(instance=currentUser) pictureForm = PictureUpdateForm(instance=currentUser) #comment_form = CreateCommentForm() context = {'user': currentUser, 'userForm': userForm, 'pictureForm': pictureForm, 'comments': comments, 'liked': liked, 'foods': foods} return render(request, 'accounts/user.html', context) I hope my problem … -
Django (DRF) Serializers and MariDB Versioning Tables
MariaDB has this cool feature of tables versioning that allow you to keep track of data changes within a table like a VCS. According to Django documentation, MariaDB is supported by the latest Django versions but it seems that this is not really the case since to query historical data you still have to use raw-sql commands. Now I have nested serializers in my project and some of the models at the bottom of the "nesting" contain versioned objects. How do I specify what version (system-time) to fetch when requesting an endpoint view that uses the parent serializer of a nested serializer? Example: # MODELS class Driver(models.Model): name = models.CharField(max_length=120) surname = models.CharField(max_length=120) car = models.ForeignKey(PortionSize, on_delete=models.SET_NULL, null=True) class Car(models.Model): brand = models.CharField(max_length=120) model = models.CharField(max_length=120) year = models.DateTimeField() # SERIALIZERS class CarSerializer(serializers.ModelSerializer): class Meta: model = Car fields = '__all__' class DriverSerializer(serializers.ModelSerializer): car = CarSerializer() class Meta: model = Driver fields = '__all__' Assuming the django model: Car has System Versioning with MariaDB (ALTER TABLE db.Car ADD SYSTEM VERSIONING;), how do I tell the Driver serializer to fetch a specific version of the Car data? -
Only POST API giving 502 badgatway => recv() failed (104: Connection reset by peer) while reading response header from upstream
I am running Django with Gunicorn + Nginx(Kubernetes, ingress). I have discovered that a particular POST request we make has a long response string. Trying to debug, it seems that Nginx is not accepting this response string based on the length - I can pass short response strings but the same issue. I have the same API with GET and POST. but get API with 1000 request no issue but post API with 300 requests some of the random request API's are giving 502 bad gateway. For more info please refer attached screenshot I couldn't find anything about this on the Nginx and Gunicorn site or via google searching. Does anyone know what could be the issue? -
Django ERROR EXTERNAL IP: Invalid HTTP_HOST header: 'www.master.loberon.patrick-thomas.de'
[Django] ERROR (EXTERNAL IP): Invalid HTTP_HOST header: 'www.master.loberon.patrick-thomas.de'. You may need to add 'www.master.loberon.patrick-thomas.de' to ALLOWED_HOSTS. I'm getting this error in production. The referenced host is not my domain. Django Version: 3.1.2 -
Django Rest Framework Optimistic locking - Etag
So...I am trying to implement optimistic locking by using the django-rest-framework-condition library with the ETag conditional view. I use the following hash function: def my_etag(request, *args, **kwargs): return hashlib.md5(':'.join(request.GET.dict().values()).encode('utf-8')).hexdigest() And here are the view functions I am using with the @etag decorator. # Usine list class UsineList(APIView): queryset = Usine.objects.all() permission_classes = (CustomDjangoModelPermissions, ) # user_gains_perms(request, request.user.pk) @etag(my_etag) def get(self, request, format=None): #print(request.META.get("ETag")) #print("JJJ",request.META.get('HTTP_IF_MATCH', '')) usines = Usine.objects.all() serializer = UsineSerializer(usines, many=True) response = Response({"usines": serializer.data}) return response class UsineDetail(APIView): queryset = Usine.objects.all() permission_classes = (CustomDjangoModelPermissions, ) def get_object(self, pk): try: return Usine.objects.get(pk=pk) except Usine.DoesNotExist: raise Http404 @etag(my_etag) def put(self, request, pk, format=None): #, *args, **kwargs): #print(request.headers) usine = self.get_object(pk) serializer = UsineSerializer(usine, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) I am simulating two users performing GET and PUT actions for the same resource. At each GET request I store the ETag value on the client and send it back in a If-Match header when I perform a PUT request. I have noticed that the hash does not change for the resource when two users are performing concomitant PUT requests, therefore the second PUT request does not get blocked from saving the new information in the resource. Is … -
Remove all keys that have values of N/A, -, or empty strings
import json def clean_data(): r = requests.get('https://coderbyte.com/api/challenges/json/json-cleaning') return r.json() print(clean_data()) Example Input {"name":{"first":"Daniel","middle":"N/A","last":"Smith"},"age":45} Example Output {"name":{"first":"Daniel","last":"Smith"},"age":45}