Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Generating end-user friendly descriptions of unique_together relationships for fields in django models
basically my problem can be summarized as below. Problem domain is Real estate. I have an ApartmentSpace table, where each row represents a rentable apartment_flat/ space with given set of facilities (such as all the utilities, amenities, floor size, number of and type of available rooms etc.) and I have a Property table, which may have one or more apartments added as ManyToMany Field. One single apartment_space_id may be attached to more than one property in this case (as many apartments in the real world may be represented with same set of facilities, I will assume all such apartments to have a single apartment_space_id only) So, a single rentable unit will be represented by a pair of (apartment_space_id, property_id) representing a unique_together relationship for that rentable unit in physical world. Bonus: if possible I would also want to represent within that Property, all the apartments attached to that property as identifiable with a local_apartment_space_id, that will give an auto-incrementing id to all the attached apartments for that property only and not depend on global apartment_space_id primary key for Apartment table. Now my problem is that if I want to send notification to the end-user for the rentable-unit, let's say for … -
How can I lookup a value based on user input and and use display it to the user in django
I'm currently learning to develop websites using Django. I have the following problem, where I have two models: class Model_1(models.Model): id = models.Charfield(max_length=250) account_name = models.Foreignkey(Accounts, on_delete=models.CASCADE) class Model_2(models.Model: account_name = models.Charfield(250) account_type = models.Charfield(250) I have a html form where the user inputs their id, and chooses the account name. I would like that to redirect them to a new html page where they can see the account type that is associated with that account name. What is the best way to do this? -
Is it possible to create own class in Django views to avoid code duplicates?
I have 3 subpages to redirect to and each of them must contain the same piece of code: new_user = User.objects.get(username=user) user_profile = Profile.objects.get(user=new_user) adverts = Advert.objects.filter(user=new_user) editable = False if request.user.username == user: editable = True context = { "objects":adverts, "user_profile":user_profile, "no_data":"No comments", "editable":editable, "user":user } and only "objects" in context change. 3 almost the same methods don;t look good. Is there a way to inherit that code from one class or maybe create own tag to do it ? I'm kinda new in django and I do not know what are the good habits here ;) -
problem in connecting django html templates
whenever i try to connect my template my browser shows following error TemplateDoesNotExist at / test.html Request Method: GET Request URL: http://localhost:8000/ Django Version: 3.0.5 Exception Type: TemplateDoesNotExist Exception Value: test.html Exception Location: C:\Users\NIKHIL MISHRA\AppData\Local\Programs\Python\Python37\lib\site-packages\django\template\loader.py in get_template, line 19 Python Executable: C:\Users\NIKHIL MISHRA\AppData\Local\Programs\Python\Python37\python.exe Python Version: 3.7.7 Python Path: ['C:\pro\myproject', 'C:\Users\NIKHIL ' 'MISHRA\AppData\Local\Programs\Python\Python37\python37.zip', 'C:\Users\NIKHIL MISHRA\AppData\Local\Programs\Python\Python37\DLLs', 'C:\Users\NIKHIL MISHRA\AppData\Local\Programs\Python\Python37\lib', 'C:\Users\NIKHIL MISHRA\AppData\Local\Programs\Python\Python37', 'C:\Users\NIKHIL ' 'MISHRA\AppData\Local\Programs\Python\Python37\lib\site-packages'] Server time: Mon, 4 May 2020 21:28:42 +0000 i have created templates folder and having test.html file in it also my myapp\views.py (app name)file code looks like this from django.shortcuts import render def index(request): return render(request,'test.html') and my myapp\urls.py is this from django.conf.urls import url from django.contrib import admin from django.urls import path,include from . import views urlpatterns=[ url(r'^$',views.index), ] ps edit: my templates setting TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] -
Why is my Django App failing on Azure with UUID invalid syntax
My Django App runs fine locally on macOS Catalina with Python 3.8.2 and Django 3.0.5. I am deploying it to Azure as WebApp from Github selecting Python 3.8. I have provisioned the Postgres DB, the Storage Account and the WebApp. The build process is successful. The WebApp fails at startup with: File "/antenv/lib/python3.8/site-packages/django/db/models/fields/__init__.py", line 6, in <module> import uuid File "/antenv/lib/python3.8/site-packages/uuid.py", line 138 if not 0 <= time_low < 1<<32L: ^ SyntaxError: invalid syntax I have verified that the uuid package is not within my requirements.txt file. DB environment variables are set up. Collectstatic successfully replicated my static data. The WebApp is running with Docker. Any help on this greatly appreciated. -
csrf verification failed. request aborted, CSRF cookies not set in Internet Explorer
I am trying to fetch one POST request from javaScript file to my Django endpoint but it is giving error 403 (Forbidden). However it is working fine (no any type of error) in Chrome Browser but not in MicroSoft Edge and Internet Explorer. I have also included csrf token but i am getting this error. After digging in console i found this When i went to that endpoint directly (without post request) from browser in different browser i found error in all browser but i think that is because there is no POST data but other thing that is noticed is in Chrome where it is working fine the COOKIES values are set In Chrome but in Internet Explorer and Microsoft Edge COOKIES values are not set In Internet Explorer And in Microsoft Edge And i m pretty much sure something is wrong with COOKIES. Please Help me to find the bug. -
How do I get my python program onto my portfolio website?
I am fairly new to programming and I have a python program that I developed this past semester at school. I am currently working on my personal portfolio website and would like to include my python program on my site to display my programming skills. If someone could point me in the right direction on where to start that would be much appreciated. Any information would help. Thanks. -
Failed to populate a django3 database
I have an error, at the time of trying to save data in the database, the data is not saved, at the time of filling the data it seems that it saved the data but this does not do it, because each field is validated and when I send it not no error comes out this is the view which is class based. from django.shortcuts import render, redirect from django.views.generic import View from .models import Comment from .forms import CommentForm class IndexView(View): model = Comment template_name = 'home/index.html' form_class = CommentForm def get_queryset(self): return self.model.objects.all().order_by('-pk') def get_context_data(self, **kwargs): context = {} context['commentaries'] = self.get_queryset() context['form'] = self.form_class return context def get(self, request, *args, **kwargs): return render(request, self.template_name, self.get_context_data()) def post(self, request, *args, **kwargs): form = self.form_class(request.POST) if form.is_valid(): form.save() form.errors.as_json() return redirect('home:index') and this is the form from django import forms from django.urls import reverse_lazy from .models import Comment class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ['name', 'comment'] labels = { 'name': 'Nombre', 'comment': 'Comentario' } widgets = { 'name': forms.TextInput( attrs={ 'class': 'form-control', 'placeholder': 'Ingrese su Nombre', 'id': 'name', } ), 'comment': forms.Textarea( attrs={ 'class': 'form-control', 'placeholder': 'Ingrese su comentario', 'id': 'comment', } ) } This is … -
Django optimise duplicate query
I'm new to Django, and the ORM is a bit hard for me, I have a search page with a query and a few criteria filters and the get_queryset is as follows (its an app store): def get_queryset(self): ... filter object list based on GET parameter... return object_list.annotate( rating=Avg('reviews__stars'), downloads=Count('order_history', distinct=True), flag1_rate=100*Count( 'reviews', filter=Q(reviews__status=Review.FLAG1) ) / (Count( 'reviews', filter=Q(reviews__status=Review.FLAG2) ) + Count( 'reviews', filter=Q(reviews__status=Review.FLAG1) )) ).order_by(ordered_sort) As you can see I am querying for the Count of FLAG1 twice (not the real name but you get the idea, I am calculating a ratio between two flags that users give during reviews using 100*FLAG1/(FLAG1+FLAG2)): Count( 'reviews', filter=Q(reviews__status=Review.FLAG1) ) How can I prevent this? is there a way to store it in a variable for the annotation? -
Creating user groups and assigning permissions on signup
I'm using Allauth and I am trying to: 1- Create user groups within my code (not in the command line). I found the following code which I think will do this, but I don't know exactly where in my project to put it (also, does this code look right?). from django.contrib.auth.management import create_permissions def create_group(apps, schema_editor): for app_config in apps.get_app_configs(): create_permissions(app_config, apps=apps, verbosity=0) # I dont understand this piece of code group, created = Group.objects.get_or_create(name='registered_users') if created: add_thing = Permission.objects.get(codename='add_thing') group.permissions.add(add_thing) group.save() 2- I am wanting to add users to a group upon signup (rather than manually). I found this code, which seems to look correct to me, but am unsure where to put it (in users/signals? also, does this code look okay?). # set group to registered_user @receiver(post_save, sender=User) def set_group(sender, instance, created, **kwargs): if created: group = Group.objects.get(name='registered_users') instance.groups.add(group) instance.save() Thank you very much. -
display jason data in html with ajax
i want to display jason data in htmal,but not working js {% block js %} {{ block.super }} <script type="text/javascript"> $(document).ready(function () { $.getJSON("{% url 'app_software:list' %}", { get_param: 'value' }, function(data) { $.each(data, function(index, element) { $('#posts').append(element.title) }); }); }); </script> {% endblock js %} html <div id="posts"> </div> view.py def home(request): ctx={} ctx['asd']=Software.objects.all() return render(request,'index.html',ctx) class Pagination_pro(ListAPIView): queryset=Software.objects.all() serializer_class=pagination_ser pagination_class=PageNumberPagination url.py urlpatterns = [ path('', home ,name='home'), path('pagination/', Pagination_pro.as_view(), name='list'), path('software_detail/<str:slug>/',software2, name='software1'), ] noting error display, but not working. Jason's data is shown in the postman. -
Django display html page based on user type
I want to display the home page of my site based on the user type (admin, guest, student, etc.). It would be nice to display a link to the login page for guest users, but this link should be hidden for already authenticated users. For admins there should be a link to django-admin. Besides that there also some differences in the home page for other user roles. What is a good way to implement this? I have several options for that: Create html page for each user role: home_guest.html, home_admin.html, ... Create a single html page but put some if-clauses inside it like {% if user.is_authenticated %} -
How to send POST or GET requests to one API and get data from ERP API?
I have access to API of ERP software. I want to give my clients access to it but not directly, just by another API. I want to restrict what They can POST and GET, but API from ERP couldn't do it so need to create my own like some connector or something. I want to use Django for it. How my clients make POST or GET requests and get info from ERP API? -
how to link between chrome extension and auth system built in django?
I'm making a chrome extension & I've made a log in and create a new account system using Django. When users try to use the extension for the first time it will take them to the "Create new account" page, What I need to know is how to link between the extension & the Django authentication system in a way that it can always remember the user after signing up for the first time or logging in afterwards. I know that I need to use API end point but if someone can give more detailed steps to do so will be much appreciated -
Django, how to reuse views code in other views and template
I'm new in django and I was wondering if is it possible to reuse code and annotate output write in a views.py. I have created a lot of new annotate output that I want to reuse to figure out a dashboard with graphs and key indicator. I don't like to rewrite all code because I wouldn't follow the DRY principles. -
django cannot find object field. error: Items() got an unexpected keyword argument 'sellbtn'
I am trying to access my object but a field I created, it is telling me it is not there. $ cat userdash/views.py from django.shortcuts import render from django.http import HttpResponse, HttpResponseRedirect from .models import AssetList, Items from .forms import CreateNewTrade # Create your views here. #def index(response): # return HttpResponse("<h1>Hello Dark World!</h1>") def userdash(response, id): ls = AssetList.objects.get(id=id) if response.method == "POST": print(response.POST) if response.POST.get("save"): for item in ls.items_set.all(): if response.POST.get("c" * str(item.id)) == "clicked": item.sellbtn = True else: item.sellbtn = False item.save() elif response.POST.get("newItem"): txt = response.POST.get("new") if len(txt) > 2: #this validation is retarded and needs to be fixed ls.items_set.create(user_asset=txt, sellbtn=False) #this is the line in question else: print("invalid") #items = ls.items_set.get(id=1) #return HttpResponse("<h1>User Dashboard!</h1><h2>%s</h2><br></br><p>%s</p>" %(ls.name, str(items.user_asset))) return render(response, "userdash/list.html", {"ls":ls}) def home(response): #pass return render(response, "userdash/home.html", {}) def create(response): if response.method == "POST": form = CreateNewTrade(response.POST) if form.is_valid(): n = form.cleaned_data["user_asset"] t = AssetList(name=n) t.save() return HttpResponseRedirect("/userdash/%i" %t.id) else: form = CreateNewTrade() return render(response, "userdash/create.html", {"form":form}) $ cat userdash/templates/userdash/list.html {% extends 'userdash/base.html' %} {% block title %} List Page {% endblock %} {% block content %} <h2>{{ls.name}}</h2> <form method="post" action="#"> {% csrf_token %} <ul> {% for item in ls.items_set.all %} {% if item.sell_asset == True %} … -
"AttributeError: module 'django.contrib.auth.views' has no attribute 'password_reset' " error in urls.py
I am using Django 3.0.5 and python 3.6 and getting the error from the terminal as : " AttributeError: module 'django.contrib.auth.views' has no attribute 'password_reset' " in my urls.py file. urls.py ``` from django.contrib import admin from django.urls import path from django.contrib.auth import views as auth_views from django.conf.urls import url from blog import views urlpatterns = [ path('admin/', admin.site.urls), path('index/',views.index, name='index'), path('datetime/',views.current_datetime,name='datetime'), path('',views.post_list,name='post_list'), url(r'^blog/(?P<id>\d+)/(?P<slug>[\w-]+)/$',views.post_detail,name="post_detail"), url('post_create/',views.post_create,name = "post_create"), url('login/', views.user_login,name="user_login"), url('logout/', views.user_logout,name="user_logout"), #Password reset urls url('password-reset/',auth_views.password_reset, name='password_reset'), url('password-reset/done/',auth_views.password_reset_done,name="password_reset_done"), url('password-reset/confirm/(?P<uidb64>[\w-]+)/(?P<token>[\w-]+)/',auth_views.password_reset_confirm, name="password_reset_confirm"), url('password-reset/complete/', auth_views.password_reset_complete,name="password_reset_complete"), ] ``` I have checked here which is talking about the same 4 views which I have written then why I am getting the error. When I change "auth_views.password_reset" to "auth_views.PasswordResetForm in "url('password-reset/',auth_views.password_reset, name='password_reset')" then, terminal does not show any error for "password_reset" but then it shows error for "password_reset_done". Can anyone please tell why I am getting this error and how to fix it. Any help would be appreciated. -
How can I avoid hard-coding multiple elements into my Django model?
I'm pretty new to Stack Overflow, so thank you in advance for your insight. This is a question about Django 3.0 (so Python 3.6+). Use case: Let's say I've successfully parsed through the Code of Federal Regulations and I've determined that each regulation has three parts - the citation, the subject, and the regulation itself. I can parse these into a nested dictionary at need (or XML, or CSV, or any format really). Let's also assume I have a complex business that needs to comply with many of these regulations, so I have to figure out whether the regulation is applicable and how I'm going to implement it. So this is my models.py class CFR(models.Model): citation = models.CharField(max_length = 25) subject = models.CharField(max_length = 25) regulation_text = models.TextField() applicable = models.BooleanField(default = True) implementation = models.TextField() My forms.py. Yes I know I shouldn't use __all__. class RegulationForm(forms.ModelForm): class Meta(): model = CFR fields = ('__all__') and my views.py class ApplicabilityView(CreateView): model = CFR template_name = "template.html" form_class = RegulationForm I'd like to use the model to: Iterate through each regulation. Render a form containing each regulation (there could could be hundreds of regulations, so the length of the form doesn't … -
Datatables do not update with jQuery when using Django models
I am trying to implement the answers given in an old post(1). It describes a "problem" when jQuery Datatables is not refreshed after adding a row of data / writing to the model database in Django. The two non-accepted answers suggests: $("#analytic-table").DataTable().destroy(); flush DT's cache and then re-initialize the DataTablead table with $("#analytic-table").DataTable(); or, to add a row trough table.rows.add($(data.html_analytic_list))).draw(); After consulting other posts suggestion similar solutions, nothing really works. With this I mean, I can write data to the model/database but changes does not appear in the table until I manually reload the page containing the table. To instruct Datatables to contact Django for a refresh of data does not seems to work. Given this, I am let to believe I am missing some crucial steps within the combination of jQuery Datatables and Django models and would like to ask if someone else have experienced the same problem and know the solution. Please note that I visually can "fake" data by $("#analytic-table > tbody:last-child").append(`<tr> table data </tr>') However, I cannot apply any other action until i refresh the page with the table. -
Django AttributeError: 'ManyToManyDescriptor' object has no attribute 'filter'
Hi I am trying to see if a user exists users in a ManyToMany relationship between my models. I have two models: A Course model A Profile model My course model is: class Course(models.Model): course_code = models.CharField(max_length=20) course_content = models.CharField(max_length=100) course_name= models.CharField(max_length=100) course_likes = models.ManyToManyField(Profile, blank=True, related_name='course_likes') and my user models I have this field: courses = models.ManyToManyField('home.Course',related_name='profiles') in my course model, I have a method that filters courses based on the course regardless of the course description and checks to see if user exists: def is_liked(self,user): Course.course_likes.model.objects.filter(course_code=self.course_code, profiles__id=user.id).exists() and I am also trying to add a user to likes by: Course.objects.get(course_code=code).course_likes.add(request.user) Which I believe is also incorrect(Haven't tested yet since the first step is to check if user already exists) Now when I test the method for checking if the user exists I get an error: return Course.likes.filter(course_code=self.course_code,profiles__id=user.id).exists() AttributeError: 'ManyToManyDescriptor' object has no attribute 'filter' I am using a template tag execute the method using: @register.simple_tag(takes_context=True) def check_is_liked(context): request = context['request'] course = context['course'] return course.is_liked(request.user) Which I believe is working properly as the error is related to my models function. In my template I use (I have tested the course object is being sent correctly): {% with course=course … -
Should i quit Django for freelancing? [closed]
THIS IS NOT A TECHNICAL QUESTION....! Just looking for a sincere advice.... The thing is i have been learning python & django since last year spending 4-6 hours each day. My ultimate goal was to be a successful freelance web developer afterwards. I had an option of Php but i didn't choose it because i just liked python (as i was using Linux that time) and now i think that was the biggest mistake i made. Now when i am in the freelance business, i see there is only php everywhere. 90% of jobs in web development are for php and it is very hard for a newbie to get the job for django when it is in such a low demand. Now, I am quite confused if i should quit django right now and learn php from scratch to make some stand in the business or should i just stick with it ? Sincere advices would be really appreciated...! Thankyou -
Django-Simple-Captcha Cron Job To Delete Captcha Records
I need some help with making a cron job for django-simple-captcha to be able to delete captcha database records from postgresql on a daily basis or an hourly basis. According to the docs and the maintainer himself, you can use: CAPTCHA_GET_FROM_POOL, CAPTCHA_GET_FROM_POOL_TIMEOUT, CAPTCHA_TIMEOUT settings combined with python3 manage.py captcha_create_pool command. But the docs are a bit confusing and do not show you an example of how to do the cron job with postgres. I also do not know in production if it is good to run the python3 manage.py captcha_create_pool while the site is actively running in gunicorn. Does gunicorn need to be stopped to be able to run the captcha_creat_pool command with a cron job? Can any of the django packages below be used to make this easier? If so, how? I would prefer if someone gave a nice example or description of how to do this. https://djangopackages.org/grids/g/cron/ https://django-simple-captcha.readthedocs.io/en/latest/advanced.html -
Image.save() is saving empty empty image (0B)
I am saving Images in amazon s3 storage. image = models.ImageField(upload_to=upload_avatar_to, null=True, blank=True) def upload_avatar_to(instance, filename): import os from django.utils.timezone import now shop_uuid = Shop.objects.get(id=instance.shop_id).uuid instance_dict = instance.__dict__ filename_base, filename_ext = os.path.splitext(filename) return 'shops/%s/items/%s/%s%s' % ( shop_uuid, instance_dict['uuid'], now().strftime("%Y%m%d%H%M%S"), filename_ext.lower(), ) Now i am getting the image saved on storage and resizing it to thumbnail per it is saving empty file (having size 0B) by calling create_avatar_thumb def create_avatar_thumb(self): import os from PIL import Image from django.core.files.storage import default_storage as storage if not self.image: return "" file_path = self.image.name filename_base, filename_ext = os.path.splitext(file_path) thumb_file_path = "%s_thumb.jpg" % filename_base f = storage.open(file_path, 'rb') image = Image.open(f) image.thumbnail((400, 400)) f_thumb = storage.open(thumb_file_path, "w") image.save(f_thumb, "JPEG") f_thumb.close() Please help; using django -
How to view Django Rest Framework Source Code in VS Code
I am new to Django Rest Framework. I am working on a project running in Docker containers. I would like to view Django Rest Framework source code in VS Code. When I right-click on anything from the following line and click Go to Definition I get the message No definition found for 'rest_framework' from rest_framework import viewsets How can I view django rest framework source code in VS Code, particularly if I'm running my projects in containers? Thank you -
How to add other views and models into generic detail view in Django
I am creating a django ecommerce website. My cart page shows the items, quantity, price and all that stuff of the order. I am creating a mini-cart that shows up on all pages when the user hovers over the cart icon, which shows all this data, and the user can click on it to go to the cart page. This worked on all my other pages (products page and cart page), but I can't seem to add the needed variables into my DetailView page for each product. The models that are related to this are: class Product(models.Model): name = models.CharField(max_length=200, null=True) price = models.FloatField(max_length=200) description = models.TextField(max_length=500, default='No description') digital = models.BooleanField(default=False, null=True, blank=False) image_1 = models.ImageField(null=True, blank=False, default='') image_2 = models.ImageField(null=False, blank=True, default='') image_3 = models.ImageField(null=False, blank=True, default='') images = [image_1,image_2,image_3,] def __str__(self): return self.name def get_absolute_url(self): return reverse('product-detail', kwargs={'pk':self.pk}) class Order(models.Model): customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, blank=True, null=True) date_ordered = models.DateTimeField(auto_now_add=True) complete = models.BooleanField(default=False, null=True, blank=False) transaction_id = models.CharField(max_length=200, null=True) def __str__(self): return str(self.id) @property def shipping(self): shipping = False orderitems = self.orderitem_set.all() for i in orderitems: if i.product.digital == False: shipping = True return shipping @property def get_cart_total(self): orderitems = self.orderitem_set.all() total = sum([item.get_total for item in orderitems]) …