Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
mkvirtualenv is not recognized as an internal or external command
while i was trying to execute 'mkvirtualenv' command on command prompt i'am getting this error C:\Users\mukesh>mkvirtualenv myproject 'mkvirtualenv' is not recognized as an internal or external command, operable program or batch file. -
How to make redirect?
How to redirect from http://127.0.0.1:8000/accounts/signin/ to http://127.0.0.1:8000/profile/ with HttpResponseRedirect -
Django admin 2.2.2 TabularInline/StackedInline form additional fields
Im working with Django version 2.2.2 Im using django admin site. I have a class called Author and other called Book. An Author can have many Books. I configured book as TabularInline in django admin. Its fine so far. Now I want to add some extra dynamic fields on the BookInline form. Classes: from django.db import models # Create your models here. class Author(models.Model): name = models.CharField(max_length=100, unique=True) def __str__(self): return self.name class Book(models.Model): author = models.ForeignKey(Author, on_delete=models.PROTECT) name = models.CharField(max_length=100, unique=True) def __str__(self): return self.name Admin configuration: from django import forms from django.contrib import admin from books.models import Book, Author # Register your models here. class BookForm(forms.ModelForm): class Meta(): fields = '__all__' model = Book class BookInline(admin.TabularInline): model = Book extra = 1 form = BookForm @admin.register(Author) class AuthorAdmin(admin.ModelAdmin): inlines = [ BookInline, ] How add some extra fields on form used by TabularInline or StackedInline? -
Cannot authenticate custom user
I'm relatively new to Django. I have a web application (in the works) that uses a custom user model called User, which is then inherited by 3 subclasses: Contractor, Supervisor, and Client, which gives us 3 user types. I can create all three types of users just fine, and I can view/edit/delete them using the admin site just fine. However. When I try to login as a Client and a Supervisor using their respective credentials, I get an incorrect email/password error. Strangely enough, this error does not occur when I login with a Contractor email/password. I can't really figure out what the issue is, therefore I can't really troubleshoot. Would be great if somebody could point out the mistake(s) I must be making. models.py: from django.db import models from django.contrib.auth.models import AbstractUser, AbstractBaseUser from django_countries.fields import CountryField from django.contrib.auth.base_user import BaseUserManager from myproject import settings # Create your models here. class UserAccountManager(BaseUserManager): def create_user(self, email, password=None): if not email: raise ValueError('Email must be set!') user = self.model(email=self.normalize_email(email), ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, password): user = self.create_user(email, password) user.is_admin = True user.is_staff = True user.is_superuser = True user.save(using = self._db) return user class User(AbstractBaseUser): email = models.EmailField(max_length=150, unique=True) … -
Django: sum annotation on relation with a limit clause
I have a situation similar to the following one: class Player(models.Model): pass class Item(models.Model): player = models.ForeignKey(Player, on_delete=models.CASCADE, related_name='item_set') power = models.IntegerField() I would like to annotate Player.objects.all() with Sum(item_set__power), taking into account only the top N Item when sorted by descending power. Ideally, I would like to do this with a subquery, but I don't know how to write it. How can this be done? -
What is the best way to convert a file in amazon s3 with Django/python?
I am making a website to get to know aws and Django better. The idea is to let a user upload an excel file, convert it to csv and then let the user download the converted csv file. I am using amazon s3 for file storage. My question is, what is the best way to make the conversion? Is there any way to access the excel file once it is stored in the s3 bucket and convert it to csv via Django? Sorry if my question is silly but I haven’t been able to find much information on that online. Thanks in advance -
Django Rest Framework search_fields viewset from genericforeignkey field model
All models (Customer, Provider, Contact, Employee) have the same name field to search, in the main or generic model (Comments) have generic foreign key. I need search the field in the main model. It's that posible? Models: class Customer(TimeStampedModel): name = models.CharField() class Provider(TimeStampedModel): name = models.CharField() class Contact(TimeStampedModel): name = models.CharField() class Employee(TimeStampedModel): name = models.CharField() class Comment(TimeStampedModel): content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() commentator = GenericForeignKey('content_type', 'object_id') Viewset class CommentsViewSet(BaseViewSet): queryset = Comments.objects.all() serializer_class = CommentsSerializer search_fields = ["object__name",] django.core.exceptions.FieldError: Field 'commentator' does not generate an automatic reverse relation and therefore cannot be used for reverse querying. If it is a GenericForeignKey, consider adding a GenericRelation. -
How to get access token from Composer rest server into Django API calls?
I am using Django server to call GET/POST request to composer-rest-server. Composer-rest-server: localhost:4000 Django: localhost:8000 In order to make a request in multiple user mode (composer-rest-server), access token is required to be passed in requests API (python). Does the Oauth stores the access-token in browser cookies? Well How may I actually get the access token for API calls? -
Trouble Connecting MySQL to Django
I am having trouble connecting MySQL to my Django application. When I run "pip3 list", I see I have the latest version of mysqlclient installed (1.4.2.post1). However, when I try to run my Django application with "python3 manage.py runserver", I get the following error message: django.core.exceptions.ImproperlyConfigured: mysqlclient 1.3.13 or newer is required; you have 0.9.3. I am using Ubuntu for context. Can someone please provide some help? -
Get value/state of checkbox for each row in a Django when POST
I want to display a table with : on rows: the date for each weekday (calculate in my views.py) on columns: the Mealselection of an user. I can get value from models and display it : https://i.imgur.com/TyvI0DH.png But when i look source code on the page i see https://i.imgur.com/wY0QC62l.png So obviously it does not work when i try to save the user choice. I try with a formset but i can't pass initial value to the template "selection_template.html" (i try with the exmple below but don't work because i need to display the user selection regarding the date. formset = ArticleFormSet(initial=[{'title': "Form %d" % (i+1), 'pub_date': datetime.date.today()} for i in range(10)]) I know how to display multi form using formset but don't know how to pass value to the template. models.py class MealSelection(models.Model): user = models.ForeignKey('User', on_delete=models.CASCADE) date = models.DateField(auto_now_add=True) salad = models.BooleanField(default=False) meal = models.BooleanField(default=False) sandwich = models.BooleanField(default=False) forms.py class GetUserMeal(forms.ModelForm): class Meta: model = MealSelection fields = ['meal', 'salad', 'sandwich'] widget = forms.CheckboxInput( attrs={ 'name': 'choices' } ) views.py for day in weekDay: try: userSelection = MealSelection.objects.get(user=u1,date=startWeek + datetime.timedelta(days=daysCount)) userSelection = {'meal':userSelection.meal, 'salad':userSelection.salad, 'sandwich':userSelection.sandwich} except: userSelection = {'meal':False, 'salad':False, 'sandwich':False} userSelection = forms.GetUserMeal(userSelection) dateDayCorresp[day] = {'date':startWeek + datetime.timedelta(days=daysCount),'userSelection': … -
In my blog app i want to display image in post details.But the tricky part is i want to display image corresponding to users first name alphabet?
In my blog app i want to display image in post details.But the tricky part is i want to display image corresponding to users first name alphabet.For example if the users name is Sam i want to display letter 'S' image.I know that i could write if elif else for 26 alphabets but it could increase the program size.Is there any other way to do this? <!--code for displaying image from database---> <img src={{post.author.profile.image.url}} class='logo3'/> -
Changes made from the wagtail admin does not reflect on the front-end
Changes made from the wagtail admin does not implement at the front end. I have confirmed that changes made to the wagtail admin reflect on at the django admin layer. Still after multiple reloads, the changes made do not reflect on the front end. models.py: class AboutUs(models.Model): """ This holds the info being displayed at the '/authors' page. This model just stores info about the blog, it's visions and what it hopes to achieve through the internet """ id = models.PositiveIntegerField(blank=True, unique=True, primary_key=True ) title = models.CharField("Title of About Us Text", max_length=100, null=True, blank=True, help_text="Default can be named 'Default', Christmas season can be named 'Christmas'" ) about_us = RichTextField("About us", null=True, blank=True, features=['bold', 'italic', 'hr', 'link', 'document-link', 'embed'], ) date_created = models.DateField() our_story = RichTextField("Our Story", null=True, blank=True, features=['bold', 'italic', 'hr', 'link', 'document-link', 'embed'], ) our_vision = RichTextField("Our Vision", null=True, blank=True, features=['bold', 'italic', 'hr', 'link', 'document-link', 'embed'] ) our_quote = RichTextField("Our Quote", null=True, blank=True, features=['bold', 'italic', 'hr', 'link', 'document-link', 'embed'] ) author_of_quote = models.CharField("Quote Author", null=True, blank=True, max_length=100 ) panels = [ FieldPanel('title'), FieldPanel('about_us'), FieldPanel('date_created'), FieldPanel('our_story'), FieldPanel('our_vision'), FieldPanel('our_quote'), FieldPanel('author_of_quote'), ] template = 'templates/about.html' def __str__(self): return self.title about.html: {% include "nav_and_navbars/nav_and_navbars.html" %} <div class="page-header"> <div class="container"> <div class="row"> <div class="col-md-offset-1 … -
The model is used as an intermediate model, but it does not have a foreign key
I need to make a multi-select selection to the City model from the (location application). I have chosen for this MTM connection from Bank (banks) to City (location), but I get an error. banks.Bank_city: (fields.E336) The model is used as an intermediate model by 'banks.Bank.city', but it does not have a foreign key to 'Bank' or 'City'. class Bank(models.Model): city = models.ManyToManyField('location.City') -
ModuleNotFoundError: No module named 'encodings' in Django on NGINX / uWSGI
Django 2.2 running on Ubuntu 16.04 / NGINX / uWSGI / Python 3.6 I keep getting: ModuleNotFoundError: No module named 'encodings' in the uWSGI error logs when trying to reload uWSGI. Also, uWSGI will restart without an error message, but it won't reload. Even when it restarts, however, the problem app is not started. uWSGI configuration file: [uwsgi] chdir = /var/sites/mysite module = mysite.wsgi virtualenv = /opt/virtualenvs/mysite_venv processes = 5 vacuum = True -
No schema supplied error when creating user but it gets created anyway
I'm following this tutorial to implement an API using Django RestFramework. I've implemented the OAuth2 API and now I'm getting this error when creating a user. I'm not sure if it's related to the OAuth2 API, I think it does because the error says: Exception Type: MissingSchema at /authentication/register/ Exception Value: Invalid URL '127.0.0.1/o/token/': No schema supplied. Perhaps you meant http://127.0.0.1/o/token/? And the URL /authentication/register/ was implemented when implementing the OAuth API. When using the following command to create a user I get an error, but even with this error, the user is created in data base. $ curl -d "username=halfsping&password=1234abcd" "http://127.0.0.1:8000/authentication/register/" part of the error: Exception Type: MissingSchema at /authentication/register/ Exception Value: Invalid URL '127.0.0.1/o/token/': No schema supplied. Perhaps you meant http://127.0.0.1/o/token/? It does not matter if I use this instead: $ curl -d "username=halfsping&password=1234abcd" "http://127.0.0.1:8000/authentication/register/" proyect's urls.py: from django.contrib import admin from django.urls import path, include from rest_framework import routers from core.views import * from unicorns.views import UnicornViewSet router = routers.DefaultRouter() router.register(r'customers', CustomerViewSet) router.register(r'professions', ProfessionViewSet) router.register(r'data-sheet', DataSheetViewSet) router.register(r'document', DocumentViewSet) router.register(r'unicorn', UnicornViewSet) urlpatterns = [ path('admin/', admin.site.urls), # Authentication path('o/', include('oauth2_provider.urls', namespace='oauth2_provider')), path('authentication/', include('users.urls')), # API path('api/', include(router.urls)), path('api-auth/', include('rest_framework.urls')), ] Complete error: Internal Server Error: /authentication/register/ Traceback (most … -
Django responds with file contents but does not prompt for download
I am working on a Django app where the user clicks a button, calling a python script to do work, and then downloads a .zip file created by said work. I have checked that the file is created successfully, and in javascript I used an alert to print the response from the server. The file's contents are returned, but there is no file download appearing in browser/anywhere on my computer. Here is the code I am using for downloading : if os.path.exists(zip_file_location_server): with open(zip_file_location_server, 'rb') as zip_file: response = HttpResponse(FileWrapper(zip_file), content_type='application/zip') response['Content-Disposition'] = 'attachment; filename="foo.zip"' return response I have tried: Removing the FileWrapper (leaving just the file object as the first argument to HttpResponse) Changing the filename argument to zip_file_location_server Changing the content_type argument to application/force-download All to no avail. What am I missing to download the returned .zip file? -
Rendering a FormSet in Django
I want to create a FormSet which allows users to add forms as needed. However, when I render the page, I am receiving a ValueError: The view website.views.presales didn't return an HttpResponse object. It returned None instead. I would like to always render the form blank. Please let me know if any other information is needed, thanks! Note: cwObj.get_opportunities() is an API call to create an object from a JSON response to populate the select_opportunity dropdown. Lastly, I am using AJAX to dynamically calculate the value of the span Total using data-total-url="{% url 'presales_total' %}". forms.py class PresalesForm(forms.Form): class Meta: model = Presales fields = ('selected_opportunity', 'task_description', 'hours', 'selected_engineer_level', 'total_cost') views.py def presales(request): my_opportunities = cwObj.get_opportunities() PresalesFormSet = formset_factory(PresalesForm, extra=1) if request.method == 'POST': presales_formset = PresalesFormSet(request.POST) if presales_formset.is_valid(): for presales_form in presales_formset: selected_opportunity = request.POST.get('selected_opportunity') task_description = request.POST.get('task_description') hours = request.POST.get('hours') select_engineer_level = request.POST.get('select_engineer_level') else: presales_formset = PresalesFormSet(initial="None") context = {'presales_formset': presales_formset, 'my_opportunities': my_opportunities} return render(request, 'website/presales.html', context) presales.html <form action="{% url 'presales' %}" method="post" name="presalesForm" id="presalesForm" data-total-url="{% url 'presales_total' %}"> {% csrf_token %} {{ presales_formset.management_form }} {% for presales_form in presales_formset %} <div class="field"> <label class="label is-large">Create Task</label> </div> <div class="section"> <div class="field"> <label class="label">Opportunity</label> <div class="select"> <select … -
Django Custom User Login
I created a cumstom user by inhering 'AbstractBaseUser' class AppUser(AbstractBaseUser, PermissionsMixin): """ Custom User """ username = None email = models.EmailField(_('email address'), unique=True) name = models.CharField(max_length=100) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) date_joined = models.DateTimeField(default=timezone.now) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['name'] objects = UserManager() def __str__(self): return self.email I am able to register new user but facing problem to login using: path('api-auth/', include('rest_framework.urls')) I can login in admin portal but not able to login by api - shared the screen -
Why should a self-modifying method not return its self?
I recently found in this accepted answer, "It's generally considered good practice in Python to have functions that primarily affect existing objects not return themselves. " Why? (Both in general, and with particular reference to an ORM .save() method, which can only fail by raising an exception, not by returning some failure code). -
Right settings for uwsgi.ini file with Django and pipenv
Usually, I don't use pipen and working with virtualenv, virtualenvwrapper and requirements.txt with my django projects. In this case my uwsgi.ini file looks like: [uwsgi] project = cv-base uid = cvc base = /home/%(uid) chdir = %(base)/%(project) home = %(base)**/Env**/%(project) <----!!!!!!! module = %(project).wsgi:application master = true processes = 5 socket = /run/uwsgi/%(project).sock chown-socket = %(uid):www-data chmod-socket = 660 vacuum = true Where values home have links to my virtualenv thrue folder Env. But now I cant have this folder, and cant unrestand what to substitute here. At log file I got an error !!! Python Home is not a directory: /home/cvc/Env/cv-base !!! Jun 26 13:48:55 CV-base uwsgi[12482]: Set PythonHome to /home/cvc/Env/cv-base -
Parse a dictionary in django template
I have a dictionary A A: {<truck_name: Tempo 407 1500>: [<ItemBatch: Iphone>, <ItemBatch: Iphone>, <ItemBatch: Iphone>], <truck_name: Tempo 407 1500>: [<ItemBatch: Iphone>, <ItemBatch: Iphone>, <ItemBat ch: Iphone>], <truck_name: Tempo 407 2000>: [<ItemBatch: Iphone>, <ItemBatch: Iphone>, <ItemBatch: Iphone>, <ItemBatch: Iphone>]} Can I parse this dictionary in django template? views.py def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) dispatch_plans = DispatchPlan.objects.filter(owner_id=self.request.user.pk) idict = {} print("dispatch_plans", dispatch_plans) for i in dispatch_plans: t = i.truck_name idict[t] = [get_object_or_404(ItemBatch, id=v_id) for v_id in i.items] context['items'] = idict return context html {% for x,v in items.items %} <tr> <td>{{ v }}</td> </tr> {% endfor %} I have tried the above but it doesn't show anything on the HTML page, What do i need to change to parse it ? -
Django foreignkey mismatch error not allowing classes to have relation in database
I am trying to add a foreign key to the posts class so that each person can have multiple posts, I keep getting a foreign key mismatch error. The tables are empty. I don't understand what the problem here is. """ Definition of models. """ from django.db import models # Create your models here. class Users(models.Model): name = models.CharField(primary_key=True, max_length=30) class Posts(models.Model): priority = models.CharField(max_length=30) client = models.CharField(max_length=30) title = models.CharField(max_length=150) assigned_to = models.ForeignKey(Users, on_delete=models.CASCADE) exp_comp_time = models.FloatField(max_length=4) percent_comp = models.FloatField(max_length=4) post_date = models.CharField(max_length=20) due_date = models.CharField(max_length=20) latest_mod = models.CharField(max_length=20, null=True) When I go to migrate I get this error: django.db.utils.operationalError: foreign key mismatch - "app_posts" referencing "app_users" -
Date subtraction from two date column Django ORM for filter
I have two keys/columns in MongoDB. I am using Django ORM to get data from mongo using a connector called djongo. I need a apply a filter. I have to take a difference from the column date and check if the difference is less than 24 hours. This is my query - time_threshold = datetime.datetime.now() - timedelta(days=1) total_count = ArticleFeed.objects.annotate( diff=ExpressionWrapper(F('crawled') - F('published'), output_field=DurationField()) ).filter(diff__lte=time_threshold, crawled__lte=report_start_ISO, crawled__gte=last_ISO, data_source="TOI").exclude( reject='repeat').count() But I am getting the following exception - File "/home/embed/inmobi/content_curation_project/ccp_env/lib/python3.7/site-packages/django/db/backends/base/operations.py", line 621, in subtract_temporals raise NotSupportedError("This backend does not support %s subtraction." % internal_type) django.db.utils.NotSupportedError: This backend does not support DateTimeField subtraction. Please help. Thanks -
django + gunicorn + virtualenv + supervisor + nginx. click home issue
my website (blog) use django + gunicorn + virtualenv + supervisor + nginx. when my website didn't add nginx ,everything works fine. after i add nginx in my website, i click my blog 'home',url show 'mydjangoblogserver' and result is not found, but other functions work fine except 'click home'. i think nginx and gunicorn set is problem, just guess. here is my settings. ngnix conf --------------------------------------------------------------------- user root; worker_processes 1; events { worker_connections 1024; } http { include mime.types; default_type application/octet-stream; sendfile on; keepalive_timeout 65; upstream mydjangoblogserver { server unix:/home/blog/dev/DjangoBlog/run/gunicorn.sock fail_timeout=0; } server{ server_name www.xxx.club; root /home/blog/dev/DjangoBlog; listen 80; keepalive_timeout 70; location /collectedstatic/ { expires max; alias /home/blog/dev/DjangoBlog/; } location / { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; if (!-f $request_filename) { #proxy_pass http://xxx.club; proxy_pass http://mydjangoblogserver; break; } } } django_start file ------------------------------------------------------------ #!/bin/bash NAME="djangoblog" # Name of the application DJANGODIR=/home/blog/dev/DjangoBlog # Django project directory SOCKFILE=/home/blog/dev/DjangoBlog/run/gunicorn.sock # we will communicte using this unix socket USER=root # the user to run as GROUP=root # the group to run as NUM_WORKERS=3 # how many worker processes should Gunicorn spawn DJANGO_SETTINGS_MODULE=DjangoBlog.settings # which settings file should Django use DJANGO_WSGI_MODULE=DjangoBlog.wsgi # WSGI module name echo "Starting $NAME as `whoami`" # Activate the virtual environment cd $DJANGODIR source … -
Migrate existing database fields.E340 error on run
Hey everyone I'm fairly new to Python Anywhere, I'm running a django app on python 3.7, I've manually added the tables and fields I need via SSH in MySQL Workbench and ran [migrate.py inpectdb > /app/models.py] then makemigrations then when I run Migrate I get this: ERRORS: auth.Group.permissions: (fields.E340) The field's intermediary table 'auth_group_permissions' clashes with the table name of 'app.AuthGroupPermissions'. auth.User.groups: (fields.E340) The field's intermediary table 'auth_user_groups' clashes with the table name of 'app.AuthUserGroups'. auth.User.user_permissions: (fields.E340) The field's intermediary table 'auth_user_user_permissions' clashes with the table name of 'app.AuthUserUserPermissions'. If I remove the auth tables from the models.py and try to migrate I get: File "/usr/lib/python3.7/site-packages/MySQLdb/connections.py", line 276, in query _mysql.connection.query(self, query) django.db.utils.OperationalError: (1071, 'Specified key was too long; max key length is 767 bytes') From what I've read it is conflicting with the settings.py [INSTALLED_APPS] but I'm not sure where to go from here to get the migration to work properly.