Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Declare queryset only in modelviewset methods Django rest
Hey I have a view like this class ProjectShareView(viewsets.ModelViewSet): queryset = ShareProject.objects.all() serializer_class = ShareProjectSerializer def post(self, request, *args, **kwargs): project = Project.objects.get(id=kwargs['project_id']) ... def get(self, request, *args, **kwargs): share_project = ShareProject.objects.filter(project=kwargs['project_id']) ... def delete(self, request, *args, **kwargs): share_projects = ShareProject.objects.filter(project=kwargs['project_id']) ... I use a separate queryset for each method. How can I remove the queryset of the class, without it, an error appears, and leave it only in methods. Or i can use queryset.objects.none () for this? -
connecting devices with my django web application using TCP IP
I'm trying to connect couple of devices with my django web app using TCP IP and i'm new in django so my question is what is the best way to do that, i've seen some suggestion about using twisted but the thing that when i've tried to use twisted but every time a run the server i got this error (twisted.internet.error.CannotListenError: Couldn't listen on any:8015: [WinError 10048] Only one usage of each socket address (protocol/network address/port) is normally permitted.) (the twisted application works good but when i add it to django i got that error, and i tried to use a diffrent pores for the django app) -
Reading data from Javascript Promise
I'm using the django framework and I'm trying to get the data from a Javascript Promise as follows: Js file console.log("working"); $("#username").keyup(function(event){ let user=event.target.value fetch("/login/userValidation/",{ body:JSON.stringify({username:user}), method:"POST" }).then((res)=>{ console.log(res.json()); }); }); Py file (views.py) from django.contrib.auth.models import User from django.http import JsonResponse as jresp from django.views import View import json class userValidation(View): def post(self,req): data=json.loads(req.body) user=data['username'] print(user) if(user.isalnum()): if(User.objects.filter(username=user)): print("Username not available") return jresp({"user_status":"Username not available, try something else"}) else: print("Username Valid") return jresp({"user_status":"Username Valid"}) else: print("Please enter alphanumeric characters only") return jresp({"user_status":"Please enter alphanumeric characters only"}) Fetch() is posting the data from the client side to the server and the server is receiving the data just fine, as I have checked by printing out the data in the backend. However, the JsonResponse that is being returned to the client is showing undefined instead of the actual data - I'm not able to get the required data from the promise, using response.json() under the subsequent then() function. Anything I'm missing out? Please help. -
My reply button is not working in django.. please someone help me how to make working reply button in comments of django
My comment section is working fine but I don't know why my reply button is not working.. please can you go through my code and help me to find out error... I think it is a logical error. 1.Views.py from django.shortcuts import render, get_object_or_404, redirect from datasecurity.models import Post, Comment from django.urls import reverse from django.http import HttpResponseRedirect from django.contrib.auth.decorators import login_required from django.contrib import messages from django.contrib.auth.models import User from .forms import CommentForm # Create your views here. @login_required def likes(request, pk): post=get_object_or_404(Post, pk=pk) post.likes.add(request.user) return HttpResponseRedirect(reverse('datasecurity:datasecurity')) def datasecurity(request): allPosts= Post.objects.all() context={'allPosts': allPosts} return render(request, 'datasecurity/data.html',context=context) def blogHome(request, slug): post=Post.objects.filter(slug=slug).first() cf = CommentForm(request.POST or None) comments = Comment.objects.filter(post=post).order_by('sno') if request.method == 'POST': if cf.is_valid(): content = request.POST.get('content') comments = Comment.objects.create(post = post, user = request.user, content = content) comments.save() return HttpResponseRedirect(reverse('datasecurity:datasecurity')) else: cf = CommentForm() parentSno= request.POST.get('parentSno') if parentSno=="": comment=Comment(comment= comment, user=user, post=post) comment.save() else: parent= BlogComment.objects.get(sno=parentSno) comment=Comment(comment= comment, user=user, post=post , parent=parent) comment.save() context={'post':post, 'comments':comments,'comment_form':cf, 'user': request.user} return render(request, "datasecurity/blogHome.html", context) 2.models.py from django.db import models from ckeditor.fields import RichTextField from django.contrib.auth.models import User from django.utils.timezone import now # Create your models here. class Post(models.Model): sno=models.AutoField(primary_key=True) title=models.CharField(max_length=255) author=models.CharField(max_length=14) slug=models.CharField(max_length=130) timeStamp=models.DateTimeField(blank=True) content=RichTextField(blank=True, null=True) img = models.ImageField(blank=True, null=True, upload_to="dataimage/") likes … -
How to get the correct path for a django script
Here is my arborescence V1 : project/ ---AppUser/ ------models.py, view.Py etc ... ---project/ ------settings.py, manage.py etc ... myscript.py here my script works perfectly : import sys import os import django sys.path.append("../../../project") os.environ["DJANGO_SETTINGS_MODULE"] = "project.settings" django.setup() from AppUser.models import Subscription maps = Subscription.objects.get(uuid="1234565") print(maps) It works fine, i launch it from the root of the project ... But when i want to put my script in a script folder : V2 : project/ ---AppUser/ ------models.py, view.py etc ... ---project/ ------settings.py, manage.py etc ... ---script/ ------myscript.py Here is my script : import sys import os import django sys.path.append("../../../../project") os.environ["DJANGO_SETTINGS_MODULE"] = "project.settings" django.setup() from AppUser.models import Subscription maps = Subscription.objects.get(uuid="123") print(maps) and when i am in script/ and i do a python3 script.Py I have a : Traceback (most recent call last): File "myscript.py", line 12, in <module> from AppUser.models import Subscription ModuleNotFoundError: No module named 'AppUser' error How to be in script and not having this error ? The django.setup() seems to works fine. -
Why does my python anywhere show me 'install worked successfuly' page instead of the web app that i created
so i created a simple blog, tried deploying with heroku(it just told me application error), so now i tried with python everywhere. It didn't give me any errors but it acts as if my app is empty, it shows that page that u see when you firstly make a django app that is still emptythat's this page It says i see that page because DEBUG=True, but no it's off in my settings .It also says that this is because i have no configured URL's but i did configure URL's and they worked in localhost, but now i don't know why it doesn't work Please can someone help me check my SETTINGS.py and urls.py files. Thank you This is the repository containing my code https://github.com/GamerDTK/tishas-lifestyle I have a feeling the problem is from how i included the url of the app 'blog' to the main app. But it looks correct to me -
Getting AnonymousUser instead of real username authenticated when calling request.user
I am working on a form to create custom questions for a questionnaire. Both logged-in users and not logged-in ones can create questions (I am using default Django user authentication models and features). What I want to do is: when saving a question in the database, its attribute user can be saved as well, being user a field of Question model, as showed in models.py: class Question(models.Model): filepath = models.CharField(max_length=255, null=True, blank=True) slug = models.CharField(max_length=255, null=True, blank=True) order = models.CharField(max_length=255, null=True, blank=True) category = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True, blank=True) user = models.ForeignKey(User, on_delete=models.SET_NULL, blank=True, null=True) def __str__(self): return "{}".format(self.id) I am logged in as an admin user, so I have and id and username, but I can not get yet the Question saved with the (admin) username but AnonymousUser. In views.py file: class QuestionViewSet(generics.GenericAPIView): serializer_class = QuestionSerializer permission_classes = [AllowAny] @csrf_exempt def post(self, request, *args, **kwargs): data = request.data if request.user.is_authenticated: question = Question(user=request.user) else: question = Question() question.save() return JsonResponse(data={"success": True}, status=200) In serializers.py file (I am not using a model serializer but a generic one because I need to save several values from several models in only one post request): class QuestionSerializer(serializers.Serializer): title = serializers.CharField() description = serializers.CharField() categories … -
Django show save buttons for nlineModelAdmin not the main ModelAdmin?
I am not giving users the permissions to change the main modelAdmin. However I am allowing them to add a record to the InlineModelAdmin. Unforutnately the save button does not show. I tried overriding the method: def has_change_permission(self, request, obj=None): '''Show the save button''' return True That shows the save button but now gives the user permission to change the main model. It seems that this context variable has_editable_inline_admin_formsets in django/contrib/admin/templatetags/admin_modify.py is set to false. Even though the inline formset is editable. After a deeper dive it looks as though this section of code on line 1486 of django/contrib/admin/options.py overrides everything to false if you cannot edit the parent. if can_edit_parent: has_add_permission = inline.has_add_permission(request, obj) has_change_permission = inline.has_change_permission(request, obj) has_delete_permission = inline.has_delete_permission(request, obj) else: # Disable all edit-permissions, and overide formset settings. has_add_permission = has_change_permission = has_delete_permission = False formset.extra = formset.max_num = 0 So what should I do to allow for adding and deleting of the inline - I assume all that needs to be done is override the template in templates/admin/app_name/model_name_change_form.html and change this row to always show save: {% block submit_buttons_bottom %}{% submit_row %}{% endblock %} to: {% block submit_buttons_bottom %} {% submit_row %} <input type="submit" value="Save" … -
Is Django Apache or Nginx
I have made a project in the framework Django and I am setting up SSL encryption so it gets https instead of http and removes the safety sign in browsers. In the installation process of Certbot I am asked which software it is running. Django is sadly not an option. I've heard that Django often gets under the category Apache or Nginx, but I am not sure which one my Django project is. It is an Ubuntu server. https://certbot.eff.org/ https://letsencrypt.org/getting-started/#with-shell-access -
When I run code in Docker I get a Django error [Errno 2]. When running locally everything works. Why?
I don't know what's going on. A script run by Django works fine, but not through Docker and Django. An error is returned: Pic Errno 2 No such file or directory Below is the code of the function with the error and the code of the Dockerfile. ''' def mediainfo(filepath): Original code: prober = get_prober_name() command_args = [ "-v", "quiet", "-show_format", "-show_streams", filepath ] command = [prober, '-of', 'old'] + command_args Modified code: command = f"ffprobe -v error -show_format -show_streams -select_streams v:0 {filepath}" The rest of the functions: res = Popen(command, stdout=PIPE) output = res.communicate()[0].decode("utf-8") if res.returncode != 0: output = Popen(command, stdout=PIPE).communicate()[0].decode("utf-8") rgx = re.compile(r"(?:(?P<inner_dict>.*?):)?(?P<key>.*?)\=(?P<value>.*?)$") info = {} if sys.platform == 'win32': output = output.replace("\r", "") for line in output.split("\n"): # print(line) mobj = rgx.match(line) if mobj: # print(mobj.groups()) inner_dict, key, value = mobj.groups() if inner_dict: try: info[inner_dict] except KeyError: info[inner_dict] = {} info[inner_dict][key] = value else: info[key] = value return info ''' Code of the Dockerfile ''' FROM python:3.7 as base EXPOSE 80 WORKDIR /app COPY . /app ENV PYTHONDONTWRITEBYTECODE=1 ENV PYTHONUNBUFFERED=1 RUN pip install --upgrade pip RUN echo 'deb http://deb.debian.org/debian buster-backports main contrib non-free' >> /etc/apt/sources.list RUN apt-get update RUN apt-get -y install ffmpeg RUN apt-get update … -
Duplicate key error when saving a new object
I'm creating a new object with a form and when I hit the save button I got this error: IntegrityError at /department/add duplicate key value violates unique constraint "feedback_department_pkey" DETAIL: Key (id)=(1) already exists. Although, I have 18 records in this table in the database, but I can't figure out why is trying to start saving from the first id. my views.py: # Add new department def department_add(request): form = DepartmentEditForm() if request.method == "POST": print('Printing POST', request.POST) form = DepartmentEditForm(request.POST) if form.is_valid(): form.save() return redirect('feedback:department') return render(request, 'departmentadd.html', {'form': form}) my models.py: class Department(models.Model): name = models.CharField(max_length=100) title_bg = models.CharField(max_length=50) title_en = models.CharField(max_length=50) title_de = models.CharField(max_length=50) def __str__(self): return self.name urls.py path('department/add', views.department_add, name="departmentadd"), and forms.py: class DepartmentEditForm(forms.ModelForm): class Meta: model = Department #fields = '__all__' fields = [ 'name', 'title_bg', 'title_en', 'title_de', ] widgets = { 'name': forms.TextInput(attrs={'class': 'form-control'}), 'title_bg': forms.TextInput(attrs={'class': 'form-control'}), 'title_en': forms.TextInput(attrs={'class': 'form-control'}), 'title_de': forms.TextInput(attrs={'class': 'form-control'}), } Can someone say what I'm missing here? Thanks a lot! -
Django logging still prints out stacktrace
For some reason instead of just printing out the error message with logging it prints the stack trace to the console followed by the message: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'standard': { 'format': '[%(asctime)s] p%(process)s {%(pathname)s:%(lineno)d} %(levelname)s - %(message)s', }, }, 'handlers': { 'default': { 'level': env.str('LOGGING_LEVEL'), 'class': 'logging.StreamHandler', 'formatter': 'standard', }, }, 'loggers': { 'default': { 'handlers': ['default'], 'level': env.str('LOGGING_LEVEL'), 'propagate': True }, } } from logging import getLogger log = getLogger('default') def test(): try: raise Exception('This is a test exception') except Exception as error: log.error(str(error)) output: $ python manage.py custom_test_command # calls test method ... raise Exception('This is a test exception') Exception: This is a test exception [2021-02-08 16:27:40,299] p21052 {<console>:4} ERROR - This is a test exception -
How to update File field django
how to update a file field using the object model? my current code: impressao = Impressao.objects.get(id=id) My current condition: (it is getting inside the if condition, but it doesn't save the data) if request.FILES.get("uri_arquivo"): #uri file impressao.arquivo = request.FILES.get("uri_arquivo") impressao.save() model class Impressao(models.Model): comentario = models.CharField('comentario', max_length=255, blank=True, null=True) arquivo = models.FileField(name='uri_arquivo', max_length=400) qtd_copias = models.SmallIntegerField("qtd_copias") visualizado_em = models.DateTimeField("visualizado_em", blank=True, null=True) prazo_entrega = models.DateTimeField("prazo_entrega", blank=True, null=True) colorida = models.BooleanField("colorida", default=False) cliente = models.ForeignKey(Usuario, name="cliente", on_delete=models.CASCADE, null=True) imprimida = models.BooleanField("is_imprimida", blank=True, default=False) tipo = models.ForeignKey(TipoImpressao, on_delete=models.SET_NULL, null=True, name="tipo") -
Nginx (on docker)return 403 Forbiden when trying to get static files
I'm trying to render static and media files using Nginx but i'm always getting 403 forbidden. Some are ssaying that I need to set a USER in nginx.conf file but how ? Need your help. Dockerfile FROM nginx:1.19.0-alpine RUN rm /etc/nginx/conf.d/default.conf COPY ./nginx/nginx.conf /etc/nginx/conf.d my nginx.conf file upstream zandu { server gunicorn:8000; } server { listen 80; server_name localhost; root /app/nginx; location / { proxy_pass http://zandu; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; } location /static/ { alias /etc/nginx/staticfiles/; } location /media/ { alias /etc/nginx/media/; } } -
Custom field not showing in Admin page
I created a cutom user model for my project. And the extra fileds I created is not showing in the Admin page. I just see the standard fields and none of the extra made. I can't fins anything online about what i'm missing. My model for customuser: from django.contrib.auth.models import AbstractUser from django.db import models class CustomUser(AbstractUser): email = models.EmailField(blank=False, null=False) firstname = models.CharField(max_length=25, blank=True, null=True) surname = models.CharField(max_length=45, blank=True, null=True) mobilephone = models.IntegerField(blank=True, null=True) def __str__(self): return self.email My admin.py from django.contrib import admin from django.contrib.auth import get_user_model from django.contrib.auth.admin import UserAdmin from .forms import CustomUserCreationForm, CustomUserChangeForm from .models import CustomUser class CustomUserAdmin(UserAdmin): add_form = CustomUserCreationForm form = CustomUserChangeForm model = CustomUser list_display = ["surname", "firstname", "email", "mobilephone"] admin.site.register(CustomUser, CustomUserAdmin) Also, the field 'First name' and 'Last name' is not the same field as my custom user model. -
Multi step form category specified fields in vue js
I have built multi step form by using vue js. When user type is "business" we have to prompt multi step form in that we have 3 steps They are. first step form:- This form contains only one fields Category field. If user enters first form field then user can able to open category specified fields. second step form:- This form contains category specified fields. If user entered for example IT in first form in second form it has salary, job type,..etc. third step form:- Price package form for business user. If logged in user type is "Consumer" we need prompt like this multi step form. we have 3 steps again her, Those are. First step form:- In this we have category field. If user enters category then user clclick on next button we prompt next form. Second step form:- In this second form it prompts We asks a question like weather he want to continue as consumer or business in this form we have two radio button if user selects consumer we need prompt category specified fields again in third form. else if user selects business we need to prompt signuup form to update user to business in thrid … -
DigitalOcean spaces with django
I have a Learning Management System frontend written in React Js and backend written in django. Users can upload PDF files and image files from the frontend. PDF files are lessons and image files going to be user profile pictures, Subject pictures and course pictures I've configured Digitalocean spaces with the current setup. All the static files, images and pdf files are saving in the object storage. But I need to save pdf files and static files inside the object stiarage and Images inside backend servers. How can I configure django settings file to achieve that task AWS_ACCESS_KEY_ID = 'KEY_ID' AWS_SECRET_ACCESS_KEY = 'ACCESS_KEY' AWS_STORAGE_BUCKET_NAME = 'elearn-storage' AWS_S3_ENDPOINT_URL = 'https://fra1.digitaloceanspaces.com' AWS_S3_OBJECT_PARAMETERS = { 'CacheControl': 'max-age=86400', } AWS_LOCATION = 'storage' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static/'), ] STATIC_URL = 'https://%s/%s/' % (AWS_S3_ENDPOINT_URL, AWS_LOCATION) STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' DEFAULT_FILE_STORAGE ='storages.backends.s3boto3.S3Boto3Storage' This is my current configuration. What chages I need to make? -
Python Django website not showing on Ubuntu like on Windows
I run into a problem without understanding where it could come from. I have the same website in Django 3.0.8 under environment which works on one side on a PC with windows 10: preview on Windows On the other side, on an old PC with Xubuntu 20.04: preview on Xubuntu Everything is the same: code, files, environments, version of python (3.8). However, the Xubuntu version doesn't perform well as you can see. Do you have any idea what could be blocking? I have the impression that Bootstrap and FontAwesomeIcon are not working correctly. -
DJango admin read_only fields
Below is my admin.py file: # readonly_fields=['product_images'] def product_images(self, obj): return mark_safe( f''' <img class='product' src="{obj.product_image.url}"> <img class='product' src="{obj.product_back_image.url}"> <img class='product' src="{obj.product_pack_image.url}"> <img class='product' src="{obj.product_detailed_image.url}"> ''' ) def get_form(self, request, obj=None, **kwargs): # Proper kwargs are form, fields, exclude, formfield_callback if obj: # obj is not None, so this is a change page kwargs['exclude'] = ['product_image', 'product_back_image', 'product_pack_image', 'product_detailed_image'] # self.readonly_fields=['product_images'] else: # obj is None, so this is an add page kwargs['exclude'] = ['product_image_link', 'product_back_image_link', 'product_pack_image_link', 'product_detailed_image_link'] return super(ProductAdmin, self).get_form(request, obj, **kwargs) The problem is with the first line, if I uncomment it I get an error as below: Is there any work around for the same? -
Nuxt auth with cookies with DRF
I'm trying to implement authentication on my frontend (which is written in NuxtJS) using cookies as opposed to local storage. I'm using the nuxt-auth package, with the following configuration:- auth: { strategies: { cookie: { token: { required: false, type: false, }, user: { property: false, }, endpoints: { login: { url: '/auth/token/login/', }, user: { url: '/auth/users/me/', method: 'get', }, logout: { url: '/auth/token/logout', }, }, }, local: false, }, } My backend is django with rest framework and djoser with the following config:- DJOSER = { 'CREATE_SESSION_ON_LOGIN': True } REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.SessionAuthentication' ), } When I call the auth login method in my frontend, like this:- this.$auth.loginWith('cookie', { data: this.login, }) it all works as expected. The frontend calls /auth/token/login. The backend authenticates the user and sets the cookie in the browser. The frontend calls /auth/users/me which returns the user data and the frontend sets loggedIn to true. But when the user tries to logout in the frontend, the POST request fails because the CSRF token is not set. HTTP 403: CSRF Failed: CSRF token missing or incorrect. I've tried all sorts of other ways to set this stuff up and none of them seem … -
How to set '%' mark in as_sql query (custom Lookup) in Django?
I try to select phone numbers from DB ignoring (, ) , - symbols and allowing to search by substring I have a custom lookup from django.db.models import Lookup from django.db.models import Field class ContainsPhoneNo(Lookup): lookup_name = 'contains_phone_no' def as_sql(self, compiler, connection): lhs, lhs_params = self.process_lhs(compiler, connection) rhs, rhs_params = self.process_rhs(compiler, connection) print(lhs_params, rhs_params) params = lhs_params + rhs_params return "REPLACE(REPLACE(REPLACE(%s, '(', ''), ')', ''), '-', '') ILIKE %s" % ( lhs, rhs), params Field.register_lookup(ContainsPhoneNo) So right now, for example, if I filter by 2345, I can get (23)-45, 2-3-45, etc numbers. But I want to get also 123456. So my query should be "REPLACE(REPLACE(REPLACE(%s, '(', ''), ')', ''), '-', '') ILIKE %%s%" But I don't know how to set % symbols before and after second %s. Django don't allow to set % as is inside query string (I also tried '%'+str(rhs)+'%' way). So how can I do that? -
Django - Add custom field in django admin get_queryset method with multiple levels of prefetch_related
I have the following models. There are Stops in Cities. There are Connections between Stops. MODEL.PY class City(models.Model): pass class Stop(models.Model): city = models.ForeignKey(City, related_name='stops') class Connection(models.Model): origin = models.ForeignKey(Stop, related_name='origin_connections') destination = models.ForeignKey(Stop, related_name='destination_connections') In Django Admin view of City, I want to have clickable custom field showing the number of Connections with links to those Connections. I need the prefetch_related to prevent repetitive queries. Prefetch_related decreased the loading duration from 20 seconds to 1 seconds. ADMIN.PY class CityAdmin(TranslationAdmin): list_display = ["get_connection_count"] def get_queryset(self, request): queryset = super().get_queryset(request) queryset = queryset.prefetch_related('stops__origin_connections', 'stops__destination_connections') return queryset def get_connection_count(self, obj): """ City has 'stops' that, in turn, have 'origin_connections' and 'destination_connections'. Connection count for the city will be the count of connections that either start (origin) or end (destination) in 'stops' """ connections = [] for stop in obj.stops.all(): connections.extend(stop.origin_connections.all()) connections.extend(stop.destination_connections.all()) connections = list(set(connections)) # to drop duplicates connection_count = len(connections) url = reverse("admin:loc_connection_changelist") if connection_count: connections_id_str = ','.join(str(x.id) for x in connections) return format_html('<a href="{}?id__in={}">{} Connections </a>', url, connections_id_str, connection_count) else: return format_html('<a href="{}?id__in=-1">{} Connections </a>', url, connection_count) get_connection_count.short_description = "Connection count" I want to move the loop part from custom field to get_queryset() function. In other words I want to … -
Apostrophe showing as ' in html template
I have a template in django that is pulling in a question title into the title tag. <title>{{question.title}}</title> I find though that is the question contains an Apostrophe the resulting html file shows it as &#x27. e.g. If the title is: 'It won't work' the resulting html source looks like <title>It won&#x27;t work</title> Is this an issue? or will google etc see the title as it was meant to be and present it normally in search results? note: the title is pulled from a question model stored in a postgres db -
How Can I Publish My Flask Script Into Web
I made A Website With Flask And IDK How To Compile It And Publish Can You Help Me? -
django run server is not working from crontab script
I m writing my cronjob as below: */5 * * * * /bin/bash /root/gitsync.sh and content of gitsync.sh is as below: #!/bin/bash cd /root/devices-web git checkout main git pull echo "log1" >> /root/log.txt pip install -r requirements.txt python manage.py runserver 0.0.0.0:8000 Script is getting called every 5 minutes, but services are not running.