Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Session handling in django
I have created web-app in django. App doesn't require any login logout activity. But, I used session variable and I am not deleting session. will it harm my site database? -
Adding a single field into group django admin
I'd like to know how to add a single field to a group of fields in a fieldset in DjangoAdmin. I've got this: class SecretarioAdmin(UserAdmin): model=Secretario def get_fieldsets(self, request, obj=None): fieldsets = list(super(UserAdmin, self).get_fieldsets(request, obj)) # update the `fieldsets` with your specific fields fieldsets.append(('Administrar', {'fields': ('administrar')})) return fieldsets That's my model: class Secretario(Usuario): administrar = models.OneToOneField(CentroEducativo, on_delete=models.CASCADE, null=True) And this is the error I'm getting: Unknown field(s) (i, a, r, s, m, d, t, n) specified for Secretario. Check fields/fieldsets/exclude attributes of class SecretarioAdmin. -
Change the Language that Django retrieves in timezone.now
So, Im running this code where I save the current time in the database when the field is created,however, It saves the time as "March 23,2020,4:11 pm", and I wanted to show it in Portuguese if possible. Can you explain me how I do it? This is the code, thanks: from django.db import models from django.utils import timezone from django.contrib.auth.models import User class Post(models.Model): titulo=models.CharField(max_length=100) conteudo=models.TextField() data_publicacao=models.DateTimeField(default=timezone.now) autor=models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.titulo -
Python/Django filtering posts by its categories
Trying to filter the posts by using anchor tag in template <a href="{% url 'post_list' %}?school=SchoolA&category=CategoryA">GO to POSTS</a> url of above is http://127.0.0.1:8000/post/?school=SchoolA&category=CategoryA For some reason this doesn't work and shows all posts no matter what category they have. def post_list(request): school_slug = request.GET.get('school') category_slug = request.GET.get('category') posts = VideoPost.objects.all() if school_slug: posts.filter(school=school_slug) if category_slug: posts.filter(category=category_slug) posts = posts.order_by('-date_posted') return render(request, 'stories/browse.html', {'posts': posts}) This works somehow, but I can't filter the posts by either one of them only. def post_list(request): school_slug = request.GET.get('school') category_slug = request.GET.get('category') posts = VideoPost.objects.all().filter(school=school_slug).filter(category=category_slug).order_by('-date_posted') return render(request, 'stories/browse.html', {'posts': posts}) It seems like there's some problem with if statement I assume, but I was not able to figure out. Any help would be much appreciated. -
Django ratelimit - how to display used limit in template?
on my website the user has the option to trigger a specific event 5 times a day, now I want to display the user how many times of today he has already triggered this action e.g.: "used: 2/5 times today". So how can I display the users ratelimit key in a django template? I found nothing at the documentations so far. https://django-ratelimit.readthedocs.io/en/stable/index.html thanks for reading -
Django: query to select model instances in a ManyToMany relation using set() method in serializer
I have a model for article tags: class Tag(models.Model): tag_name = models.CharField(max_length=10) additional_info = models.CharField(max_length=80) My Article model has ManyToMany relation with Tag model. class Article(models.Model): tag = models.ManyToManyField('Tag') When writing a article, writer gets to select as many tags as is available. Now, for the serializer to work, I have to use the set() method in the serializer class. My difficulty is in writing the query to fetch the tags selected while writing the article. I tried this but it's taking all the tags insted of only the selected ones: def update(self, instance, validated_data): instance.tag.set(Tag.objects.all()) What should be the query to fetch the tags selected during writing the blog only. -
Save large file AWS S3 django redis queue
Currently, a user is able to upload files, but large files* take too long. So far, I've been looking at solutions to upload the file async through the backend (django/python). For example a redis queue job that uploads (saves) the file. Is this a smart solution? If not, what could be another solution to upload large files without the user having to wait on the same page for the upload to be finished? Tech stack: vuejs django 2.2 python 3.5 AWS S3 bucket (file storage) *large files are considered files with a size from 10mb till 1gb. -
How can I run a python program with cooperation of a web server?
I want to launch a program from a local pc and connect it to a web server for some database operations such as creating a new user, creating a user list, listing all users who accessed the web server earlier. But I don't have information how to do it. I think Django can help me out in somewhere but I'm not sure. How can I do it, with which technologies or modules or methods? Thanks in advance... -
How to log django-kronos tasks with logging module?
I have switched from celery to dramatiq and celery beat to django-kronos and now I am stuck - I am not able to figure out, how to make tasks run by kronos to log using the logging module. Is it even possible or what is the best practice to log progress of django-kronos tasks? -
Django/Apache2 Context variables not availables
i'm a Django/Apache novice. following lots of tutorial i was able to build my small app for Home Domotic. Nevertheless i'm now experiencing a new problem. In Django app i have some templates that i call with views passing some CONTEXT variables. When i load the page with the internal Django Web Server (RUNWEBSERVER) the variables values are printed on the screen, but when i load the page with Apache the variables values are missing. Can somebody help me ? Thank you. Ciao. g -
PATCH doesn't save the new object state
I'm making a PATCH endpoint. It works almost fine.. but it doesn't save the endstate of the object when returning it to my test class. So in my serializer/view everything is updated but when I return serialiser.data to my test, it seems like my self.device is not updated. This is my code: view: def patch(self, request, site_pk, device_pk): """ PATCH the device's supplier info of the site. """ site_device = Device.objects.filter(site_id=site_pk, pk=device_pk) if not site_device.exists(): raise PermissionDenied("The device does not belong to the site.") device = site_device.first() serializer_class = self.get_serializer_class() serializer = serializer_class(device, data=request.data, partial=True,) serializer.is_valid(raise_exception=True) if "supplier" in self.request.data: new_supplier = serializer.validated_data["supplier"] device.supplier = new_supplier device.save() serializer.save() return Response(serializer.data, status=status.HTTP_200_OK) serializer: class AdminDeviceInfoSerializer(AdminDeviceSerializer): site = serializers.SerializerMethodField() owner = serializers.SerializerMethodField() country = serializers.SerializerMethodField() class Meta(AdminDeviceSerializer.Meta): fields = AdminDeviceSerializer.Meta.fields + [ "site", "owner", "country", "disk_space", "supplier", ] @staticmethod def get_site(device): #somecode @staticmethod def get_owner(device): #somecode @staticmethod def get_country(device): #somecode def to_representation(self, device): data = super().to_representation(device) if not device.supplier: data["supplier"] = None data["supplier"] = SupplierSerializer(device.supplier).data return data class AdminSiteDevicePatchSerializer(AdminDeviceInfoSerializer): class Meta(AdminDeviceInfoSerializer.Meta): fields = AdminDeviceInfoSerializer.Meta.fields test class: def test_change_supplier_devices_site(self): new_supplier = SupplierFactory(name="STWEB") self.client.force_login(self.admin_user) url = reverse( "admin-site-device-detail", kwargs={"site_pk": self.site.pk, "device_pk": self.device_1.pk}, ) response = self.client.patch(url, data={"supplier": new_supplier.pk}) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(new_supplier.pk, self.device_1.supplier_id) -
how can i solve this "POST 400: Bad request"? Using Django REST API and React frontend
i'm pretty new to web development so please forgive me in advance for my ignorance. I'm using React to try to post data into the database managed by django using this method: sendData(data) { const url = "http://127.0.0.1:8080/api/filtros/1/"; const requestOptions = { method: "POST", headers: { Accept: "application/json", "Content-Type": "application/json" }, body: JSON.stringify(data) }; fetch(url, requestOptions); } On the onClick of a NavDropdown React component: <NavDropdown.Item key={item.id} onClick={() => this.sendData({ id: 0, dimension_id: dimension.id, item_id: item.id, usuario_id: 1 }) } > {item.descripcion} </NavDropdown.Item> This is how I register the url on the router using Django: router.register('api/filtros/1', FiltroUsuariosViewSet, 'filtro') My Django ModelViewSet looks like this: class FiltroUsuariosViewSet(viewsets.ModelViewSet): queryset = FiltroUsuarios.objects.all() permission_classes = [ permissions.AllowAny ] serializer_class = FiltroUsuariosSerializers And my Django Serializer looks like this: class FiltroUsuariosSerializers (serializers.ModelSerializer): class Meta: model = FiltroUsuarios fields = ('id', 'dimension_id', 'item_id', 'usuario_id') def create(self, validated_data): post = FiltroUsuarios.objects.create(**validated_data) When i click on the Component I get this: POST http://127.0.0.1:8080/api/filtros/1/ 400 (Bad Request) and apparently the error is on the fetch request. Do you guys have any idea on whats the problem? Thanks a lot in advance! -
nginx and django setting for docker-compose
I have setting with nginx and django(named python container). I can access see the top page with localhost:8000, however I cannot fetch the static file nor use API localhost:8000/api/items I am newbee for nginx and django so still confusing. I am planning the setting like this belo normal files browser ->8000 -> nginx -> 8001 ->django for static file django ->8000 -> nginx am it correct???or where should I fix?? These are settings below. docker-composer.yml version: '3' services: python: container_name: python build: ./python command: uwsgi --socket :8001 --module myapp.wsgi --py-autoreload 1 --logto /tmp/mylog.log expose: - "8001" nginx: image: nginx:1.13 container_name: nginx ports: - "8000:8000" volumes: - ./nginx/conf:/etc/nginx/conf.d - ./nginx/uwsgi_params:/etc/nginx/uwsgi_params - ./nginx/static:/static depends_on: - python app_nginx.conf upstream django { ip_hash; server python:8001; } server { listen 8000; server_name 127.0.0.1; charset utf-8; location /static { alias /static; } location / { uwsgi_pass django; include /etc/nginx/uwsgi_params; } } server_tokens off; uwsgi_prams uwsgi_param QUERY_STRING $query_string; uwsgi_param REQUEST_METHOD $request_method; uwsgi_param CONTENT_TYPE $content_type; uwsgi_param CONTENT_LENGTH $content_length; uwsgi_param REQUEST_URI $request_uri; uwsgi_param PATH_INFO $document_uri; uwsgi_param DOCUMENT_ROOT $document_root; uwsgi_param SERVER_PROTOCOL $server_protocol; uwsgi_param REQUEST_SCHEME $scheme; uwsgi_param HTTPS $https if_not_empty; uwsgi_param REMOTE_ADDR $remote_addr; uwsgi_param REMOTE_PORT $remote_port; uwsgi_param SERVER_PORT $server_port; uwsgi_param SERVER_NAME $server_name; -
Name error in django name 'index' is not defined
I am building a travel website.The project name is travel. I am getting the following error message: NameError at / name 'index' is not defined Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 2.2.5 Exception Type: NameError Exception Value: name 'index' is not defined Exception Location: E:\coding\fyp\travel\app1\views.py in cities, line 20 Python Executable: D:\anacondapython3\python.exe Python Version: 3.7.4 Python Path: ['E:\coding\fyp\travel', 'D:\anacondapython3\python37.zip', 'D:\anacondapython3\DLLs', 'D:\anacondapython3\lib', 'D:\anacondapython3', 'D:\anacondapython3\lib\site-packages', 'D:\anacondapython3\lib\site-packages\win32', 'D:\anacondapython3\lib\site-packages\win32\lib', 'D:\anacondapython3\lib\site-packages\Pythonwin'] Server time: Mon, 23 Mar 2020 15:51:04 +0000 Traceback Switch to copy-and-paste view D:\anacondapython3\lib\site-packages\django\core\handlers\exception.py in inner response = get_response(request) … ▶ Local vars D:\anacondapython3\lib\site-packages\django\core\handlers\base.py in _get_response response = self.process_exception_by_middleware(e, request) … ▶ Local vars D:\anacondapython3\lib\site-packages\django\core\handlers\base.py in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) … ▶ Local vars E:\coding\fyp\travel\app1\views.py in cities return render(request,index.html,{'dests':dests}) … ▶ Local vars My travel urls.py look like: """travel URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/2.2/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL … -
Django Char vs. Varchar
Please Help, I have an existing database that uses a char(12) as its PK. CREATE TABLE sop_customer ( customer_id char(12) NOT NULL, PRIMARY KEY (customer_id), ) ENGINE=InnoDB DEFAULT CHARSET=utf8; I then create a Django Model and create a model based on inspectdb (awesome tool :-)) The problem is when I create another table with a foreign key to this table, the new table will use varchar() and MySQL at the database level will not honour the relationship because of the different types (char vs .varchar) HELP! I am in the process of trying: 1 - Update the existing db to Varchar (seems like a rather extreme operation just to get this thing to work :-0) 2 - Get Django's foreign Key class to recognise the type properly (I understand ORM agnostisism etc). 2 - Force Django to create a char field and then add the constraint after in Django, although I cant see how this could be achieved without heavy lifting 3 - Not use Django Help! -
Django URL language prefix redirect
brand new into programming& django so be gentle with me :) i just implemented (using the docs) bellow form with a drop-down list for language change: <form action="{% url 'set_language' %}" method="post"> {% csrf_token %} <input name="next" type="hidden" value="{{request.get_full_path }}"/> <select name="language"> {% get_current_language as LANGUAGE_CODE %} {% get_available_languages as LANGUAGES %} {% get_language_info_list for LANGUAGES as languages %} {% for language in languages %} <option type="submit" value="{{ language.code }}"{% if language.code == LANGUAGE_CODE %} selected="selected"{% endif %}> {{ language.name_local }} ({{ language.code }}) </option> {% endfor %} </select> <input type="submit" value={% trans "GO" %} /> </form> All works just as expected so i can use the drop-down list to do the switch. As the value="{{request.get_full_path }}" i get back to the link where i was (which is fine); still just for learning purpose i would like to change this and be redirected to a link with the lang_code in the prefix. I have noticed that the prefix feature is already in place -> http://127.0.0.1:8000/en/Django_book_app_1/ & http://127.0.0.1:8000/fr/Django_book_app_1/ working just fine. How i can implement this already in place feature while still using the drop down list for changing the language (get redirected to the prefix link when switching)? For the … -
How do I move the following code in view to serializer?
I have written the following code, and after review I was told that this is not the correct way, instead I should use DRF and serializer to do the work. I am having hard time to move this code to the serializer. And the problem is, I have done this in every view. See the view below, and please tell me how do I take the help of serializers and get_object to move most of my code in serializer and let it handle the data. The example below takes an email_token and verifies the user if the token is correct. class EmailVerifyView(APIView): def post(self, request, *args, **kwargs): token = request.data['token'] user_obj = get_object_or_404(UserProfile, email_token=token) if user_obj.verified: return Response("Already verified", status=status.HTTP_400_BAD_REQUEST) user_obj.verified = True user_obj.save() return Response("Verified successfully", status=status.HTTP_200_OK) -
Django Convert HTML that has JS charts to PDF
I am trying to build an application that can make Report Cards. These report cards have charts made in ChartJs showing student's growth and development each semester. I need to make these cards into PDF or an Image and then download them. I have already tried XHtml2pdf and it is not able to generate the charts. I just wanna know, is there a way I could covert my HTML ( with JS charts) into PDF or Image. -
I want to add my own qrcode generator to my django application and store the qrcode to my MySQL database
So i was trying to add my own QRCode generator to my django application so that the user info will also be stored into a custom QRCode with an image on the middle. And i want the QRCode to be stored to my database (im using mysql) so that i can display that QRCode on the user dashboard. How do i do that? #models.py from django.db import models from django.contrib.auth.models import User from django_countries.fields import CountryField from phonenumber_field.modelfields import PhoneNumberField from short_text_field.models import ShortTextField class UserProfileInfo(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) nama_lengkap = models.CharField(default="", null=False, max_length=30) birthdate = models.DateField(default="") city = ShortTextField(default='', blank=True, help_text="Masukkan nama kota dengan benar") GENDER_CHOICES = (('Laki-laki', 'Laki-laki'), ('Perempuan', 'Perempuan')) gender = models.CharField(choices=GENDER_CHOICES, max_length=10) phone_number = PhoneNumberField(default='+62',null=False, blank=False, unique=True, max_length=15) qrcode = models.ImageField(default="") Akun_Instagram = models.CharField(blank=True, null=False, default="@", max_length=35) bio = models.TextField(default='', blank=True) def __str__(self): return self.user.username #views.py from django.shortcuts import render from accounts.forms import UserForm,UserProfileInfoForm from django.contrib.auth import authenticate, login, logout from django.http import HttpResponseRedirect, HttpResponse from django.urls import reverse from django.contrib.auth.decorators import login_required from PIL import Image from django.contrib.auth.models import User from accounts.models import UserProfileInfo import qrcode def index(request): return render(request, 'templates/landing.html') @login_required def special(request): return HttpResponse("You are logged in !")\ @login_required def user_logout(request): logout(request) … -
Django - context must be a dict rather than ReturnList
I am working on a django project and I have a Post Model, which has this view: class PostListApiView(ListCreateAPIView): queryset = Post.objects.all() serializer_class = PostSerializer filter_backends = [SearchFilter] search_fields = ['user','title','content'] I use this view to create new posts: @method_decorator(login_required, name='dispatch') class PostCreateView(APIView): queryset = Post.objects.all() serializer_class = PostCreateSerializer renderer_classes = [TemplateHTMLRenderer] permission_classes = [IsAuthenticated] template_name = 'post_form.html' def get(self, request, format=None): serializer=PostCreateSerializer() return Response({'serializer':serializer}) def post(self, request): serializer = PostCreateSerializer(data=request.data) if not serializer.is_valid(): return Response({'serializer':serializer}) serializer.save() return redirect('/') I want to consolidate both views into one view, class PostListApiView(ListCreateAPIView): queryset = Post.objects.all() serializer_class = PostSerializer filter_backends = [SearchFilter] search_fields = ['user','title','content'] renderer_classes = [TemplateHTMLRenderer] template_name = 'post_form.html' but when I try to add the TemplateHTMLRenderer to the ListCreateAPIView, I get this error: Traceback (most recent call last): File "C:\...\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\...\lib\site-packages\django\core\handlers\base.py", line 145, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\...\lib\site-packages\django\core\handlers\base.py", line 143, in _get_response response = response.render() File "C:\...\lib\site-packages\django\template\response.py", line 105, in render self.content = self.rendered_content File "C:\...\lib\site-packages\rest_framework\response.py", line 70, in rendered_content ret = renderer.render(self.data, accepted_media_type, context) File "C:\...\lib\site-packages\rest_framework\renderers.py", line 167, in render return template.render(context, request=request) File "C:\...\lib\site-packages\django\template\backends\django.py", line 59, in render context = make_context(context, request, autoescape=self.backend.engine.autoescape) File "C:\...\lib\site-packages\django\template\context.py", line 270, … -
UTF-8mb4 encoding on MySQL in Django Rest Framework shows question marks
I have a site based on Django Rest Framework, with a high amount of non-Latin characters (namely CJV). I have changed my database encoding, my specific table encoding and and the encoding of all of my columns encodings to UTF-8mb4. All of the data is showing in the CMS I have added on top of the site (Wagtails), and in the database, however when I try to make a call to DRF, I get the following (this is inside one of my JSON objects in DRF): "title": "Reason launches the world’s first remote team escape experience: Lola...", "date": "2018-12-15", "rendered": "?????????????? ... When in fact it should look like this: "title": "Reason launches the world’s first remote team escape experience: Lola...", "date": "2018-12-15", "rendered": "佛罗里达州杰克逊维尔 .... As far as I can tell, Django should automatically figure out the correct encoding - but it does not seem to do so here. How do I get DRF to output UTF-8mb4? -
Django, GraphQL query login issue
I was following along with the following tutorial... https://www.howtographql.com/graphql-python/4-authentication/ For the resolve_me query... def resolve_me(self, info): user = info.context.user if user.is_anonymous: raise Exception('Not logged in!') When I do the query in Insomnia Rest client it works OK. When I do the query in the GraphiQL web interface it works OK. But when I do the query in the Vue/ Apollo code it is returning "Not logged in!". Even after I have logged in via JWT. I have the JWT token in the header auth. When I print user variable above, it returns AnonymousUser in the python server(it returns my username when I do the query in browser with GraphiQL web interface). Vue main.js... const middlewareLink = setContext(() => ({ headers: { authorization: `Bearer ${localStorage.getItem("jwt")}` } })); const link = middlewareLink.concat(httpLink); export const apolloClient = new ApolloClient({ link, cache: new InMemoryCache(), connectToDevTools: true }); Is there any setting or configuration I may be missing? I am using Vue 2.6 and Python 3.8.1 and Django 3.0.3. -
Database error during the test: cannot change column
I changed one field of the model, to create migrations and applied it. There were no errors. But when I try to run the tests, there's an error. django.db.utils.OperationalError: (1833, "Cannot change column 'rfiid': used in a foreign key constraint 'elements_attachments_rfi_id_bc723558_fk_rfis_rfiid' of table 'test_smap_production.elements_attachments'") field that I changed - rfiid. I switched it from Integer to CharField. models.py class Rfis(models.Model): rfiid = models.CharField(max_length=6, primary_key=True) .... The migration was successful, and there is no already created instance of the model in the database. Why such an error occurs and how to correct it? -
NoReverseMatch at / in django3
Reverse for 'delete_order' with no arguments not found. 1 pattern(s) tried: ['delete_order/(?P[^/]+)/$'] This is the error. Dashboard html file after adding the url in Remove link i am getting this error <div class="col-md-7"> <h5>LAST 5 ORDERS:</h5> <hr> <div class="card card-body"> <a class="btn btn-primary btn-sm btn-block" href="{% url 'create_order' %}">Create Order</a> <table class="table table-sm"> <tr> <th>Product</th> <th>Date Ordered</th> <th>Status</th> <th>Update</th> <th>Remove</th> </tr> {% for or in orders %} <tr> <td>{{or.product}}</td> <td>{{or.date_created}}</td> <td>{{or.status}}</td> <td><a class = "btn btn-sm btn-info" href="{% url 'update_order' or.id %}">Update</a> </td> <td><a class="btn btn-sm btn-danger"href="{% url 'delete_order' %}">Remove</a> </td> </tr> {% endfor %} </table> This is my views.py file. def updateOrder(request,pk): order = Order.objects.get(id=pk) form = OrderForm(instance=order) if request.method == "POST": form=OrderForm(request.POST,instance=order) if form.is_valid: form.save() return redirect('/') con = {'form':form} return render(request,'food/orderform.html',con) def deleteOrder(request,pk): order = Order.objects.get(id=pk) con={'item':order} return render(request,'food/deleteform.html',con) This is my urls.py file. Last one is the url for delete operation from django.urls import path from . import views urlpatterns = [ path('',views.home, name="home"), path('products/', views.products,name="products"), path('customer/<str:pk_test>/',views.customer,name = "customer"), path('create_order/',views.create_order,name="create_order"), path('update_order/<str:pk>/',views.updateOrder,name="update_order"), path('delete_order/<str:pk>/',views.deleteOrder,name="delete_order"), ] This is the models.py file code from django.db import models # Create your models here. class Customer(models.Model): name = models.CharField(max_length = 200,null = True) phone = models.CharField(max_length = 200, null = True) email … -
How to store a polygon field in PostgreSQL and Django?
I am trying to store images in PostgreSQL and a polygon storing coordinates of some shape on top of the image. I tried using PostGIS for the same but it doesn't allow for making polygon on the image being stored rather it shows a map of the globe to mark coordinates on. How can I change it so that it takes coordinates relative to the image I am storing? Here are my models in Django `class Image(models.Model): image_id = models.IntegerField(primary_key=True, unique=True) image_source = models.URLField() provider_id = models.CharField(max_length=20, null=True) def __str__(self): return self.image_source class Annotation(models.Model): annotation_id = models.IntegerField(primary_key=True, unique=True) image_id = models.ForeignKey('Image', on_delete=models.CASCADE) user = models.IntegerField() coordinates = models.PolygonField(null=True) label = models.CharField(max_length=300)`