Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Newer version of Django URL is not working , "throws not found error " while passing string arguments
The newer version Django URL throws not found error while earlier version works as expected url(r"^delete_comments/(?P<id>\w+)/$",DeleteComments.as_view(),name="del_comments"), url('delete_comments/<str:id>/',DeleteComments.as_view(),name="del_comments"), I am just passing a string a parameter in the URL,the django literally throws there is no such URL in the system -
django and wsgi outputs blank page with no error
When I run my django server with uwsgi (probably) my static files are not loading correctly. My connection is fine since I get 200 OK, but the page is blank. Response seems to be fine: <!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <title>Label It</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700&display=swap" /> </head> <body style="margin: 0"> <div id="main"> <div id="app"> </div> </div> <scipt type="application/javascript" src="/vol/web/static/frontend/main.js"></scipt> </body> </html> my config for UWSGI: uwsgi --http 0.0.0.0:8000 \ --master \ --module label_it.wsgi \ --processes 2 \ --static-map /static=/vol/web/static/frontend My application runs in docker container, and I tell django to put static files to /vol/web/static, and I can confirm- those files are there (main.js is there). Django app setting.py : STATIC_URL = '/static/' MEDIA_URL = '/static/media/' STATIC_ROOT = '/vol/web/static' MEDIA_ROOT = '/vol/web/media' On development, everything is fine. UWSGI output on console when connecting: [pid: 34|app: 0|req: 2/3] 172.18.0.1 () {38 vars in 721 bytes} [Wed Feb 17 16:03:00 2021] GET / => generated 680 bytes in 0 msecs (HTTP/1.1 200) 6 headers in 180 bytes (1 switches on core 0) -
django.db.utils.ProgrammingError: column does not exist LINE 1
I've created a boolean column in an existing Model and Migrated. I can see the column in the table with default values. but while running ./manage.py test, I'm getting the below errors. psycopg2.errors.UndefinedColumn: column xxxx does not exist LINE 1: django.db.utils.ProgrammingError: column xxxx does not exist LINE 1: -
How to filter query value in one if there is few of same value in Django
My views.py, I want to show only one value of the same value filtermyfriends = [] myfriends = Friends.objects.filter(Q(friend_one = request.user.pk) | Q(friend_two = request.user.pk)) for checkf in myfriends: if Friends.objects.filter(Q(friend_one = checkf.friend_one) | Q(friend_two = checkf.friend_two)) not in filtermyfriends: filtermyfriends.append(checkf) -
Rendering Django Model to HTML
I made a Django app to fill my single html pages. This is my model.py class Flatpage(models.Model): title = models.CharField(max_length=200) slug = models.SlugField(max_length=40) short_description_text = models.TextField(blank=True) content = RichTextField(blank=True, null=True) published_date = models.DateTimeField('Published_Date') meta_keyword = models.CharField(max_length=30) meta_description = models.TextField(blank=True) How should views.py look like to print the output of my model on the relevant pages? How can I print my model output according to slug to single page htmls (About us, FAQ, etc.) -
Django-rest-auth multiple Google Apps
I am writing a Django REST Application that uses Django-all-auth plugin. I want the user to be able to login both via their Mac or Website. So in my Google Console, I have created 2 OAuth2.0 Apps. One for Mac and one for Website, the difference being that the website one has the redirect URI of my website and the Mac one to have redirect URI of https://google.com Under my Social Applications in admin, I have added both Apps with their Client IDs and Secrets. Now, after logging the user in with Google account, I POST the "access_token" returned to Django-all-auth google login url at my REST server. Before I only had the Website app and it used to work fine but now I am getting this error: Does it not allow you to have 2 Google Apps attached at the same time? Is there a setting I am unaware of to allow 2 Google OAuth2.0 apps? I couldn't find anything in the docs for this: https://django-allauth.readthedocs.io/en/latest/overview.html Any suggestions will be highly appreciated. -
Django Ajax Get method giving 405 (Method Not Allowed) error
$(document).on("click", "#btn_create_card", function () { url1 = $(this).attr("data-url"); $.ajax({ url: url1, type: "GET", data: { description: "test", }, success: function () { console.log("sucess"); Get_CardView(); }, }); }); Below is my Class-based view for the call class CreateCard(View): def get(self, request): description1 = request.GET.get('description', None) print(description1) return redirect('/') but I am getting below error message GET http://127.0.0.1:8000/create_card?description=test 405 (Method Not Allowed) below is my url path('create_card', views.CreateCard.as_view(), name='create_card'), -
pylint django with django-configurations
How to make pylint-django work together with django-configurations ? I've setup a Django project in VS code with pylint and django-pylint as linter. I have a conflict with django-configurations, a package that I use to have different config file depending on environment. I specify django-settings-module in order for django-pylint to understand django project. Settings.json in vscode looks like this : { // ... "python.linting.pylintArgs": [ "--load-plugins", "pylint_django", // Works fine // "--django-settings-module", "project.settings" // Do not work anymore when adding this ], ], // ... } Also I've tried the same config file with another django project that does not use django-configurations and pylint django works well with second line on. -
How to repeat a many-to-many relationship in Django?
I have these models in my Django app from django.db import models from django.contrib.auth import get_user_model User = get_user_model() class Animal(models.Model): name = models.CharField(max_length=100, unique=True) class AnimalList(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) list = models.ManyToManyField(Amimal) I want to add the same pokemon to the same list twice: >>> animal = Animal.objects.create(name='milla') >>> user = User.objects.create(username='user') >>> list = AnimalList.objects.create(user=user) >>> list.list.add(animal) >>> list.list.add(animal) >>> animal.save() The animal is added only once, though: >>> list.list.all() <QuerySet [<Animal: Animal object (3)>]> I expected that, the documentation is explicit that Adding a second time is OK, it will not duplicate the relation: Yet, I do want to repeat the animals. How could I do that? Is it possible by using ManyToManyField? -
Store multiple inputs values of form in single json to store in model field. - Django
I am working on a project which is online printing ordering service. Here on the order page I am getting different attributes of product in radio button list in the form, and all the attributes I want to store in a single json in database. models.py class Product(models.Model): prod_ID = models.AutoField("Product ID", primary_key=True) prod_Name = models.CharField("Product Name", max_length=30, null=False) prod_Desc = models.CharField("Product Description", max_length=2000, null=False) prod_Price = models.IntegerField("Product Price/Piece", default=0.00) prod_img = models.ImageField("Product Image", null=True) def __str__(self): return "{}-->{}".format(self.prod_ID, self.prod_Name) # this is the order table , there is a "attribute_field" I wantto store the attributes in this field # as JSON. class Order(models.Model): order_id = models.AutoField("Order ID", primary_key=True) user_id = models.ForeignKey(User, on_delete=models.CASCADE, null=False, verbose_name="Customer ID") prod_id = models.ForeignKey(Product, on_delete=models.CASCADE, null=False, verbose_name="Product ID") quantity = models.ImageField('Product Quantity', max_length=10, default=500) attribute_value = models.CharField("Item Details JSON", max_length=2000, null=False) order_date = models.DateField("Order Date", auto_now_add=True, null=False) order_job_title = models.CharField("Name of Company/Business", max_length=100, null=False) order_desc = models.CharField("Details for Product", max_length=1000, null=False) product_img = models.ImageField("Template Image", null=False) address = models.CharField("Customer Address ", max_length=100, null=False) state = models.CharField("Customer State", max_length=30, null=False) city = models.CharField("Customer City", max_length=30, null=False) postal_code = models.IntegerField("Area Pin Code", null=False) order_price = models.DecimalField(max_digits=8, decimal_places=2, default=0000.00) class Size(models.Model): size_id = models.AutoField("Size ID", primary_key=True, auto_created=True) prod_size … -
Django raising 'django.urls.exceptions.NoReverseMatch: Reverse for '/' not found. '/' is not a valid view function or pattern name.' in base.html
I am making a website using Django and DTL. I wanted to comment the embedded javascript in my code, but it happens that Django Template Language does not comment the same way as plain HTML. Traceback when I go to ***any ***page: NoReverseMatch at / Reverse for '/' not found. '/' is not a valid view function or pattern name. Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 3.1.4 Exception Type: NoReverseMatch Exception Value: Reverse for '/' not found. '/' is not a valid view function or pattern name. Exception Location: /Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/urls/resolvers.py, line 685, in _reverse_with_prefix Python Executable: /usr/local/bin/python3 Python Version: 3.9.0 Python Path: ['/Users/william/Documents/coding/WDTP/almostanything/django/almostanything', '/Library/Frameworks/Python.framework/Versions/3.9/lib/python39.zip', '/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9', '/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/lib-dynload', '/Users/william/Library/Python/3.9/lib/python/site-packages', '/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages'] Server time: Wed, 17 Feb 2021 09:43:34 -0500 Error during template rendering In template /Users/william/Documents/coding/WDTP/almostanything/django/almostanything/templates/base.html, error at line 20 Reverse for '/' not found. '/' is not a valid view function or pattern name. 10 display: none; 11 } 12 /* tr's 13 .tr1{top:4px;right:4px;}.tr2{top:4px;right:39px;}.tr3{top:4px;right:79px;} 14 .shadowed{box-shadow:3px 3px 1px 0px blue;} */ 15 </style>{% endblock %} 16 </head> 17 <body> 18 {% block script %} 19 <script> 20 # var st = document.getElementById('shadowtopbar'); 21 # function load(); 22 # st.style.display = "block"; 23 # setTimeout(500, load()); 24 </script> 25 {% endblock … -
Changing img tag src value with javascript with the Django framework
I am trying to load a random image from a dictionary on page load using Javascript. This is the HTML <div class="img-container"> {% load static %} <img id="qimage" src="{% static '' %}"></img> </div> So basically I want to change the src to a random generated image src from dictionary on page load: this is the Javascript: window.onload = function(){ var image = document.getElementById("qimage"); let src = getRandomImage(); image.setAttribute("src",src); } And this is the generate random image function: function getRandomImage(){ var keys = Object.keys(dict); var index = getRandomInt(0,keys.length); var selection = keys[index]; var image = dict[selection][0]; return image; } and lastly this is the dictionary: var dict = { "barrackStreet":["{% static 'images/hard/bstreet.jpg' %}",{"lat":51.893897,"lng":-8.477632}], "GrandParade":["{% static 'images/hard/gparade.jpg' %}",{"lat":51.893897,"lng":-8.477632}], "PatricksHill":["{% static 'images/hard/phill.jpg' %}",{"lat":51.893897,"lng":-8.477632}], }; -
how can i extract from my django model into a javascript variable (Django)
How can I extract data from my django model and put it into a javascript variable. I have a music player that uses javascript, within the JS code there is a variable 'trackUrl' which is a list of the track paths. How can i use my music model to extract the track and place into this JS code ? I've been trying to find a solution but was only advised to use Django REST framework, is there another method I could use. Could you please explain in detail as I'm still learning Django. Thanks This is the music player : https://codepen.io/himalayasingh/pen/QZKqOX models.py class Music(models.Model): track = models.FileField(upload_to='path/to/audio') title = models.TextField(max_length=50) artwork = models.ImageField(upload_to='path/to/img', blank=True) artist = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.title views.py @login_required def music_upload(request): if request.method == "POST": form = MusicForm(request.POST, request.FILES) if form.is_valid(): user = request.user song = form.save(commit=False) song.artist = user song.save() messages.success(request, f'Track Uploaded') return redirect('my_profile') else: form = MusicForm() return render(request, 'feed/music_upload.html', {'form':form}) -
Caller Device Detection of a Django-Python Rest API
We are developing a REST API using Python-Django. API is consumed by IOS and Andriod native apps and a browser-based web application. With each user login, we need to detect and store the device users are connecting. Right now I have tried to achieve this using django_user_agents. It detects the device correctly when calls are coming from browsers. But it can't detect the devices of calls from native apps. So I'm just guessing django_user_agents works only for browser-originated calls. I'm kinda new to python and Django world. Any help on how to detect calling devices universally would be really appreciated. Thanks, -
Plesk Django Server Error 403 Forbidden You do not have permission to access this document
Error log: [Wed Feb 17 14:39:51.592472 2021] [autoindex:error] [pid 147736:tid 140504350598912] [client 203.78.146.30:0] AH01276: Cannot serve directory /var/www/vhosts/allfamousbd.com/django-app/django-public/allfamousbd/: No matching DirectoryIndex (index.html,index.cgi,index.pl,index.php,index.xhtml,index.htm,index.shtml) found, and server-generated directory index forbidden by Options directive -
Django: How To Add To Existing Filter
I am trying to create a page where the user can filter out products based on genres and keywords but I don't like the way that the ModelMultipleChoiceFilter looks so I am trying to do this using buttons because that looks a lot better. I have created a form for each genre and keyword using a for loop in the templates so that I can do a GET request to filter the queryset. I could pass in the id of the genre button that is clicked but that would only filter one genre and I want the user to be able to choose multiple genres to filter at once. So I am trying to find a way to add muliple filters on to the query that already exists: is there a way to add filters on to an existing query? I have looked on stackoverflow and some one said that it could be done by creating a dictionary with each genre filter and pass that into the filtering so maybe that could work? Here is some relevant info: templates: <div class="filters_label">Genres</div> <div class="filter_buttons_container"> {% for genre in genre_list %} <form class="filter_sub_form" id="{{ genre }}" action="{% url 'find' %}" method="GET"> <button … -
How do I make a query with CASE statement on WHERE clause on django ORM?
I'm having some troubles trying to make a complex query on Django ORM. This is the query: SELECT "app_client"."name", "app_order"."client_id", "app_client"."country", (SUM("app_order"."grand_total") - SUM("app_order"."shipping_amount")) AS "total", COUNT("app_order"."id") AS "orders", SUM("app_order"."total_item_count") AS "products", (AVG("app_order"."grand_total") - AVG("app_order"."shipping_amount")) AS "avg", SUM("app_order"."shipping_amount") AS "total_shipping" FROM "app_order" INNER JOIN "app_client" ON ("app_order"."client_id" = "app_client"."id") WHERE (NOT (NOT "app_client"."is_active") AND "app_order"."created_at" at time zone 'utc' at time zone (case WHEN app_client.country = 'CL' THEN 'America/Santiago' WHEN app_client.country = 'CO' then 'America/Bogota' WHEN app_client.country = 'PE' then 'America/Lima' WHEN app_client.country = 'AR' then 'America/Buenos_Aires' else 'GMT' END) BETWEEN '2020-01-01 00:00:00+00:00' AND '2020-01-31 23:59:59+00:00') GROUP BY "app_client"."name", "app_order"."client_id", "app_client"."country" ORDER BY "total" DESC; I have this query on the ORM, but I need to add the CASE statement on the WHERE clause. My ORM query: Order.objects.exclude(client__is_active=False).values('client__name', 'client__pk', 'client__country').filter(created_at__range=(self.request.GET['created_at__gte'], self.request.GET['created_at__lte'])) \ .annotate(total=Sum('grand_total') - Sum('shipping_amount')) \ .annotate(orders=Count('pk')).annotate(products=Sum('total_item_count')) \ .annotate(avg=Avg('grand_total') - Avg('shipping_amount')).annotate(total_shipping=Sum('shipping_amount')).order_by('-total') I try to do it using raw method, but it didn't work. Someone can help me please! Thanks for the help! -
store multiple inputs into single JSON as a Dictionary- Django
I am working on a project which is online printing ordering service. Here on the order page I am getting different attributes of product in radio button list in the form, and all the attributes I want to store in a single json in database. models.py class Product(models.Model): prod_ID = models.AutoField("Product ID", primary_key=True) prod_Name = models.CharField("Product Name", max_length=30, null=False) prod_Desc = models.CharField("Product Description", max_length=2000, null=False) prod_Price = models.IntegerField("Product Price/Piece", default=0.00) prod_img = models.ImageField("Product Image", null=True) def __str__(self): return "{}-->{}".format(self.prod_ID, self.prod_Name) # this is the order table , there is a "attribute_field" I wantto store the attributes in this field # as JSON. class Order(models.Model): order_id = models.AutoField("Order ID", primary_key=True) user_id = models.ForeignKey(User, on_delete=models.CASCADE, null=False, verbose_name="Customer ID") prod_id = models.ForeignKey(Product, on_delete=models.CASCADE, null=False, verbose_name="Product ID") quantity = models.ImageField('Product Quantity', max_length=10, default=500) attribute_value = models.CharField("Item Details JSON", max_length=2000, null=False) order_date = models.DateField("Order Date", auto_now_add=True, null=False) order_job_title = models.CharField("Name of Company/Business", max_length=100, null=False) order_desc = models.CharField("Details for Product", max_length=1000, null=False) product_img = models.ImageField("Template Image", null=False) address = models.CharField("Customer Address ", max_length=100, null=False) state = models.CharField("Customer State", max_length=30, null=False) city = models.CharField("Customer City", max_length=30, null=False) postal_code = models.IntegerField("Area Pin Code", null=False) order_price = models.DecimalField(max_digits=8, decimal_places=2, default=0000.00) class ImageTemplate(models.Model): temp_id = models.AutoField("Template ID", primary_key=True, auto_created=True) temp_img … -
Email not send from server office 365
SMTPAuthenticationError at /clientportal/open_demoac (535, b'5.7.139 Authentication unsuccessful, SmtpClientAuthentication is disabled for the Tenant. Visit aka.ms/smtp_auth_disabled for more info. [AM0PR04CA0059.eurprd04.prod.outlook.com]') Request Method: POST Request URL: https://hme158.com/clientportal/open_demoac Django Version: 2.2.6 Exception Type: SMTPAuthenticationError Exception Value: (535, b'5.7.139 Authentication unsuccessful, SmtpClientAuthentication is disabled for the Tenant. Visit aka.ms/smtp_auth_disabled for more info. [AM0PR04CA0059.eurprd04.prod.outlook.com]') Exception Location: /usr/lib/python3.7/smtplib.py in auth, line 642 Python Executable: /home/divsolution/HNXINLUAN/hnxenv/bin/python3 Python Version: 3.7.9 Python Path: ['/home/divsolution/HNXINLUAN/HME/new_crm', '/home/divsolution/HNXINLUAN/hnxenv/bin', '/usr/lib/python37.zip', '/usr/lib/python3.7', '/usr/lib/python3.7/lib-dynload', '/home/divsolution/HNXINLUAN/hnxenv/lib/python3.7/site-packages'] Server time: Wed, 17 Feb 2021 19:53:01 +0530 -
Search & Display Polygons on Geodjango-Leaftlet Web App
I am currently working on a Geodjango-Leaflet-Openstreetmap web app. I have around 540000 polygons of property boundaries that were drawn in Arcmap; the polygons will be imported to the web app later through Postgres+Postgis. There is a search bar on the web app. I want the user to enter a polygon's unique ID in the search bar, and the polygon to appear on the screen soon after. However, after entering the polygon's ID at the home page, the site redirects me to the results page with no polygon. Please help me fix the code. Your help will be greatly appreciated. On a separate note, what is the maximum no. of polygons that Geodjango-Leaflet & Postgres/postgis can support? According to this website , it's 67mil vertices. Is this actually correct? I'm asking because I might need to import more than the aforementioned figure in the future. results.html <!DOCTYPE html> <html> {% load static %} {% load leaflet_tags %} <head> {% leaflet_js %} {% leaflet_css %} <title>Home</title> <style type="text/css"> #gis {width: 100%;height:1080px;} </style> <script type="text/javascript" src="{% static 'dist/leaflet.ajax.js' %}" > </script> </head> <body> <h3>Welcome</h3> <br> <script type="text/javascript"> function our_layers(map,options){ var osm = L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',{ maxZoom: 19, attribution: '&copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>' }); {% for … -
Aunt folly 'pip' and the details
I " virtualenv env_site-Access denied??" can among leap explain what's sowing on her Set Virtual environment- Setting up the virtual environment will allow you to edit the dependency which generally your system wouldn’t allow. Follow these steps to set up a virtual environment- Create a virtual environment by giving this command in cmd- virtualenv env_site C:/Users/viren>virtualenv env_site Access is denied -
send_email is slow in django, how to speed it up?
Getting an email after 10-12 mins or more, I have added email verification feature and reset password mail feature, when user register email is received in 10-12 mins which doesn't looks nice, how to get rid of this? Here is my settings.py: # EMAIL_BACKEND socket.getaddrinfo('smtp.gmail.com',587) EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = socket.gethostbyname('smtp.gmail.com') EMAIL_HOST_USER = 'zoderadmn781@gmail.com' EMAIL_HOST_PASSWORD = 'password' EMAIL_PORT = 587 EMAIL_USE_TLS = True DEFAULT_FROM_EMAIL = 'Zoder Team <noreply@zoderadmin.com>' #email verification def verified_callback(user): user.is_active = True EMAIL_ACTIVE_FIELD = 'is_active' EMAIL_VERIFIED_CALLBACK = verified_callback EMAIL_TOKEN_LIFE = 60 * 60 * 3 EMAIL_SERVER = socket.gethostbyname('smtp.gmail.com') EMAIL_PORT = 587 EMAIL_ADDRESS = 'zoderadmn781@gmail.com' EMAIL_FROM_ADDRESS = 'Zoder Team <noreply@zoderadmin.com>' EMAIL_PASSWORD = 'password' EMAIL_MAIL_SUBJECT = 'Zoder admin: Confirm Email' EMAIL_MAIL_HTML = 'verify/mail_body.html' EMAIL_MAIL_PLAIN = 'verify/mail_body.txt' EMAIL_PAGE_TEMPLATE = 'verify/confirm_template.html' EMAIL_PAGE_DOMAIN = 'http://127.0.0.1:8000/' -
Missing "sessionid" cookie using SessionAuthentication
I got the issue that the sessionid cookie seems not to be saved after deploying on the Amazon EC2. In the setting.py I wrote REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.SessionAuthentication', ) } I login via a rest call that is defined such as from django.contrib.auth import authenticate, login, logout from django.views.decorators.csrf import csrf_protect from django.utils.decorators import method_decorator from rest_framework import status, views from rest_framework.response import Response class LoginView(views.APIView): @method_decorator(csrf_protect) def post(self, request): user = authenticate( username=request.data.get("username"), password=request.data.get("password")) if user is None or not user.is_active: return Response({ 'status': 'Unauthorized', 'message': 'Username or password incorrect' }, status=status.HTTP_401_UNAUTHORIZED) return Response({"username": request.data.get("username")}) class LogoutView(views.APIView): def get(self, request): logout(request) return Response({}, status=status.HTTP_204_NO_CONTENT) On the local windows machine that works well and the sessionid cookie is available and used for all rest-calls. However, using the Amazon EC2, that cookie is not created. Can someone help? THX Lazloo -
How to set ForeignKey attribute knowing just the attribute name and related object's ID?
Is there a way to set ForeignKey attribute value knowing just the name of the attribute and the ID of the ForeignKey related object? I tried to do this using setattr(): setattr(instance, 'product', 41) The result is: Cannot assign "41": "MyModel.product" must be a "Product" instance. -
pass data to form filed in django templae
How can I pass data to form fields in django templat ? , for example I have below code in my project: <td class="col-3"> {{form.number|as_crispy_field}} </td> Can I use <td class="col-3"> {{form.number}} = 10 </td> in django template ?