Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Can't access Django Admin with my Custom User credentials
I created an app 'accounts' from which I created my CustomUser. Then, I created superuser from the command line successfully. But I can't login to Django Admin. Everytime, it displays "Please enter the correct username and password for a staff account. Note that both fields may be case-sensitive." This is my accounts.models file, The only one I modified. from django.db import models from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager from django.contrib.auth.models import User class MyUserManager(BaseUserManager): def create_user(self, username, email, password=None): if not email: raise ValueError() if not username: raise ValueError() user = self.model(email=self.normalize_email(email), username=username) user.set_password(password) user.save() return user def create_superuser(self, username, email, password=None): user = self.create_user(username=username, email=email, password=None) user.admin = True user.staff = True user.superuser = True user.save() return user class CustomUser(AbstractBaseUser): username = models.CharField(max_length=12, primary_key=True, unique=True) id = models.IntegerField(default=1) email = models.EmailField(max_length=255, blank=False, unique=True) active = models.BooleanField(default=True) staff = models.BooleanField(default=False) admin = models.BooleanField(default=False) superuser = models.BooleanField(default=False) USERNAME_FIELD = "username" REQUIRED_FIELDS = ['email'] objects = MyUserManager() def has_perm(self, perm, obj=None): return True def has_module_perms(self, app_label): return True @property def is_staff(self): return self.staff @property def is_superuser(self): return self.superuser @property def is_active(self): return self.active -
How to handle MigrationSchemaMissing Unable to create the django_migrations table (relation "django_migrations" already exists )
Our system has been facing some weird issues in production that I have not been able to figure out until recently. I added Sentry to the Django backend to send error reports and came across - a migration/database sync issue. The error occurs when the django python manage.py migrate (actually python manage.py migrate_schemas since we are using the django-tenant-schemas package) command is being executed. The error reads as such: Traceback (most recent call last): File "/backend/manage.py", line 21, in <module> main() File "/backend/manage.py", line 17, in main execute_from_command_line(sys.argv) File "/usr/local/lib/python3.9/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.9/site-packages/django/core/management/__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python3.9/site-packages/django/core/management/base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python3.9/site-packages/django/core/management/base.py", line 398, in execute output = self.handle(*args, **options) File "/usr/local/lib/python3.9/site-packages/django_tenants/management/commands/migrate_schemas.py", line 89, in handle executor.run_migrations(tenants=tenants) File "/usr/local/lib/python3.9/site-packages/django_tenants/migration_executors/standard.py", line 14, in run_migrations run_migrations(self.args, self.options, self.codename, schema_name, idx=idx, count=len(tenants)) File "/usr/local/lib/python3.9/site-packages/django_tenants/migration_executors/base.py", line 45, in run_migrations migration_recorder.ensure_schema() File "/usr/local/lib/python3.9/site-packages/django/db/migrations/recorder.py", line 70, in ensure_schema raise MigrationSchemaMissing("Unable to create the django_migrations table (%s)" % exc) django.db.migrations.exceptions.MigrationSchemaMissing: Unable to create the django_migrations table (relation "django_migrations" already exists ) I have backups dating back 1 month but this issue must have occurred prior to those backups because they did not fix the issue. I have … -
Import "decouple" could not be resolvedPylancereportMissingImports even after retrying pip install python-decouple
How can I get off this <<<Import "decouple" could not be resolvedPylancereportMissingImports>>> even after retrying pip install python-decouple. Check the screenshot ! https://i.stack.imgur.com/6XOjd.png -
Django, store internal link in database
I want to save the internal URL (you can see in the picture below, the last input), and then access it from the code, so I will be able to change it from the admin panel, but it shows error like in image 2 -
Celery Worker Disconnects But Continues To Run Task
I have 8 workers in celery all running on different machines that run very long tasks (multiple hours) These tasks are able to be stopped with app.control.revoke(task_id, terminate=True) and are visible in app.control.instpect() What happens is that some order of events causes the workers to disconnect from RabbitMQ and are no longer visible within the app.control.instpect() method, but the underlying code continues to run within the worker. These tasks are also not able to be terminated. And what would cause something like this to happen? Is there a way to prevent this disconnect from happening? And what would cause something like this to happen? The worker is started with celery -A project worker -l info -P eventlet --concurrency 5 > /dev/null -
AttributeError: module Django.contrib.auth.views has no attributes
I am new to the django development. In my Django app useraccounts, I am creating blog site. However, when I went to run python manage.py makemigrations, I encounter the error: AttributeError: module Django.contrib.auth.views has no attribute 'login'. Don't know what to do . Here is my code: model.py from django.db import models from django.utils import timezone from django.urls import reverse # Create your models here. class Post(models.Model): author = models.ForeignKey('auth.User',on_delete=models.CASCADE) title = models.CharField(max_length=200) text = models.TextField() created_date = models.DateTimeField(default=timezone.now) published_date = models.DateTimeField(blank=True, null=True) def publish(self): self.published_date = timezone.now() self.save() def approve_comments(self): return self.comments.filter(approved_comment=True) def get_absolute_url(self): return reverse("post_detail",kwargs={'pk':self.pk}) # kwargs--handle named arguments that you have not defined in advance. #reverse()--if you change the url in future then you can reference that url using reverse(urlname). #This looks through all URLs defined in your project for the URL defined with the name url_name and returns the actual URL def __str__(self): return self.title class Comment(models.Model): post = models.ForeignKey('blog.Post',related_name='comments',on_delete=models.CASCADE) author = models.CharField(max_length=200) text = models.TextField() created_date = models.DateTimeField(default=timezone.now) approved_comment = models.BooleanField(default=False) def approve(self): self.approved_comment = True self.save() def get_absolute_url(self): return reverse("post_list") def __str__(self): return self.text views.py from django.shortcuts import render, get_object_or_404, redirect from django.contrib.auth.decorators import login_required from blog_app.models import Post, Comment from django.utils import timezone … -
Python for web development [closed]
I am newbie in development field. What do I need to know about python programming language to learn Django python for web dev backend. -
PyCharm CE: Django Unexpected expression syntax
I am doing the following code using PyCharm and Django and I'm getting the unexpected expression syntax error at the very end for ('products':products)) and I'm not sure why. from django.shortcuts import render from django.http import HttpResponse from .models import Product def admin_console(request): products = Product.objects.all() return render(request, 'products/products_page.html', ('products': products)) -
Writable Nested Serializers Error in POST - Invalid Pk - object does not exist
I’m working on writable nested serializers. I want to enter data containing 2 tables — request, and parts in one request. I was able to do serialization but as I try to POST a request, it sends me an error throwing that an object does not exist. Probably because parts has foreign key referencing to request. What could be the solution for this? # API - Response HTTP 400 Bad Request Allow: POST, OPTIONS Content-Type: application/json Vary: Accept { "parts": [ { "requestid": [ "Invalid pk \"ID0000001\" - object does not exist." ] } ] } #serializer.py class PartSerializer(serializers.ModelSerializer): class Meta: model = partsTable fields = '__all__' class RequestSerializer(serializers.ModelSerializer): parts=PartSerializer(many=True, write_only=True) class Meta: model = requestTable fields = ['requestid', 'requeststatusid', 'requesterid', 'businessunitid', 'plantid', 'requestname', 'projectmanager', 'parts'] def create(self, validated_data): parts_data = validated_data.pop('parts') request = requestTable.objects.create(**validated_data) for part_data in parts_data: partsTable.objects.create(request=request, **part_data) return request # models.py class partsTable(models.Model): partsid = models.CharField(max_length=100, null=False, primary_key=True) validatorid = models.ForeignKey(userTable, on_delete=models.CASCADE) request = models.ForeignKey(requestTable, related_name='parts', on_delete=models.CASCADE) partsstatusid = models.ForeignKey(partsStatusTable, on_delete=models.CASCADE) userpartsid = models.CharField(max_length=40, null=True) class requestTable(models.Model): requestid = models.CharField(max_length=12,primary_key=True) requeststatusid = models.ForeignKey(requestStatusTable, on_delete=models.CASCADE) requesterid = models.ForeignKey(userTable, on_delete=models.CASCADE) businessunitid = models.ForeignKey(businessUnitTable, on_delete=models.CASCADE) plantid = models.ForeignKey(plantTable, on_delete=models.CASCADE) requestname = models.CharField(max_length=100, null=False) projectmanager … -
Wagtail internationalization - add pages with other language
I followed the steps from the official wagtail documentation to add a mulit-lingual django-app. So far I got one Page which indicates the language english. I added german to the wagtail.locales and want to translate the english page into german but I didn't find any input or select to change the pages's language. Unforunatly I didn't found any example code on how to translate text. I tried packages like wagtail-localize but those are not compatible with the latest version (v4.0.2). -
in Django, does class based view is enough for CRUD and can do anything a "noraml view" can do?
I have found that class-based views can save time and effort and are more efficient than normal views however I have learned it In the scope of CRUD operation and I don't know if it can do more than this. my question is if class-based views can do anything so no need to create views in a regular way or if the regular way has some pros over class-based views? -
registration form methods in django custom user model
I am creating a custom user model for django.My question is When I create a user via the template form the methods (clean_user_name,clean_password2,clean_email) in RegistrationForm class in forms.py get automatically called when a user attempt to fill the form so why does that happen as for what I know only init method gets automatically called. models.py class CustomAccountManager(BaseUserManager): def create_superuser(self, email, user_name, password, **other_fields): other_fields.setdefault('is_staff', True) other_fields.setdefault('is_superuser', True) other_fields.setdefault('is_active', True) if other_fields.get('is_staff') is not True: raise ValueError( 'Superuser must be assigned to is_staff=True.') if other_fields.get('is_superuser') is not True: raise ValueError( 'Superuser must be assigned to is_superuser=True.') return self.create_user(email, user_name, password, **other_fields) def create_user(self, email, user_name, password, **other_fields): if not email: raise ValueError(_('You must provide an email address')) email = self.normalize_email(email) user = self.model(email=email, user_name=user_name, **other_fields) user.set_password(password) user.save() return user class UserBase(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_('email address'), unique=True) user_name = models.CharField(max_length=150, unique=True) first_name = models.CharField(max_length=150, blank=True) about = models.TextField(_( 'about'), max_length=500, blank=True) # Delivery details country = CountryField() phone_number = models.CharField(max_length=15, blank=True) postcode = models.CharField(max_length=12, blank=True) address_line_1 = models.CharField(max_length=150, blank=True) address_line_2 = models.CharField(max_length=150, blank=True) town_city = models.CharField(max_length=150, blank=True) # User Status is_active = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) objects = CustomAccountManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = … -
How to call class method in Django URLs path?
How to call class method in Django URLs path? I want to call data_display method inside DataLoad class. how can i call it in my URLs.py file? so when i hit the path then it will render to the data_display.html template. views.py class DataLoad: def __init__(self, save_path, name_of_file): self.save_path = save_path self.name_of_file = name_of_file def file_load(self): file_path = os.path.join(self.save_path, self.name_of_file+".html") return file_path def data_display(request,*args, **kwargs): df = pd.read_csv("/home/satyajit/Desktop/opensource/data/us_amz.csv", low_memory=False) json_records = df.reset_index().to_json(orient ='records') data = [] data = json.loads(json_records) context = {'data': data} return render(request, "home/data_display.html", context) urls.py from apps.home.views import DataLoad data = DataLoad.data_display(request) urlpatterns = [ #path('data_display', DataLoad.as_view(), name='data_display'), path('data_display', data, name='data_display'), ] -
I cannot create the new user in django
I cannot create any new user from this method redirect is working and every thing is working but new user is not creating this id my view from urllib import response from django.shortcuts import redirect, render from .forms import RegisterForm from main.views import home # Create your views here. def register(request): form = RegisterForm(request.POST or None) if request.method == "POST": if form.is_valid(): form.save() return redirect("home") else: form = RegisterForm() return render(request, "register.html", {"forms":form}) Forms.py from dataclasses import field from socket import fromshare from xml.parsers.expat import model from django.contrib.auth import login, authenticate from django.contrib.auth.forms import UserCreationForm from django import forms from django.contrib.auth.models import User class RegisterForm(UserCreationForm): email = forms.EmailField() class Meta: model = User fields = ["username","email","password1","password2"] -
why 'ImproperlyConfigured ' by an id prefix in django serializer's fields= ('userid',) and not in fields='__all__'?
At the following code I get the 'ImproperlyConfigured' error, while with the uncommented line and won't. Why? class EigenBankRekeningSerializer(serializers.ModelSerializer): class Meta: model = EigenBankRekening fields = ( 'id' 'userid', 'aangemaakt', 'gewijzigd', 'naam', 'informatie', 'iban_prefix', 'bankrekening', 'valuta', 'eigen_gbr', 'zakelijke_rekening', 'oudedagsreserve', ) # fields = '__all__' Exception Value: Field name iduser is not valid for model EigenBankRekening. In views.py I've got a filter by userid, but why is it prefixed with id in the API? class EigenBankRekeningView(viewsets.ModelViewSet): permission_classes = [AllowAny] serializer_class = EigenBankRekeningSerializer queryset = EigenBankRekening.objects.all() def get_queryset(self, **kwargs): user_bank = EigenBankRekening.objects.filter(userid=self.request.user.id) return user_bank -
Make a "django-filter" dynamic
I have django-filter that works for one category and I am trying to make it dynamic for it to work for all categories of an eCommerce website. Here is the model: class Listing(models.Model): sub_category = models.ForeignKey(SubCategory, on_delete=models.SET_NULL, related_name="sub_category", blank=False, null=True) is_active = models.BooleanField(default=True, null=True, blank=True) facilities = models.JSONField(default=dict, null=True, blank=True) nearby = models.JSONField(default=dict, null=True, blank=True) details = models.JSONField(default=dict, null=True, blank=True) # ... OTHER FIELDS Here is the version that works: class ListingFilter(django_filters.FilterSet): class Meta: model = Listing fields = { 'sub_category__sub_category_name': ['contains'], 'is_active': ['exact'], } country = django_filters.CharFilter(field_name="details__country", lookup_expr="icontains") min_price = django_filters.NumberFilter( method=lambda queryset, _, value: queryset.filter(details__price__gte=float(value)) ) max_price = django_filters.NumberFilter( method=lambda queryset, _, value: queryset.filter(details__price__lte=float(value)) ) kindergarten = django_filters.BooleanFilter(field_name="nearby__kindergarten", lookup_expr="exact") # ...OVER 40 OTHER FIELDS class ListingNode(DjangoObjectType): class Meta: model = Listing interfaces = (graphene.relay.Node, ) class Query(graphene.ObjectType): one_listing = graphene.relay.Node.Field(ListingNode) all_listingss = DjangoFilterConnectionField(ListingNode, filterset_class=ListingFilter) Here is what I have attempted to make it dynamic: class ListingFilter(django_filters.FilterSet): def __init_subclass__(cls, **kwargs): super().__init_subclass__(**kwargs) for field in Listing._meta.get_fields(): field_name = (field.__str__().split('.'))[-1] if field_name == 'details': cls.get_declared_filters['min_price'] = \ django_filters.NumberFilter( field_name='details__price', lookup_expr='gte', method='details_filter' ) class Meta: model = Listing fields = { 'sub_category__sub_category_name': ['contains'], 'is_active': ['exact'], } def details_filter(self, queryset, name, value): return queryset.filter(details__price__gte=float(value)) The problem is I'm not sure which django-filter method … -
Javascript: Execute python file (Raspberry Pi)
I got a Django Webserver running on my Raspberry Pi. I got an JavaScript file, where I want to execute a external python file to do something. I also want to give a value from JS to the python file. How can I execute a python file from JavaScript and also, is there a way to set a parameter to the python file, which he receives from JavaScript. -
PostgreSQL is not reachable when trying to deploy dockerized application on the same host [closed]
I have created an application consisting of four docker containers and compose it via docker-compose. Apart from the application, there is a remote host that serves a PostgreSQL database and have a public IP and DNS record. When compose is up on the local machine, it connects to the database on the remote host just fine. However, once the application is transferred to that remote host and composed there, it stops connection to that database anymore. Actually, the part that tries to connect to the database by hostname is a Django server. If I run the server on the remote host but not in a container, it runs just fine as at the local machine. Once it containerized, it stops working. I allowed all hosts in PostgreSQL config and the problem seems to be with containers, but I have no clue why they are working at my local machine. -
Ceating two objects instead of one in Django
I want to create an object with transmitting some data from other model. And it works good, but instead of creation one object of model, I got two objects. I create one object and try modify it, but it saves two objects, created and modified. I want to save only one object, which was modified. I am using the approach that was suggested to me: Django instance in model form Views topic = Topic.objects.get(id=pk) room = Room.objects.create(topic=topic) form = RoomForm(request.POST, instance=room) if request.method == 'POST': if form.is_valid(): room = form.save(commit=False) room.host=request.user room.save() return redirect('home') -
Correct way to get user details from django User
I'm Building project for practice and i have a product and i want to show to everyone all the names of users that selling this product. I've set the user field as ForeignKey of User in models,but I'm getting in the response object only the id of the user without anything else. What is the correct way to access the user name? The model of the product sellers: class ProductSeller(models.Model): product_id=models.ForeignKey(Product,on_delete=models.CASCADE,default = None) user=models.ForeignKey(User,on_delete=models.CASCADE) condition = models.CharField(max_length=100, choices=condition_choices) asked_price=models.IntegerField() image=models.ImageField(null=True,blank=True) The view: @api_view(['GET']) def getSellersById(request,pk): sellers=ProductSeller.objects.filter(product_id=pk) seralizer=SellersSerializer(sellers,many=True) return Response(seralizer.data) The response object: { "id": 2, "condition": "Almost new", "asked_price": 50, "image": "image.jpg", "product_id": 8, "user": 1 }, -
I have a problem that I could not fetch product details by category
I have a problem that I could not fetch product details by category Because Viwes contains two variables and I couldn't get them to show the product details Model from django.db import models # Create your models here. class Category(models.Model): name = models.CharField(max_length=200) slug = models.CharField(max_length=200) def __str__(self): return self.name class Product(models.Model): Category = models.ForeignKey(Category, on_delete=models.CASCADE) name = models.CharField(max_length=200, null=False, blank=False) slug = models.CharField(max_length=200, null=False, blank=False) description = models.TextField(max_length=350, null=False, blank=False) image = models.ImageField( null=False, blank=False) quantity = models.IntegerField(null=False, blank=False) def __str__(self): return self.name Urls path('category/<str:product_category_slug>/<str:product_slug>/', views.product_detail, name="product-detail") Viwes def product_detail(request, product_category_slug=None, product_slug=None): #How do I get product details through this path that contains a category and then the product I hope someone can help me -
'NoneType' object has no attribute 'subscription_type'
I am currently learning Django and try to implement payment method watching youtube. so for payement i use Stripe. the payement was sucessful. however i face the following error when i try to link the profile model. but i get the error enter image description here the view.py was enter image description here the model was: enter image description here -
the django tutorial part 5 the python shell returns "TypeError: 'NoneType' object is not subscriptable" but should return "<QuerySet[<...>]>
I am currently doing the official django tutorial. https://docs.djangoproject.com/en/4.1/intro/tutorial05/#the-django-test-client This is the expected return of the python shell >>> from django.test import Client >>> client = Client() >>> response = client.get('/') Not Found: / >>> response.status_code 404 >>> from django.urls import reverse >>> response = client.get(reverse('polls:index')) >>> response.status_code 200 >>> response.content b'\n <ul>\n \n <li><a href="/polls/1/">What&#x27;s up?</a></li>\n \n </ul>\n\n' >>> response.context['latest_question_list'] <QuerySet [<Question: What's up?>]> But this is what it looks like for me: >>> from django.test import Client >>> client = Client() >>> response = client.get('/') Not Found: / >>> response.status_code 404 >>> from django.urls import reverse >>> response = client.get(reverse('polls:index')) >>> response.status_code 200 >>> response.content b'\n <ul>\n \n <li><a href="/polls/2/">What&#x27;s going on?</a></li>\n \n <li><a href="/polls/1/">What&#x27;s new?</a></li>\n \n </ul>\n' >>> response.context['latest_question_list'] Traceback (most recent call last): File "<console>", line 1, in <module> TypeError: 'NoneType' object is not subscriptable Instead of the TypeError I expect a QuerySet! Now what can help here? I will include the polls/models.py and polls/views.py here: polls/views.py from django.http import HttpResponseRedirect from django.shortcuts import get_object_or_404, render from django.urls import reverse from django.views import generic from .models import Choice, Question class IndexView(generic.ListView): template_name = 'polls/index.html' context_object_name = 'latest_question_list' def get_queryset(self): """Return the last five published questions.""" return … -
what is the minimum amount is have to pay for Heroku app if it is not free?
as you all know that Heroku is closing their free tier in November till now i am using free Heroku version my website is in Django(python) i want to upgrade the Heroku to a paid tier i want to know what will be the minimum amount i have to pay on Heroku if i select the lowest plan? i have tried to understand from https://www.heroku.com/pricing but i have not understood it. thanks in advance please also guide me if we have two select all (app princing , dyno pricing, postgre pricing) or we just have to select a one from all of them? -
Model Forms not saving ManytoMany Field
here is my code. I am using Modelforms and Crispy forms library to generate form. when I click form submit everything is saved, except Category(manytomanyfield), that I have to specify manually from admin panel. NOTE: I FOUND SOME SOLUTIONS ONLINE to do form.save_m2m() but I get Object has no attribute save_m2m() my modelform. from django.forms import ModelForm from .models import Article class ArticleForm (ModelForm): class Meta: model = Article fields = '__all__' exclude = ('user',) my views. def create(request): if request.method =="POST": form = ArticleForm(request.POST, request.FILES) if form.is_valid(): form = form.save(commit=False) form.user = request.user return redirect('home') form = ArticleForm() context = {'form': form} return render(request, 'article_form.html', context) my template. <form action="" enctype="multipart/form-data" method="post"> {% csrf_token %} {{form|crispy}} <button type="submit" class="btn btn-primary">Submit</button> </form>