Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to can I upload a form on django
I am trying to make a matchmaking project on python django such as snapchat's hoop, but first I am trying to do the easiest part(what I know) which is just making the user create a profile to find a mate and then show that created profile to the other users, currently I am not using any matchmaking based on questions, I need to first show the created user to other users. The error comes when I pass the variables to the html via for loops, and now the mates.html file doesnt show anything. Please if you need more explanation let me know in the comments. models.py (Profile model show the profile of the user which is created by default wen the user is created and Mates model shows the profile that the user has to create which provide an image and a description) class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) bio = models.CharField(max_length=400, default=1, null=True) class Mates(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="user") users_requests = models.ManyToManyField(User, related_name="users_requests") req_bio = models.CharField(max_length=400) req_image = models.ImageField(upload_to='requestmates_pics', null=True, blank=True, default=False) views.py def matesmain(request): contents = Profile.objects.all(user=request.user) matesthings = Mates.objects.all(user=request.user) args123 = { 'contents': contents, 'matesthings': matesthings, } return render(request, 'mates.html', args123) def mates(request): if request.method == … -
Django filters PDF export
I'm trying to export my django-filters query to PDF, but I don't know how to call the function. Actually I have the follow views.py: def searchClient (request): clientFilter = ClientFilter(request.GET, queryset=Client.objects.all().order_by('id')) clients_list = clientFilter.qs paginated_filtered_clients_list = Paginator(clients_list, settings.ITEMS_PER_PAGE) page_number = request.GET.get('page') clients_list = paginated_filtered_clients_list.get_page(page_number) return render(request,'agenda/searchClient.html', {'clients_list': clients_list, 'clientFilter': clientFilter}) def getsearchedClientsAsPDF (request): clientFilter = ClientFilter(request.GET, queryset=Client.objects.all().order_by('id')) clients_list = clientFilter.qs pdf_file = generateTablePDF('Clients', clients_list) # Download the pdf file return FileResponse(pdf_file, as_attachment=True, filename='Clients.pdf') And this for the HTML. <a class="btn btn-default btn" href="{% searchClient 1 'page' request.GET.urlencode %}" title="Bootstrap 3 themes generator"> <a class="btn btn-info btn" href ="{% url 'getsearchedClientsAsPDF' %}" title="Bootstrap 3 themes generator">Print</a> Basicly, my problem it's thath I can't pass the search request to my getsearchedClientsAsPDF view. Maybe, there are another way, but i don't know how to resolve it. All help its wecome. -
using Django and DRM, I receive the error "Invalid resource identifier object: missing 'type' attribute" when trying to POST with a nested object
I am trying to POST with nested objects in Django, following the documentation here. I would like the child objects to be written at the same time as the parent. Here are my models: class Om_payload(models.Model): occupant_id = models.CharField(max_length=50) zone = models.CharField(max_length=50) transaction_id = models.CharField(max_length=50) payload_id = models.CharField(max_length=50) def __str__ (self): return self.payload_id class Gateway(models.Model): gate = models.CharField(max_length=50) direction = models.CharField(max_length=50) def __str__ (self): return self.gate class Payment(models.Model): requested_amount = models.IntegerField() om_payload = models.ForeignKey( Om_payload, related_name='payment_om_payload', on_delete=models.CASCADE ) timestamp = models.IntegerField() type = models.CharField(max_length=50) gateway = models.ForeignKey( Gateway, related_name='payment_gateway', on_delete=models.CASCADE ) name = models.CharField(max_length=50) receipt = models.TextField() def __str__ (self): return self.name my serializers: class Om_payloadSerializer(serializers.ModelSerializer): class Meta: model = Om_payload fields = [ 'occupant_id', 'zone', 'transaction_id', 'payload_id' ] class GatewaySerializer(serializers.ModelSerializer): class Meta: model = Gateway fields = [ 'gate', 'direction' ] class PaymentSerializer(serializers.ModelSerializer): class Meta: om_payload = Om_payloadSerializer() gateway = GatewaySerializer() model = Payment fields = [ 'requested_amount', 'om_payload', 'timestamp', 'type', 'gateway', 'name', 'receipt'] def create(self, validated_data): gateway_data = validated_data.pop('gateway') om_payload_data = validated_data.pop('om_payload') payment = Payment.objects.create(**validated_data) Gateway.objects.create(payment=payment, **gateway_data) Om_payload.objects.create(payment=payment, **om_payload_data) return payment the body of my request: { "requested_amount": 1, "om_payload": { "occupant_id": "lkj", "zone": "lkj", "transaction_id": "lkj", "payload_id": "lkj" }, "timestamp": 1, "type": "lkj", "gateway": { "gate": "lkj", … -
Django - cannot import name 'config' from 'decouple'
I'm trying to run this project locally but when i try manage.py makemigrations i keep getting the following error: ImportError: cannot import name 'config' from 'decouple' Here are my steps: Clone the repository from github Create a virtual environment Install the dependencies I made some research but i found nothing about what could be generating that error. Can anyone help me out on this? Thanks in advance!I'm running Django 3. -
Marking message as read in django
I have a model message, that is related to the user: class Message(models.Model): content = models.TextField(verbose_name='content') msg_to = models.ForeignKey(User, related_name='message_to', on_delete=models.CASCADE) msg_from = models.ForeignKey(User, related_name='message_from', on_delete=models.CASCADE) creation_date = models.DateTimeField(auto_now_add=True) read = models.BooleanField(default=False) Also have an url when an user can see the message: path('message/<int:msg_id>', ex_views.MessageView.as_view(), name="message"), How to make changing "read" in message models to 'True' if user which the message is to, open the link with the specific message? For example, i have an message id=2 and it's addressed to user1, user1 click/open the link: message/2 and automatically read changes to True. -
Django hosting with Azure Web App Server Error 500
My project code: https://github.com/Daniel-C02/forexflow_project I followed this tutorial as well as 2 others trying to host my project using Azure. https://docs.microsoft.com/en-us/azure/app-service/containers/tutorial-python-postgresql-app?tabs=bash#clone-the-sample-app I managed to host the sample web app used in the tutorial, but could not host my own project I keep getting "Server Error 500". I've spent around 36 hours trying to fix the problem. I checked the application logs - nothing I checked the kudu/scm logs - nothing I looked under "App Service logs" and checked the ftp logs - nothing I checked to see if all the files had been uploaded at this location "<>.scm.azurewebsites.net/wwwroot/" The staticfiles successfully uploaded. I went to "Web SSH" and installed all the dependencies** "pip install -r requirements.txt" then did "python manage.py runserver" AND NO ERRORS, but it did not want to connect to "127.0.0.1:8000" or "localhost:8000" ??? I spend around 6 hours searching for answers - tried everything - nothing worked WEBSITES_PORT set to 8000 (tried different ports and removed this setting after no luck) I changed DEBUG to False and True - didn't work I did set all the necessary environment variables (eg, DB_HOST, DB_PASSWORD ...) I hosted my project using heroku - it worked - but I want to … -
404 on file upload in google cloud storage with django-storages
When using the django-storages library to upload files to google cloud, I get NotFound at /accounts/profile/1/edit/ 404 POST https://storage.googleapis.com/upload/storage/v1/b/moneygame-42/o?uploadType=multipart: ('Request failed with status code', 404, 'Expected one of', <HTTPStatus.OK: 200>) Here is my code in settings.py: DEFAULT_FILE_STORAGE = 'storages.backends.gcloud.GoogleCloudStorage' GS_PROJECT_ID = GS_BUCKET_NAME = 'moneygame-42' GS_CREDENTIALS = service_account.Credentials.from_service_account_file( "moneygame-42-1fa2467e74eb.json" ) Here is the error: Internal Server Error: /accounts/profile/1/edit/ Traceback (most recent call last): File "/Users/jayjayjay/.conda/envs/moneygame/lib/python3.7/site-packages/google/cloud/storage/blob.py", line 1795, in upload_from_file if_metageneration_not_match, File "/Users/jayjayjay/.conda/envs/moneygame/lib/python3.7/site-packages/google/cloud/storage/blob.py", line 1654, in _do_upload if_metageneration_not_match, File "/Users/jayjayjay/.conda/envs/moneygame/lib/python3.7/site-packages/google/cloud/storage/blob.py", line 1321, in _do_multipart_upload response = upload.transmit(transport, data, object_metadata, content_type) File "/Users/jayjayjay/.conda/envs/moneygame/lib/python3.7/site-packages/google/resumable_media/requests/upload.py", line 108, in transmit self._process_response(response) File "/Users/jayjayjay/.conda/envs/moneygame/lib/python3.7/site-packages/google/resumable_media/_upload.py", line 109, in _process_response _helpers.require_status_code(response, (http_client.OK,), self._get_status_code) File "/Users/jayjayjay/.conda/envs/moneygame/lib/python3.7/site-packages/google/resumable_media/_helpers.py", line 96, in require_status_code *status_codes google.resumable_media.common.InvalidResponse: ('Request failed with status code', 404, 'Expected one of', <HTTPStatus.OK: 200>) During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/Users/jayjayjay/.conda/envs/moneygame/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/Users/jayjayjay/.conda/envs/moneygame/lib/python3.7/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/Users/jayjayjay/.conda/envs/moneygame/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/jayjayjay/.conda/envs/moneygame/lib/python3.7/site-packages/django/views/generic/base.py", line 71, in view return self.dispatch(request, *args, **kwargs) File "/Users/jayjayjay/.conda/envs/moneygame/lib/python3.7/site-packages/django/views/generic/base.py", line 97, in dispatch return handler(request, *args, **kwargs) File "/Users/jayjayjay/programming/project/moneygame/user/views.py", line 120, in post form_p.save() File "/Users/jayjayjay/.conda/envs/moneygame/lib/python3.7/site-packages/django/forms/models.py", line 458, in save … -
Fetch API with blocked CORS policy vs Fetch API not blocked
I have 2 API endpoints on a server. However, 1 API call is successfully called, while the other is blocked by CORS policy. Both are also called with the same fetch API in react. I can't tell the difference in how I am calling them which resulted in one of the requests being blocked. In my django settings, I have set CORS_ORIGIN_WHITELIST to my the domain name and CORS_ORIGIN_ALLOW_ALL = True My react API call for both starts something like that: fetch("http://127.0.0.1:8000/createdeepfake", { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(data_fake), }) .then(response => {... Am I missing something in my other API call which was blocked? -
How do I link a specific field of my two django models with each other?
I have two different models in my django database. One for my companies and for my contacts as follows: companies.models: from django.db import models class CompaniesDetailView(models.Model): name = models.CharField("Enter Company Name", max_length=50) email = models.EmailField("Enter Email") phone_number = models.CharField("Enter Phone Number", max_length=12) contact_name = models.CharField("Enter Contact Persons Name", max_length=50) company_image = models.ImageField(default='default-avatar.png', upload_to='companies/', null=True, blank=True) def __str__(self): return '%s' % (self.name) contacts.models: from django.db import models from apps.companies.models import CompaniesDetailView class Contact(models.Model): name = models.ForeignKey(CompaniesDetailView, on_delete=models.CASCADE) email = models.EmailField("Enter Email") phone_number = models.CharField("Enter Phone Number", max_length=12) company_name = models.CharField("Enter Company Name", max_length=50) contact_image = models.ImageField(default='default-avatar.png', upload_to='contact/', null=True, blank=True) def __str__(self): return '%s' % (self.name) Now I want to link the two models such that when I create a company through Django an additional contact will be created from the contact_name of CompaniesDetailView. Currently if I try to create a contact it is taking the name of the companies. I know the solution is simple but I can't seem to grasp it. -
Type error while Put Request Django Rest Framework
I am building a Django application where there is a Model called Location and another model called Property. Whenever I try to give put request it shows me type error TypeError: Object of type Location is not JSON serializable My Location Model class Location(models.Model): lat = models.DecimalField(max_digits=10,decimal_places=8) long = models.DecimalField(max_digits=10,decimal_places=8) address = models.CharField(max_length=256) class Property(models.Model): owner = models.OneToOneField(to=User,on_delete=models.CASCADE) name = models.CharField(max_length=256) bedrooms = models.SmallPositiveIntigerField() bathrooms = models.SmallPositiveIntigerField() living_rooms = models.SmallPositiveIntigerField() location = models.ForeignKey(to=Location,null=True,on_delete=models.SETNULL) Serializer class PropertySerializer(serializers.ModelSerializer): class Meta: model = Property fields = ['id','name','bedrooms','bathrooms','living_rooms','location'] read_only_fields = ['id'] class LocationSerializer(serializers.ModelSerializer): class Meta: model = Location fields = ['id','long','lat','address'] read_only_fields = ['id'] views class RenterCreate(APIView): authentication_classes = [TokenAuthentication] permission_classes = [IsAuthenticated, RenterPermission] renderer_classes = [JSONRenderer] def get(self, request): property = Property.objects.all() serializer = RenterSerializer(property , many=True) return Response(serializer.data, status=status.HTTP_200_OK) def post(self, request): serializer = PropertySerializer(data=request.data) if serializer.is_valid(): serializer.save(user=request.user) return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.error_messages, status=status.HTTP_400_BAD_REQUEST) def put(self, request): serializer = PropertySerializer(request.user, data=request.data) if serializer.is_valid(): serializer.save(user=request.user) return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) After saving a Property when I use PUT request to update the information it shows me TypeError: Object of type Location is not JSON serializable I have saved a couple of locations in the database. First I made a post request with it, … -
How to send push notification to a browser endpoint using django?
I have created a javascript program which send push notification requests to browser and when the user allows the push services then the browser endpoint details are sent to a django view (say fetch_browser_endpoint()) using $.post() The view stores the endpoint details in a database successfully. From the same view I am trying to send a demo message because I already have the browser enpoint details in that view (that came from javascript function). from webpush import WebPusher def fetch_browser_subscription(request): # code for saving browser endpoint details ... # send push notification payload = { "head": "Welcome!", "body": "Hello World", "icon": "https://i.imgur.com/dRDxiCQ.png", "url": "https://www.google.com" } WebPusher(subscription).send(json.dumps(payload), ttl=1) I also have the listener event in sw.js file self.addEventListener('push', function(pushEvent) { if (!(self.Notification && self.Notification.permission === 'granted')) { return; } payload = pushEvent.data.text(); pushEvent.waitUntil( self.registration.showNotification(payload.title, payload.options) ); }); self.addEventListener('notificationclick', function(clickEvent) { if (clickEvent.action === 'close') { clickEvent.notification.close(); } else { clients.openWindow('https://www.google.com'); notification.close(); } }); Starting from push request to storing browser endpoint in DB is working fine but not able to send push notification to browser. I have included webpush in INSTALLED_APPS and WEBPUSH_SETTINGS = { "VAPID_PUBLIC_KEY": "your_vapid_public_key", "VAPID_PRIVATE_KEY": "your_vapid_private_key", "VAPID_ADMIN_EMAIL": "admin@example.com" } in setting.py I am inserting vapid public and private … -
mod_wsgi: Permission denied for my Virtual Envs
I can't figure out how to allow access of mod_wsgi to my Python virtual envs folder. There are some questions about it but they are 2 years old with old apache feature (I'm on Apache 2.4.43) /etc/httpd/conf/httpd.conf LoadModule wsgi_module modules/mod_wsgi.so ServerName localhost <VirtualHost *:80> # location of the wsgi file WSGIScriptAlias / /var/www/wsgi.py <Directory /var/www> <Files wsgi.py> Require all granted </Files> </Directory> <Directory /var/www/.Envs/mysiteProject Require all granted </Directory> <Directory /var/www/.Envs/mysiteproject/lib/python3.8/site-packages> Require all granted </Directory> # the WSGI daemon WSGIDaemonProcess mysiteproject python-home=/var/www/.Envs/mysiteproject python-path=/var/www/.Envs/mysiteproject/lib/python3.8/site-packages WSGIProcessGroup mysiteproject </VirtualHost> If I comment out the line WSGIDaemon ...., it works without error. But with this line, I've got the error of Permission denied to access this folder. No such file or directory: mod_wsgi (pid=307672): Unable to stat Python home /var/www/.Envs/mysiteproject. Python interpreter may not be able to be initialized correctly. Verify the supplied path and access permissions for whole of the path. I've modified the permission inside the conf file (as you see with the lines: <Directory /var/www/.Envs/mysiteProject Require all granted </Directory> <Directory /var/www/.Envs/mysiteproject/lib/python3.8/site-packages> Require all granted </Directory> and also done sudo chmod -R 755 /var/www/ But Apache still can't access my Virtual env folder. -
Django filer thumbnail's path
I've created a custom User model based on AbstractUser model. How can I find the right path to my thumbnail to use in a template file ? models.py class User(AbstractUser): photo = FilerImageField(related_name='profile_photo', null=True, on_delete=models.SET_NULL) home.html {% extends "base.html" %} {% load thumbnail %} {% block content %} {% thumbnail users.photo 250x250 crop %} {% thumbnail user.photo 250x250 crop %} # {% endblock %} TemplateSyntaxError Exception Value: Variable 'user.photo' is an invalid source. -
When and where should I connect and disconnect Mongoengine
I'm new to Mongonengine and I'm using it in a Django project. As the documents say, I should first make a connection using connect method. My question is that where should this be done? Also there is a disconnect method, I'm wondering whether I should use it and if yes, where should I use it? I mean should I connect in a separate file Or every time I want to query the database I should open a connection and then close it? -
Unable to Start Redis server in Django
I am going through Django channel documentation(https://channels.readthedocs.io/en/latest/tutorial/part_2.html), at some point it advise to start redis server with docker as mention below, We will use a channel layer that uses Redis as its backing store. To start a Redis server on port 6379, run the following command: $ docker run -p 6379:6379 -d redis:5 However I skipped using docker so I dont know how to run above command. Is there any way I can start redis server in virtualenv /pip ? -
Live streaming of images in django to frontend html
I have a lot of images in my project media folder,which is saved by using a sdk camera(Alliedvision).I need to stream these images to html page one by one whenever the camera saves it in the media folder.Is it possible to stream images in django ? -
NGINX returns empty response for index but works fine for other paths
Here's my configuration file for serving Django using Gunicorn: server { listen 80 default_server; server_name _; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/ubuntu/contest_platform; expires 30d; gzip on; } location /media/ { root /home/ubuntu/contest_platform; expires 365d; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } I've tried setting server_name to the IP address of the server (I don't have a domain yet) but that had no effect. All paths, including the admin pages and static and media files, are served properly, but when I try to visit the index it returns an empty response. -
Django Rest how to get multiple objects with lookup_field
I want to create simple filtering for my api. What I want to search in my url is: /api/videoquestionset/2/ And get every videoquestion object that has the video field with 2 or any other number, depending on what the devs request. The error I get right now is: get() returned more than one VideoQuestions -- it returned 2! Here is my code: models.py class Questions(models.Model): """ Questions class for the e-learner overlay """ question_text = models.CharField(max_length=150) answer = models.OneToOneField(QuestionAnswers, on_delete=models.CASCADE, related_name='correct_answer', null=True, blank=True) choices = models.ManyToManyField(QuestionAnswers, related_name='choices') class Meta: verbose_name_plural = "Questions" class VideoQuestions(models.Model): """ Categorize questions per video """ video = models.ForeignKey(Video, on_delete=models.CASCADE) created = models.DateTimeField() question = models.ManyToManyField(Questions, blank=True, related_name='question') class Meta: verbose_name_plural = "learner questions" views.py: class VideoQuestionSet(viewsets.ModelViewSet): serializer_class = VideoQuestionSerializer queryset = VideoQuestions.objects.all() lookup_field = 'video' # def get_queryset(self): # queryset = VideoQuestions.objects.all() # video = self.request.query_params.get('video', None) # if video is not None: # queryset = queryset.filter(video=video) # return queryset my urls.py: from django.conf.urls import include, url from rest_framework import routers from .views import VideoQuestionsListView, VideoQuestionSet router = routers.DefaultRouter() router.register(r'videoquestions', VideoQuestionsListView, basename='vq-list'), router.register(r'videoquestionset', VideoQuestionSet, basename='vq-detail'), urlpatterns = [ url(r'', include(router.urls)) ] What I tried: Django filtering with regex, like /videoquestionset/?v=2. I could not really figure … -
DJANGO how to make boolean field (True/False) display "Available / Not Available" in View?
My code in Django: class Product(models.Model): available = models.BooleanField(default=True) My code in HTML: {% for product in products %} <li> <a href="{% url 'product_detail' product.id %}"> {{ product.name }}{{ product.price }}{{ product.available }} </a> </li> {% endfor %} -
Rendering models in template which are related themselfes
I write a twitter-like app in django, I've got two models: class Tweet(models.Model): content = models.CharField(max_length=140) creation_date = models.DateTimeField(auto_now_add=True) user = models.ForeignKey(User, on_delete=models.CASCADE) class Replies(models.Model): reply = models.CharField(max_length=140) tweet = models.ForeignKey(Tweet, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.reply And the fragment of template: {% block content %} {% for t in tweets %} <table class="table1"> <br> <tr> <td> @{{t.user}} <br> <br> {{t.content}} <br> <br> {{t.creation_date}} </td> ####### ####### </tr> </table> {% endfor %} {% endblock %} Between '####' i would like to have all the replies to the specific tweet, how can i do that? Thanks in advance -
Best practice for Django project name
I have a project with long name i want create a django project (django-admin startproject myprojectname) which case is the best practice format for my project name: 01- ProductionManagemet 02- productionManagemet 03- productionmanagement 04- production_management -
is there any way to run React + Django in same project without running npm run build again and again?
I have enough knowledge about Django and recently learned react and i like to combine both. I have gone through a couple of video tutorials and i am successful in integrating them. but the problem is i should either build a rest API and a react app in two different projects and them combine them or i need to run npm run build every time i make any changes on my front end. so if anybody have an alternative for this(Running React on Django server continuously without running build again and again) please tell me. please don't downvote this since i am new to this platform i will learn things slowly. -
Deployment of Django with ReactJS build on Cpanel
I developed an application using Django and ReactJS. I bought domain name and hosting using namecheap. I have generated build of ReactJS so that only django server needs to run and build will automatically accessible to Django server. I followed this blog: https://blog.umersoftwares.com/2019/09/django-shared-hosting.html But after deployment backend works fine but front-end won't work. I have integrated django and reactjs using this: https://medium.com/@zackliutju/building-react-and-django-web-application-and-deploy-it-on-google-cloud-545f06eb5521 Locally it works fine but on deployment it won't work. Only blank white page. -
Django Auth User and Custom User
So far, I have been creating a user class in Django without inheriting AbstractBaseUser or AbstractUser classes. For example, class User(models.Model): realname = models.CharField(max_length=50) username = models.CharField(max_length=50, unique=True) birthday = models.DateField() phone = models.CharField(max_length=50, unique=True) password = models.CharField(max_length=2000) ... Now I am thinking about creating a user model that actually inherits AbstractBaseUser class. My question is, in what ways does inheriting AbstractBaseUser increase efficiency and productivity, if any? I guess set_password() function may relieve the burden of manually encrypting input password with bcrypt; however, additional work is needed to create a UserManager class, refer to my custom User model with auth.get_user_model() function (django documentation says this way is recommended to return the currently active user model) instead of simply referring to it as 'User', and etc. Your help will be greatly appreciated!! -
Django admin filter on edit page
On a Django admin edit page, I would like to add a little search box to be able to filter a list of tags. The field tag is a many to many field. Is there a special trick?