Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How exactly to use `current_app` and `urlconf` arguments of the `reverse()` function in Django
I had to use the reverse() function in my project and saw usage of the reverse() in other projects, but i have never used current_app and urlconf arguments. As i read in docs: The current_app argument allows you to provide a hint to the resolver indicating the application to which the currently executing view belongs. This current_app argument is used as a hint to resolve application namespaces into URLs on specific application instances, according to the namespaced URL resolution strategy. The urlconf argument is the URLconf module containing the URL patterns to use for reversing. By default, the root URLconf for the current thread is used. And i never saw examples of their usage. Could you give me some tips or maybe a little usage example, please, to understand how should i use them properly? -
How to use update_or_create when updating values in Django database from CSV files
Problem summary: I don't understand the syntax for objects.update_or_create in Django. CSV files have the field names in first row: # data.csv field1, field2, 12, 14, 35, 56, I have a model for my postgresql database in models.py: from django.db import models # example model, real one has 100 fields of different types class MyModel(models.Model): field1 = models.IntegerField(blank=True, null=True) field2 = models.IntegerField(blank=True, null=True) Now I want to create/update the database when new data comes in in form of CSV files: import csv with open('./datafiles/data.csv') as csvfile: reader = csv.DictReader(csvfile) for row in reader: update, created = MyModel.objects.update_or_create( defaults={???}, ??? ) update.save() What goes into the question mark marked places? -
Unable to run Django code on localhost, using pythonanywhere's bash console
I installed Django and started a project. The moment I made the project, I ran python manage.py runserver on pythonanywhere's bash console. It gave the output Starting development server at http://127.0.0.1:8000/ However when I opened the URL, it showed me "This site can't be reached" (venv) 18:31 ~/django_sample $ python manage.py runserver Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). You have 17 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions. Run 'python manage.py migrate' to apply them. March 18, 2020 - 18:35:54 Django version 3.0.4, using settings 'django_sample.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. Error: That port is already in use. (venv) 18:35 ~/django_sample $ -
Where and how put my business logic in django
A friend recommended that I read the book two scoops Django and I was amazed at the recommendations he makes for a robust and well-designed Django project. This reading created a doubt in me and it is where I put the business logic, I give an example. Suppose I have two models: models.py class Sparks(models.Model): flavor = models.CharField(max_length=100) quantity = models.IntegerField(default=0) class Frozen(models.Model): flavor = models.CharField(max_length=100) has_cone = models.BooleanField() quantity_sparks = models.IntegerField(default=0) Let's suppose that every time I add a frozen, if it has sparks, I have to subtract it from the Sparks model and check that there is an available quantity. In the book they recommend putting this logic in models.py or forms.py. Where and how should I put this? -
How to initialize Django forms where fieldtype is variable
I have a json object like this: { "Enzyme": { "order": 1, "required": "no", "help": "enzyme", "dataType": "CharField" }, "Date": { "order": 2, "required": "yes", "help": "date", "dataType": "DateField" } } And now I want to initialize a form something like this: class MyForm(forms.Form): def __init__(self, *args, **kwargs): super(MyForm, self).__init__(*args, **kwargs) for key,values in jsonObj.items(): self.fields[key] = forms.values["dataType"] I am not sure how can I do this, as taking this datatype from my json input. What should I write after forms. to initialize forms? Right now it's throwing an error module 'django.forms' has no attribute 'values' -
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: …