Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Reverse for 'hobbieswithCSS.html' not found. 'hobbieswithCSS.html' is not a valid view function or pattern name
I am trying to attach hobbieswithCSS.html file to my website, while using Django. I am a beginner when it comes to Django, so I have naturally came across some problems (in the title) like this. I have this anchor tag on my homepage - <a href="{% url 'basic_app:hobbieswithCSS.html' %}">My Hobbies</a> I have this view in my views.py file - def hobbieswithCSS(request): return render(request,'basic_app/hobbieswithCSS.html') I think, that the main problem will be with the urlpatterns in urls.py file, because I am not sure how to set it up. These are my urlpatterns - urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^admin/', admin.site.urls), url(r'^basic_app/',include('basic_app.urls')), url(r'^logout/$',views.user_logout,name='logout'), url(r'^$', views.hobbieswithCSS, name='hobbieswithCSS'), ] Could anybody please tell me, how could I change the code in order to make that hobbieswithCSS.html file display, when I am trying to run it on my server? Thank You very much for any help. -
Django Subtract a field from another field in another table and save the result
class prodect(models.Model): name = models.CharField(max_length=50) cwan = models.DecimalField(max_digits=5, decimal_places=2) class orders(models.Model): names = models.CharField(max_length=50) prodects = models.ForeignKey(prodect,on_delete=models.CASCADE) count = models.DecimalField(max_digits=7, decimal_places=2) I have two models the first have a int field and The second is a int and I Want After the user enters a value in the second field, it is subtracted from the first, and the result of the first changes to its old result minus the value that the user entered in the second -
Django group by Choice Field and COUNT Zeros
consider the following django model: class Image(models.Model): image_filename = models.CharField(max_length=50) class Rating(models.Model): DIMENSIONS = [ ('happy', 'happiness'), ('competence', 'competence'), ('warm_sincere', 'warm/sincere'), ] rating_value = models.IntegerField(), rating_dimension = models.CharField(max_length=50, choices=DIMENSIONS), image = models.ForeignKey(Image, on_delete=models.CASCADE) Now, I'd like to group all Ratings by the number of ratings per category like this Rating.objects.values("rating_dimension").annotate(num_ratings=Count("rating_value")) which returns a QuerySets like this: [{'rating_dimension': 'happy', 'num_ratings': 2}, {'rating_dimension': 'competence', 'num_ratings': 5}] Is there a way to include all not-rated dimensions? To achieve an output like [{'rating_dimension': 'happy', 'num_ratings': 2}, {'rating_dimension': 'competence', 'num_ratings': 5}, {'rating_dimension': 'warm_sincere', 'num_ratings': 0}] # ← zero occurrences should be included Thanks in advance! -
Can not make SerializerMethodField() work
So I have this view, I passed the request through the context to the serializer so I can use it to get the user def create(self, request, *args, **kwargs): """ Handle member creation from invitation code. """ serializer = AddMemberSerializer( data=request.data, context={'circle': self.circle, 'request': request} ) serializer.is_valid(raise_exception=True) member = serializer.save() data = self.get_serializer(member).data return Response(data, status=status.HTTP_201_CREATED) In the serializer I did this but it does not work,I get "KeyError: 'user'", I ran a debugger and when I tried to call the get_user method it says "TypeError: get_user() missing 1 required positional argument: 'obj'" user = serializers.SerializerMethodField() def get_user(self, obj): request = self.context.get('request', None) if request: return request.user So what am I missing? I looked up other implementations of this field and none of them seem very different of mine, so I would really apreciate it if someone explains to me why it is not working. Also if there is a more efective way to get the user into a field (Need it to run a user_validate method on it) -
Django rest framework saving seralizer with foregin key
Quick question I am trying to save model and have following setup models.py class Example1(models.Model): field1 = models.CharField(max_length=90, null=True, blank=True) class Example2(models.Model): field2 = models.CharField(max_length=90, null=True, blank=True) example1 = models.ForeignKey(Example1, on_delete=models.CASCADE, related_name='example1_example2') serializers.py class Example1Serializer(serializers.ModelSerializer): def create(self, validated_data): return Example1.objects.create(**validated_data) class Meta: model = Example1 fields = ['id', 'field1'] class Example2Serializer(serializers.ModelSerializer): def create(self, validated_data): return Example2.objects.create(**validated_data) class Meta: model = Example2 fields = ['id', 'example1', 'field2'] upon initiating following code new_example1 = Example1Serializer(data=JSONEXAMPLE1DATA) if new_example1.is_valid(): new_example1.save() **works well** JSONEXAMPLE2DATA = { 'field2' = 'test', 'example1' = new_example1.data['id'] } new_example2 = Example2Serializer(data=JSONEXAMPLE2DATA) if new_example2.is_valid(): new_example2.save() **doesnt work gives must be a "Example1" instance** upon changing JSONEXAMPLE2DATA to JSONEXAMPLE2DATA = { 'field2' = 'test', 'example1' = new_example1 } gives Incorrect type. Expected pk value, received Example1Serializer. is setup wrong? -
Python/Django - How to set default value in custom form?
I've got form in Django: class NewsletterForm(forms.Form): first_name=forms.CharField(max_length=50,required=True,label='Twoje imię:') email=forms.EmailField(required=True,label='Twój email:') Now there is logic part: def subscribe2newsletter(request): if request.method == 'POST': form = NewsletterForm(request.POST) if form.is_valid(): cd = form.cleaned_data else: form = NewsletterForm() categories = get_categories_with_subcategories() return render(request, 'subscribe2newsletter.html', { 'form': form, 'sent': sent, 'categories': categories } ) And view part: <form method="post"> {# {{ form.as_p }}#} {% csrf_token %} <div> {{ form.first_name.errors }} <label for="{{ form.first_name.id_for_label }}">Twoje imię:</label> {{ form.first_name }} </div> <br><br> <div> {{ form.email.errors }} <label for="{{ form.email.id_for_label }}">Adres email:</label> {{ form.email }} </div> <input type="submit" value="Zatwierdź"/> </form> My problem is - how to set default value for form from logic part? I've tested construction like: form = NewsletterForm() form.first_name='some value' but it doesn't work. Input field on view is still empty. How to fill it inside subscribe2newsletter function? -
Django How to make table with attributes?
I created a system with Django. This system has a limiting system. I have several ranks and several risks. According to the these ranks and risks there are some credit values. For example: example table Users can add/update these limits (10$, 9$ ... ) For better user experience I want to create a detailed table like this: my table How can I fill cells with the format that I want? models.py class DoaTable(models.Model): LIMITS =( ('Low Risk', 'Low Risk'), ('Medium Risk', 'Medium Risk'), ('Moderately High Risk','Moderately High Risk'), ('High Risk', 'High Risk'), ('Very High Risk', 'Very High Risk'), ('Strict Credit Check', 'Strict Credit Check'), ('No Credit Check', 'No Credit Check'), ) RANKS = ( ('Analyst', 'Analyst'), ('Senior Analyst', 'Senior Analyst'), ('Lead', 'Lead'), ('Manager', 'Manager'), ('Senior Manager', 'Senior Manager'), ('Director', 'Director'), ('Regional Director', 'Regional Director'), ('Chief Financial Officer', 'Chief Financial Officer'), ) rank = models.CharField(max_length=200, choices=RANKS) risk = models.CharField(max_length=200, choices=LIMITS) limit = models.FloatField() comp_name = models.ForeignKey(CompanyProfile, on_delete=models.CASCADE, null=True) def __str__(self): return self.rank table.html <table class="table table-bordered"> <thead> <tr> <th> </th> <th>Low Risk</th> <th>Medium Risk</th> <th>Moderately High Risk</th> <th>High Risk</th> <th>Very High Risk</th> <th>Strict Credit Check(CIA/LC)</th> <th>No Credit Check</th> </tr> </thead> <tbody> <tr> <th scope="row">Analyst</th> </tr> <tr> <th scope="row">Senior Analyst</th> </tr> <tr> … -
How to use multiple databases for unit test cases in django pytest
I have been working on a django application which uses multiples databases through database router like the following. I want to write unit test cases for the apis developed using Django Rest Framework. class MultiDbRouter(object): """ Router for handling multiple database connections based on the db configs in the request object """ def _multi_db(self): if hasattr(request_cfg, 'db'): if request_cfg.db in settings.DATABASES: return request_cfg.db else: raise Http404 else: return 'default' def db_for_read(self, model, **hints): """ Set database for reading based on request config """ if model._meta.app_label == 'survey': return 'survey' if model._meta.app_label != 'analytics': return 'default' return self._multi_db() def db_for_write(self, model, **hints): """ Set database for writing based on request config """ if model._meta.app_label == 'survey': return 'survey' if model._meta.app_label != 'analytics': return 'default' return self._multi_db() def allow_relation(self, obj1, obj2, **hints): """ allow relation between objects """ return True def allow_syncdb(self, db, model): """ allow syncing of database """ return True I have started using pytest for writing the testcases, but as I read the docs of pytest-django library, it says that "Currently pytest-django does not specifically support Django’s multi-database support." Is there any way to workaround this limitation? Or should I use some other library other than pytest-django to write … -
How to get list of only one object in django
I have a model class OrderEntries(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) quantity = models.IntegerField() I need to get list of Product that is saved in this model OrderEntries.objects.all() This queryset gives me all the OrderEntries but how can I get list of all the product objects that is saved inside OrderEntries -
'QuerySet' object has no attribute 'Count1'....?
Why is this error coming i could not understand What is wrong thats my view.py from django.shortcuts import render from .models import poll # Create your views here. def index(request): polls = poll.objects.get() context ={ 'polls':polls, } if request.method == 'POST': # print(request.POST) selected_option = request.POST.get('polls') # print(selected_option) if selected_option == 'choice1': print(selected_option) polls.Count1 = polls.Count1 + 1 elif selected_option == 'choice2': print(selected_option) polls.Count2 += 1 elif selected_option == 'choice3': print(selected_option) polls.Count3 += 1 return render(request,'index.html',context) model.py from django.db import models # Create your models here. class poll(models.Model): question = models.CharField(max_length=100) choice1 = models.CharField(max_length=100) choice2 = models.CharField(max_length=100) choice3 = models.CharField(max_length=100) count1 = models.IntegerField(default=0) count2 = models.IntegerField(default=0) count3 = models.IntegerField(default=0) def __str__(self): return self.question As we can see count1 is in my models then why does'nt it shows even when i put it in my html file it also shows there. What to do next -
Django - How to send form to database then show cleaned_data on new url that contains a field from the form
I have a form where users fill in some info, one of these fields is a "job_number". Currently when I go to the url 127.0.0.1:8000/home i have my blank form. When I submit the information gets sent to the database and I get a new .html page showing the cleaned_data but on the same 127.0.0.1:8000/home. Below is my views.py from django.shortcuts import render, redirect from django.contrib.auth.decorators import login_required from django.urls import reverse from .forms import QuoteInformationForm from .models import QuoteInformation @login_required def quote_view(request): data_form = QuoteInformationForm() if request.method == "POST": data_form = QuoteInformationForm(request.POST) if data_form.is_valid(): data_form.save(commit=True) return render(request, "quote.html", {'data_form': data_form.cleaned_data}) else: print('Error') return render(request, "index.html", {'data_form': data_form}) What I want to do when the form is submitted is to continue sending this information to the db, but instead of showing 127.0.0.1:8000/home i want it to show as 127.0.0.1:8000/quote/job_number - so the job number from the form is in the url. My idea is to then have a page for submitted jobs with a link that takes you to this url. urls.py urlpatterns = [ path('home/', quote_view, name='home'), ] models.py from django.conf import settings from django.db import models # Create your models here. class QuoteInformation(models.Model): job_number = models.CharField(max_length=10) data_files = … -
Django AttributeError at /accounts/profile/ 'User' object has no attribute 'get' while update profile
Hello i get the following error when i tried to add form to update description of the user profile My models : class Profile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) birth_date = models.DateField(null=True, blank=True) profile_img = models.ForeignKey(Image,on_delete=models.CASCADE,related_name='images',null=True) description = models.TextField() My form : class ChangeUserDescription(ModelForm): class Meta: model = Profile fields = ['description','profile_img'] widgets = { 'description': forms.Textarea(), 'profile_img':forms.ImageField() } labels = { 'description':'Description', 'profile_img':'Image' } My view : @login_required def profile(request): if request.method == 'POST': form = ChangeUserDescription(request.user, request.POST) if form.is_valid(): form.save() else: messages.error(request, 'Please correct the error below.') else: form = ChangeUserDescription(request.user) return render(request, 'registration/profile.html', {'form': form}) And my template : <div class="mainPage"> <h1>Profile</h1> <h2>Bonjour {{user.get_username}}</h2> <form method="post"> {% csrf_token %} {{ form }} <button type="submit">Save changes</button> </form> <a href="{% url 'adoptYourOcApp:password_change'%}" >Change password</a> {% include "annonces/my_list.html" %} </div> Direclty when i go on the corresponding page i get the following error : AttributeError at /accounts/profile/ 'User' object has no attribute 'get' Request Method: GET Request URL: http://localhost:8000/accounts/profile/ Django Version: 2.2.17 Exception Type: AttributeError Exception Value: 'User' object has no attribute 'get' -
read json JsonResponse django
I'm trying to read data Json Data sent from Django views in html. The query depends on the on the url. I query data depending in the ikey. I dont't know how to read the data especially in the data-url="{% url 'show_pp'| add:selection pk=ikey %}. If i have a static data-url it works, but i don't know how to create a dynamic url depending on the ikey. Thank you very much for your help. I'm really stuck here. Here is the code: Django urls: urlpatterns = [ path('show_pp/<str:ikey>/', views.show_pp, name = 'show_pp'), path('plant', views.plant, name = 'plant'), ] Django views: def show_pp(request, ikey, *args, **kwargs): "code..." queryset = CriMvProductionPlan.objects.filter(plant=str(ikey)) "code..." data = { 'ikey': ikey, 'month': date_list, 'generation': generation_list, 'quantity': quantity_list, } return JsonResponse(data) HTML: <div id="container" style="width: 75%;"> <canvas id="data_pp" data-url="{% url 'show_pp'| add:selection pk=ikey %}"></canvas> </div> -
error on heroku "Push rejected, failed to compile Python app."
I have a problem i cant deploy my Django app i tried every solutions I found on stackoverflow with this topic but it doesn't work, i still have this message during building on heroku. ! Push rejected, failed to compile Python app. Push failed -
Postgres DB creation using Django rest
I am trying to create New Database based on user input using Django Rest Framework. I wrote a function to save and create the DB. DB name has saved to Model but DB not Created. I am new for this DRF method. Request your suggestion please. class WorkSpaceSerializerListCrtApi(ListCreateAPIView): queryset = WorkSpace.objects.all() serializer_class = WorkSpaceSerializer def get_queryset(self, *args, **kwargs): queryset_list = WorkSpace.objects.all() query = self.request.POST.get("WorkSpaceName") if query: dbname = query con = psycopg2.connect(user='postgres', host='127.0.0.1', password='sugan@123') con.set_isolation_level(ISOLATION_LEVEL_AUTOCOMMIT) cur = con.cursor() cur.execute('CREATE DATABASE '+ dbname) cur.close() con.close() return dbname -
How to structure django template to use Material web component
How can I set up Django templet with the official google Material.io component? I added style component link in a web page but it's not working . The tutorial link is most welcome -
Node.js: Calling external python scripts, should i migrate to python web server?
I have a node.js application that requires calling external programs. Should i migrate to a python-based web server like Django or Flask? The idea is that the python code will be embedded inside the server, so the server will not make external calls to scripts. Does this make sense? Perhaps from the sense that in my current situation a lot of different processes are spawn. What do you think about this situation? -
Django ORM search product but group by category
I am trying to implement search system wich will diplay all the result by category. This is my models. class Category(models.Model): name = models.CharField(max_length=255) slug = models.SlugField( verbose_name="slug", allow_unicode=True, max_length=255, help_text='A slug to identify posts by this category', ) class Product(models.Model): name = models.CharField( max_length=255, verbose_name=_('Product Name'), ) categories = ManyToManyField("product.ProductCategory", related_name="product_category") I need to render all the item group by categtory in frontend/template but query will be based on product name. prod_cat = Category.objects.annotate( filtered_product=Product.objects.filter(name__incontains="My Search Term goes There") ) and it is not working at all. Also i can query by like this way: result = [] prod_cat = Category.objects.all() for cat in prod_cat: p = cat.product_category.filter(name__incontains='My Another Search Term') result.append(p) But i think it is not group by, it's list product based on each list, in that way i cant name the category name on template as category heading. is there anyone knows about it how i can query and group by each category? -
Django: Is there a way to use static with default_if_none?
In my Django template I'm using static to pull images from the static/ folder based on each item's (byte) id property. An example of a path to an image would be: static/images/promo-abc.png I'm building the path to the image using with: {% for byte in bytes %} {% with 'images/'|add:'promo-'|add:byte.id|add:'.png' as image_static %} <img class="promo-image" src="{% static image_static %}"/> {% endwith %} However if there is no image based on the item's id I'd like the 'default' image to be used: static/images/promo-dummy.png. For that I'm trying to use default_if_none but so far this isn't working (getting error: Could not parse some characters:...) {% with 'images/'|add:'promo-'|add:byte.id|add:'.png' as image_static %} <img class="promo-image" src="{{% static image_static |default_if_none:'images/promo-dummy.png' %}}"/> {% endwith %} -
Django UserCreationForm not showing errors
I have a very simple sign up template in django. This form is just not working, wether it's valid or not. the html code: <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <form method="POST" action=""> {% csrf_token %} {{ form }} <input type="submit"> </form> {{ form.errors }} </body> </html> the view: def test(request): if request.method == 'POST': form = UserCreationForm(request.POST) if form.is_valid(): redirect('index') form = UserCreationForm() return render(request, 'test.html', {'form': form}) I expect to get redirected back to the index page if the form is valid, and get the form errors if it's not valid. I end up not getting anything in return - only the chrome prompt that suggests saving my details. -
Why does Django give this error: Invalid block tag on line 3: 'else'
I have the following Django template: {% if request.is_ajax %} {% extends "ajax.html" %} {% else %} {% extends "base.html" %} {% endif %} When I render it I get the following error: Invalid block tag on line 3: 'else'. Did you forget to register or load this tag? Why am I getting this error? -
Last Update field in Django... 'auto_now' or 'hidden' widget
I would like to set a field in a Django model which should be updated everytime a record of the corresponding table is updated by a ModelForm (any field of the table). I am wondering which of the following options is the best practices one: Add the "auto_now" argument to the model field. Include the 'type': 'hidden' attribute to the corresponding widget in the form where the records will be submitted. If this... how should be included the 'value' attribute for the widget? I know the auto_now argument updates the field only when Model.save() is called. So the question could be rebuilt as... Is the Model.save() called when a ModelForm (linked to the model) is submitted? Thank you very much. -
IndexError: index -2 is out of bounds for axis 0 with size 1
Created a chatbot in Django using nltk and sklearn while sending the message I am experiencing this error C:\Users\xxx\django\project\env\lib\site-packages\sklearn\feature_extraction\text.py:388: UserWarning: Your stop_words may be inconsistent with your preprocessing. Tokenizing the stop words generated tokens ['ha', 'le', 'u', 'wa'] not in stop_words. warnings.warn('Your stop_words may be inconsistent with ' Internal Server Error: /addmsg Traceback (most recent call last): File "C:\Users\xxx\django\project\env\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\xxx\django\project\env\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\xxx\django\project\env\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\xxx\django\project\home\views.py", line 19, in addmsg bot_msg(c) File "C:\Users\xxx\django\project\home\views.py", line 23, in bot_msg c = give_response(msg) File "C:\Users\xxx\django\project\home\nlp.py", line 69, in give_response return find_response(input_given) File "C:\Users\xxx\django\project\home\nlp.py", line 42, in find_response idx = values.argsort()[0][-2] IndexError: index -2 is out of bounds for axis 0 with size 1 This is the Code that sends the response to the message I am not aware of why the file somefile.txt used and how to store data in it from sklearn.metrics.pairwise import cosine_similarity import nltk import numpy import random import string from sklearn.feature_extraction.text import TfidfVectorizer def find_response(response): chatbots_file = open(r'somefile.txt','r',errors = 'ignore') info_data = chatbots_file.read() info_data = info_data.lower() nltk.download('punkt') nltk.download('wordnet') sentence_tokens = nltk.sent_tokenize(info_data) word_tokens = nltk.word_tokenize(info_data) bot_response = … -
Multiple model files and auth_user_model
Learning Django and doing custom user thing.When i create a model folder and keep the user model there i get the error django.core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL refers to model 'core.user' that has not been installed App name is core and is installed. In AUTH_USER_MODEL = core.user In models folder init.py from .user import * Folder Structure: --core --model --init.py user.py Works well when models.py is not deleted.When i get these to folder, i get the above error. Help appreciated. -
Django : after include tag getting critical Error
after i'm using include tag in django template, i'm getting error. error: RecursionError at /home/ maximum recursion depth exceeded Error during template rendering my base.html file . <html> {% load static %} <some static css here> {% include "inc/header.html" %} {% block header %} HEADER {% endblock header %} <some static js here> </html> my header file is {% extends 'base.html' %} <p> test header</p>