Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Deploying through Heroku button failed
I tried to deploy all three of them on Heroku but failed at doing it with storefront. Deploying other two was successful but when installing nodejs packages it failed. At the end of the build log it mentioned the model's key? Should be unique but I am not quite sure. The store core when opened with dashboard looked prepopulated already without me hitting populatedb command as mentioned in their docs. Is this fact related to my store front deployment failure? -
Django redirect after successful login is not working in production with Nginx
So I have a project that works fine in localhost and all redirects work after a successful login but in production (Ubuntu 18.04 digitalocean + Nginx and Gunicorn) the page just redirects me again to the homepage which is the login page. Here is my project config file for Nginx server { listen 80; server_name ip_addres; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/user/project; } location /static/admin { alias /home/user/project/projectenv/lib/python3.6/site-packages/django/contrib/admin/static/admin; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } and this is proxy params that is included proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; client_max_body_size 10m; client_body_buffer_size 128k; proxy_connect_timeout 90; proxy_send_timeout 90; proxy_read_timeout 90; proxy_buffers 32 4k; -
Django fcm gives InvalidRegistration
I'm currently trying to use django-fcm to push notifications but I'm having a problem. I followed many configs but I'm always having a problem connecting to firebase, I'm getting the following error {'multicast_ids': [5220972250677554440], 'success': 0, 'failure': 1, 'canonical_ids': 0, 'results': [{'error': 'InvalidRegistration'}], 'topic_message_id': None} my FCM config in settings.py FCM_DJANGO_SETTINGS = { "FCM_SERVER_KEY": USER_FCM_KEY , "ONE_DEVICE_PER_USER": False, "DELETE_INACTIVE_DEVICES": False, } And my test code is from fcm_django.models import FCMDevice from django.contrib.auth import get_user_model device = FCMDevice() device.device_id = "Device ID" device.registration_id = "Device registration id" device.type = "Android" device.name = "Can be anything" device.user = get_user_model().objects.all().first() device.save() device.send_message(title="Title", body="Message", data={"test": "test"}) My API_KEY is valid I tried generating it again many times from firebase console > cloud messaging Please do you know what might be going wrong ? thanks. -
Case When then column name Django
I need to add a column to my query and change the value based on a condition for example if buy = True then column value should be amount column otherwise it should be price column * amount column I'm trying this but doesn't work: OrderBook.objects.filter(Q(user_id=self.owner.pk), Q(is_open=True)).annotate( locked_value=Case( When(condition1,then=Value(F("amount"))), When(condition2, then=Value(F("amount") * F("price")), default=Value(F("amount")), output_field=models.DecimalField() ) ) i keep getting this error: Error binding parameter 1 - probably unsupported type. -
Build a persistent elasticsearch index in Docker?
I am using Docker for my Django Project where I use Elastic search. I can create an elastic search index successfully with docker-compose exec web python3 manage.py search_index --rebuild but as soon as I close the elastic search terminal and run docker run -p 9200:9200 -p 9300:9300 -e "discovery.type=single-node" docker.elastic.co/elasticsearch/elasticsearch:7.13.4 again, to start elastic search, aftwerwards the index is gone. How can I make the index persistent? -
Deleting currently viewed data after button click - Django
When the user clicks an html button, I call a django view function. This function should delete the data that the user is currently viewing and redirect them to a new page, but it seems to be deleting the entire database, not just specific data. I have tried filtering and using self.pk, but it does not seem to work. I render out my data using a url which is assigned to a class based view, I then have a function associated with the button to delete. Can someone please help me with my problem? My code is down bellow. URL: path('donations/<int:pk>/', views.DonationDetail.as_view(), name='donation-detail'), Class Based View (To get the data and render it out): class DonationDetail(DetailView): model = Donation queryset = Donation.objects.all() template_name = 'acceptdonation.html Function to delete data: def acceptdonation(request): deleteitem = DonationDetail.queryset() deleteitem.delete() #seems to delete the entire database return redirect('/dashboard/') return render(request, 'acceptdonation.html', ) -
django-rest-framework-simplejwt validate parameter inside the token
I use django-rest-framework-simplejwt to authentification. In each request I need to check tokens if some variable is valid (if create_time < last change password i will refuse connection). Whats the best way to do it in django? I think the best solution is to create new class with validation, but I have no idea what it should include? I have 3 candidates 'USER_AUTHENTICATION_RULE': 'rest_framework_simplejwt.authentication.default_user_authentication_rule', 'AUTH_TOKEN_CLASSES': ('rest_framework_simplejwt.tokens.AccessToken',), 'DEFAULT_AUTHENTICATION_CLASSES':('rest_framework_simplejwt.authentication.JWTAuthentication',) -
Django Equivalent to SQL SCORE(1) when using contains
I am trying to rewrite this raw SQL query as Django: SELECT SCORE(1), * FROM article WHERE CONTAINS(synopsis, 'something', 1) > 0 ORDER BY 1 DESC With the model setup, it is quite simple really (synopsis is a models.CharField) article.filter(synopsis__icontains=query) But I cannot find how to pull out some kind of best match ordering from the Django query. I've also noted that the actual SQL query generated by Django does not use CONTAINS, it uses LIKE. It is important to maintain the ordering of results returned based on the SCORE result of CONTAINS. However, I cannot find a Django equivalent to SCORE. Is there a Django equivalent to the SQL SCORE? -
Django Telegram bot not responding on Heroku
I deployed my bot to Heroku but it is not responding I have a doubt regarding the Procfile, thi is what I currently have: web: python3 bot.py web: gunicorn tlgrmbot.wsgi This is what I see in the logs: 2021-07-27T21:25:56.080317+00:00 heroku[web.1]: Starting process with command `gunicorn tlgrmbot.wsgi` 2021-07-27T21:26:00.590684+00:00 heroku[web.1]: State changed from starting to up 2021-07-27T21:26:00.092958+00:00 app[web.1]: [2021-07-27 21:26:00 +0000] [4] [INFO] Starting gunicorn 20.1.0 2021-07-27T21:26:00.093896+00:00 app[web.1]: [2021-07-27 21:26:00 +0000] [4] [INFO] Listening at: http://0.0.0.0:54428 (4) 2021-07-27T21:26:00.094088+00:00 app[web.1]: [2021-07-27 21:26:00 +0000] [4] [INFO] Using worker: sync 2021-07-27T21:26:00.106699+00:00 app[web.1]: [2021-07-27 21:26:00 +0000] [9] [INFO] Booting worker with pid: 9 2021-07-27T21:26:00.157630+00:00 app[web.1]: [2021-07-27 21:26:00 +0000] [10] [INFO] Booting worker with pid: 10 2021-07-27T21:25:59.000000+00:00 app[api]: Build succeeded 2021-07-27T21:26:06.266840+00:00 app[web.1]: 10.43.228.207 - - [27/Jul/2021:21:26:06 +0000] "POST / HTTP/1.1" 200 10697 "-" "-" 2021-07-27T21:26:06.267235+00:00 heroku[router]: at=info method=POST path="/" host=tlgrmbotgym.herokuapp.com request_id=a7b1fd84-93d2-4fdb-88cd-941dd581b4c1 fwd="91.108.6.98" dyno=web.1 connect=0ms service=37ms status=200 bytes=10924 protocol=https and this is how I setup the webhook in bot.py mode = os.environ.get("MODE", "polling") if mode == 'webhook': # enable webhook updater.start_webhook(listen="0.0.0.0", port=PORT, url_path=TOKEN) updater.bot.setWebhook('https://tlgrmbotgym.herokuapp.com/'+TOKEN) else: # enable polling updater.start_polling() updater.idle() -
My data from my model is not showing up on my webpage through templates
I am trying to show the data on the webpage but I am not able to figure out why the data is not populated on the webpage my model is this class Staff(models.Model): staffid = models.BigAutoField(primary_key=True) firstname = models.CharField(max_length=20) lastname = models.CharField(max_length=20) phonenumber = models.CharField(max_length=15, unique=True) def __str__(self): return self.firstname def staff_name(self): return "{} {}".format(self.firstname, self.lastname) def get_absolute_url(self): # new return reverse('staffdetail', args=[str(self.staffid)]) my views for this is class StaffListView(ListView): model = Staff template_name = 'staffview.html' and the template is {% extends 'base.html' %} {% block content %} <p><a href="{% url 'staffnew' %}">Add a new Staff member</a></p> {% if staff %} There are {{ staff|length }} records: {% for s in staff %} <div class="client-entry"> <p><a href="{% url 'staffdetail'%}">{{ s.staffid }}</a></p> </div> {% endfor %} {% else %} There are no staff in the system {% endif %} {% endblock content %} The output on the web page just gives me the else statement. I checked in Django admin and found that there is data in the staff table. Not sure what I am doing wrong. Any help would be appreciated. -
Having trouble to get the total price of the basket's items (Django)
So I'm trying to get the total amount of the basket but having trouble doing so. Am I calling it wrong? I'm new so... Html(here is the way i calling it): <p>Total:{{basket.get_basket_total}}</p> models: class Products(models.Model): products_name = models.CharField(max_length=30) pub_date = models.DateTimeField(auto_now=True) price = models.DecimalField(max_digits=5, decimal_places=2) note = models.CharField(max_length=200) inventory = models.IntegerField(default=1) product_pic = models.ImageField(upload_to ='images/', default='images/broken/broken.png') def __str__(self): if (self.inventory<=0): return self.products_name + ' (Out of Stock)' return self.products_name class Basket(models.Model): products = models.ForeignKey(Products, on_delete=models.SET_NULL, null=True, blank=True) pub_date = models.DateTimeField(auto_now=True) amount = models.IntegerField(default=1) def __str__(self): return str(self.products) @property def get_total(self): total = self.products.price * self.amount return total @property def get_cart_total(self): basket_items = self.basket_set.all() total = sum([item.get_total for item in basket_items]) return total -
Cannot send Django sampling to XRAY on aws
I have a EC2 instance, with XRAY daemon installed in it. Also, policy AWSXRayDaemonWriteAccess is attached to the role. Simple Django application deployed to EC2, with default xray configuration. In the application logs I see: File "/usr/local/lib/python3.9/site-packages/botocore/httpsession.py", line 352, in send raise EndpointConnectionError(endpoint_url=request.url, error=e) botocore.exceptions.EndpointConnectionError: Could not connect to the endpoint URL: "http://127.0.0.1:2000/GetSamplingRules" I have the following configurations in django app: XRAY_RECORDER = { 'AWS_XRAY_CONTEXT_MISSING': 'LOG_ERROR', 'AWS_XRAY_TRACING_NAME': 'My application', 'PLUGINS': ('EC2Plugin', 'ECSPlugin'), } Why the application fails to connect to Xray daemon? -
Django get access to foreign key of current object in views.py
I have three models: Class Collection(models.Model): var_1 = ..... var_2 = .... Class Titles(models.Model): var_a = models.ForeignKey(Collection, related_name="has_titles", on_delete=models.CASCADE) var_b = ... Class OtherObject(models.Model): var_x = models.ForeignKey(Collection, related_name="has_other_object", on_delete=models.CASCADE) var_y = ... In views.py I use CBV DetailView with a form in it (using then formMixin or MultipleFormsMixin, but this is not the point). So basically each Title is linked to a Collection by a ForeignKey and each OtherObject is linked to a Collection by a ForeignKey as well. So, when the user is in a detail page of Title model, he has the posibility to fill in a form to add a OtherObject, that will then be displayed on the Collection detailView that is linked to the Title. In other words, what I want is var_x = var_a of current Title : if form.is_valid(): new_other_object = form.save(commit=False) new_other_object.var_x = HERE I WANT TO GET var_a OF CURRENT OBJECT new_fact.save() So, as Title has a ForeignKey containing the ID to Collection it belongs to, I tried to use things such as self.get_object(). I read things such as using self.get_object().var_a could work but with all the different solutions I tried I got errors, mainly the error mentionning that object must be … -
using (post) request from frontend to trigger Django script on backend
Pretty new to Django (and fullstack), thanks for help! Objective: My basic need is to be able to have React (or any frontend) communicate/trigger a django script from within frontend, (and eventually get the results back into frontend after the script runs). I have created the following code to create this utility, if you have a totally different way to achieve this objective, feel free to inform me regardless of code below. Approach: I THINK I need to structure the view in views.py to trigger when it receives a post/get request and then send the data to the source of the request. I tried using @require_POST by importing django.views.decorators.http. From my understanding this means it will ONLY except post requests, and run if the trigger is a post request. When I post to the url I get a 404 error, but when I comment out @require_POST and throw in a return HttpResponse the website loads fine. I also have a working django restapi via restapi_framework (which I need for other purposes) and I have made successful get requests to it. I am happy to use this part of the app/views if it'll help me. (parts of) my Code: I am … -
Django Haystack and Whoosh: How do I store the whoosh index created on Amazon S3?
I'm a newbie trying to build a website and have deployed it onto heroku. I have incorporated a search function using Django haystack and whoosh. I noticed that my search function fails because heroku wipes the search indexes created during its daily dynos restart. With that being said, I'm looking for ways to save the search index on amazon s3 such that the search index will be preserved beyond 24 hours. Is anyone familiar with this and is able to guide me through the process? Thank you very much for your help!! -
How can I send email from Django app deployed in digital ocean?
I created a Django project where I send email using Gmail. It's working on my local server, but when I deploy the project to the digital ocean, the email is not sent. What can I do now? -
django how to convert request json string to object to process it
I receive this json response from web page data=%7B%22header%22%3A%22%7B%5C%22salno%5C%22%3A%5C%220%5C%22%2C%5C%22saldt%5C%22%3A%5C%22Wed+Jul+28+2021+00%3A33%3A40+GMT%2B0530+(India+Standard+Time)%5C%22%2C%5C%22soldto%5C%22%3A%5C%22%5C%22%2C%5C%22remark%5C%22%3A%5C%22%5C%22%2C%5C%22totqty%5C%22%3A310%2C%5C%22subtot%5C%22%3A20251%7D%22%2C%22details%22%3A%22%5B%7B%5C%22status%5C%22%3A%5C%22old-modified%5C%22%2C%5C%22saldtlid%5C%22%3A%5C%221%5C%22%2C%5C%22itemnm%5C%22%3A%5C%22item1%5C%22%2C%5C%22qty%5C%22%3A%5C%2218%5C%22%2C%5C%22rate%5C%22%3A%5C%2212.00%5C%22%2C%5C%22amount%5C%22%3A%5C%22216.00%5C%22%7D%2C%7B%5C%22status%5C%22%3A%5C%22new-record%5C%22%2C%5C%22saldtlid%5C%22%3A%5C%22-10%5C%22%2C%5C%22itemnm%5C%22%3A%5C%22new+item%5C%22%2C%5C%22qty%5C%22%3A%5C%2210%5C%22%2C%5C%22rate%5C%22%3A%5C%2210.00%5C%22%2C%5C%22amount%5C%22%3A%5C%22100.00%5C%22%7D%5D%22%7D&csrfmiddlewaretoken=q1ortMN1jyzBIJVn6qOREBLiNr3Lc7njhvI24lT93gLb5VNzWutot0qDeNvlyY5d the actual object contains invoice information and one csrfmiddlewaretoken the invoice data has 1 header dict object and multiple detail dict array how to convert the above to python objects so that I can process it -
Django Tabularinline with Auto complete field
I am trying to implement an auto complete field in a tabular inline model.where a user selects a site and the address cell is consequently filled with the appropriate address I defined my fields in a form as below : self.fields['sites'].widget = forms.Select( attrs={ 'id': 'id_sites', 'onchange': 'getsiteaddress(this.value)', 'style': 'width:200px' }, choices=sites_list, ) self.fields['site_address'].widget = forms.TextInput( attrs={ 'id': 'id_siteaddress', 'style': 'width:200px' } ) Everything works fine for the first row My issue is that when I move to the second row of the inline model and select an address the cell of the first row is the one that changes. How can I call the second row? This is my jquery function function getsiteaddress(site){ let $ = django.jQuery; $.get('/Delivery/deploymentsite/'+ site, function(resp){ $('#id_siteaddress).val(resp.data) }); } I would really appreciate any help -
How do you set up a subprocess to receive api requests in Heroku?
I have a react frontend deployed to a web process on Heroku. I have a django backend that is deployed to an app process as shown below. I keep getting a 502 error, so I originally thought my issue was in django. However, after a mistake where I had the react open already, and changed the web process to be django, I had a fully functioning app. However, after a little bit of clicking around, I only got the backend. Long story short, I need a way for my backend to receive api request calls from my frontend. Nothing I have done seems to have worked. Having two web processes doesn't work because Heroku only takes the last one and basically ignores the other one. As it stands, I am using http requests as the api call, but realistically, I just need a way to communicate between Django and React. If I have to redo something, I am willing to do so. Procfile release: python manage.py migrate backend api: gunicorn backend.wsgi:application web: bin/boot To be clear, web: bin/boot is a buildpack specifically for react apps. It works just fine, and I do not believe it is the issue. -
Djanog - Is there a better approach for a DRY CRUD solution in views.py?
I'm fairly new to Django, and I am trying to understand a better way to implement CRUD in my views.py file. Example view.py: # Assume I have two generic models: Foo and Bar from django.views.generic import UpdateView, DeleteView from .forms import FooForm, BarForm from .models import Foo, Bar class FooUpdateView(UpdateView): model = Foo form_class = FooForm template_name = 'foo_form.html' success_url = reverse_lazy('success-page') class BarUpdateView(UpdateView): model = Bar form_class = BarForm template_name = 'Bar_form.html' success_url = reverse_lazy('success-page') class FooDeleteView(DeleteView): model = Foo template_name = 'foo_delete.html' success_url = reverse_lazy('success-page') class BarDeleteView(DeleteView): model = Bar template_name = 'Bar_delete.html' success_url = reverse_lazy('success-page') Is there a way like the example below, where I can create a base class that I can inherit from, but still allows me to override and customize functions and variables. class UpdateBaseView(UpdateView): form_class = self.model_form template_name = 'self.model_form.html' success_url = reverse_lazy(success_url) class FooUpdateView(UpdateBaseView): model = Foo class BarUpdateView(UpdateBaseView): model = Bar success_url = reverse_lazy('bar-success') -
Django Models: How to write query for multiple value with filtering multiple value
I have user local_user and personal models. I try to make a query with the multiple results but should filtered with multiple value. Models have one to one relations between each other. There are models. class Hospital_Local_User(models.Model): id = models.AutoField(primary_key=True) email = models.CharField(max_length=45) password = models.CharField(max_length=45) phone = models.CharField(max_length=45) class Personal (models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=255) lastname = models.CharField(max_length=255) user_roles_id = models.ForeignKey(User_Role, on_delete=models.CASCADE) hospitals_id = models.ForeignKey(Hospital, on_delete=models.CASCADE) hospital_local_users_id = models.OneToOneField( Hospital_Local_User, on_delete=models.CASCADE) and This is the code I try to build. def listDoctors(request): userRole = User_Role.objects.get(id=2) Doctors = Personal.objects.filter(user_roles_id=userRole) hospLocUser = Hospital_Local_User.objects.filter(id=Doctors) serialized_queryset = serializers.serialize('json', hospLocUser) return JsonResponse(json.loads(serialized_queryset), safe=False) I try to make two objects then merge them into one object because when I try to convert Personal model to json it does not show email and phone fields. It just shows them as local_user_id. I do not need local user id I need fields in it. -
Pytest and mixer does not raise errors when testing non model fields
I am following Test driven development and am working through Django models with mixer, Pytest and pytest-django. This is the test for the Project model: class TestProject: def test_model_valid_fields(self, django_user_model): project = mixer.blend( 'workspaces.Project', title="Road map", non_model_field="some value" ) assert project.pk == 1 assert project.title == "Road map" assert project.non_model_field == "some value" The Project model, notice that Project model has only the title field: class Project(models.Model): title = models.CharField(max_length=200) Two things: How is mixer allowing the use of non model fields? Why is Pytest not raising an error, since the Project model does not have non_model_field field? What am I missing here? -
Difference between a File and Record
Please what's the difference between File and Record I have searched the whole Google and I have not seen any answer. -
Running django view/function on button click
I have the following button: <a class="btn btn-success">Accept</a>. Like this previous stack overflow question, I want to call my view after the button is clicked, but I can not seem to get it to work. What I have tried: Using AJAX, treating button like a form, requesting post data, but this does not seem to work. How can I make it so when my button is clicked, I call the bellow view? def acceptdonation(request, pk): Donation.objects.filter(pk=pk).update(views=F('views')+1) return HttpResponseRedirect(request.GET.get('next'))) -
innerHTML not working for select tag when i want to change new options
html code: <div class="row clearfix"> <div class="col-sm-12"> <div class="form-group"> <select id="domain" class="form-control show-tick" onchange="myFunction1()"> {% for item in domains %} <option value=" {{item.0}} ">{{item.1}}</option> {% endfor %} </select> </div> </div> </div> <div class="row clearfix"> <div class="col-sm-12"> <div class="form-group"> <select id="2"> <option></option> </select> </div> </div> </div> js function: <script> function myFunction1() { x = document.getElementById("domain").value; document.getElementById("2").innerHTML += "<OPTION>1</OPTION>"; alert(x); } </script> I am trying to change the drop-down box with id set as 2 when an on-change function is called in other drop-down box. Code looks good but i cant see the new options added.