Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Creating a Reference Code for each new order
For my E-commerce project, I am trying to generate a reference code that can be understandable yet unique at the same time: I am trying to generate a reference code that after each purchase is made that includes that day, month, year, hour, minute and a digit that increases with a new transaction DDMMYYHHMMXXX Day, Month, Year, Hour, Minute,3 digits starting with 001 and increasing with each new order. How do I do it? My current code generated is: def create_ref_code(): return ''.join(random.choices(string.ascii_lowercase + string.digits, k=6)) model.py class Order(models.Model): ref_code = models.CharField(max_length=20, blank=True, null=True) ordered_date = models.DateTimeField() def __str__(self): return self.user.username -
i am using django classed view i want to give permission to admin dynamically
if form.is_valid(): #import pdb;pdb.set_trace() user = form.save(commit=False) user.is_partner = True user.is_staff = True password = request.POST.get('password') user.set_password(password) permission = Permission.objects.get(name="Can view employee") user = user.user_permissions.add(permission) user.save() permission = Permission.objects.get(name="Can view employee") user = user.user_permissions.add(permission) this two lines give an error "<partnerData: shubham@storemanagement>" needs to have a value for field "id" before this many-to-many relationship can be used. how can i solved this. -
google.maps is undefined in Django
I have the next code: {% extends "block.html" %} {% load media_tags staticfiles %} {% block blocktitle %}{% endblock %} {% block blockbody %} {% addmedia "css" %} <link href="{% static "merengue/css/map/map.css" %}" rel="stylesheet" type="text/css" /> {% endaddmedia %} <script src="//maps.googleapis.com/maps/api/js" type="text/javascript"></script> <style type="text/css"> html, body, #map { height: 100%; margin: 0; }</style> <script type="text/javascript"> var blocked_maps; var setup_blocked_maps; var map; var script = document.createElement('script'); script.src = 'https://maps.googleapis.com/maps/api/js?v=3&amp;key=AIzaSyBwdVf-Ezph3llEXy-cK0HnTLLfGEx3p-Q&libraries=places'; //script.defer = true; if (! blocked_maps) { blocked_maps={} } blocked_maps["#mapblock_{{ reg_block.id }}"]={ use_cluster: false, show_directions: false, {% if render_ui %} use_small_controls: true {% else %} no_ui: true {% endif %} }; function initialize() { var map = new google.maps.Map( document.getElementById('map'), { center: new google.maps.LatLng(37.4419, -122.1419), zoom: 13, mapTypeId: google.maps.MapTypeId.ROADMAP }); var marker = new google.maps.Marker({ position: new google.maps.LatLng(37.4419, -122.1419), map: map }); } google.maps.event.addDomListener(window, 'load', initialize); </script> <div id="mapblock_{{ reg_block.id }}" style="width: {{ width }}px; height: {{ height }}px;"> <div class="mapParameters hide"> <span class="zoom">{{ zoom }}</span> <span class="longitude">{{ longitude|safe }}</span> <span class="latitude">{{ latitude|safe }}</span> <span class="markersShownInitially">1</span> </div> <div class="mapPoint hide"> <span class="longitude">{{ longitude|safe }}</span> <span class="latitude">{{ latitude|safe }}</span> <span class="iconImage">{% static "merengue/img/map/default_map_icon.png" %}</span> </div> </div> {% endblock %} If I run this code, give the error: You have included the Google Maps … -
Display Instagram Public Profiles in Django Template
I would like to display Instagram public profiles in my Django template. Instagram usernames are stored in the database through the model. I'm pulling the usernames from the database. By using "django_instagram" I was able to show media contents in my template. How do I show the profile like this in my template? My model: class Listing(models.Model): account_name = models.ForeignKey(Account, on_delete=models.CASCADE, verbose_name='Account Name', null=True, blank=True) profile_username = models.CharField('Username', unique=True, max_length=200) class Meta: verbose_name = 'Listing' verbose_name_plural = 'Listings' def __str__(self): return self.profile_username My view: def index(request): instagram_profile_name = 'cabinwellnessclinic' context = {'instagram_profile_name': instagram_profile_name} return render(request, 'instagram/index.html', context) My template: <!DOCTYPE html> {% load instagram_client %} <html lang="en"> <head> <meta charset="UTF-8"> <title>{{ instagram_profile_name|capfirst }} Instagram Profile</title> </head> <body> <h1>{{ instagram_profile_name }} Instagram Profile</h1> <div id="django_recent_media_wall"> {% instagram_user_recent_media instagram_profile_name %} {% for media in recent_media %} <div class="django_instagram_media_wall_item"> <a href="//instagram.com/p/{{ media.shortcode }}" target="_blank"> <img src="{{ media.thumbnail_src }}"/> <span>{{ media.edge_media_to_caption.edges.0.node.text }}</span> </a> </div> {% endfor %} </div> </body> </html> Any help would be much appreciated. -
How Do I Install sdl-config -Heroku Django deploy error
So i am getting this error that i need to install sdl config i tried pip install sdl-config but its not working and i am stuck on this last part to deploy my website heres an image of the error If you know how to install sdl-config please explain it step by step because this is my first time launching my website using heroku with github -
Unable to create warehouse using graphql in Saleor ("NoneType' object has no attribute 'save'")
I have followed the documentation for createWarehouse mutation in graphql for saleor. the error is related with address because error pops up if the address is in the code. The address is a required field mutation { createWarehouse( input: { slug: "test" address: { streetAddress1: "1" streetAddress2: "2" city: "New York" cityArea: "New your" postalCode: "123" country: US countryArea: "bla" phone: "2" } name: "as" companyName: "a" email: "en" } ) { warehouse { id name } warehouseErrors { message } } } error message returns NoneType' object has no attribute 'save' -
Add parameters to ForeignKey field?
I'm trying to build an auctions site and I have a ForeignKey field that I may want to add some extra parameters to if possible. Right now, when I go to /admin and I go to Listings and click on a listing, there is a drop-down selector for Winners. But the drop-down selector is showing me all the bids that have been placed, including bids placed on other listings. How do I get the drop-down selector to only allow me to select from users that have placed bids on that specific listing. I'm assuming I need to add some kind of condition to the winners field? models.py class Listing(models.Model): class NewManager(models.Manager): def get_queryset(self): return super().get_queryset().filter(status='active') options = ( ('active', 'Active'), ('closed', 'Closed'), ) title = models.CharField(max_length=64) description = models.TextField(max_length=64) start_price = models.DecimalField(max_digits=9, decimal_places=2, validators=[MinValueValidator(0.99)]) image = models.URLField(max_length=200, blank=True) category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name="listings") lister = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, default=None, null=True, blank=True, related_name="lister_user") date_added = models.DateTimeField(default=timezone.now) status = models.CharField(max_length=10, choices=options, default="active") winner = models.ForeignKey('Bid', on_delete=models.CASCADE, null=True, related_name="bid_winner") favourites = models.ManyToManyField(User, related_name="favourite", default=None, blank=True) objects = models.Manager() listingmanager = NewManager() def __str__(self): return f"{self.title} ({self.pk}, £{self.start_price}, {self.lister})" class Bid(models.Model): bidder = models.ForeignKey(User, on_delete=models.CASCADE, related_name="bidders") bid_item = models.ForeignKey(Listing, on_delete=models.CASCADE, related_name="bid_items", default=None) bid_input = models.DecimalField(max_digits=9, … -
Passing image URL as a prop in Vue not working
I am new to Django Rest Framework and am trying to learn how to create a Full-Stack application with Django Rest Framework and VueJS. I am using Django Rest Framework to deliver image URLs from the Django server to my Vue application. When I pass the imageURL as a prop, and bind the src attribute, the image is not displayed. When I go directly to the imageURL (in this example 127.0.0.1:8000/static/images/meal_1.jpg), it is the correct URL and the image displays correctly. If I manually set the src attribute, it displays correctly. <img :src="imageURL" alt="Product Image"/> {{ imageURL }} <img src="http://127.0.0.1:8000/static/images/meal_1.jpg" alt="Product Image" /> {{ imageURL }} I have researched similar problems and they all mention using require(), but this image is not located in the Vue application's assets folder, is is getting served from the Django application. Any help would be appreciated. -
How to use Ajax to send redirect page when a user clicks the 'submit' button after PayPal executed in Django Project
I have set PayPal payment for my project which is currently working until the user submits the payment and the PayPal windows closes the website page is still there with items in the cart. My goal is thast when the user submits the payment and the PayPal windows closes, the website goes to "order_completed.html" page I have set in the views. I have tried to add the code in the onApprove in scripts but it is not working. My question: How to set the JavaScript Ajax so that when the payment is executed and user clicks submit the website directs to another page Here is the views.html: def payment_complete(request): body = json.loads(request.body) order = Order.objects.get( user=request.user, ordered=False, id=body['orderID']) payment = Payment( user=request.user, stripe_charge_id=body['payID'], amount=order.grand_total() ) payment.save() # assign the payment to order order.payment = payment order.ordered = True order.ref_code = create_ref_code() order.save() messages.success(request, "Your Order was Successful ! ") # Email when order is made template = render_to_string("payment_confirmation_email.html", {'first_name': request.user.first_name, 'last_name': request.user.last_name, 'order': order}) msg = EmailMessage('Thanks for Purchasing', template, settings.EMAIL_HOST_USER, [request.user.email]) msg.content_subtype = "html" # Main content is now text/html msg.fail_silently = False msg.send() # End of the email send return render(request, "order_completed.html", {'order': order}) class PaymentView(View): def get(self, … -
TemplateDoesNotExist Error in django on a simple hello world project
I have a problem using templates in django. I believe I have the template in the right spot and after looking at the path from the error log, the file is there. I also have it working without using render(). But I have tried multiple things and in the error log it shows a path that I can follow to the html file that I am trying to render. Here is the file structure of my project Relevant code: Below is my view from the hello app I created. How it is currently there is an error but if I comment out the render() call and use the uncommented code It displays the contents of index.html C:\my_website\my_website\hello\views from django.shortcuts import render from django.http import HttpResponse # Create your views here. import os import logging #MS ADDED logger = logging.getLogger(__name__)#MS ADDED def index(request): #!!! It works with this stuff uncommented #index_path = os.path.join(os.path.dirname(os.path.dirname(__file__)),'hello\\templates\\hello\\index.html') #logger.error('Views - index_path is ' + index_path) # MS ADDED #with open(index_path) as f: # html_string = f.read() #return HttpResponse(html_string) return render(request, 'hello/index.hmtl') Below is everything that I have changed in the settings. I read in the Django docs that if you didnt specify a path it would … -
upload application which backend is django and frontend is Vue using Docker
I'm working on an application which uses these technologies: Django Backend Vue JS front end PostgreSQL database Docker as a container Traefik as a reverse proxy. redis. awscli Here is my production.yml file which i use to the docker-compose to run all applications: version: '3' volumes: production_postgres_data: {} production_postgres_data_backups: {} production_traefik: {} services: django: build: context: . dockerfile: ./compose/production/django/Dockerfile image: goplus_backend_production_django depends_on: - postgres - redis env_file: - ./.envs/.production/.django - ./.envs/.production/.postgres command: /start volumes: - ./static:/static # adding static & media file for django - ./media:/media vue: build: context: /root/goplus_front/new_dashboard_v2 container_name: new_dashboard_v2 environment: - HOST=localhost - PORT=8080 ports: - "8080:8080" depends_on: - django postgres: build: context: . dockerfile: ./compose/production/postgres/Dockerfile image: goplus_backend_production_postgres volumes: - production_postgres_data:/var/lib/postgresql/data - production_postgres_data_backups:/backups env_file: - ./.envs/.production/.postgres ports: - "5432:5432" traefik: build: context: . dockerfile: ./compose/production/traefik/Dockerfile image: goplus_backend_production_traefik depends_on: - django # volumes: # - production_traefik:/etc/traefik/acme ports: - "0.0.0.0:80:80" - "0.0.0.0:443:443" redis: image: redis:5.0 awscli: build: context: . dockerfile: ./compose/production/aws/Dockerfile env_file: - ./.envs/.production/.django volumes: - production_postgres_data_backups:/backups Till now everything is fine and if I use IP:80 I got redirected to Django app (admin panel), and if I use IP:8080 I got redirection to Vue app. The problem is now I want to use Domain Name not IP address, … -
Django join 4 tables with select_related and almost successful
I have models in Django like this : class cart(models.Model): user_id = models.BigIntegerField() class cart_details(models.Model): total = models.BigIntegerField() cart_id = models.ForeignKey(cart, on_delete= models.CASCADE) product_id = models.ForeignKey(product, on_delete= models.CASCADE) class product(models.Model): name = models.CharField(max_length=50) class product_images(models.Model): url = models.SlugField(max_length=100) product_id = models.ForeignKey(product, on_delete= models.CASCADE) I have succesfull join 3 tables (cart, cart_details and product) with this code below: cart_details.objects.filter(id=1).select_related('cart_id').select_related('product_id').all() for item in cart_details: print item.cart_id.user_id print item.product_id.name But now, how to join 4 tables (cart, cart_details, product and product_images) and get url from product_images with select_related? This is SQL query, and it works: select product_images.url, cart.user_id from cart_details join cart on cart.id = cart_details.cart_id join product on product.id = cart_details.product_id where cart.user_id = 1 Help me please.. Thank you! -
Django check if Object in model is parent or child
below I have a model structure with Post and Comment objects: class Post(models.Model): author = models.ForeignKey(Profile, on_delete=models.CASCADE) class Comment(models.Model): post = models.ForeignKey(Post,on_delete=models.CASCADE,related_name='comments') author = models.ForeignKey(Profile, on_delete=models.CASCADE) dels.CASCADE, null=True, related_name="replies") reply = models.ForeignKey('self', on_delete=models.CASCADE, null=True, related_name="replies") How can I check if my comment is a reply or it's not a reply? You can reply only to the parent comment meaning there are not nested replies. However, a comment may initially never have replies. -
Real Time Webcam Data Processing in Django
I created a website based on Django. My goal is to take data from webcam, send each frame to the background (view part),and process each frame. For this, I used Canvas and Ajax Post method. However, Ajax Post method is really slow for me. It takes more than one second for one frame (Only posting, processing frame in the background is not included) and this is not convenient to perform real time or close to real time processing. Is this slow posting with Ajax normal? Do you have any suggestion to perform my goal? Thank you for your insterest. Best. -
Docker compose nginx config setup to broadcast on port 8000
I am at the end of a project where I have an Nginx as a router in a docker container that works with a test node app on port 8000, but I need it to point to another Nginx Docker compose container which is setup to run a Django app. I don't think the second Nginx is configured right to run the app on port 8000, and am looking for any advise as this. Basically I've been following two separate tutorials and this is where they meet. Here are the files that I think you'll need but feel free to ask for anything additional. docker-compose.prod.yml version: '3.7' services: web: build: context: ./dcahill dockerfile: Dockerfile.prod command: gunicorn dcahill.wsgi:application --bind 0.0.0.0:8000 volumes: - static_volume:/home/dchll/web/staticfiles - media_volume:/home/dchll/web/mediafiles expose: - 8000 env_file: - ./.env.prod depends_on: - db db: image: postgres:12.0-alpine volumes: - postgres_data:/var/lib/postgresql/data/ env_file: - ./.env.prod.db nginx: build: ./nginx volumes: - static_volume:/home/dchll/web/staticfiles - media_volume:/home/dchll/web/mediafiles ports: - 8000:80 depends_on: - web volumes: postgres_data: static_volume: media_volume: nginx.conf (not he main router directing public traffic to 8000) upstream dcahill.com { server web:8000; } server { listen 80; location / { proxy_pass dcahill.com; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; client_max_body_size 100M; } location /staticfiles/ { alias … -
I am not getting time according to my timezone
i live in India and right now the time is 5:14 AM 8-10-2020 but using this time in my project i am getting a different time Oct. 7, 2020, 11:41 p.m. from django.utils.timezone import now timeStamp=models.DateTimeField(default=now) -
Serving up multiple protected media files on one page in Django
I have read about using "X-Sendfile" or "X-Accel-Redirect" on various server softwares to allow a page to be given access to a protected file, working alongside code like this in a view: response = render(request, 'mypage.html') response['X-Accel-Redirect'] = '/protected/foo.png' return response But I'm wondering how this would work (if at all possible) if you had multiple protected files: response['X-Accel-Redirect'] = '/protected/foo.png, /protected/bar.png' Would that work? Reference questions: SO 1, SO 2 -
no such file or directory "credentials.json"
I know other people have had this error, but my issue seems different from any I could find. I am trying to get data from a google sheet using questsheet.py, and posting that data to the caller. If I run my questsheet.py file by itself as a standalone, printing the data, it works fine. If I run it the way it's intended (this is using the evennia engine but it's basically all python with Django/twisted) I get this: FileNotFoundError: [Errno 2] No such file or directory: 'credentials.json' Here is a pastebin of my code: https://pastebin.com/h2tYhXh5 Both my credentials.json file and my questsheet.py file are in the same folder. I've been learning python for a bit over six months. Still pretty new. -
Creating a LIVE ftp progressbar using ftp.apixml.net's js library
I want to create a live progress bar for an FTP upload using http://ftp.apixml.net/ 's FTP.JS. But the problem is when it is uploaded it does not shows complete. And not even Progress. from what I have read of progress bars It can be created with PHP,AJAX I read other answers but couldn't find one related with this js library. (It works little differently.!) // Script from http://ftp.apixml.net/ // Copyright 2017 http://ftp.apixml.net/, DO NOT REMOVE THIS COPYRIGHT NOTICE var Ftp = { createCORSRequest: function (method, url) { var xhr = new XMLHttpRequest(); if ("withCredentials" in xhr) { // Check if the XMLHttpRequest object has a "withCredentials" property. // "withCredentials" only exists on XMLHTTPRequest2 objects. xhr.open(method, url, true); } else if (typeof XDomainRequest != "undefined") { // Otherwise, check if XDomainRequest. // XDomainRequest only exists in IE, and is IE's way of making CORS requests. xhr = new XDomainRequest(); xhr.open(method, url); } else { // Otherwise, CORS is not supported by the browser. xhr = null; } return xhr; }, upload: function(token, files) { var file = files[0]; var reader = new FileReader(); reader.readAsDataURL(file); reader.addEventListener("load", function() { var base64 = this.result; var xhr = Ftp.createCORSRequest('POST', "http://ftp.apixml.net/upload.aspx"); if (!xhr) { throw new … -
custom registration serializer IntegrityError: NOT NULL constraint failed
i'am trying to create a custom Registration serializer and add phoneNumber field ,i followed some examples in questions asked in here,so while adding a new user i get this error. here is my serializer what i did wrong ? class AccountSerializer(RegisterSerializer): phoneNumber=serializers.IntegerField(required=True) def validate_phoneNumber(self,phoneNumber): return phoneNumber def get_cleaned_data(self): return { 'phoneNumber': self.validated_data.get('phoneNumber', ''), 'username': self.validated_data.get('username', ''), 'password1': self.validated_data.get('password1', ''), 'email': self.validated_data.get('email', ''), } def save(self, request): adapter = get_adapter() user = adapter.new_user(request) self.cleaned_data = self.get_cleaned_data() adapter.save_user(request, user, self) setup_user_email(request, user, []) user.phoneNumber = self.cleaned_data.get('phoneNumber') user.save() return user -
DjangoDash plot showing in scrollable but short div
So I am new to DjangoDash and Plotly and trying to learn to build a simple dashboard. But the issue is when I am just following the second example from https://dash.plotly.com/basic-callbacks, the div is cropped and scrollable when displaying the whole page. This is the output of the page in local is As you can see, the div for displaying the plot is cut off and showing the next paragraph which I put as a test. The code in .py is exactly same as the second example, linked above. The only difference is instead of using dash.Dash(...), I am using DjangoDash(...) In html, my code is {% extends "base.html" %} {% load static %} {% block content %} <h2>Test</h2> <div class="container"> {%load plotly_dash%} {%plotly_app name="testPlot"%} </div> <div> <p>This is another test</p> </div> {% endblock %} It would really be appreciated if anyone can tell me the reason this is caused. Thank you in advance! -
Django - I'm getting "This field is required" error on UPDATING an object
When I try to use a form to edit an object that includes an image upload I get "This field is required". A similar form works fine to create the object, but when I retrieve the object and attempt to modify other fields, it fails on the image. #-------models.py: class Star(models.Model): firstname = models.CharField(max_length=32) lastname = models.CharField(max_length=32, blank=True) portrait = models.ImageField(upload_to='images/') #------views.py: class StarForm(forms.ModelForm): class Meta: model = Star fields = ["firstname", "lastname", "portrait"] def staredit(request, star_id): instance = Star.objects.get(pk=star_id) form = StarForm(request.POST or None, instance=instance) context = { "form": form, } return render(request, "stars/edit.html", context) def starchange(request): form = StarForm(request.POST, request.FILES) if form.is_valid(): newstar.save() context = { "message": "The form was posted", } return render(request, "stars/edit.html", context) else: context = { "message": form.errors, } return render(request, "stars/edit.html", context) #-----edit.html <form action="/starchange" method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="Submit"> </form> {{message}} Error message: portrait This field is required. -
Change default Django site on digitalocean to my app from the gunicorn file
I'm struggling with configuring my gunicorn file correctly, I would greatly appreciate any help. I setup a digitalocean server with django preloaded. I then added my domain and it's all working fine on the default django app. Now I have a django app i made and put on a private github repository that I want the server to run, I cloned this into the django project but when I go to edit the gunicorn file to point to that instead of the default app it fails to start presumably because I incorrectly edited the file. What is best practice for where to clone the repository to ? Should I clone the github repository into the django folder and delete the django_project folder that comes as default so I have django ├WebApp |├WebsiteName ||├__pycache__ ||├static ||├__init__.py ||├asgi.py ||├settings.py ||├urls.py ||└wsgi.py |├dashboard |├homepage |├users |├manage.py |└requirements.txt └gunicorn.socket What would I need to change the gunicorn in order to make this work correctly? my repository is called WebApp and the folder structure inside as follows WebsiteName ├__pycache__ ├static ├__init__.py ├asgi.py ├settings.py ├urls.py └wsgi.py dashboard homepage users manage.py requirements.txt Default digitalocean django app Folder structure django ├-django_project |├-django_project ||├-__init__.py ||├-__pycache__ ||├-settings.py ||├-settings.py.orig ||├-static ||├-urls.py … -
TemplateSyntaxError at /blog/second Invalid filter: 'get_val'
this is my function in views where I am separating comments and replies and changing reply into a dictionary def blogpost(request,slug): variable=Post.objects.filter(slug=slug).first() comments=Comments.objects.filter(post=variable,parent=None) replys=Comments.objects.filter(post=variable).exclude(parent=None) replyDict={} for reply in replys: if reply.parent.sno not in replyDict.keys(): replyDict[reply.parent.sno]=[reply] else: replyDict[reply.parent.sno].append(reply) return render(request,"blog/blogpost.html",{'blog':variable,'comments':comments,'user':request.user,"replys":replyDict}) here I am displaying my replies {% for reply in replys|get_val:comment.sno %} {{reply}} {% endfor %} here i am parsing my dictionary to find a proper pair for the sno from django import template register=template.Library() @register.filter(name='get_val') def get_val(dict,key): return dict.get(key) -
Linking one table to each user in Django
I am working on a Django project where I need to link one table(model) to each user. Assume MyTable_1 maps to user_1 and so on. The primary key for MyTable will be a DateField which contains continuous dates from the time user signed-up. MyTable_1 for User_1 |-----------|----------|-------------|-----------------| | Date(PK) | food_ate | game_played | ran_today | |-----------|----------|-------------|-----------------| | 10/01/20 | rice | chess | Yes | |-----------|----------|-------------|-----------------| | 11/01/20 |sandwhich | tennis | No | |-----------|----------|-------------|-----------------| MyTable_2 for User_2 |-----------|----------|-------------|-----------------| | Date(PK) | food_ate | game_played | ran_today | |-----------|----------|-------------|-----------------| | 16/03/19 | pizza | rugby | Yes | |-----------|----------|-------------|-----------------| | 17/03/19 | pasta | football | Yes | |-----------|----------|-------------|-----------------| And so on for every new user created. User logs in those information in MyTable. How can I implement this? I am using PostgreSQL and have written custom User Model.