Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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> -
Django (DRF) ManyToMany field choices / limit
Working with Django REST Framework I am wondering if it's possible to limit the choices / options of a ManyToMany field on a model to a specific QuerySet? Using the models below (scroll down to see models), I am curious if it's possible to define this limit in the definition of the model, to achieve the following: # Having the following Employee instance emp = Employee(...) # Should return only the instances with value 'case' in EmployeeSubstitute.type field emp.substitute_case.all() # Should return only the instances with value 'phone' in EmployeeSubstitute.type field emp.substitute_phone.all() Models: class Employee(models.Model): substitute_case = models.ManyToMany(through=EmployeeSubstitute, ...) substitute_phone = models.ManyToMany(through=EmployeeSubstitute, ...) class EmployeeSubstitute(models.Model): from = models.ForeignKey(Employee, ...) to = models.ForeignKey(Employee, ...) type = models.CharField(choices=..., ...) # choose between type 'case' and 'phone' I see that there's the limit_choices_to parameter, but that's not what I am looking for, since that only effects the options shown when using a ModelForm or the admin. -
Django Background Task run once
I want to run a background once using the Django Background Tasks package I tried the solution given here How to run Django background task only once but it seems like I am missing something I have the following code, what I am I doing wrong? Task.py from background_task import background @background(schedule=5) def get__data(): print(" === get data ===") @background(schedule=5) def update__data(): print(" === update data ===") Urls.py from tracker.tasks import * urlpatterns = [ path('admin/', admin.site.urls), path('', include("tracker.api.urls")) ] if not Task.objects.filter(verbose_name="get_data").exists(): get__data(repeat=10) update__data(repeat=10, repeat_until=None) -
Python socketio not running in 'gevent_uwsgi' mode
i am trying to start a socketio server with async mode 'gevent_uwsgi' - sio = socketio.Server(async_mode='gevent_uwsgi'), but i have an error raise ValueError('Invalid async_mode specified') ValueError: Invalid async_mode specified. What i need to import/download to make this work? -
Django 3 primary key issues
i have an issue with my django model, basically with its primary keys. I use the admin interface to manage my data. I have set up a database that consists of 3 primary keys to reduce multiple entries(year,month,bnr). But i dont get this covered in my model, as django only accept one primary key. I have tried out a few things but none where helpful for me. The Admin Interface gives me an error all the time. Removing all primary keys in my model Tried to add an ID Column in my model/Database but not declared as primary key in my DB added unique_together Right now my model looks like this: class BalBalance(models.Model): month = models.PositiveIntegerField(default=datetime.datetime.now().month, validators=[MinValueValidator(1), MaxValueValidator(12)]) year = models.PositiveIntegerField(default=datetime.datetime.now().year, validators=[MinValueValidator(1990), MaxValueValidator(datetime.datetime.now().year)]) bnr = models.ForeignKey('BalBankaccount', models.DO_NOTHING, db_column='BNR') # Field name made lowercase. balance = models.DecimalField(db_column='BALANCE', max_digits=10, decimal_places=2) # Field name made lowercase. available_balance = models.DecimalField(db_column='AVAILABLE_BALANCE', max_digits=10, decimal_places=2) # Field name made lowercase. unavailable_balance = models.DecimalField(db_column='UNAVAILABLE_BALANCE', max_digits=10, decimal_places=2) # Field name made lowercase. date_checked = models.DateTimeField(db_column='DATE_CHECKED') # Field name made lowercase. created_at = models.DateTimeField(db_column='CREATED_AT') # Field name made lowercase. class Meta: managed = False db_table = 'BAL_BALANCE' unique_together = (('month', 'year', 'bnr'),) and my admin.py looks like this from django.contrib … -
QuerSet object has no attribute
i am trying to create a "Kriskras" that has a list of activities behind it. so i used a foreign key to link them. but every time i am trying to add something to the list i get the error enter image description here this is my model enter image description here how can i solve it so i can use the vergadering_set attribute? -
Django Serializer takes too much time to query
I have an API which is currently returning just returning 465 KB data but taking too long to process: Here's an image of postman: There are just 300 objects in the query and the views and serializers are like the following: Views.py class MaterialRequestListEmployeeAPIView(generics.ListAPIView): serializer_class = EMaterialRequestListSerializer permission_classes = (permissions.IsAuthenticated,) queryset = MaterialRequest.objects.all().order_by('-id') def get_queryset(self): queryset = super(MaterialRequestListEmployeeAPIView, self).get_queryset() return queryset Serializer.py class EMaterialRequestFlowsListSerializer(serializers.ModelSerializer): class Meta: model = MaterialRequestFlow fields = "__all__" depth = 1 class EMaterialRequestListSerializer(serializers.ModelSerializer): flows = EMaterialRequestFlowsListSerializer(many=True) class Meta: model = MaterialRequest fields = "__all__" depth = 1 Models.py class MaterialRequestFlow(models.Model): flow = models.ForeignKey(Flow, on_delete=models.CASCADE) kit = models.ForeignKey(Kit, on_delete=models.CASCADE) quantity = models.IntegerField(default=0) class MaterialRequest(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE, related_name='owner') flows = models.ManyToManyField(MaterialRequestFlow) is_allocated = models.BooleanField(default=False) delivery_required_on = models.DateTimeField(default=datetime.now) raised_by = models.CharField(max_length=1000, default="__________", blank=True, null=True) How can I increase the performance of the API? I tried increasing the instance configuration on AWS but it had no effect on the retrieval time -
AttributeError at when I add entries in admin for Season , This Error comes 'Season' object has no attribute 'tv_show_publish'
Theres alot of same type of questions but Im blank now how to create this model without this error. I want to create a tree like model, Imagine a Netflix like Tv show has multiple seasons and their multiple episodes. For each episode I want to store some links to play that episode. Model Pattern Should be Like this ; OneTv_Show > Multiple Season > Each Season with multiple Episodes Lets take a look #models.py class Tv_Show_PublishedManager(models.Manager): def get_queryset(self): return super(Tv_Show_PublishedManager, self).get_queryset().filter(status='published') class Season_PublishedManager(models.Manager): def get_queryset(self): return super(Season_PublishedManager, self).get_queryset().filter(status='published') class Episode_PublishedManager(models.Manager): def get_queryset(self): return super(Episode_PublishedManager, self).get_queryset().filter(status='published') class Tv_Show(models.Model): STATUS_CHOICES = ( ('draft', 'Draft'), ('published', 'Published'), ) tv_show_name = models.CharField(max_length=250) tv_show_slug = models.SlugField(max_length=250, unique_for_date='tv_show_publish') tv_show_author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='tv_shows') tv_show_cover = models.ImageField(upload_to='upload/', null=True) tv_show_body = models.TextField() tv_show_imdb_rating = models.DecimalField(null=True, max_digits=12, decimal_places=1) tv_show_publish = models.DateTimeField(default=timezone.now) tv_show_created = models.DateTimeField(auto_now_add=True) tv_show_updated = models.DateTimeField(auto_now=True) tv_show_views = models.IntegerField(default=0) tv_show_status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='draft') class Meta: ordering = ('-tv_show_publish',) def __str__(self): return self.tv_show_name objects = models.Manager() published = Tv_Show_PublishedManager() tags = TaggableManager() class Season(models.Model): STATUS_CHOICES = ( ('draft', 'Draft'), ('published', 'Published'), ) number = models.ForeignKey(Tv_Show, on_delete=models.CASCADE, related_name='season') season_slug = models.SlugField(max_length=250, unique_for_date='tv_show_publish') season_publish = models.DateTimeField(default=timezone.now) season_status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='draft') season_views = models.IntegerField(default=0) class Meta: ordering = ('-season_publish',) …