Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django admin login won't grant me access even though information is correct
I have created a custom user model in django called 'Agent'. The command-line allows me to successfully create a superuser but the admin page won't allow me access even though all the credentials are correct. My app is included under INSTALLED_APPS and my AUTH_USER_MODEL = Audit.Agent I have registerred my model under admin.py but still, nothing. I am probably forgetting something small, but still can't find it. A guide in any direction would be of extreme value. Thank you in advance class AgentManager(BaseUserManager): def create_user(self, agent_email, agent_name, validation_date, company_name, password=None, **extra_fields): if not agent_email: raise ValueError("Given email must be set") email = self.normalize_email(agent_email) agent = self.model(agent_email=agent_email, agent_name=agent_name, company_name=company_name, validation_date=validation_date, **extra_fields) agent.save(using=self._db) return agent def create_superuser(self, agent_email, agent_name, validation_date, company_name, password, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) if extra_fields.get('is_staff') is not True: raise ValueError('Superuser must have is_staff=True.') if extra_fields.get('is_superuser') is not True: raise ValueError('Superuser must have is_superuser=True.') return self.create_user(agent_email, agent_name, validation_date, company_name, password=password, **extra_fields) class Agent(AbstractBaseUser, PermissionsMixin): agent_email = models.EmailField(unique=True, verbose_name='Agent email') agent_name = models.CharField(max_length=100, verbose_name='Agent name') validation_date = models.DateField(default=timezone.now, verbose_name='Validation date') company_name = models.CharField(max_length=150, verbose_name='Company name') is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) USERNAME_FIELD = 'agent_email' REQUIRED_FIELDS = ('agent_name', 'validation_date', 'company_name') -
Register signals or receivers in django
I did not like the idea of putting my receivers in my models.py file and I started to investigate where should my code live? as for my receivers. Then I realized that it is best practice for the receivers to be located in a file called signals.py, but this leads to the need to register the receivers, so that they work correctly, I started researching the subject and I gave realize that there are 2 ways to do it. Importing or establishing the connection of the receivers in the file models.py. Importing the receivers or establishing the connection in the apps.py file, precisely in theready ()method. This was specified in the documentation of Django but in a way not very clear or specific from my point of view. I started to investigate more about the subject and in different cases, I saw that many problems arose, either using the first method or the second one, and therefore, a question arose. Why have to register the receivers ?, specifically Why the need to have to import them? What is the best method or the best option to use ?. And what exactly is the ready () method? Thanks in advance for … -
The viewset didn't return an HttpResponse object. It returned None instead
I am returning TemplateResponse from viewset like this: return TemplateResponse(request, 'payments/cybersource_stampduty.html', template_data) but I am getting error: The view payments.views.CyberSourceResponseViewSet didn't return an HttpResponse object. It returned None instead. Why am I getting this error? incase if someone want to see entire function, here is how it looks like def create(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) self.perform_create(serializer) headers = self.get_success_headers(serializer.data) transaction = CyberSourceTransaction.objects.filter( uuid=request.data['req_transaction_uuid']).first() # if its a stampduty if transaction.selected_plan_name == 'stampduty': template_data = { 'consumer': transaction.transfer_to, 'decision': request.data['decision'], 'transaction_uuid': request.data['req_transaction_uuid'], 'reference_number': transaction.reference_number, 'amount': transaction.amount, 'currency': transaction.currency, 'wukla_url': settings.WUKLA_URL, 'paksign_url': settings.PAKSIGN_URL, 'subscription_url': settings.DOMAIN } logger.info("Handling Cybersource transaction response with transaction_uuid: " + request.data['req_transaction_uuid'], extra={'user': ''}) return TemplateResponse \ (request, 'payments/cybersource_stampduty.html', template_data) -
Cant create a record within viewset custom view based on url parameters
Hello I have a django rest framework view set. For the create view I want to create a custom view that will create a new record based on two different parameters that are passed on through the url which are namespace and path. I looked at the documentation but i couldnt find how it should look like. I am noit sure what I need to do in order to create a record based on both url parameters. I basically tried setting the create to a CreateAPIView but it did not work class PreferenceViewSet(viewsets.ViewSet): queryset = Preference.objects.all() serializer_class = PreferenceSerializer def get_permissions(self): if self.action == 'create' or self.action == 'destroy': permission_classes = [IsAuthenticated] else: permission_classes = [IsAdminUser] return [permission() for permission in permission_classes] def list(self, request): queryset = Preference.objects.all() serializer = PreferenceSerializer(queryset, many=True) return Response(serializer.data) def create(self, request): queryset = Preference.objects.all() serializer = PreferenceSerializer(queryset, many=True) return Response(serializer.data) I want to setup the create to create a preference with the two parameters that are passe in the url path('preferences/<str:namespace>/<str:path>', preference_path, name='preference-path'), I wanted it to create a new object with the namespace and path -
Data Migration produces ValueError that must be "User" instance but it is?
I'm trying to add a staff member to the database. I'm doing this via a data migration. I am able to add a User through the migration but I'm not able to assign it to user_id of the StaffPosition I am trying to create. The error I get is a ValueError that says I need to use a "User" instance but I thought I was doing that. I've used ipdb to troubleshoot this and look at what the values of some properties are. I've also tried grabbing user different ways, such as with the pk or id of the User instance. Another thing I did was comment out all lines of code in create_urechr_user except for the section that creates the User object. With that, I was able to successfully add the User to the database. But I'm unable to make my StaffPosition's user_id that User. # -*- coding: utf-8 -*- # Generated by Django 1.11.6 on 2019-02-08 21:23 from __future__ import unicode_literals from django.db import migrations from django.contrib.auth.models import User def create_urechr_user(apps, schema_editor): staffPosition = apps.get_model("hr", "staffPosition") User.objects.create_user( username = "urechr", password = "TechOps", is_active = True, email = "", ) staff = staffPosition.objects.get(pk = 95) user = User.objects.get(username … -
How to solve - Provisional headers are shown?
How to solve - Provisional headers are shown? I have a Django application using rest_framework, simple JWT and corsheaders. GET request works perfectly, however POST I get a 200 code, but with restrictions. Provisional headers are shown Authentication works perfectly, however I am having problem in request. INSTALLED_APPS = [ ... 'rest_framework', 'corsheaders', ... ] CORS_ORIGIN_ALLOW_ALL = True REST_FRAMEWORK = { 'DEFAULT_RENDERER_CLASSES': ( 'rest_framework.renderers.JSONRenderer', ), 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_simplejwt.authentication.JWTAuthentication', ), } SIMPLE_JWT = { 'ACCESS_TOKEN_LIFETIME': timedelta(days=1), 'REFRESH_TOKEN_LIFETIME': timedelta(days=1), 'ROTATE_REFRESH_TOKENS': False, 'BLACKLIST_AFTER_ROTATION': True, 'ALGORITHM': 'HS256', 'SIGNING_KEY': SECRET_KEY, 'VERIFYING_KEY': None, 'AUTH_HEADER_TYPES': ('Bearer',), 'USER_ID_FIELD': 'id', 'USER_ID_CLAIM': 'lbuser_id', 'AUTH_TOKEN_CLASSES': ('rest_framework_simplejwt.tokens.AccessToken',), 'TOKEN_TYPE_CLAIM': 'token_type', 'SLIDING_TOKEN_REFRESH_EXP_CLAIM': 'refresh_exp', 'SLIDING_TOKEN_LIFETIME': timedelta(days=1), 'SLIDING_TOKEN_REFRESH_LIFETIME': timedelta(days=1), } -
Why is my Class-based delete view not working?
My delete view is not working and the error message is: Page not found (404) Request Method: GET. I am trying to delete my uploaded file based on its primary key and so far, my url is able to link me correctly based on the pk. This is my urls.py: path('post/<int:post_id>/lesson_delete/<int:lesson_id>', LessonDeleteView.as_view(), name='lesson_delete'), My views.py: class LessonDeleteView(DeleteView): model = Lesson success_url = '../' template_name = 'lesson_confirm_delete.html' This is the html template that brings user to the delete view: {% extends "store/base.html" %} {% block content %} <div id="main"> <table class="table mb-0"> <thead> <tr> <th>Title</th> <th>Author</th> <th>Download</th> <th>Delete</th> </tr> </thead> <tbody> {% for l in Lesson %} <tr> <td> {% if l.file %} {{ l.title }} {% else %} <h6>Not available</h6> {% endif %} </td> <td>{{ l.post.author }}</td> <td>{% if l.file %} <a href="{{ l.file.url }}" class="btn btn-primary btn-sm" target="_blank">Download</a> {% else %} <h6>Not available</h6> {% endif %} </td> <td> <a class="btn btn-danger btn-sm mt-1 mb-1" href="{% url 'lesson_delete' lesson_id=l.id %}">Delete</a> </td> </tr> {% endfor %} </tbody> </table> </div> {% endblock %} This is my html template for DeleteView: {% extends "store/base.html" %} {% block content %} <div class="content-section" id="main"> <form method="POST"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">Delete Lesson</legend> … -
mysql query function works in python shell but ImproperlyConfigured error when run in python
I am practicing using mysql in django and wanted to run a simply query on a database that I set up in my settings.py. I am connected to the database and can run the query fine in the manage.py shell. However, when I run the same code in a python file it does not work. Does anybody know why the query does not work in the python file? query : from django.db import connections def query(id): c = connections['default'].cursor() c.execute("SELECT * FROM `peptides_proteins_000005 WHERE protein_id=%s;",[id]) rows = c.fetchone() return rows print(query(4519)) In the shell I will get a row back with the information I want however, when run in the python file I get this error: django.core.exceptions.ImproperlyConfigured: Requested setting DATABASES, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. -
render template after form submit ajax django
i have a form which getting user input and i'm passing to python script on view.py and then rendering to html template. i want all this done without refreshing the page. view.py: def index(request): if request.method == 'POST': form = PnrForm(request.POST) if form.is_valid(): pnr_numbers = form.cleaned_data['pnr_number'] api_key = "df566" base_url = "https://api.railwayapi.com/v2/pnr-status/pnr/" complete_url = base_url + pnr_numbers + "/apikey/" + api_key + "/" response_ob = requests.get(complete_url) output = response_ob.json() if output["response_code"] == 200: train_name = output["train"]["name"] passengers_list = output["passengers"] aka = "this is the" for passenger in passengers_list: # store the value or data # of "no" key in variable passenger_num = passenger["no"] # store the value or data of # "current_status" key in variable current_status = passenger["current_status"] # store the value or data of # "booking_status" key in variable booking_status = passenger["booking_status"] # print following values print(" passenger number : " + str(passenger_num) + "\n current status : " + str(current_status) + "\n booking_status : " + str(booking_status)) aka = str(passenger_num) else: print("record is not found for given request") return render(request, 'main_site/index.html', {'form': form,'output': aka}) else: form = PnrForm() #print(pnr_numbers) return render(request, 'main_site/index.html', {'form': form}) index.html: <form method="POST" id="pnr_form"> {% csrf_token %} {{ form }} <input type="submit" value="Submit"> </form> … -
Django ORM concat for related rows
Two simple models: class Thread(models.Model): pass class Message(models.Model): thread = models.ForeignKey(Thread, related_name='messages') Is it possible to do something like this? >>> thread = Thread.objects.create() >>> Message.objects.create(thread=thread, content='One') >>> Message.objects.create(thread=thread, content='Two') >>> Message.objects.create(thread=thread, content='Three') >>> t = Thread.objects.annotate( message_content=MySuperConcat('messages__content')).first() >>> t.messages_content OneTwoThree Seems like Django's Concat can't do this and now I'm not sure if desired behavior is possible at all. Note: we are using PostgreSQL 9.5 and Django 1.11. -
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 …