Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
In Django E-commerce app, how I send user wishlist (when user is not logged in) data to cart after user logged in, I used session for Wishlist
For that I used session to store product information for the wishlist and bu can't send when user is logged in/. -
Django backward foreign key query not working
hi i am working on a chat application on django with django channels and i am trying to query all the first messages of the user here when i do user.message_set.all() it is throwing AttributeError at / 'User' object has no attribute 'message_set' full traceback: Traceback (most recent call last): File "/home/__neeraj__/.local/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/home/__neeraj__/.local/lib/python3.9/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/__neeraj__/Documents/chat/home/views.py", line 10, in index print(i.messages_set.all()) AttributeError: 'User' object has no attribute 'message_set' my models.py class Message(models.Model): sender = models.ForeignKey(User, on_delete=models.CASCADE, related_name="sender") receiver = models.ForeignKey( User, on_delete=models.CASCADE, related_name="receiver" ) text = models.CharField(max_length=2000) created_on = models.DateTimeField(auto_now=True) my view : def index(request): users = User.objects.all() context = {"users": users} for user in users: print(user.message_set.all()) return render(request, "index.html", context=context) is this because i have double foreign key reference of user model on message table? -
while going through api/register url the following error occurs AttributeError: 'function' object has no attribute '_meta'
urls.py file from .views import RegisterAPI , LoginAPI from knox import views as knox_views from django.urls import path from accounts import views urlpatterns = [ path('' , views.index , name='home') , path('register' , views.register , name='register') , path('login' , views.login , name='login') , path('logouts' , views.logouts , name='logouts') , path('api/register/', RegisterAPI.as_view(), name='register'), path('api/login/', LoginAPI.as_view(), name='login'), path('api/logout/', knox_views.LogoutView.as_view(), name='logout'), path('api/logoutall/', knox_views.LogoutAllView.as_view(), name='logoutall'), ] above file is my urls.py file in which i am getting error when i am trying api/register -
How do you set select date in class CreateView (django.views.generic) for deadline?
I can select date for deadline if I creating gig in admin, but when user creates a new gig the datefield doesn't work in the form and I don't know how to set it. Can someone help? views.py class GigCreateView(CreateView): model = Gig template_name = 'gigs/create_gig.html' fields = ['title', 'industry', 'city', 'country', 'gigdescription', 'deadline', ] create_gig.html <form method="POST" enctype="multipart/form-data"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">Create Gig</legend> <div class="card-body"> <h6 class="card-text">Title: &nbsp; {{form.title}}</h6> <h6 class="card-title">Profession: &nbsp; {{form.profession}}</h6> <h6 class="card-title">City: &nbsp; {{form.city}}</h6> <h6 class="card-text">Deadline: &nbsp; {{form.deadline}}</h6> <h6 class="card-text">Description: &nbsp; {{form.gigdescription}}</h6> </div> </fieldset> <div class="row justify-content-center"> <!-- Edit button --> <div class="form-group col-3 text-center"> <button class="btn btn-edit" type="submit">UPDATE</button> </div> <!-- Delete button --> <div class="form-group col-3 text-center"> <button class="btn btn-delete" type="#">DELETE</button> </div> </div> </form> -
Cannot assign "...'": "TestData.user" must be a "User" instance
Very new to the Django Rest Framework, so would appreciate some help with this one. I get the error in the title when I try and do a POST request in Postman with an appropriate auth token. I've made a table that I want to send a POST request to, but having issues with getting a user FK to be accepted as one of the columns. Plz see model/serializer/view below: Model class TestData (models.Model): TestSDG = models.DecimalField(decimal_places=0, max_digits=2, default=0) user = models.ForeignKey("auth.User", related_name="testdata", on_delete=models.CASCADE) Serializer class TestDataSerializer(serializers.ModelSerializer): class Meta: model = TestData fields = ('id', 'TestSDG') View @csrf_exempt def testDataApi(request, id=0): if request.method == 'GET': testdata = TestData.objects.all() testdata_serializer = TestDataSerializer(testdata,many=True) return JsonResponse(testdata_serializer.data,safe=False) elif request.method == 'POST': testdata_data=JSONParser().parse(request) testdata_serializer=TestDataSerializer(data=testdata_data) if testdata_serializer.is_valid(): testdata_serializer.save(user=request.user) return JsonResponse("Added Successfully", safe=False) The POST request works fine if I don't use the user as a foreign key, and I change testdata_serializer.save(user=request.user) back to testdata_serializer.save(), but I want the table to require a user's id. Appreciate any help, thank you. -
drf-yasg cover all responses to following implemented standard api response
I did implement the standard API response such as this article in my app. And I also implement drf-yasg for my API documentation. As we know the schema are using directly serializer to present the response. How I can cover all these below response examples by using drf-yasg schema? 1. Success Single { "status": 200, # int : http status, can be 201, 200, etc. "success": true, # bool: boolean to identify the response is success or failed. "message": "The success message", # str : string success message or null "result": {} # dict: a dict response data } 2. Success List { "status": 200, # int : http status "success": true, # bool: boolean to identify the response is success or failed. "message": null, # str : string message or null. "results": [], # arr : a list/array "count": 2, # int: all total result items "page_size": 5, # int: maximum items per-page "current_page": 1, # int: your current page "next": "http://127.0.0.1:8000/api/page/?page=2&search=a", # str: string link or null. "previous": null # str: string link or null. } 3. Error or Failed { "status": 400, # int : http status, can be 403,404,500,etc.. "success": false, # bool: boolean to identify … -
How to make new blog page with Wagtail in existing Django web-application project
I'm looking to add a blog page to an existing Django app that can be managed by Wagtail. Currently, using the official Wagtail documentation, Wagtail can be installed in the Django project, and the blog administration page (http://127.0.0.1:8000/cms/) is shown. However, even if I edit view.py and template.py, the Blog page (http://127.0.0.1:8000/blog/ ) remains in the initial screen("Welcome to..."), and the HTML file I created is not reflected Please,tell me how to create and show the blog page. The settings.py etc. are almost the same as in this page. index.html is a very simple one in templates\blog as a test. # blog/views.py from django.http import HttpResponse from django.views.generic.list import ListView from blog.models import TopPage class IndexView(ListView): model = TopPage template_name = 'blog/index.html' # blog/urls.py from django.urls import path from . import views app_name = 'blog' urlpatterns = [ path('', views.IndexView.as_view(), name='index'), ] # blog/models.py from django.db import models from wagtail.core.models import Page from wagtail.search.models import Query from wagtail.core.fields import RichTextField from wagtail.admin.edit_handlers import FieldPanel from wagtail.images.edit_handlers import ImageChooserPanel class TopPage(Page): cover_image = models.ForeignKey( 'wagtailimages.Image', null=True, blank=True, on_delete=models.SET_NULL, related_name='+' ) intro = models.CharField(max_length=255) main_body = RichTextField(blank=True) side_image = models.ForeignKey( 'wagtailimages.Image', null=True, blank=True, on_delete=models.SET_NULL, related_name='+' ) side_title = models.CharField(blank=True, max_length=255) side_body = … -
Get foreign key element from a related_name on django
I have three models such as the one below and I am trying to write a query that allows me to access all the Day_Type associated to the Day objects that are pointing to a specific JobProject. I know that I can get all the Day pointing at a JobProject by querying project.jobproject_days.all() and I can get the values of the Day_Type by doing project.jobproject_days.values_list('day_type__name', flat=True) BUT how can I get the Day_Type themselves? class JobProject(models.Model): ...... class Day_Type(models.Model): name = models.CharField(max_length=30) class Day(models.Model): .... day_type = models.ForeignKey(Day_Type, blank=True, on_delete=models.CASCADE, null=True, related_name='day_type') project = models.ForeignKey(JobProject, blank=True, on_delete=models.CASCADE, related_name='jobproject_days', null=True) -
Django: select all data from a row in a html table and use them in a view
I am new to both django and web development. The task is to run a script when pressin a button using the data contained in the specific row of an html table. So if i clik on the second button "Run script" it uses all the data in that row (8888, 2020/06/21 06:00) in a separate script to performe some task. Currently my html file looks like this: There are 2 sections one for uplading the information that goes in the table one the table which displays them <h1>Approach Path KML Generator</h1> <h2>Generate the KML file here:</h2> <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <button onclick="location.href='{% url 'approach_path_receptorsKML:Proejct Creator' %}'">Upload</button> </form> <h2>Projects Available:</h2> <table class="table"> <thead> <tr> <th>Project ID</th> <th>Date KML</th> <th>Time KML</th> <th>Date-Time Uploaded</th> <th>Run The Conversion</th> <th>KML File</th> </tr> </thead> <tbody> {% for project in latest_project_list %} <tr> <td>{{ project.project_ID }}</td> <td>{{ project.date_kml }}</td> <td>{{ project.time_kml }}</td> <td>{{ project.upload_time }}</td> <td> <button method="post" value="collect data" name="{{ project.project_ID }}|{{ project.date_kml }}|{{ project.time_kml }}|{{ project.upload_time }}">Run script</button> </td> <td> <a href="{{ project.download_doc }}" class="btn btn-primary btn-sm">Download KML File</a> </td> </tr> {% endfor %} </tbody> </table> And this is the view I have created: def ProjectCreator(request): form = DocumentForm() … -
How to change html background color using django code
I was doing a project and I was wondering, I wanted to make a button in HTML which would be controlled in the Django views.py. So basically when someone clicks on the button the background becomes dark and it gets saved, what I mean is if the person refreshes the page the background will still be dark. I wanted to know if it was possible to do it. Thanks. -
Run Django and GRPC same application
I'm working on the Django rest framework project and I need to work with gRPC as well. But I don't know how to manage to run both HTTP server and gRPC server same time. Like in .NET it has option to listen both HTTP1 and HTTP2. When I use command python manage.py runserver then gRPC doesn't work and when I used python manage.py grpcserver then Rest API doesn't work Is there any solution to this problem? Thanks. I used packages: djangorestframework and django-grpc -
Traces inside a celery task are logged in console but not reported to Jaeger backend
So in our company we are using Django as the backend web framework and have heavily used celery for backgroun processing and now we want to start implementing distributed tracing now that things are getting complex. We decided to go with Jaeger as the tracer, and have used django_opentracing to auto instrument our existing codebase. Things work perfectly for a normal request and we can see traces in jaeger ui but when a api request triggers a celery task in background, in the console logs we can see that jaeger is sending traces but they are not visible in the ui. Following django_opentracing doc below is our code setup. # settings.py file # ... # OpenTracing settings OPENTRACING_TRACE_ALL = True OPENTRACING_TRACED_ATTRIBUTES = ['META', 'body', 'path', 'path_info', 'method', 'FILES', 'headers'] def get_tracer(): from jaeger_client import Config config = Config( config={ # usually read from some yaml config 'sampler': { 'type': 'const', 'param': 1, }, 'local_agent': { 'reporting_host': '127.0.0.1', 'reporting_port': '5775' }, 'logging': True, }, service_name='optimus-store', validate=True, ) return config.initialize_tracer() tracer = get_tracer() OPENTRACING_TRACING = django_opentracing.DjangoTracing(tracer) from opentracing_instrumentation.client_hooks import install_all_patches install_all_patches() # Opentracing settings end ... other settings stuff My celery file for django project, import os from celery import Celery from … -
Direct assignment to the forward side of a many-to-many set is prohibited. Use product_variation.set() instead
I am new to Django and didn't find any reference regarding this issue. I am getting this error when i use many to many field in Django model. Im trying to add ProductVariationCategory to ProductVariation and then to products. and i get following error : Direct assignment to the forward side of a many-to-many set is prohibited. Use product_variation.set() instead. here is my models.py class Product(models.Model): headline = models.CharField(max_length=150) product_variation = models.ManyToManyField(ProductVariation, blank=True) class ProductVariationCategory(models.Model): headline = models.CharField(max_length=255, default="") class ProductVariation(models.Model): category = models.ForeignKey(ProductVariationCategory, on_delete=models.SET_NULL, null=True) headline = models.CharField(max_length=255, default='') and here is my views.py* product_variation_categories, _ = ProductVariationCategory.objects.get_or_create(headline=product_variation_category) product_variations, _ = ProductVariation.objects.get_or_create(headline=product_variation, category=product_variation_categories) products, _ = Product.objects.get_or_create(product_variation=product_variations) im trying to assign productvariation with its relations to products. any idea? -
Not able to establish connection with Heroku Redis using Django channels_redis
I'm using Django Channels in my app to make a person to person chat function. For this I'm using Django Channels channel layers that uses 'Redis' as a backing store. I have following configuration in the settings.py: CHANNEL_LAYERS = { "default": { "BACKEND": "channels_redis.core.RedisChannelLayer", "CONFIG": { "hosts": [os.environ.get('REDIS_URL', ("localhost", 6379))], }, }, } The CHANNEL_LAYERS is working fine for development when 'hosts' points to localhost. However for production, when I'm trying to make sure that the channel layer can communicate with Redis on Heroku it does not work. Using code as giving in Channels Docs as shown below, gives the following error import channels.layers >>> channel_layer = channels.layers.get_channel_layer() >>> from asgiref.sync import async_to_sync >>> async_to_sync(channel_layer.send)('test_channel', {'type': 'hello'}) Traceback (most recent call last): File "<console>", line 1, in <module> File "/app/.heroku/python/lib/python3.7/site-packages/asgiref/sync.py", line 223, in __call__ return call_result.result() File "/app/.heroku/python/lib/python3.7/concurrent/futures/_base.py", line 428, in result return self.__get_result() File "/app/.heroku/python/lib/python3.7/concurrent/futures/_base.py", line 384, in __get_result raise self._exception File "/app/.heroku/python/lib/python3.7/site-packages/asgiref/sync.py", line 292, in main_wrap result = await self.awaitable(*args, **kwargs) File "/app/.heroku/python/lib/python3.7/site-packages/channels_redis/core.py", line 299, in send async with self.connection(index) as connection: File "/app/.heroku/python/lib/python3.7/site-packages/channels_redis/core.py", line 835, in __aenter__ self.conn = await self.pool.pop() File "/app/.heroku/python/lib/python3.7/site-packages/channels_redis/core.py", line 73, in pop conns.append(await aioredis.create_redis(**self.host, loop=loop)) File "/app/.heroku/python/lib/python3.7/site-packages/aioredis/commands/__init__.py", line 175, in create_redis loop=loop) … -
what is the meaning of request.POST['first'] and this is predefined dictionary and what will be value of 'first' key?
request.POST['first'] has POST[] dictionary made in request object and what will be the value of 'first' key? -
Get the value of a list to upload an Image on a djanog models
I need some help with a question, I'm currently working on a django project and I have a models like this : CATEGORY = ( ('raw', 'raw'), ('jpg', 'jpg'), ('psd', 'psd') ) Row = ( ('Homepage1', 'Homepage1'), ('Homepage2', 'Homepage2'), ('Homepage3', 'Homepage3') ) name = models.CharField(null=True, max_length=200) album = models.ForeignKey(Album, on_delete=models.CASCADE) file = models.ImageField(upload_to=Row.__getattribute__, null=True, blank=True) file_type = models.CharField(max_length=200, null=True, choices=CATEGORY) is_favorite = models.BooleanField(default=False) date_uploaded = models.DateTimeField(default=now) def __str__(self): return str(self.album) + "ID.{:0>3}".format(self.id) How can I use the Row list to say where I would upload the Images, do I get it right ? by saying this : models.ImageField(upload_to=**Row.__getattribute__,** null=True, blank=True) ???? Thanks y'all in advance -
Please suggest some of file uploading JS library for VueJS
I want to have a loading based file file upload feature in Vuejs while uploading the file to Django backend. -
Django-fcm how to set senderId
I'm working with django-fcm and I'm getting a mismatch senderId error, here's how I'm sending messages devices = DeviceNotification.objects.filter(user__id__in=get_user_model().objects.filter_by_targeting(instance.targeting)) res = devices.send_message(title=instance.title_fr, body=instance.content_fr, data={"title": instance.title_fr, "body": instance.content_fr}) Is there a way to add senderId to send_message function? thanks. -
Is there a way to combine a list of querysets into a sql union?
Given a list of querysets, is it possible to combine them into a union? Ideally the Django API would allow something like this - union(*querysets) But as far as I can see a union is only possible like this - q1.union(*rest_of_querysets) So given this is the only way how can I get the first item of the list of querysets without evaluating it? At the moment I have this which doesn't work - q1 = querysets[0] # it is evaluated at this point so doesn't work q1.union(*querysets[1:], all=True) -
Django is not matching same query
Hi I am trying to match 2 same query print('{prd} match from {category} {tf}'.format(prd=p.category.subtitle, category=c.subtitle, tf=p.category==c.title)) Output: bullet-network-camera match from bullet-network-camera False -
How do I convert an API UTC time to local time (+13:00) and ensure it is correct?
I am trying to convert a datetime from an API that stores datetime values as UTC. I need to convert the datetime to my local time 'Pacific/Auckland' The API I am using is Sunrise-Sunset https://sunrise-sunset.org/api The specific location I am requesting is Christchurch, New Zealand https://sunrise-sunset.org/search?location=christchurch The below code outputs 2021-09-26T22:47:45+00:00 however I'm certain this is incorrect. (see below) import requests api_url = 'https://api.sunrise-sunset.org/json?lat=40.712784&lng=-74.005943&formatted=0' response = requests.get(api_url) if response.status_code == 200: sunset_today = response.json()['results']['sunset'] print(sunset_today) # outputs '2021-09-26T22:47:45+00:00' The reason I believe the printed value is incorrect is because when I subtract 13 hours from todays sunset time of Sunday 26 Sep 7:31:42 pm NZ time (+13:00) to get the UTC time I should get Sunday 26 Sep 06:31:42 UTC (+00:00) which is significantly different from the UTC value I am receiving. I have searched StackOverflow and Google extensively, but cannot seem to find a solution that fits my needs. There are two questions I'm asking Why am I getting an odd UTC value for the sunset time? How can I convert the correct result ('2021-09-26T06:31:41+00:00') to my local datetime ('Pacific/Auckland')? FYI, I don't want to add bloat to the application, but from previous (unsuccessful) attempts at solving this problem … -
Django Rest + Gunicorn, static files for admin are missing
I am running Django REST using gunicorn and serving it using NGINX. PROBLEM: Static files for admin are not served correctly while static files for API routes are. CONFIGURATION: docker-compose.yml drf: ...* volumes: - .:/code - static_files:/static_files depends_on: - postgres nginx: ...* volumes: - static_files:/static_files ports: - 8081:8081 nginx.conf server { listen 8081; server_name localhost; access_log /var/log/nginx/example.log; server_tokens off; include /etc/nginx/mime.types; location /static { autoindex off; alias /static_files/; } location ~ (api|admin) { proxy_pass http://drf:8000; proxy_set_header Host $host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_redirect off; } } Settings.py STATIC_URL = "/static/" STATIC_ROOT = "/static_files/" On deployment I also run the following command: python manage.py collectstatic I can see that API routes have static files served while /admin do not. However, files can be found inside the docker volume. And there is one log from nginx container where we can see that nginx is trying to access the right static file...: ADMIN SITE GET /static/admin/css/responsive.css HTTP/1.1" 404 API SITE GET /static/rest_framework/js/default.js HTTP/1.1" 200 -
CSS is not loading in Django Admin Panel App?
I have created my first Django project, but in the admin panel, when I run http://127.0.0.1:8000/admin/ the CSS files is not loaded and I also created a new Django app but still got the same error, I have also visited the question but my problem is not solved: Django admin site not showing CSS style It looks like this: I can log in: It should look like this: settings.py import os STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') Note: I have used STATIC_ROOT = os.path.join(BASE_DIR, 'static') in settings.py and also run the command python manage.py collectstatic, but still, I got the same error. -
Django NoReverseMatch at /topic/ pk=
Hi i want to add the url for if user click and will go to delete page but i don't want i want to put in pk= i already try pk=topic.id but fail view.py class DeleteTopic(DeleteView): model = Topic success_url = reverse_lazy('index') html.py <a class="btn btn-danger" href="{% url 'delete_topic' pk= %}">Delete</a> urls.py path('topic/<int:pk>/delete', DeleteTopic.as_view(), name='delete_topic'), -
DoesNotExist: matching query does not exist
I'm writing models tests in django and here is my test: class StockTest(TransactionTestCase): def setUp(self): Stock.objects.create( product_id=Products.objects.get(product_id=1), date='2021-10-10', count=1) def test_stocks(self): stocks_milk = Stock.objects.get(count=1) stocks_cookies = Stock.objects.get(count=2) self.assertEqual( stocks_milk.__str__(), 1) self.assertEqual( stocks_cookies.__str__(), 2) and my model where product_id is a foreign key to Products: class Stock(models.Model): stock_id = models.AutoField(primary_key=True) date = models.DateField() count = models.IntegerField() product_id = models.ForeignKey(Products, models.DO_NOTHING, db_column='product_id') user = models.CharField(max_length=255) def __str__(self): return str(self.count) When I run a test I get the error: grocery_check.models.Products.DoesNotExist: Products matching query does not exist. How to get the id from Products table properly?