Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
switching from one app to another app in django
I am here C:/Users/MaitRi/Desktop/PROJECT/MyProject/HappyHomes/templates/reg.html and want to move at C:/Users/MaitRi/Desktop/PROJECT/MyProject/HappyHomesAdmin/templates/home.html Can anyone please help me with this. HappyHomes and HappyHomesAdmin are my two different app in django. I want to move from first app to second app. How to give path of moving to different app in views.py file in django. -
How to validate child serializer that requires data from parent in django rest framework nested serializer?
I am using DRF Writable Nested to create writable nested serializer. I need to validate 'ItemDetail' but it requires 'product_id' which is present in the parent serializer i.e. 'InvoiceItem'. Models class InvoiceItem(models.Model): product = models.ForeignKey( Product, on_delete=models.CASCADE, related_name="invoice_items" ) class ItemDetail(models.Model): invoice_item = models.ForeignKey( InvoiceItem, on_delete=models.CASCADE, related_name="item_details" ) size = models.ForeignKey( Size, on_delete=models.CASCADE, related_name="item_details" ) quantity = models.PositiveIntegerField() Serializers class InvoiceItemSerializer(WritableNestedModelSerializer): product = ProductMiniSerializer(read_only=True) product_id = serializers.IntegerField(write_only=True) item_details = ItemDetailSerializer(many=True) class Meta: model = InvoiceItem fields = [ "id", "product_id", "product", "item_details", ] class ItemDetailSerializer(serializers.ModelSerializer): class Meta: model = ItemDetail fields = [ "id", "size", "quantity", ] def validate(self, data): return item_detail_validate(self, data) Validator def item_detail_validate(self, data): # How to get product_id here so I can use it in a query return data -
How to get the human readable name when saving a ModelMultipleChoiceField in Local Storage in a Django Form
I have this model: class TourCreator(models.Model): preferred_location = models.ManyToManyField('tours.TourDetailPage', blank=True) For which I use a form: from django_select2.forms import Select2MultipleWidget class TourCreatorForm(ModelForm): class Meta: model = TourCreator fields = '__all__' widgets = { 'preferred_location': Select2MultipleWidget, } I am using Django Select2 to render a nice Select2MultipleWidget. When going through a form wizard I am saving the form input to Local Storage with JavaScript. The problem is, it is saving the PK's of the ManyToMany relationship, I want it to save the string name of the model. See the screenshot as example: How can I make sure that the string name of the ManyToMany relationship gets stored instead of the PK? -
Python Django signals 'int' object has no attribute 'save'
I creating badminton sport app in Django where you can create matches, etc.. What I am trying to do now is update matches_played from my models.py via signals. Here is my signals.py: class Player(models.Model): ... matches_played = models.IntegerField(default=0, blank=True, null=True) ... class Match(models.Model): player_home = models.ForeignKey(Player, null=True, on_delete= models.SET_NULL, related_name='player_home') player_away = models.ForeignKey(Player, null=True, on_delete= models.SET_NULL, related_name='player_away') player_home_sets = models.IntegerField(default=0, blank=True, null=True) player_away_sets = models.IntegerField(default=0, blank=True, null=True) Here is my signals.py: def add_match_count(sender, instance,**kwargs): home_player_sets = instance.player_home_sets away_player_sets = instance.player_away_sets if home_player_sets > 0 or away_player_sets > 0: instance.player_home.matches_played += 1 instance.player_away.matches_played += 1 instance.player_home.matches_played.save() If I edit any match I receive error: 'int' object has no attribute 'instance'. Any idea how to fix it? -
Is it possible to run celery tasks inside of the django runserver when testing?
I have a django project with several Celery tasks. Also, I have several tests (using django TestCase) and I'm mocking the celery tasks. I don't want to run celery for the tests. I have searched a lot on the internet, but no luck. So I want to ask: would there be any way not to mock these functions and have the task code executed inside the django runserver? More info (I can't update them right now): python 2.7 django 1.11 celery 4.3 Thank you so much for your help! :) -
Django Logging Config By Apps
Django application uses logger but was not configured and I used this in settings.py: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'verbose': { 'format' : "[%(asctime)s] %(levelname)s [%(name)s:%(lineno)s] %(message)s", 'datefmt' : "%d/%b/%Y %H:%M:%S" }, 'simple': { 'format': '%(levelname)s %(message)s' }, }, 'handlers': { 'file': { 'level': 'DEBUG', 'class': 'logging.FileHandler', 'filename': LOGGING_FILE_PATH, 'formatter': 'verbose' }, }, 'loggers': { 'django': { 'handlers':['file'], 'propagate': True, 'level':'DEBUG', }, 'MYAPP': { 'handlers': ['file'], 'level': 'DEBUG', }, } } Which I think realized Everything was being included. Including django.db.backends which shows all of the SQL queries being made. Which is useful but can be cumbersome to comb through when debugging. How can I configure Django to filter out these loggings into specific files to make it easier to debug. There are management commands that are executed on cronjobs, I would like designate specific log files for them. -
how to solve 500 internal server error mod_wsgi apache "importerror: No Module named 'django'
I have been trying to solve this error but I am not been able to solve, totally frustrated because I have tried every single answer on these related question , any help would be appreciated. My configuration of VPS server Ubuntu 18.04 django 2.2.5 apache 2.4.49 python 3.6(virtualenv) libapache2-mod-wsgi-py3 My folder structure is: /var/www/dataforze/prediction_project/venv (virtualenv folder) bin include lib /var/www/dataforze/prediction_project |- manage.py static prediction_project |__init__.py |settings.py |urls.py |wsgi.py 000-default.conf file code <VirtualHost *:80> <Directory /var/www/dataforze/prediction_project/prediction_project> Require all granted </Directory> <Directory /var/www/dataforze/prediction_project/prediction_project> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess prediction_project python-path=/var/www/dataforze/prediction_project python-home=/var/www/dataforze/prediction_project/venv WSGIProcessGroup prediction_project WSGIScriptAlias / /var/www/dataforze/prediction_project/prediction_project/wsgi.py ErrorLog ${APACHE_LOG_DIR}/mysite_error.log LogLevel warn </VirtualHost> my wsgi.py file code import os from django.core.wsgi import get_wsgi_application sys.path.append('/var/www/dataforze/prediction_project/prediction_project') # add the virtualenv site-packages path to the sys.path sys.path.append('/var/www/dataforze/prediction_project/venv/lib/site-packages') os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'prediction_project.settings') application = get_wsgi_application() My server logs [Wed Mar 18 17:29:01.003624 2020] [wsgi:error] [pid 82169:tid 140431942575872] mod_wsgi (pid=82169): Target WSGI script '/var/www/dataforze/prediction_project/prediction_project/wsgi.py' cannot be loaded as Python module. [Wed Mar 18 17:29:01.003722 2020] [wsgi:error] [pid 82169:tid 140431942575872] mod_wsgi (pid=82169): Exception occurred processing WSGI script '/var/www/dataforze/prediction_project/prediction_project/wsgi.py'. [Wed Mar 18 17:29:01.003823 2020] [wsgi:error] [pid 82169:tid 140431942575872] Traceback (most recent call last): [Wed Mar 18 17:29:01.003844 2020] [wsgi:error] [pid 82169:tid 140431942575872] File "/var/www/dataforze/prediction_project/prediction_project/wsgi.py", line 12, in <module> [Wed Mar … -
Django read_frame on filterset returns 'property' object has no attribute '_iterable_class'
I'm trying to create and xlsx file from a filterset queryset (HostServiceFilterSet.qs) using this view: def exportHostServices(request): qs_hostServices = HostServiceFilterSet.qs df = read_frame(qs_hostServices) # my "Excel" file, which is an in-memory output file (buffer) # for the new workbook excel_file = IO() # pylint shows a false positive error here, # so the alert is suppressed with the comment after the code xlwriter = pd.ExcelWriter(excel_file, engine='xlsxwriter') # pylint: disable=abstract-class-instantiated df.to_excel(xlwriter, 'Host Services') xlwriter.save() xlwriter.close() # rewind the buffer excel_file.seek(0) # set the mime type so that the browser knows what to do with the file response = HttpResponse(excel_file.read(),\ content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') # set the file name in the Content-Disposition header response['Content-Disposition'] = 'attachment; filename=Anagrafica-Servizi.xlsx' return response The view works correctly when used with the model's queryset HostService.objects.all() and the xlsx file is correctly generated. The filterset that i'm trying to convert to xlsx is declared as follows: import django_filters from django import forms from .models import HostService class HostServiceFilterSet(django_filters.FilterSet): hostname_input = django_filters.CharFilter(widget=forms.\ TextInput(attrs={'placeholder':'Hostname', 'type': 'search', 'class': 'form-control'}), field_name='hostname', lookup_expr='icontains', label="",) ip_input = django_filters.CharFilter(widget=forms.\ TextInput(attrs={'placeholder':'Ip Address', 'type': 'search', 'class': 'form-control'}), field_name='ip', lookup_expr='icontains', label="",) servicename_input = django_filters.CharFilter(widget=forms.\ TextInput(attrs={'placeholder':'Service Name', 'type': 'search', 'class': 'form-control'}), field_name='servicename', lookup_expr='icontains', label="",) port_input = django_filters.CharFilter(widget=forms.\ TextInput(attrs={'placeholder':'Port Number', 'type': 'search', 'class': … -
Django ImportError: cannot import name 'views'
The command python3 manage.py makemigrations projectxap keeps returning the import error. ImportError: cannot import name 'views' from 'projectxproject'. I have tried different variation of importing the views e.g from projectxapp import views , import views and from projectxapp.views import * but i keep getting the same error. Here is my folder structure and code. -
Django views.py function
I am trying to run an enternal python script upon clicking a button in a django website, however I think the path of my external script which i have specified is in the wrong formatting: from django.shortcuts import render, render_to_response from subprocess import run,PIPE import requests import sys from django.views.decorators.csrf import csrf_exempt # Create your views here. def index(request): return render_to_response('index.html') @csrf_exempt def external(request): inp=request.POST.get('param') out=run(sys.executable==['//D://Desktop//new//file1//test.py',inp], shell=False,stdout=PIPE) print(out) return render(requests, "index.html",{'data1':out}) I also have an error which says TypeError at /external/ 'bool' object is not iterable when I run it on the local server. My urls.py file: from django.contrib import admin from django.urls import path from myapp import views as v from django.contrib.staticfiles.urls import staticfiles_urlpatterns urlpatterns = [ path('admin/', admin.site.urls), path('', v.index, name="index"), path("external/", v.external), ] urlpatterns += staticfiles_urlpatterns() -
Is there a way to get the cookie value in RShiny application which we pass with redirect url
I am having web application in django framework and hosted n azure. I am having another web application in RShiny and its hosted in AWS. We are having proper authentication process for the django application . Once a user will logged in django application we want that the user should be able to access the RShiny application without again asking for authentication . For this we were passing a token value in a cookie with redirect url of Rshiny .But we were not able to fetch the cookie in the Rshiny app. Neither cookie is visible in developer tool of chrome. The django code which we have written after a user clicks on the button def buttonclick(request): response=redirect('http://example.com') expires=datetime.now()+timedelta(seconds=480) response.set_cookie('token',value='tokenmmx',expires=expires) return response "http://example.com" is the web url of Rshiny app -
Q/A package for django, what are the options?
What are the questions answers packages still updated for django ? I tried askbot or django-qa but they are not suitable for django-3 Thanks -
Missing libraries debugging Django REST Framework app
I'm trying to debug my rest-framework django app using Visual Studio Code with no success at all. I followed the higly detailed guide in here https://code.visualstudio.com/docs/python/tutorial-django but I'm getting errors with my libraries. My settings.INSTALLED_APPS is this: INSTALLED_APPS = [ ... 'rest_framework', 'corsheaders', 'django_filters', ] My first error running in debug is this: ModuleNotFoundError: No module named 'corsheaders' Just to try, I commented out this library in my settings, and my next error was ModuleNotFoundError: No module named 'django_filters' Ready to get at the end of the hole, I commented out that line too, and my new error is this: django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module. Did you install mysqlclient? I'd need some hints to include my custom libraries and/or properly configure MySQL client. Thanks in advance -
How to get QuerySet as TextChoice in Django
from django.conf import settings from django.db import models from django.utils import timezone class ShoppingList(models.Model): title = models.CharField(max_length=15) author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) created_date = models.DateField(default=timezone.now) def __str__(self): return self.title class ZutatenHinzufügen(models.Model): ingredient = models.CharField(max_length=15, name="Zutat") quantity = models.DecimalField(max_digits=5, decimal_places=2, name="Menge") author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, name="Hinzugefügt durch") created_date = models.DateTimeField(default=timezone.now, name="Hinzugefügt am") def __str__(self): return self.ingredient How can I get the QuerySet "title" of the ShoppingList class as input for list=models.TextChoice(...) I tried ShoppingList.objects.all() but there comes an Error called it ist not possible to take this as a TextChoice -
Creating django user in an automated fashion
I want to create a django user automaticaly when the application starts. I have been considering the following addition to settings.py: from django.contrib.auth.models import User u1 = User.objects.get(username='abcd') u.set_password(os.environ["password"]) u.save() Is there a better way to achieve this than adding it to settings.py ? -
Accessing self-referencing field in Django
I have class User, with field friends class User(AbstractUser): USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['password'] username = models.CharField(max_length=30, unique=True) password = models.CharField(max_length=100) friends = models.ManyToManyField('self') when I migrated class to database, it created two tables. app_user and app_user_friends app_user in itself has no reference to friends, but app_user_friends has id of a user, and id of a friend. The issue is: qhen I try to access friends of a user by calling user = models.User.objects.get(id=user_id) print(user.friends) I get app.User.None Should I be calling it differently or is there something wrong with the model? -
Get associative array from raw sql query in django
I am developing an django web application. I am using raw sql queries without using models. Below is the code what I have till now. def getCntlData(self, FID, PID): sqlst = 'select * from employee where employeeid = %s' cursor.execute(sqlst, [PID]) data_row = cursor.fetchall() return data_row The data I want is in the format of Associative array or in the form of dictionary, like what PHP gives on querying mysql. [{"employeename":"Max","employeeage":"34"}] -
Using Django in AWS lambda
I'm writing a simple http server in aws lambda and would like to use Django, however I'm not looking to deploy an entire django app on lambda through zappa. Is there any way to just import django's HttpResponse library in a lambda function like below? from django.http import HttpResponse def lambda_handler(event, context): # TODO implement msg = "hello its me" return HttpResponse(msg, content_type='text/plain') I've already created a deployment package with all the django libraries inside and uploaded to lambda, but I'm getting an error: Requested setting DEFAULT_CHARSET, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.: ImproperlyConfigured any help is appreciated, thanks in advance! -
Struggling with Class Based Form Django (save foreign key attributes)
I have imported my MySQL DB to Django. In this DB, I have an intermediate table called GroupUsers which links User and GroupName. I would like to make a form where I can fill in the user attributes and add it directly to a selected group. So basically we have an user form with an extra field corresponding to the groups that I need to select among three categories: family, friends, pro. I'm not able to make it work. #models.py class GroupUsers(models.Model): group = models.ForeignKey(GroupName, on_delete=models.CASCADE) user = models.ForeignKey('User', on_delete=models.CASCADE) class Meta: managed = False db_table = 'group_users' unique_together = (('group', 'user'),) def __str__(self): return self.group.name class User(models.Model): email = models.CharField(unique=True, max_length=180) last_name = models.CharField(max_length=32) first_name = models.CharField(max_length=32) class Meta: managed = False db_table = 'user' verbose_name = "user" def __str__(self): return self.first_name class GroupName(models.Model): group_id = models.AutoField(primary_key=True) name = models.CharField(max_length=32) description = models.TextField(blank=True, null=True) class Meta: managed = False db_table = 'group_name' verbose_name = 'Group' def __str__(self): return self.name #forms.py class UserCreateForm(forms.ModelForm): class Meta: model = User fields = ('first_name','last_name', 'email') def __init__(self, *args, **kwargs): super(UserCreateForm, self).__init__(*args, **kwargs) self.fields['group'] = forms.ModelChoiceField(queryset=GroupName.objects.all()) #view.py class UserCreateView(SuccessMessageMixin, LoginRequiredMixin, CreateView): template_name = 'dashboard/users/user_create_form.html' model = User form_class = UserCreateForm def get_object(self, queryset=None): obj … -
MultiValueDictKeyError at /main/add at 'num1'
The project tree look like this project files tress views.py from django.shortcuts import render from django.views.decorators.csrf import csrf_exempt def home(request): return render(request, 'base.html') @csrf_exempt def add(request): val1 = int(request.POST['num1']) val2 = int(request.POST['num2']) res = val1 + val2 return render(request, "main/index.html", {'add_result': res}) Index.html {% extends 'base.html' %} {% block content %} <h3>This two number adding form</h3> <form action="{% url 'add' %}" method="POST"> Enter the first here: <input type="text" name="num1" placeholder="First Number"><br> Enter the second here: <input type="text" name="num2" placeholder="Second Number"><br> <input type="submit"> </form> <hr> <div> Result : <p>{{ add_result }} </p> </div> {% endblock %} base.html <!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>ADDTWONUMBER</title> </head> <body> <H4>THIS IS FORM OF ADDING TWO NUMBER</H4> <li><a href="main/add">click here to add two number</a></li> <div> {% block content %} {% endblock %} </div> </body> </html> urls.py from django.urls import path from . import views urlpatterns = [ path('', views.home, name = 'home'), path('main/add' , views.add, name = 'add'), ] Errors MultiValueDictKeyError at /main/add 'num1' Request Method: GET Request URL: http://127.0.0.1:8000/main/add Django Version: 3.0.4 Exception Type: MultiValueDictKeyError Exception Value: 'num1' Exception Location: /home/hudacse6/Env/lib/python3.7/site-packages/django/utils/datastructures.py in getitem, line 78 Python Executable: /home/hudacse6/Env/bin/python Python Version: 3.7.4 Python Path: … -
How to change Django app name from a plugin?
I've installed a plugin called Django Constance and I want to change the app name in the admin page. I normally use ugettext_lazy from Django but I couldn't here as the verbose app name in the library doesn't have it. how can I change the app name? is there a way to override only this app name from the admin template without overriding the whole content block? thanks. -
Django - Models category error in Admin: “Select a valid choice. That choice is not one of the available choices”
So I am trying to build a recipe field in django-admin. I have a Model category called Meals and I have categories to chose from on the admin page but as soon as I try to save my entry, I get the Select a valid choice. Breakfast is not one of the available choices & prevents me from saving anything. I've tried moving the daily_meals value from Recipe Field into Meal Category and uncommenting the first meal and commenting the second value in Recipe Field. I would like to be able to create new meals in the meals category just like the food category while already having pre-saved meals in the list. Meal categories admin error after save Here is my code: Models.py from django.db import models from django.contrib.auth.models import User from django.utils import timezone # Food Category class Category(models.Model): name = models.CharField(max_length=250) slug = models.SlugField(max_length=250, unique=True) class Meta: ordering = ('name',) verbose_name = 'category' verbose_name_plural = 'categories' def __str__(self): return self.name # Meal Category class Meal(models.Model): name = models.CharField(max_length=250) slug = models.SlugField(max_length=250, unique=True) class Meta: ordering = ('name',) verbose_name = 'meal' verbose_name_plural = 'meals' def __str__(self): return self.name # Recipe Field class Recipe(models.Model): title = models.CharField(max_length=200) category = models.ForeignKey(Category, … -
In Django, how do I render fields of fields from a queryset in JSON when sending a response from an AJAX view?
I'm using Django 2 with Python 3.7. In my view, I have this code for sending JSOn to an AJAX call ... articlestat_query = ArticleStat.objects.get_stats() ... data = { 'articlestat': serializers.serialize('json', list(articlestat_query)), ... } return JsonResponse(data) The query "articlestat_query" pulls models that look like this ... class ArticleStat(models.Model): objects = ArticleStatManager() article = models.ForeignKey(Article, on_delete=models.CASCADE, related_name='articlestats') elapsed_time_in_seconds = models.IntegerField(default=0, null=False) score = models.FloatField(default=0, null=False) The issue is when my JSON is generated, the "article" piece gets returned as "article" and its numeric primary key, e.g. "article": 12345678 How do I configure my serialization so that the JSON of that field is rendered instead of its primary key. IOW, the JSON would be "article": {"title": "hello world", "author": "George Costanza" ... -
How to modify and get session's variables with Django
I'm working on a form which is rendered in all web site's pages, I need that the server (Django) stops rendering this form on the web pages if the user closes or completes it. I've been reading about request.session but it does not clear the data when, for example, I restart the browser or clean the cache. Any idea about how to do this? Thank you in advance! -
Object of type Decimal is not JSON serializable Django 2
I am trying to reload previous cart if a user logs in, but its giving me, Object of type Decimal is not JSON serialisable and I am totally unable to track the trace of the error. I tried different ways to manipulate the cart dictionary but it seems i'm getting stuck at one single point after all. class Cart(object): def __init__(self, request): self.request = request self.session = request.session cart = self.session.get(settings.CART_SESSION_ID) if not cart: # save an empty cart in the session cart = self.session[settings.CART_SESSION_ID] = {} self.cart = cart if request.user.id: order, created = Order.objects.get_or_create(user=request.user, status='CART') if not created: for p in order.particulars.all(): self.add(p.product, quantity=p.qty, update_quantity=True) else: print('user not found') def add(self, product, quantity=1, update_quantity=False): """ Add a product to the cart or update its quantity. """ quantity = int(quantity) product_id = str(product.id) if product_id not in self.cart: self.cart[product_id] = {'quantity': 0, 'price': str(product.price)} if update_quantity: self.cart[product_id]['quantity'] = quantity else: self.cart[product_id]['quantity'] += quantity self.save() def save(self): # update the session cart self.session[settings.CART_SESSION_ID] = self.cart # mark the session as "modified" to make sure it is saved self.session.modified = True print(self.request.user) if str(self.request.user) != 'AnonymousUser': # load the data from user order = Order.objects.get(user=self.request.user, status='CART') for k in self.cart.keys(): p …