Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Access to django filter data on view
I want to display information regarding the filter criteria received in the form, in the template. What is the best way to access this data in the view? -
Python subprocess doesn't find the PYTHONPATH
I'm using subprocess to call a python script but it doesn't work because it doesn't find my PYTHONPATH. I have a my PYTHONPATH put and it goes inside my folder. let's say my PYTHONPATH contains this path: /home/myproject. My architecture is this one: /myproject/djangoView/view_x.py from my view_x.py I use subprocess to launch a script that is on /myproject/scripts/script.py Then I start my server django, I have to click on a button and it should launch my script.py, to be clear it does work in local, but it doesn't work in preprod which is a server ubuntu. The error I have is ModuleNotFoundbecause in my script I call/utils/utils.py` So I just don't really understand why I have an error, my PYTHONPATH is set and correct, all the imports calling /utils/utils.py are working except when I'm using subprocess in my preprod server. I can't reproduce it in local. Is someone have an explanation for this behavior ? Here is my call: subprocess.run(["nohup python3 /home/myproject/scripts/script.py &"], shell=True) Thanx. -
how can i create a html file template in django application?
I'm learning Django and I have a problem that there is no answer for it on internet here is the problem, I created a folder as 'app', and I create another folder in app as 'challenges' (in VS Code in a Django application), so we have 2 nested folders now I want to create an HTML page, and I create a file as 'index.html', but VS Code cannot know this file as an HTML file -
how to send multi args to Django custom templates from JS code inside HTML template
I'm trying to use a custom template tag to run a specific function on a variable that I get in JS inside my HTML template. here is a sample of what I tried : python template tag def calculate_km(value, arg): """ Calculate the km from the source """ args_list = eval(arg) layer_id = value return f"layer_id_is:{layer_id}, args_list:{args_list}" then am using it inside my HTML js block like this : const args_data = "[" + kmlEvent.featureData.id + "," + kmlEvent.latLng.lat + "," + kmlEvent.latLng.lng + "]"; console.log(`{{single_layer.id|calculate_km: ${args_data} }}`); The problem here is in adding the JS variable inside the template tag , as you see using args_data inside the string that should return syntax for normal Django template so what is expected is that the console.log line renders as follows : {{12|calculate_km:[12,Foo,123,456]}} But the problem is that it is not reading the value of the variable args_data and it is being rendered as : {{12|calculate_km: ${args_data}}} and of course, that returns an error which is : django.template.exceptions.TemplateSyntaxError: calculate_km requires 2 arguments, 1 provided so it seems like not even reading the value of args_data -
Django annotation + filtering
I've some data that I've loaded from SQLite to PSQL using pgloader, it works more or less but some types are a bit clunky, so that's why my dates are in string, but I don't think that's the issue ( might be wrong here) Consider the following models: class User(models.Model): hash_id = models.TextField(primary_key=True) first_name = models.TextField(blank=True, null=True) last_name = models.TextField(blank=True, null=True) class Education(models.Model): hash_code = models.ForeignKey('Users', models.CASCADE) startdate = models.TextField(blank=True, null=True) enddate = models.TextField(blank=True, null=True) class Job(models.Model): hash_code = models.ForeignKey('Users', models.CASCADE) jobends = models.TextField(blank=True, null=True) jobstarts = models.TextField(blank=True, null=True) I'm trying to get all the jobs after X years from the user's first Education. So far I've got a Subquery, to get the first education's start date for each user: # This should return a date eg: '2000-01-01' mba_start_subq = Educations.objects.filter(hash_code=OuterRef('hash_code')) .order_by('startdate') .values('startdate')[:1] ) Then I append this to each Job via: jobs = (Job.objects.all() # .distinct('hash_code') .order_by('hash_code') .annotate(mba_start = Subquery(mba_start_subq)) ) So far so good, the issue is when I try to add a .filter() afterwards it takes ages to get the response (basically an infinite loop kind of thing) # Filtering with date strings works jobs.filter( Q(jobstarts__lt = '2000-01-01'), Q(jobends__gt = '2002-01-01') ) # this is the desired … -
how to get object position in a queryset without for loop?
i have a queryset with length = 10000 users sorted_users = User.ojbects.all().order_by("-money") and i need to get a position of a particular user in this sorted query set, i can do it with foor loop: user_position = 1 for account in sorted_users: if account.username == "admin": break my_position += 1 print(user_position) it works fine, but in case of growing user numbers for example to 100 000, it would take a long time to count users position every time, for loop is slow how can i make it faster, without a for loop? -
Nginx raising 403 Forbidden when accessing Staticfiles in Django app on Digital Ocean
having completed a django project on local development in my system, i followed the Digital Ocean tutorial to deploy a django app here Digital Ocean Django ASGI setup Tutorial. i configured gunicorn according to the tutorials and all tests and confirmations are passed But when i load my site from its Public IP address the site loads without any styles or designs and no images...just as plain text (just html content) my nginx configuration is as follows server { listen 80; server_name XXX.XX.XXX.XX; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { alias /home/username/projectdir/staticfiles; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } and my django Project setting is as follows # The absolute path to the directory where collectstatic will collect static files for deployment. STATIC_ROOT = BASE_DIR / 'staticfiles' # The URL to use when referring to static files (where they will be served from) STATIC_URL = '/static/' # extra places to find static filed outside static folder inside installed apps STATICFILES_DIRS = [ BASE_DIR/"static" ] MEDIA_ROOT = BASE_DIR/"media" can any solution be suggested. i have seen all the other related stackoverflow questions that had similar issues but their solutions did not work for … -
DRF : 'DemoView' should either include a `queryset` attribute, or override the `get_queryset()` method
I want to create a serializer without model. myproject/myapp/views.py : from rest_framework import viewsets from rest_framework.response import Response from .serializers import DemoSerializer class DemoView(viewsets.ModelViewSet): def get(self, request): my_data = [{"name": "Harsha"}, {"name": "Harsha"}] results = DemoSerializer(my_data, many=True).data return Response(results) myproject/myapp/urls.py from django.urls import path, include from . import views from rest_framework import routers router = routers.DefaultRouter() router.register('demo', views.DemoView, basename='Demo') urlpatterns = [ path('', include(router.urls)), ] myproject/myapp/serializer.py from rest_framework import serializers # from .models import Demo class DemoSerializer(serializers.Serializer): name = serializers.CharField() When I goto URL: http://localhost:8000/demo/, it is giving me following error: DemoView should either include a queryset attribute, or override the get_queryset() method. How can I resolve this error? -
DRF SerializerMethodField ignoring result
I have 2 serializers (one nested in the other). I need to pass context so that I can get an absolute url. I can see it works based on printing as it runs. But the actual result ignores the method and just returns standard (im assuming because it doesnt think it has a context). class ProjectNoteFileSerializer(serializers.ModelSerializer): thumb = serializers.SerializerMethodField() def get_thumb(self, obj): try: print(self.context.get("request")) #this actually prints like it does have it thumbnail = get_thumbnailer(obj.path)["big"].url return self.context.get("request").build_absolute_uri(thumbnail) except: return None class Meta(object): model = models.ProjectNoteFile fields = ("id", "path", "thumb") class ProjectQuestionnaireSectionSerializer(serializers.ModelSerializer): note_files = serializers.SerializerMethodField() def get_note_files(self, obj): serializer_context = {"request": self.context.get("request")} serializer = ProjectNoteFileSerializer( obj.note_files.all(), many=True, context=serializer_context, ) print(serializer.data) #prints results as expected return serializer.data class Meta(object): model = models.ProjectQuestionnaireSection fields = ( ... "note_files", ... ) My actual result is "note_files": [ { "id": 1, "path": "/media/project_notes/project_note_d5c598da-d4e8-480e-a50a-c474d57a7d44.png", "thumb": null } ], I have other versions of this working across the app. Maybe I am missing something basic? -
Django restrict foreign key to common order
Below is an extract from my models.py. For the foreign key ce_hostname I am getting the options to include all ce_hostnames that exist within the database. What I actually want is the ce_hostname which only share the same order_reference. How can I achieve this? class Cx_Base(models.Model): order_reference = models.ForeignKey(Order, null=True, on_delete=models.CASCADE) #Order reference cx_hostname = models.CharField(max_length=15, validators=[CX_HOSTNAME_REGEX]) #Hostname of router i.e. PENNER-DCNCE-01. Always required. ce_hostname = models.ForeignKey(Ce_Base, null=True, on_delete=models.CASCADE) #Hostname of router in which the module will be inserted. -
DRF, Firebase FCM. Sending push notifications
I am creating a DRF project and want to implement sending push notifications to devices. I have configured firebase in Django settings. But after that I faced a problem as I can't send test notification even from admin, I get an error: enter image description here I understand that FCM registration token is required, but there is no way I can get it on backend side. Please advise if anyone has come across how is it possible to generate registration token on backend. -
Django- How can I allow only a set number of duplications with UniqueConstraint?
I'm making a webpage - a rental place that can rent movies, music cd's and books. I've created a model of cd - class Cd(models.Model): cd_band=models.CharField(max_length=100) cd_title=models.CharField(max_length=100) CD_GENRE= ( ('POP', "POP"), ("HIP", "Hip-Hop"), ("ROC", "Rock"), ("BLU", "Blues"), ("SOU", "Soul"), ("COU", "Country"), ("JAZ", "Jazz"), ("CLA", "Classical music"), ) cd_genre=models.CharField(max_length=3, choices=CD_GENRE) cd_length=models.DurationField() cd_rental=models.ForeignKey(Rental, on_delete=models.CASCADE, default=1) def __str__(self): # return self.cd_title, '\n', self.cd_band, '\n' return "{} {} {}".format(self.cd_band,self.cd_title,self.cd_genre) But there is a rule that I have to apply here: -One band can offer cd's in up to 2 genres. So let's say I create a cd of Band1 - Band1 can have cd's in only 2 genres - f.e rock and blues. I have no idea how to implement that. I'm thinking about making a constraint, but I don't know what condition to implement: UniqueConstraint.condition(fields=['cd_band','cd_genre'],condition=??????, name='unique_cd') I've also thought of restructurizing my entire database - making a separate classes for bands and music genres, and then linking it with foreign keys, setting up validators. I think it should work, but I'd have to put in so much work. Is there any other way of doing it? -
Please help me to host django project [closed]
Please help me to know how to host a django. https://i.stack.imgur.com/VmCkz.jpg /home/atmadevrt99/.virtualenvs/test/lib/python3.7/site-packages/django/core/wsgi.py File line 24 , in setup " /home/atmadevrt99/.virtualenvs/test/lib/python3.7/site-packages/django/init.py " , apps.populate ( settings . INSTALLED APPS ) line 91 , in populate File " /home/atmadevrt99/.virtualenvs/test/lib/python3.7/site-packages/django/apps/registry.py " , app_config AppConfig.create ( entry ) ) File " /home/atmadevrt99/.virtualenvs/test/lib/python3.7/site-packages/django/apps/config.py " , line 239 , in create " % s must supply a name attribute . " % entry ********************************** you're seeing -
DRF - make query parameter's key case insensitive
is it possible in DRF to make url query keys case insensitive. food_id = self.request.query_params.get("food_id") get value of food_id even if it is passed as FOOD_ID or food_ID and etc. Thank you in advance. -
Django Access to font gives origin has been blocked by CORS policy:
I have been trying to load fonts in my django html template but I am always seeing this error. Access to font at 'https://inson.s3.eu-central-1.amazonaws.com/fonts/Noah-Bold.woff2' from origin 'http://127.0.0.1:8000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. small part of my html code is here. <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Title</title> <style> @font-face { font-family: 'Noah-Medium'; src: url( 'https://inson.s3.eu-central-1.amazonaws.com/fonts/Noah-Medium.eot'); src: url('https://inson.s3.eu-central-1.amazonaws.com/fonts/Noah-Medium.eot?#iefix') format('embedded-opentype'), url('https://inson.s3.eu-central-1.amazonaws.com/fonts/Noah-Medium.woff2') format('woff2'), url('https://inson.s3.eu-central-1.amazonaws.com/fonts/Noah-Medium.woff') format('woff'), url('https://inson.s3.eu-central-1.amazonaws.com/fonts/Noah-Medium.ttf') format('truetype'), url('https://inson.s3.eu-central-1.amazonaws.com/fonts/Noah-Medium.svg#Noah-Medium') format('svg'); font-weight: 500; font-style: normal; font-display: swap; } my CORS config are here. CORS_ALLOWED_ORIGINS = ["http://127.0.0.1:8000"] CORS_ALLOW_HEADERS = list(default_headers) + [ "user-id", "phone-number", ] Any reason for the issue above? -
Is a heroku hobby dyno and hobby basic postgres a fixed monthly cost or can it become variable?
I'm interested in purchasing a heroku hobby dyno and hobby basic postgres for deploying my django app as it seems they are fixed prices which means I would have predictable pricing. My concern however is that since I am an amateur, I am worried about accidentally attracting a large bill which seems to happen with people using other modern deployment platforms. The cost should be $16 US per month. I get confused because it says charges are based on usage. Hasn't the price already been provided as a fixed cost? I simply want to deploy my django mvp web app and not have any surprise costs regardless of traffic or whatever could possibly incur extra charges. I'm quite confused can anyone help? -
Django-PayPal: I have 3 models and 3 signal receiver functions, but I’m unable to specify which should be called when a payment is received
I am using Django-Paypal to receive payments for 3 different services. Each service has a separate model (say, Service1, Service2 and Service3) but all are within the same app ‘payments’. I need to update the payment status of the correct model to ‘paid=True’ after receiving payment for the corresponding service. I have 3 payment processing views (each per service) which are working well, as all payments are completed successfully. Similarly, I have created 3 signals/receiver functions (each per model) and placed them in signals.py. When I test one signal at a time, it works well. The payment status is successfully updated to ‘paid=True’. However, when I include all the three signals in signals.py, things stop working. I noted that each time a payment is received, the first 2 receiver functions are fired, leading to an error. See the code at the bottom How do I specify which receiver function should be called when a payment is received from a specific model? Or which is the best way to implement the above successfully? When I am using inbuilt signals such as pre-save, it is possible to specify the model to be updated by adding the sender at the decorator e.g. @receiver(pre-save, … -
django allauth sign up error showing csrfmiddlewaretoken= in url
I am working on a project. I am using django allauth for authentication and I have properly configured the installation and application of django allauth. Login is working properly but when I go to signup form is takes the input but nothing happens on the screen but a little change appears on the url it shows : localhost:8000/accounts/signup/csrfmiddlewaretoken=... -
Django filter related objects use ORM
Imagine that, I have A Model and B Model. Class A (models.Model): a_name = models.CharField(max_length=100) Class B (models.Model): b_name = models.CharField(max_length=100) a_name = models.ForeignKey(A, on_delete=models.CASCADE, to_field="a_name", db_column="a_name") Then, I want to get A , and every A will have all related B A.filter(a_name="a_name").all() But I also want to filter B by b_name when I get the A result above, How can I do that? -
Objects don't upload the object in DB
I am trying to upload the object in DB, using django, but nothing happened. I run the command makemigration, migrate. admin.py from .models import Product admin.site.register(Product) models.py class Product(models.Model): user = models.OneToOneField(User, null = True, on_delete=models.CASCADE) #data = models.DateTimeField(verbose_name='date joined', auto_now_add=True) productC = ( ('apple', 'apple'), ('water', 'water'), ('tomato', 'tomato'), ) productChoose = models.CharField(max_length=10, blank=False, null= False, choices = productC) numbers= models.PositiveIntegerField() def __str__(self): return f"{self.user}" forms.py class ProductForm(forms.ModelForm): class Meta: model= Product fields =['productChoose', 'numbers',] productC = ( ('apple', 'apple'), ('water', 'water'), ('tomato', 'tomato'), ) widgets = { # 'data': forms.DateTimeField(attrs= {'class': 'form-control'}), 'productChoose': forms.Select(choices= productC, attrs= {'class': 'form-control'}), 'numbers': forms.NumberInput(attrs= {'class': 'form-control'}), } def clean_productChoose(self): if self.is_valid(): productChoose=self.cleaned_data['productChoose'] return productChoose def clean_numbers(self): if self.is_valid(): numbers=self.cleaned_data['numbers'] return numbers view.py def training_view(request, *args, **kwargs): if not request.user.is_authenticated: return redirect('/login') context = {} if request.method=="POST": products=ProductForm(request.POST, instance = request.user) if products.is_valid(): products.save() return redirect('/home') messages.info(request, 'Your training has been send with success!') else: products=ProductForm(instance = request.user) context['training_form']= prodcuts return render(request, 'product.html', context) product.html {% block content%} <form method="POST" action="."> {% csrf_token %} <h1>Products </h1> <div class="container"> {% csrf_token %} <p> <label for="productChoose"><b>Product </b></label> {{products.productChoose}} </p> <p> <label for="numbers"><b>Numbers: </b></label> {{training_form.numbers}} </p> <button type="submit" name="submit" > Submit </button> </div> </form> {% endblock%} … -
Is there a way to send messages from localhost to google [less secure]?
this question doesn't exist because there is new news about sending messages from Django using localhost to google. I know that to send messages from localhost to google I should launch the "less secure" button in google but it turns out this property is no longer available by google as you can see from the following link: https://support.google.com/accounts/answer/6010255?hl=en&utm_source=google-account&utm_medium=profile-less-secure-apps-card now I need to test my SMTP server if it was working or not by Django and if it was sending a message to google so, How can I accomplish that task by localhost in that case? -
How to serialize multi object in django?
I used ajax to fetch data from database. How can i fetch objects and send them? views.py def fetchdata(request): if request.method == 'GET': val1 = request.GET['param1'] val2 = request.GET['param2'] obj = Reserve.objects.filter(~Q(con__title = val1 ), dt__title=val2 ).values('dt__title','con__title') ser_instance = serializers.serialize('json', [obj,]) return JsonResponse({"instance": ser_instance}, status=200) else: return HttpResponse("Request method is not a GET") con and dt are foregn keys fields. -
Django nested viesets on router
In my urls.py file in some app i have the following code: from rest_framework import routers from .viewsets import (JournalViewSet, StatisticViewSet, FuelLogViewSet, MoveLogViewSet, RestLogViewSet, WinLogViewSet, GreatfulLogViewSet) router = routers.DefaultRouter() router.register(r'journal', JournalViewSet) router.register(r'journal/statistic', StatisticViewSet) router.register(r'journal/fuel', FuelLogViewSet) router.register(r'journal/move', MoveLogViewSet) router.register(r'journal/rest', RestLogViewSet) router.register(r'journal/win', WinLogViewSet) router.register(r'journal/greatful', GreatfulLogViewSet) urlpatterns = router.urls All vievsets above are not something specific, and use only serializer_class and queryset. Swagger generate correct scheme, but DRF says, that i have no POST method allowed (in viesets i actually have) and when i try to open url like 127.0.0.1:8000/journal/win, drf return scheme for journal. When registers were not nested like router.register(r'move', MoveLogViewSet), I get all correct. I understand, that DRF maybe don't provide nested routs like I have. What should I do? -
How to get my messages to show on Django for a registration form?
I am creating a registration form using the Django framework and I want to display some error messages to the user if they enter the wrong confirm password, or an email already taken etc. I have written the code and it seems to be working, but I can't seem to get the messages to show on screen upon redirecting to back to registration page if there is an error in the form. I have imported messages on the views.py page (from django.contrib import messages) and I think my setting.py is all configured correct: setting.py Here is my views.py code: def register(request): if request.method == "GET": register_form = RegisterForm() return render(request, "main/register.html", { 'form': register_form }) else: register_form = RegisterForm(request.POST) if register_form.is_valid(): first_name = request.POST['first_name'] last_name = request.POST['last_name'] username = request.POST['username'] email = request.POST['email'] password = request.POST['password'] confirm_password = request.POST['confirm_password'] if password == confirm_password: if User.objects.filter(email=email).exists(): messages.info(request, 'Email or user name Already taking') return redirect('register') elif User.objects.filter(username=username).exists(): messages.info(request, 'username is taken') return redirect('register') else: User.objects.get_or_create(username=username, first_name=first_name, last_name=last_name, email=email, password=password) return redirect('main/login.html') else: messages.error(request, 'Password Not Match') return redirect('register') #return redirect ('/') else: return render(request, 'main/login.html') and this is my register.html form: <form action="{% url 'register' %}" method="POST"> {% csrf_token %} <fieldset> … -
Django multiupload error: 'list' object has no attribute 'name'
I'm trying to use multiupload in django form for upload several images at once. I'm using django ModelForm but when i'm calling form.is_valid() in function-base view or using generic.FormView, i'm getting 'list' object has no attribute 'name' error. in generic.FormView neither of form_valid and form_invalid methods aren't called. although when I use request.POST.get(some_data) it works without any errors but I want to use generic.FormView for some validations. I think the validation of the form makes the error happen. so what should I do? here is my code. models.py class Post(models.Model): post_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False, unique=True) profile = models.ForeignKey(Profile, on_delete=models.CASCADE, related_name="posts") text = models.TextField(max_length=1000) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) ... class Image(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name="images") image = models.ImageField(upload_to="images/posts/") forms.py class PostForm(forms.ModelForm): images = MultiImageField(min_num=1, max_num=3) class Meta: model = models.Post fields = ("text", "images") views.py class CreatePostView(LoginRequiredMixin, generic.FormView): template_name = "posts/post_create.html" form_class = forms.PostForm def get_success_url(self): return redirect("profile", slug=self.request.kwargs.slug) def form_valid(self, form): ... # some codes ... return super(CreatePostView, self).form_valid(form)