Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django URLs and include() - how do you differentiate between 2 urls with the same "name" in 2 separate apps?
I have 2 apps in my project, "landing" and "news". Right now, I have the URLs configured like this: project/urls.py: urlpatterns = [ path('admin/', admin.site.urls), path('', include('landing.urls')), path('news/', include('news.urls')), ] project/landing/urls.py: urlpatterns = [ path('', landing_view, name='landing'), ] project/news/urls.py: urlpatterns = [ path('', news_view, name='news'), ] navbar link hrefs: href="{% url 'landing' %}" href="{% url 'news' %}" I believe this setup is pretty standard and it all works fine so far. What I don't like is that this setup depends on each app having unique names for each url path. I'd like to be able to specify the app when referencing a URL name. That way I wouldn't have to worry about accidentally re-using the same name for a url in different apps. The documentation mentions using app_name/namespace parameters, but they don't give any examples for how to reference a url in the url tag. I've tried something like this: project/urls.py: urlpatterns = [ path('admin/', admin.site.urls), path('', include('landing.urls', namespace='landing', app_name='landing')), path('news/', include('news.urls', namespace='landing', app_name='landing')), ] project/landing/urls.py: urlpatterns = [ path('', landing_view, name='index'), ] project/news/urls.py: urlpatterns = [ path('', news_view, name='index'), ] navbar link hrefs: href="{% url 'landing:index' %}" href="{% url 'news:index' %}" But I get this error: path('', include('landing.urls', namespace='landing', … -
My template isn't loading, but base.html is?
I'm trying to render a class based view through my template, chart.html, however I'm only able to get {% extends 'base.html' %} able to load when I test my app on localhost. Below is my view and template files for my chart.html and base.html. Note that im not getting any syntax errors in my console. Would greatly appreciate some expertise here. I don't think its a URL issue because when I land on the URL, i get the base.html template loaded, just not its main template aka chart.html. views.py from django.contrib.auth import get_user_model from rest_framework.views import APIView from rest_framework.response import Response from django.shortcuts import render from django.views.generic import View User = get_user_model() # Create your views here. class IndexView(View): def get(self, request, *args, **kwargs): return render(request, 'chart.html', {}) class ChartData(APIView): authentication_classes = [] permission_classes = [] def get(self, request, format=None): data = { "sales": 100, "customers": 10, "users": User.objects.all().count(), } return Response(data) chart.html {% extends 'base.html' %} <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> <script src='https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.min.css'></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script> <script> {% block jquery %} var endpoint = '/api/chartdata/' $.ajax({ method: "GET", url: endpoint, success: function(data){ console.log(data) console.log(data.customers) }, error: function(error_data){ console.log("error") console.log(error_data) } }) {% endblock %} </script> {% block content %} <h1>Hello World</h1> … -
Can I calculate the geometric mean with django annotation?
Is there a way to use it like Foo.objects.annotate(geometric_mean=GeometricMean('bars__value')) or Foo.objects.annotate(geometric_mean=Power(Prod('bars_value'), Count('bars'))? -
I am having trouble changing the url.py within Django
Hello I am needing assistance. I am currently doing within url.py for Django: urlpatterns = [ path('cookies/', admin.site.urls), ] This is being done from urls.py in atom and when I look at the terminal it is not able to GET the new url. When I have 127.0.0.1/cookies/ I am still directed to a not found page. Anyone please help I am currently using Ubuntu Linux. -
Django filter match url irrespective or protocol
I have below Django filter. It has one field as url. class MediaFilter(filters.FilterSet): """Filters for the MediaViewset endpoint /media """ type = django_filters.CharFilter() category = django_filters.ModelMultipleChoiceFilter( queryset=Category.objects.all(), field_name="category__name", to_field_name="name", conjoined=False, ) person_id = NumberInFilter( field_name="persons__id", lookup_expr="in", distinct=True, ) url = django_filters.CharFilter(field_name="url", lookup_expr="exact") nsfw = django_filters.BooleanFilter() class Meta: model = Media fields = ["type", "category", "person_id", "url", "nsfw"] My doubt is how do I filter for url without considering "http://www" part. For example all below combination should be considered as same. And url should always be matched by removing "^.*//www." part from it. https://www.youtube.com/watch?v=dFspPk5AUTU youtube.com/watch?v=dFspPk5AUTU http://youtube.com/watch?v=dFspPk5AUTU Please advice how do I control it? -
Rendering a custom tag with a foreign key into templates issues
Hi this is the model I am working with from django.db import models from users.models import CustomUser class Project(models.Model): id = models.AutoField(primary_key=True) user = models.ForeignKey(CustomUser, on_delete=models.PROTECT, editable=False) name = models.CharField(max_length=20, editable=False) total = models.DecimalField(max_digits=6, decimal_places=2, editable=False) created = models.DateTimeField(auto_now_add=True, editable=False, null=False, blank=False) def __str__(self): return self.name The class is populated by an HTML form using this view: def homepage(request): if request.method == "POST": project = Project() name = request.POST.get('name') total = request.POST.get('total') created = datetime.datetime.now() user = request.user project.user = user project.name = name project.total = total project.created = created project.save() #return HttpResponse(reverse("homepage.views.homepage")) return render(request, 'homepage.html') else: return render(request, 'homepage.html') and so I have added a custom tag into my app which is a function @register.filter def monthlyTotal(user): this_month = now().month return Project.objects.filter( created__month=this_month, user=user ).aggregate( sum_total=Sum('total') )['sum_total'] I call the tag like this in template <p>Total monthly sales = {{ user.username|monthlyTotal }}</p> however I get an error saying Field ID expected a number but got 'grandmaster' which is the name of my test user who has multiple Project objects.. if I switch to user.id I get no error but it displays None which makes sense because when I look at my project section in admin the field user is … -
Django cannot add background image from css
I've followed the django official document to set the static path. Document In my html, i tried : {% load static %} <link href="{% static 'css/landing-page.min.css' %}" rel="stylesheet"> Also in my setting.py, I confirmed that STATIC_URL = '/static/' is there as default. I create a new folder called static under my app folder where render this HTML page and also create the same folder under my project, I keep the content all the same in both of them because I was not sure which one really is the "static" path it recognized. It seems like the HTML gets its CSS, but not matter how I changed the path in the CSS, the image just doesn't appear. I tried the solution here Add background image in css, and it doesn't at all. I tried: header.masthead { position: relative; background-color: #343a40; background: url("../static/img/main.jpg") no-repeat center center; background-size: cover; padding-top: 8rem; padding-bottom: 8rem; } It doesn't work Please help me. Thanks! -
Django - Dynamic filters in a webpage
I am still a learner for python django. I’d like to filter dynamically data on the table below table The informations in my html template are : <table> <thead> <tr> <th>N°Commande</th> <th>Magasin</th> <th>Objet</th> <th>Date commande</th> <th>Montant</th> <th>Etat</th> </tr> </thead> <tbody> {% for item in query_results %} <tr> <td>{{ item.numero_commande }}</td> <td>{{ item.enseigne}}</td> <td>{{ item.Objet}}</td> <td>{{ item.Date_commande}}</td> <td>{{ item.Montant}}</td> <td>{{ item.Etat}}</td> </tr> </tbody> from the class : class Commande(models.Model) Here is an exemple of what I’d like to have (filters on table fields) : table with dynamic filters thank you in advance for your help Vinloup -
Reverse for 'blog/article' not found. 'blog/article' is not a valid view function or pattern name
I am currently doing a navbar in my django website. However, I'm experiencing some problems with the urls: I have created another urls.py in a new app called blogs. Here's the code for that: In the main urls.py: from django.contrib import admin from django.urls import path, include from translator.views import HomeView, TranslatorView urlpatterns = [ path('blog/', include('blog.urls')), path('', HomeView.as_view(), name='home'), path('translator/<str:phrase>/', TranslatorView.as_view(), name='translator'), path('translated/', TranslatorView.as_view(template_name='main/translated.html'), name='translated'), path('admin/', admin.site.urls), ] In the blog urls.py: from django.urls import path from .views import ArticleDetailView app_name = 'blog' urlpatterns = [ path('', ArticleDetailView.as_view(), name='article' ) ] What I want to do is to include the path ArticleDetailView (name='article) in the navbar. So I coded this: <nav class="navbar fixed-top navbar-expand-lg navbar-light" style='background-color: snow;'> <div class = 'container'> <a class="navbar-brand" href="#"> <img src="{% static 'C:\Users\marcv\OneDrive\Escriptori\Translate\Scripts\src\static\images\dna_PNG48.png'%}" width="70" height="30" class="d-inline-block align-top" alt=""> </a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarTogglerDemo01" aria-controls="navbarTogglerDemo01" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarTogglerDemo01"> <ul class="navbar-nav mx-auto"> <li class="nav-item active"> <a class="nav-link" href="{% url 'home' %}">Home <span class="sr-only">(current)</span></a> </li> <li class="nav-item"> <a class="nav-link" href='{% url "translator" "phrase" %}'>Translator</a> </li> <li class="nav-item"> <a class="nav-link" href="{% url 'blog/article' %}" >Blog</a> #Here's the problem </li> </ul> </div> </div> </nav> However, when I click on the navbar … -
Adding a link to another page in Django(3.1) (NoReverseMatch)
I'm trying to add a link to another page on my index page, but when I use {% url 'blog:BlogAbout' %} I get: Exception Type: NoReverseMatch Exception Value:'blog' is not a registered namespace index.html: <a href="{% url 'blog:BlogAbout' %}">About Me</a> blog.urls.py: path('about/', views.about, name="BlogAbout"), blog.views.py: def about(request): return render(request, 'blog/about.html') urls.py: path('', include('blog.urls')), The question is almost familiar to this: How do I add link to another page [Django 3.0]? Reverse not found I'm doing it like there but I still get an error. What is the right way to add the link? -
from django.db import models from django.utils import timezone
from django.db import models Create your models here. from django.db import modelsfrom django.utils import timezone from django.contrib.auth.models import User class Post(models.Model): STATUS_CHOICES = ( ('draft', 'Draft'), ('published', 'Published'), ) title = models.CharField(max_length=250) slug = models.SlugField(max_length=250, unique_for_date='publish') author = models.ForeignKey(User, related_name='blog_posts') body = models.TextField() publish = models.DateTimeField(default=timezone.now) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='draft') class Meta: ordering = ('-publish',) def __str__(self): return self.title -
Connecting PowerBI Online with my local Analysis Services: there was a data source access error. please contact the gateway administrator
I am trying to publish my reports to PowerBI online so I can embed it into my web application (developed using Django framework and Python). I installed the gateway On-premise, my cube already created in my Analysis Services SQL server. I configured the gateway like in the tutos but still not working, I can't access data in my dashboard. Connectivity is good Still I got the errors I tried every solution on the internet I could found, please any solution? and if you have any other idea of how to embed my reports into my application. thanks a lot. -
Stripe payment - Why when I call if payment_form.is_valid(): is it always invalid?
I am trying to take a Stripe payment but every time the function is_valid() returns false and the message "We were unable to take a payment with that card!" is displayed. The payment is for a set amount of 5 Euros. I am using the credit card number 4242 4242 4242 4242 to test the payment. Can anyone help me find what is wrong with my form? checkout.html: {% extends "base.html" %} {% load static from staticfiles %} {% load bootstrap_tags %} {% block head_js %} <script type="text/javascript" src="https://js.stripe.com/v2/"></script> <script type="text/javascript"> //<![CDATA[ Stripe.publishableKey = '{{publishableKey}}'; // ]]> </script> <script type="text/javascript" src="{% static 'js/stripe.js' %}"></script> {% endblock %} {% block content %} <form action="{% url 'checkout' %}" method="post" id="payment-form" class="col-md-6 col-md-offset-3"> <legend>Payment Details</legend> <div id="credit-card-errors" style="display: none;"> <div id="alert-message block-message error" id="stripe-error-message"></div> </div> <div class="form-group col-md-6"> {{ payment_form | as_bootstrap }} </div> {% csrf_token %} <div class="form-group col-md-12"> <input class=" btn btn-primary" id="submit_payment_btn" name="commit" type="submit" value="Submit Payment"> </div> </form> {% endblock %} forms.py: from django import forms class MakePaymentForm(forms.Form): month_choices = [(i,i) for i in range(1,13)] year_choices = [(i,i) for i in range(2018,2040)] credit_card_number = forms.CharField(label='Credit Card Number', required=False) cvv = forms.CharField(label ='Security Code', required=False) expiry_month = forms.ChoiceField(label="Month",choices=month_choices, required=False) expiry_year = … -
Djoser + Django-Rest verify user before activation email is sent?
I would like to use Djoser's built in "send activation email" with the activation link on user registration. But I want to manually verify a user (click a boolean field in django-admin for example) before the email is sent to the user. How/where would you add this extra step/stop in the registration flow? -
django botcatcher does not activate
I have a web page with 3 forms each with their own submit button. On the second form I'm trying to implement a botcatcher by creating a hidden field and checking it's length. I can't seem to get this to work. Here are the relevant files: form_page.html <!DOCTYPE html> {% load static %} <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <link rel="stylesheet" href="{% static 'basicapp/style.css' %}"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" > <title>Forms</title> </head> <body> <h2>welcome to our first form</h2> <div class="container"> <div class="jumbotron"> <form name='form001' method="post"> {% csrf_token %} {{ form.as_p }} <input type='submit' class="btn btn-primary" name='whichForm' value="Submit"> </form> </div> <div class='jumbotron'> <form method="post"> {% csrf_token %} {{ form1.as_p }} <input type='submit' class="btn btn-primary" name='whichForm' value="Submit1"> </form> </div> <div class='jumbotron'> <form method="post"> {% csrf_token %} {{ form2.as_p }} <input type='submit' class="btn btn-primary" name='whichForm' value="Submit2"> </form> </div> </div> </body> </html> views.py from django.shortcuts import render from . import forms # Create your views here. def index(request): return render(request,'basicapp/index.html') def myform_view(request): form = forms.MyForm() form1 = forms.MyForm1() form2 = forms.MyForm2() if request.method == 'POST': if request.POST['whichForm'] == 'Submit': temp = forms.MyForm(request.POST) elif request.POST['whichForm'] == 'Submit1': temp = forms.MyForm1(request.POST) elif request.POST['whichForm'] == 'Submit2': temp = forms.MyForm2(request.POST) if form.is_valid(): print("VALIDATION SUCCESS!") print("NAME: " + temp.cleaned_data['name']) print("EMAIL: … -
Breaking a forloop in django
I am currently working on a dna to protein translator. The code works pretty well. However, I'd like to improve it with some if statements: Here's the views.py code where I type the if statements: class TranslatorView(View): template_name = 'main/translated.html' stop_codon= { "taa":"Stop", "tag":"Stop", "tga":"Stop", "TAA": "Stop", "TAG": "Stop", "TGA": "Stop", } def translate_amino(self, codon): return self.amino_mapper.get(codon, "") def build_protein(self, request, phrase): if len(phrase) % 3: messages.error(request, 'CHAIN MUST BE DIVISIBLE BY 3') return () protein = [] for i in range(0, len(phrase), 3): codon_stop= self.stop_codon.get(phrase,"") amino = self.translate_amino(phrase[i: i + 3]) if amino: protein.append(amino) elif not amino: messages.error(request, "PROTEIN WAS NOT FOUND") return () elif codon_stop: #Here's where I think the error is: break return protein What I want to do is if the function detects a phrase from stop_codom, the for loop should break. However, the for loop still continues. -
Django Forms: Connecting two functions together for Email Verification
I have created a basic Create User form (username, email, password1, password2) called CreateUserForm and i would like to create an email verification process. It is simple enough to do using one function. But i want to add an additional function that asks the user to accept Terms and Conditions before a verification email is sent. In addition the terms and conditions has to be on a separate html template page. I have also created a Terms and Conditions form which is just a simple BoolianField. I am getting an error saying: ''User' object has no attribute 'get'. Do i have to use a request.get somewhere in my code? A steer in the right direction would be helpful. My code is below: view.py: def registerPage(request): form = CreateUserForm() if request.method =='POST': form = CreateUserForm(request.POST) if form.is_valid(): instance = form.save(commit=False)# Save user data but do not commit to database return redirect('accept_terms') and instance #accept_terms is the name of the registration/terms_and_conditions.html else: form = CreateUserForm() return render(request,'registration/register.html', {'form': form}) def AcceptTerms(request): form = Terms_Conditions() if request.method =='POST': form = Terms_Conditions(request.POST) if form.is_valid(): userform = registerPage # I want to get the saved User data from the registerPage function send_verification_email(request, userform) #Sends verification … -
Django rest_framework / validate PATCH request
I'm new in Django Rest framework. I'm trying to do some test task (simple RestAPI service) but it failed. I've created model Order, serializer OrderSerializer(HyperlinkedModelSerializer), and OrderViewSet(ModelViewSet). (nothing special, use code from tutorial). I tested GET/POST and it works good. But PATCH request works strange. I do PATCH with different fields in payload (which don't exist in the model) and there is no error in response, response code is 200 always. models.py class EOrderStatus(Enum): Unknown = 0 Created = 1 Paid = 2 Failed = 3 class Order(models.Model): _status = models.SmallIntegerField(default=EOrderStatus.Created.value) create_date = models.DateTimeField(default=now, editable=False) pay_date = models.DateTimeField(blank=True, null=True) description = models.CharField(max_length=50, blank=True) serializers.py class OrderSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Order fields = ['id', 'status', 'create_date', 'pay_date', 'description'] views.py class OrderViewSet(viewsets.ModelViewSet): queryset = Order.objects.all() serializer_class = OrderSerializer PATCH /api/orders/1, status code 200 { "dessssss": "aaa", "statttttt": "11" } My question is: why status code is 200? I supposed that I must to receive error something like "invalid fields ...". Do I need to write patch-validator for each model/serializer? And 2nd question: model Order contains enum-field _status. What is the best way don't use _status in request/response, but use property "status" instead? (string type, EOrderStatus.Created.name) -
Django static files are not getting copied into docker container on second time build
My docker container got buggy somehow. So I refactored a bit and made it up and running. After making some changes in my CSS files, I noticed the files doesn't reflect. Then I rebuild the image, run the container again. The result is the same. Previously copied changes are inside the container, not new edits. Here's my Dockerfile FROM python:3.7-alpine # set environment variables ENV PYTHONUNBUFFERED 1 COPY requirements.txt . RUN apk add --no-cache --virtual .build-deps \ ca-certificates gcc linux-headers musl-dev \ libffi-dev jpeg-dev zlib-dev \ && pip install -r requirements.txt \ && find /usr/local \ \( -type d -a -name test -o -name tests \) \ -o \( -type f -a -name '*.pyc' -o -name '*.pyo' \) \ -exec rm -rf '{}' + \ && runDeps="$( \ scanelf --needed --nobanner --recursive /usr/local \ | awk '{ gsub(/,/, "\nso:", $2); print "so:" $2 }' \ | sort -u \ | xargs -r apk info --installed \ | sort -u \ )" \ && apk add --virtual .rundeps $runDeps \ && apk del .build-deps RUN mkdir /code WORKDIR /code COPY . . EXPOSE 8000 RUN python manage.py collectstatic --noinput # Tell uWSGI where to find your wsgi file (change this): ENV … -
Django: Join two tables in a single query
In my template I have a table which I want to populate with data from two different tables which use foreign-keys. The solution I find while googling around is to use values(), example of my queryset below: data = Table1.objects.all().filter(date=today).values('table2__price') My template {% for item in data %} <tr class="original"> <td>{{ item.fruit }}</td> <td>{{ item.table2__price }}</td> </tr> {% endfor %} It do fetch price from table2, but it also make the data (item.fruit) from Table1 disappear. If I remove the values field, Table1 populates accordingly. Anyone have any feedback of what I am doing wrong? Thanks -
Graphene response None even when it works on server
I was added to a project where we use Graphene and Graphene-django-plus, and i'm making a test for a resource that uploads a file, and link with other 2 tables, my module is like this Model class ClientDocumentation(Resource, File): file = models.FileField(upload_to='uploads/', null=True) client = models.ForeignKey(Client, on_delete=models.CASCADE) document = models.ForeignKey(Document, on_delete=models.CASCADE) class Meta: db_table = 'client_documentation' Schema class ClientDocumentationType(ModelType): class Meta: model = ClientDocumentation interfaces = [graphene.relay.Node] connection_class = CountableConnection permissions = ['view_clientdocumentation'] filter_fields = { #'nombre': ['exact', 'icontains', 'istartswith'], #'habilitado': ['exact'] } class ClientDocumentationCreate(ModelCreateMutation): class Meta: model = ClientDocumentation exclude_fields = ["creado_en", "actualizado_en"] allow_unauthenticated = True permissions = ['add_clientdocumentation'] documentation_type = graphene.Field(ClientDocumentationType) @classmethod def mutate_and_get_payload(cls, root, info, **data): client_id = from_global_id(data["client"])[1] client = Client.objects.get(id=client_id) document_id = from_global_id(data["document"])[1] document = Document.objects.get(id=document_id) documentation = ClientDocumentation.objects.create( client=client, document=document, file=data["file"] ) return cls(documentation_type=documentation) Test def test_create(self): documentation = self.documentation.build() client = self.client.create() client.id = to_global_id(type='ClientType', id=client.id) document = self.document.create() document.id = to_global_id(type='DocumentType', id=document.id) response = self.client.execute( ''' mutation ($input: ClientDocumentationCreateInput!){ clientdocumentationCreate( input: $input ){ clientDocumentation{ id } } } ''', variables = { "input": { "file": SimpleUploadedFile( "file.txt", b"these are the file contents!" ), "client": client.id, "document": document.id } } ) print(response) data = response.data['clientdocumentationCreate']['clientDocumentation'] self.assertEqual(data, client.id) The print i set on the … -
Heroku 30s timeout error, how to make Django views variable creation as a background task (worker)?
I am facing a heroku 30s time out error with my django webapp. The reason it is taking long is because of the views variables created (reddit api onto context) Here is the code for the same. def home(request): reddit = praw.Reddit(client_id='L685-1uBBrLbKQ', client_secret='_Fk5nW1L2h3VRR6BVnkusMh43QQ_gg', user_agent='Shivam Anand') hot_posts = reddit.subreddit('AskReddit').top(time_filter="day", limit=7) x = [] y = [] for post in hot_posts: x.append(post.title) y.append(post.url) print(x) print(y) z = [] for url in y: comments = [] submission = reddit.submission(url=url) submission.comments.replace_more(limit=0) for count in range(10): comments.append(submission.comments[count].body) z.append(comments) top_EarthPorn = reddit.subreddit('EarthPorn').top(limit=100) EarthPorn_links = [] for post in top_EarthPorn: EarthPorn_links.append(post.url) request.session['EarthPorn_links'] = EarthPorn_links return render(request, template_name='base.html', context=context) How do i make sure the context dict data is being created every hour or so as a background process? which libraries can one use to achieve so -
workon is not recognized as the name of a cmdlet,django
I want to creat my first app on django3 I had created a virtual env on cmd and then called it on vscode terminal but it shows this error OS :windows & spelling is correct btw): The term workon is not recognized as the name of a cmdlet ,function,script file, or operable program. How can I check and verify the path -
Django ModelForm: Defining a value not passed into the template
I have a ModelForm, and I want to only pass some of the fields into the template. I would like to save one particular field to define after the POST request has been sent. Here is the ModelForm: class CreateListingForm(ModelForm): class Meta: model = models.ListingModel fields = ['name', 'image', 'description', 'price', 'category'] widgets = { 'description': Textarea() } And here is the Model: class ListingModel(models.Model): name = models.CharField(max_length=30) image = models.ImageField(upload_to='images') description = models.CharField(max_length=1000) price = models.PositiveIntegerField() category = models.CharField(max_length=15) objects = models.Manager() owner = models.CharField(max_length=100) In the next code block, I am attempting to define the owner field according to the current user logged in (request.user.username): @login_required(redirect_field_name=login_view) def create_listing(request): if request.method == "GET": return render(request, "auctions/createlisting.html", { "CreateListingForm": forms.CreateListingForm() }) elif request.method == "POST": form = forms.CreateListingForm(request.POST, request.FILES) if form.is_valid(): try: form.owner = request.user.username print(form.owner) form.save(commit=True) except Exception: return HttpResponseRedirect(reverse("create_listing_error")) return HttpResponseRedirect(reverse("index")) #TODO Now, when I say print(form.owner), the result is correct. However when I save the ModelForm, the owner field is left blank. Am I not defining the value of the owner field correctly? -
Django custom superuser can't create new user in admin panel
I created a custom user model and I can create new superuser with manage.py but when I login to admin panel, I can't add new user (although is_superuser column is true in database). This is my models.py: class MyUser(AbstractUser): email = models.EmailField(unique=True) department = models.ForeignKey(to=Department, on_delete=models.CASCADE, null=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username', 'password'] I also tried with custom UserManager but still not working: class MyUserManager(UserManager): def create_superuser(self, username, email=None, password=None, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) u = self._create_user(username, email, password, **extra_fields) u.save() return u class MyUser(AbstractUser): email = models.EmailField(unique=True) department = models.ForeignKey(to=Department, on_delete=models.CASCADE, null=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username', 'password'] objects = MyUserManager() Here is my admin panel screenshot: screenshot