Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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} -
How to increase loading time of post request in IIS windows server 2019
I have deployed Django on a windows server using IIS Windows Server 2019. When I submit the form, the time limit of the backend process is 100 Seconds, But after 40 seconds, IIS server responds with error 500. How can I increase this loading time of IIS. -
How to display the MQTT values in UI through Django framework
I am trying to get the values from the MQTT broker and wanted to display the values in the web UI through the Django framework. I have all the code files. I don't know where to place the python MQTT code to get the values from the broker to pass it to the UI. -
Django, DRF: How to send permission class details while making an API call using POSTMAN?
# views.py @login_required @permission_classes([IsAdminUser]) @api_view(['GET']) def say_hi_admin(request): return Response({'msg': 'Hi Admin'}) On making a GET request using POSTMAN with the following request Body(raw/json): { "user": { "id": 1, "email": "example@email.com", "password": "pass" } } But I get this as the response, { "detail": "Authentication credentials were not provided." } How can I solve this? -
In Django 1.11, how can I cache an entire page only for logged out users, but still be able to drop the cache if something substantial changes?
I would like to cache a whole page for logged out viewers, but I have a couple of requirements: The page should be cached per language If something major changes on the page, I should manually drop the cache key (i.e. from the view that performs a major change in the database that affects that page) If something minor changes on the page, I can keep the cache I'm pretty sure I can do it with a template fragment, e.g.: {% cache 600 CACHE_KEY request.user request.LANGUAGE_CODE %} And CACHE_KEY would be something that is computed by the view and passed to the template so that whenever I change something major I can recalculate CACHE_KEY and drop it. But is it possible to also do this without touching the template? Thanks! -
Partial update in action without UpdateModelMixin
I have a viewset without UpdateModelMixin and I need to able update name in extra action but it doesn't work and requires all fields of serializers: class PlacementMappingViewSet(mixins.CreateModelMixin, mixins.ListModelMixin, mixins.RetrieveModelMixin, mixins.DestroyModelMixin, viewsets.GenericViewSet): serializer_class = serializers.CampaignManagerPlacementMappingSerializer @action(detail=True, methods=['patch']) def change_name(self, request, pk=None): instance = self.get_object() serializer = self.serializer_class(instance, data=request.data, partial=True) if serializer.is_valid(): serializer.save() return Response(serializer.data) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) And my serialier: class CampaignManagerPlacementMappingSerializer(ExtendedModelSerializer): is_synchronized = serializers.BooleanField(read_only=True) failed_synchronization_reason = serializers.CharField(read_only=True) tile = serializers.IntegerField(required=True, allow_null=False) platform_item_external_id = serializers.IntegerField(required=True, allow_null=False) active = serializers.BooleanField(read_only=True) class Meta: model = models.CampaignManagerPlacementMapping fields = ( 'id', 'tile', 'site_mapping', 'tile_mapping', 'placement_id', 'placement_name', 'platform_item_id', 'platform_item_external_id', 'failed_synchronization_reason', 'is_synchronized', 'active', 'is_name_changed', 'click_through_url', 'is_click_through_url_changed', ) def update(self, instance, validated_data): if validated_data.get('placement_name') != instance.placement_name: validated_data['is_name_changed'] = True if validated_data.get('click_through_url') != instance.click_through_url: validated_data['is_click_through_url_changed'] = True return super().update(instance, validated_data) What I am doing wrong? -
django admin field level persmission
i'm trying to customize my Django admin panel for different user groups. i have three types of user's which are simple_user, admin, support .i'm trying to restrict my support user's to edit some specific model fields .this is my model and tried adding custom permissions for that. t_code = models.CharField(max_length=14, null=True) t_type = models.ForeignKey('Coding', on_delete=models.CASCADE, null=True) t_user = models.ForeignKey(UserProfile, on_delete=models.CASCADE) t_Title = models.CharField(max_length=200, null=True, blank=True) class Meta: permissions = ( ('edit_t_Title', 'can Edit title '), ) the problem is after migrations the permission is added to django permissions but when i assign it to support group the permission has no effect !. i tried two ways to check that.first i set view_ticket and edit_ticket,edit_t_Title permission to support,second i tried only view_ticket and edit_t_Title ,but non of them was working . it seems when i add edit_ticket permission support can edit all fields,and when i remove it support can only view it even when i set edit_t_Title. -
Django el pagination limit number of pages in pagination
I've got small issue and I don't know how to fix it. I'm using Django EL(Endless) Pagination. I want to limit number of pages displayed. For now is like 40 and it doesn't look so good. How can I change this? Here is my html template fragment of pagination: {% paginate advertisements %} {% get_pages %} <ul class="pagination" style="margin: auto;"> {% if pages.paginated %} <nav aria-label="Blog pagination"> <li class="page-item mr-3 {& if pages.previous.path == None %} disabled {% endif %}"> <a class="page-link text-sm rounded" href="{{ pages.previous.path }}" aria-label="Poprzednia"> <i class="fa fa-chevron-left mr-1"></i> Poprzednia</a></li> <span class="sr-only">Poprzednia</span> </a> </li> {% for page in pages %} <li class="page-item mr-3 {% if page.is_current %} active {% endif %}"> <a class="page-link text-sm rounded" href="{{ page.path }}" aria-label="Page {{page.number}}"> {{page.number}} </a> </li> {% endfor %} <li class="page-item {% if pages.next.path == None %} disabled {% endif %}"> <a class="page-link text-sm rounded" href="{{ pages.next.path }}" aria-label="Następna"> Następna<i class="fa fa-chevron-right ml-1"></i></a></li> <span class="sr-only">Next</span> </nav> </ul> -
Django rest framework - including an api key for access authorization
I'm creating a Restful API using Django Rest Framework, i'm not serving sensitive data but still i wanted to add some sort of authorization system for viewing my API endpoints. Basically each user has an API key assigned, and in order to view any endpoint, the user needs to provide the key when performing any request. All the endpoints use only GET to retrieve the data, so what i did is the following: The API key is provided in the GET params, so something like myURL/api/endpoint/?key=1234&filter=test A middleware checks if that API key exists in my database, and if it does the user is able to get the data. Here is my middleware: TOKEN_QUERY = "key" class TokenMiddleware(AuthenticationMiddleware): def process_request(self, request): if request.user.is_authenticated: return None else: try: token = request.GET[TOKEN_QUERY] except Exception as e: # A token isn't included in the query params return JsonResponse({'error': 'Missing parameter: make sure to include your key.'}) try: query = API_keys.objects.get(api_token=token) except: token = None if token != None: return None else: return JsonResponse({'error': 'Authentication failed. Make sure to provid a valid API key.'}) This system works without any problem, but i'm concerned about safety. How safe is this? Should i not use a … -
Django Group By in QuerySet
I have a table of transaction, and i am looking to extract a table summary with data grouped by year, month, user, account, id of transaction, and name of issuer of the good. I managed to do so in the view using: def monthly_activity(request): results = Personalaccountpurchase.objects.all().filter(quantity__isnull=False)\ .values_list('trade_date__year', 'trade_date__month','user','account','id' ,'name_of_issuer')\ .annotate(Sum('quantity'))\ .order_by('trade_date__year', 'trade_date__month') context = { 'results': results, } return render(request, "paccounts/monthly_activity.html", context) In the template i would like to make a clean display of the query set that came up in the form of : <QuerySet [(2021, 1, '4', '17', 35, 'Fresh Oil', 4584), (2021, 2, '4', '15', 8, 'face Sebum', 405500), (2021, 2, '4', '15', 9, 'Vegetal Oil', 450063)]> I tried using : {% for result in results %} .... </tr> {% endfor %} but I am not sure how to move from there since my column name have all been changed. result.user for example will return nothing. Is someone familiar with the grouping of record in QuerySet please ?