Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Forms Django Python
Could someone help me? I don't know what I'm doing wrong. I try to change ma value in database but it doesn't work. Still it is the same like it set default.. Below my codes...Thank You in advance. koszyk.html {% for produkt in produkty%} <div id="bin"> <div class ='name'>{{ produkt.nazwa }}</div> <div class="product_price"> {{ produkt.cena }} {{ produkt.ilosc }} <form method="POST"> {% csrf_token %} {{ form }} <button type="submit" href ="{% url 'numbers' produkt.id %}">zaktualizuj</button> </form> </div> <div class="delete"> <a href="{% url 'usun' produkt.id %}">Usuń</a></div> {% endfor %} models.py class Basket(models.Model): nazwa = models.CharField(max_length=64, blank=False, unique=True, default="") cena = models.PositiveSmallIntegerField(default=2000) opis = models.TextField(default="") ilosc = models.PositiveSmallIntegerField(default=3) forms.py from django.forms import ModelForm from .models import Shop, Basket class IloscForm(ModelForm): class Meta: model = Basket fields = ['ilosc',] views.py def numbers(request, id): form = IloscForm(request.POST or None) produkt = Basket.objects.get(pk=id) if form.is_valid(): ilosc = form.save(commit=False) produkt.ilosc = ilosc ilosc.save() return redirect('koszyk') def koszyk(request): produkty = Basket.objects.all() form = IloscForm() return render(request, 'koszyk.html', {'produkty': produkty, 'form':form}) I would be very grateful for help! Natalia -
How to call a function from models.py to views or template
I am a beginner in Django and Python. I am creating a Payroll project whose calculations are done using a function from models.py. The user must input the variables through templates and save it to sql. Then search for the employee (through templates again) and output his payroll details. That is the time when I want to use the calculation function. Data from the database is working and is outputted by the templates. As for the calculated data, it simply isn't showing. I have been trying to use the function to no avail and I've searched for 3 days already. I am at lost at what to do now. models.py from django.db import models #Class in model.py acts as a table in database class Add_Employee(models.Model): name = models.CharField (max_length = 150, default = '', null = False) position = models.CharField (max_length = 150, default = '', null = False) email = models.EmailField (max_length = 150, default = '', null = False) address = models.CharField (max_length = 500, default = '', null = False) basic_pay = models.FloatField(default=None) overtime_hours = models.IntegerField(default=None) allowance = models.FloatField(default=None) days_leave = models.IntegerField(default=None) other_deductions = models.FloatField(default=None) #Django admin page; the table will show the name def __str__(self): return … -
Can I create a Django object instance using a previous object's value, race-condition-free?
TLDR When creating a new object using Django ORM, can I, in a transactionally safe / race-condition-free manner, set a field's value based on an already existing object's value, say F('sequence_number') + 1 where F('sequence_number') refers not to the current object (which does not exist yet) but to any given object in the table? Longer version I have a model Issue with properties sequence_number and sequence_prefix. There is a unique constraint on (sequence_prefix, sequence_number) (e.g. DATA-1). class Issue(models.Model): created_at = models.DateTimeField(auto_now_add=True) sequence_prefix = models.CharField(blank=True, default="", max_length=32) sequence_number = models.IntegerField(null=False) class Meta: constraints = [ models.UniqueConstraint( fields=["sequence_prefix", "sequence_number"], name="unique_sequence" ) ] The idea is that issues —for auditing purposes— have unique sequence numbers for each variable (user-determined) prefix: when creating an issue the user selects a prefix, e.g. REVIEW or DATA, and the sequence number is the incremented value of the previous issue with that same sequence. So it's like an AutoField but dependent on the value of another field for its value. There can not be two issues DATA-1, but REVIEW-1 and DATA-1 and OTHER-1 all may exist at the same time. How can I tell Django when creating an Issue, that it must find the most recent object for … -
django admin - Define instance of formset on dynamic creation of inlines
Here's what I try to achieve: I have a Category and an Author model. To every Category I can save n authors. Category is an MPTT (tree) model. I need to show on the admin detail/change view in the admin a given category, all authors AND all the children-categories AND their authors. I can create the level-2-author-inlines very nicely like this: def get_inline_instances(self, request, obj=None): inline_list = super().get_inline_instances(request, obj) for child_category in self.object_from_request(request).children.all(): inline_list.append( ChildAuthorInline(self.model, self.admin_site, child_category=child_category)) return inline_list My Inline class looks like this: class ChildAuthorInline(admin.TabularInline): """ Dynamically created inline to show authors of child categories. """ model = Author extra = 0 fields = ('name',) def __init__(self, parent_model, admin_site, *, child_category): self.child_category = child_category self.verbose_name_plural = _(f'Category {child_category.name}') super().__init__(parent_model, admin_site) def get_queryset(self, request): return Author.objects.filter(category=self.child_category) So far, so good. The problem is: When I want to add a new author to a child category, the instance of the formset is still the parent category. I tried everything but wasn't able to inject the child category and use it in the original part of the formset. And yes, I could overwrite the template or copy a bunch of django code, but this is too hack for my taste... There … -
django rest connecting with react trough INSTALLED_APPS
I'm running trough my m8 project (Django Rest Framework + React) and there is something like this: INSTALLED_APPS = [ 'corsheaders', 'rest_framework', 'rest_framework.authtoken', 'django_database.apps.DjangoDatabaseConfig', 'rest_api.apps.RestApiConfig', 'front', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] Now, I understand that django needs to know that there is a frontend app to connect to, but in front directory are those files: settings.py urls.py admin.py apps.py tests.py views.py I'm not really sure, but why does python files are in frontend ? Without urls.py and 'views.pyfiles django server startup fails with some linking error tofront`. urls.py from django.urls import path from .views import index urlpatterns = [ path('', index) ] views.py from django.shortcuts import render def index(request, *args, **kwargs): return render(request, 'front/index.html') I wonder what is this magic ? Searching trough some tutorials covering django rest and react app connection some of them does apply this strategy, but some does not. Can someone explain ? Haven't found any solution in django docs by now. Is there a better way of doing this ? Will CORS_ORIGIN_ALLOW_ALL or CORS_ORIGIN_WHITELIST be the same ? -
How to restrict access by user groups in Django class based view?
VIEW Problem: I want to use permission restriction in django class based views. if login user is belong from students group then i want to redirect to student-dash url. if user from teacher it's redirect to teach-dash url. if student user try to access the teacher dashboard then i want to restrict that student user from teacher dashboard and render 404 error? I would be grateful for any help. class STListView(ListView): queryset = Article.objects.exclude(story_status='sn') template_name = 'index_page.html' context_object_name = 'list' def get_context_data(self, **kwargs): context = super(STListView, self).get_context_data(**kwargs) group = self.request.user.groups.filter(user=self.request.user)[0] if group.name == "student": return HttpResponseRedirect(reverse('student-dash')) elif group.name == "teacher": return HttpResponseRedirect(reverse('teacher-dash')) elif group.name == "Manger": return HttpResponseRedirect(reverse('manger-dash')) return context -
what is the path one have to follow in order to become Full Stack developer?
I am the student of 4th semester in CS dept. so far i have learnt C++,OOP(java) and data structures(java) currently learning data base. I want to be a best full stack developer. but when search for the material to study. I get so many things like there is a node.js as well as there is Django , we have React for frontEnd and as well as Angular and many others. and when i google for the best path for full stack i get different answers. and I am afraid for this that what if... what i am learning today is not going to be useful for me in future. I am confused by seeing technologies frameworks libraries in order for be a full stack. I have earn a certificate on web developing by cs50. after that i can make small web application but i have no knowledge of what is happening behind the scene. They also gave the Introduction of REACT. and currently i am doing courses on JavaScript and next i am thinking to study all this instructed by cs50(David and Brain) deeply so that i can make more elegant and large scale web application. enter image description here … -
Where is Django code inside my Django Application?
When I created a Django application, where is the code of Django? I mean, the source code of the framework my app is using? Context: I've been receiving a NoReverseMatch error, and I think my urlpatterns are ok, so I want to debug the reverse function to see why it's failing. -
How to work around heroku 30 seconds web request timeout
I am working on a Django App, which has been deployed on Heroku. A search function in the App uses an API to fetch data from a remote server. This server can take upto a minute to send a response. Problem is, Heroku's web request times out after 30 seconds. I have seen some similar problems here where people have been advised to make their code more efficient. Problem here is that I do not have control over the remote server and it's processes. Is there a way I can bypass this limit or should I be looking to host elsewhere? -
why is external address lookup javascript causing: ValueError: Missing staticfiles manifest entry?
My django App runs fine on local server and ok on heroku with DEBUG = False in settings.py. When DEBUG = True App crashes on Heroku with heroku log message: File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/staticfiles/storage.py", line 423, in stored_name raise ValueError("Missing staticfiles manifest entry for '%s'" % clean_name) ValueError: Missing staticfiles manifest entry for 'libraries/ideal-postcode/dist/ideal-postcodes-autocomplete.js' So far as per many other questions raised for this issue. But, this javascript is listed fine in the json manifest created using manage.py collectstatic Snippet "libraries/ideal-postcode/dist/ideal-postcodes-autocomplete.js": "libraries\\ideal-postcode\\dist\\ideal-postcodes-autocomplete.b7dbf9579b39.js", "libraries/ideal-postcode/dist/ideal-postcodes-autocomplete.min.js": "libraries\\ideal-postcode\\dist\\ideal-postcodes-autocomplete.min.75f7e4c76264.js", This is the only static resource to cause a problem. The ideal-postcodes-autocomplete.js is an address lookup (used by my form fields). Snippet var IdealPostcodes; (function (IdealPostcodes) { IdealPostcodes.API_URL = "api.ideal-postcodes.co.uk"; IdealPostcodes.TLS = true; IdealPostcodes.VERSION = "v1"; IdealPostcodes.DEFAULT_TIMEOUT = 10000; /* * STRICT_AUTHORISATION forces authorization header usage on * autocomplete API which increases latency due to overhead * OPTIONS request */ IdealPostcodes.STRICT_AUTHORISATION = false; ; }) I've been through very many of the previous answers but no help and spent ages making changes and re-testing. Is the problem because the script calls an external resource? If so, how do I get around this problem. If not, what am I doing wrong? Can post the full ideal-postcodes-autocomplete.js if it helps. -
I am getting error: Page not found in django. Please someone help me to solve the error
my urls.py page like this from django.contrib import admin from django.urls import path from . import views urlpatterns = [ path('admin/', admin.site.urls), path('',views.index,name='index'), path('analyze/',views.analyze,name='analyze'), path('about/',views.about,name='about'), path('contact/',views.contact,name='contact'), ] my views.py page looks like this from django.http import HTTP Response from django.shortcuts import render def index(request): return render(request,'index.html') def analyze(request): djtext=request.GET.get('text','default') removepunc=request.GET.get('removepunc','off') fullcaps=request.GET.get('fullcaps','off') spaceremover=request.GET.get('spaceremover','off') charcounter=request.GET.get('charcounter','off') wordcounter=request.GET.get('wordcounter','off') print(djtext) #analyzed=djtext if removepunc == 'on': punctuations = '''!()-[]{};:'"\,<>./?@#$%^&*_~''' analyzed="" for char in djtext: if char not in punctuations: analyzed=analyzed+char params={'purpose':'Remove punctuations','analyzed_text':analyzed} return render(request,'analyze.html',params) elif fullcaps=='on': # analyzed=djtext1 analyzed="" for i in djtext: if i==" ": analyzed=analyzed+" " else: analyzed=analyzed+i.upper() params={'purpose':'Capital Letter First','analyzed_text':analyzed} return render(request,'analyze.html',params) elif spaceremover == 'on': analyzed=djtext.replace(" ","") params={'purpose':'Space Remover','analyzed_text':analyzed} return render(request,'analyze.html',params) elif charcounter == 'on': counter=0 for char in djtext: if char==" ": continue else: counter=counter+1 params={'purpose':'Character Counter','analyzed_text':counter} return render(request,'analyze.html',params) elif wordcounter == 'on': counter=1 for char in djtext: if char==' ': counter=counter+1 params={'purpose':'Word Counter','analyzed_text':counter} return render(request,'analyze.html',params) else: return HttpResponse("Error") def about(request): return render(request,'about.html') def contact(request): return render(request,'contact.html') my index.html page-- Here I have shown only navbar part where error can be . My index.html page is in template/textutils and about and contact page are also in template/textutils. <div class="collapse navbar-collapse" id="navbarNavDropdown"> <ul class="navbar-nav"> <li class="nav-item active"> <a class="nav-link" href="/">Home <span class="sr-only">(current)</span></a> … -
How to get data from Django One to Many Fields Model using views into templates
I want to display 1 Parent Field with associated Child and further there Childs I have a Model class GrandParent(models.Model): name= models.CharField(max_length=50) .... class Parent(models.Model): parent = models.ForeignKey(GrandParent, on_delete=models.CASCADE) name= models.CharField(max_length=50) .... class Child(models.Models): parent = models.ForeignKey(Parent, on_delete=models.CASCADE) name= models.CharField(max_length=50) ... I am able to render objects from Grand Parent But I m unable to link further Parent Class objects and Child class objects in templates This approach I used in views.py def list(request): object_list = GrandParent.published.all() ... return render('app/list.html') def detail(request, post,): post = get_object_or_404(GrandParent, slug=post, status='published') return render(request, 'app/detail.html', {'post' : post, ... }) Now how to link further Classes in Same Detail View But Associated with there Parent Classes using Foreign Key. I'm following Django docs but they only giving max 2 examples using python shell with just One subclass I m confused How to implement there in this structure. Or anyone have already developed any project specifically with this type of models so please share any link of repo or something, would be wonderful. -
How can I move the Django URL requests from https:// to http:/?
All of the Django requests are directed to https:// but I want to direct all of my URL requests to http:// by default. Currently I have to manually remove s from every URL. Any solutions? -
Invalid HTTP_HOST header: '127.0.0.1:8000'. You may need to add '127.0.0.1' to ALLOWED_HOSTS. in Django
I'm getting this error whenever i'm trying to run my server locally. Here is how i've configured the allowed hosts: But it doesn't seem to work... ALLOWED_HOSTS = env.list("ALLOWED_HOSTS", default=["*", '127.0.0.1:8000']) -
Parsing an array of dictionnaries in a django for loop
In a Django application, I want to use a dictionary as elements of a result.html page: <tbody> {% for element in products%} <tr> <td>{{ element['q0']['Results'][0]['Name'] }}</td> </tr> {% endfor %} </tbody> But it returns Could not parse the remainder: '['q0']['Results'][0]['Name']' from 'element['q0']['Results'][0]['Name']': return render(request, 'todo/result.html', {'products': top_products}) File "C:\Python36\lib\site-packages\django\shortcuts.py", line 19, in render content = loader.render_to_string(template_name, context, request, using=using) File "C:\Python36\lib\site-packages\django\template\loader.py", line 61, in render_to_string template = get_template(template_name, using=using) File "C:\Python36\lib\site-packages\django\template\loader.py", line 15, in get_template return engine.get_template(template_name) File "C:\Python36\lib\site-packages\django\template\backends\django.py", line 34, in get_template return Template(self.engine.get_template(template_name), self) File "C:\Python36\lib\site-packages\django\template\engine.py", line 143, in get_template template, origin = self.find_template(template_name) File "C:\Python36\lib\site-packages\django\template\engine.py", line 125, in find_template template = loader.get_template(name, skip=skip) File "C:\Python36\lib\site-packages\django\template\loaders\base.py", line 30, in get_template contents, origin, origin.template_name, self.engine, File "C:\Python36\lib\site-packages\django\template\base.py", line 155, in __init__ self.nodelist = self.compile_nodelist() File "C:\Python36\lib\site-packages\django\template\base.py", line 193, in compile_nodelist return parser.parse() File "C:\Python36\lib\site-packages\django\template\base.py", line 478, in parse raise self.error(token, e) File "C:\Python36\lib\site-packages\django\template\base.py", line 476, in parse compiled_result = compile_func(self, token) File "C:\Python36\lib\site-packages\django\template\defaulttags.py", line 814, in do_for nodelist_loop = parser.parse(('empty', 'endfor',)) File "C:\Python36\lib\site-packages\django\template\base.py", line 449, in parse raise self.error(token, e) File "C:\Python36\lib\site-packages\django\template\base.py", line 447, in parse filter_expression = self.compile_filter(token.contents) File "C:\Python36\lib\site-packages\django\template\base.py", line 563, in compile_filter return FilterExpression(token, self) File "C:\Python36\lib\site-packages\django\template\base.py", line 663, in __init__ "from '%s'" % (token[upto:], token)) … -
Not understanding this Python script
in this example of Django project enter link description here, and in the templates section (book_detail.html), There is a code i do not understand: book.genre.all|join:", " "book.genre.all" are List of all objects from the Genre class that are connected to the book object (from Book class) by a ManyToMany key. why using pipe character for join or split these objects ? and why dont use ", ".join(book.genre.all) ? -
Using Django ORM in plain python script / infinite task
I have application in plain python with some basic libraries. I'm looking to use Django as main framework for this application and maintain frontend. My question is, can I still use my already written application and switch to Django ORM and maybe controlling the application via some callbacks. This application is running infinitely with asincio library. Or is there any way how to run background tasks in Django? I found celery but I'm not sure about starting this process. Maybe use of some Django commands and supervisor. TLDR: I need some way of running background task (command, controller, python script) infinitely long without user interaction. -
Django Querry Include Join
I tried to calculate the count of the increased and decreased competitor product price which are related to products. I couldn' handle it. Can I do this by overriding get_context_data method? I couldn't write a querry to get the data from comp_product model. How can I handle this? models: class Product(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE,related_name='products') category = models.CharField(max_length=120) brand = models.CharField(max_length=120) product = models.CharField(max_length=120) price = models.DecimalField(decimal_places=2,max_digits=100) class Comp_Product(models.Model): product = models.ForeignKey(Product,on_delete=models.CASCADE, related_name="comp_products") competitor = models.URLField() price = models.DecimalField(decimal_places=2,max_digits=100) change = models.FloatField() stock = models.BooleanField() last_update = models.DateField(auto_now_add=True) view: def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) Products = context['object_list'] context['distinct_category_count'] = Products.values('category').distinct().count() context['distinct_brand_count'] = Products.values('brand').distinct().count() context['product_count'] = Products.values('product').count() context['out_of_stock'] = Products.filter()values('stock').count() return context -
Min_value, max_value validation doesn't work if i use widget for FloatField
For use a custom css class in a input text, I had to add a widget. But now validation in django forms doesn't work anymore. class NewBind(forms.Form): new_bind=forms.FloatField(max_value=999999.99,min_value=1, widget=forms.TextInput(attrs={'class' : 'mk-off-inp'})) In this case validation doesn't works class NewBind(forms.Form): new_bind=forms.FloatField(max_value=999999.99,min_value=1) In this case validation works but i've lost css I also tried to add min e max inside widget but validation still not working -
provider-agnostic oauth2 library for django
I am looking for a django library, that can support oauth2 authentication, which is not specific to any provider. I tried django-allauth, social-auth libraries, but cant find anything general-purpose. -
Password validation not work in django-rest-framework
when I register new user at that time password validator not work.(e.g. When I enter admin123 and password is also admin123 at that time password validator not saw like this error: password must not same as username.) serializer.py: from rest_framework import serializers from django.contrib.auth import get_user_model User = get_user_model() class SignUpSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['username','email','password'] write_only_fields = ('password',) read_only_fields = ('id',) views.py: from rest_framework import status from django.contrib.auth import get_user_model from .serializers import SignUpSerializer from rest_framework.decorators import api_view, permission_classes from rest_framework.response import Response from rest_framework.permissions import AllowAny from django.contrib.auth.password_validation import validate_password from django.core.exceptions import ValidationError User = get_user_model() @api_view(['POST']) @permission_classes([AllowAny,]) def signup(request): serializer = SignUpSerializer(data=request.data) if serializer.is_valid(): username = serializer.data['username'] try: validate_password(serializer.data['password'], username) except ValidationError as e: return Response(str(e), status=status.HTTP_400_BAD_REQUEST) user = User( username = username, email = serializer.data['email'] ) user.set_password(serializer.data['password']) user.save() return Response(serializer.data, status=status.HTTP_201_CREATED) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) Thanks. -
How is this done to work in production, Django
I have a Django rest API. The API consumes Google Vision Api. When I try a call with a local file on localhost, it works just perfectly. However, when I do the same in production on a live server, the file is not found. Basically, what am doing is getting a local file path to do the vision API query like this: http://localhost:8000/api/search/image?q=/Users/user/Documents/graphics/images/testlogo.png That works fine. But if I try the same thing when the site is live in production http://vesm.com/api/search/image?q=/Users/user/Documents/graphics/images/testlogo.png I get a file not found exception. So my question is, how do I do a get request with a locally stored image? I am trying to create an image search API. What I have been doing is when someone picks a file, I get the local file path, as vision API just requires the file path. Any guide here will be helpful. -
How to pass request user to serializer in UpdateApiView with partial_update?
I have view like below. I have edited_user in my model . I want to pass current_user to serializer and in serializer I will override update() function. Problem is I cant find way to pass current user. Can Anyone help ? class Update(UpdateAPIView): serializer_class = serializer_class queryset = model.objects.all() def put(self, request, *args, **kwargs): if self.request.user.field == 1: return self.partial_update(request, *args, **kwargs) -
HTML autocomplete is not working along with Django extension in VSCode
I am currently using the latest version of VSCode and Django. Whenever I enable the Django extension by Baptiste Darthenay, HTML autocomplete stops working. If I disable the Django extension and reload VSCode, it will start to work again. What should I do to make the HTML autocomplete work along with the Django extension? -
What is acess_token and code in google auth?
I am trying to implement google authorization in django rest. I followed this instruction, but I can't figure out what code and access_token are. Where can I get them?