Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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> -
WSGI application 'Uploading.wsgi.application' could not be loaded
while i am run my project after add this middleware social_auth.middleware.SocialAuthExceptionMiddleware i got this error raise ImproperlyConfigured(django.core.exceptions.ImproperlyConfigured: WSGI application 'Uploading.wsgi.application' could not be loaded; Error importing module. -
Why do i get the error " duplicate key value violates unique constraint "" DETAIL: Key (id_application)=(PR-1005576039) already exists
my models.py def document_id(): random_numbers = random.randint(1000000000, 1009999999) doc_id = "PR-" + str(random_numbers) return doc_id class Document(models.Model): id_application = models.CharField(default=document_id(), unique=True, editable=False) applicant_name = models.CharField(max_length=100) to_whom = models.CharField(max_length=255, blank=False) comment = models.TextField(blank=False) email = models.EmailField(blank=False) through_whom = models.CharField(max_length=255, blank=False) creator = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) status = models.CharField(max_length=255, choices=STATUS_CHOICES, default='Pending') is_private = models.BooleanField(default=False) stage = models.CharField(max_length=255, choices=STAGES, default='Departmental Review') uploaded_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) the problem happens every two times i create a document application, for some reasons it is using the last document application id. I am using a postgresql database. -
How to do an optional parameter to Dict in python like "?" in javascript [duplicate]
In javascript , we Have ==> objInner["roles"]?.forEach((roleInner) => {...} like Is there any alternate in python? to check optionally in the dictionary. -
Django - Models - Linking models to another and vice versa
I am trying to link venues to the products they supply. The products supplied are not unique to each venue. As a result, Venue 1 and 2 could both provide Product A. The outcome I am looking for is twofold: when a Product is added to the database, there is an option to link it to an existing Venue When looking at a venue in particular, I would like to have the list of all the product that can be supplied I tried using Foreign Keys and ManyToManyFields but this only seems to add all the products available to the database to all the venues without leaving a choice. The second problem is obviously referring to Product from the Venue model. If I input a foreign key or any form of relation in it, Django gets upset and tells me Product is not defined. I thought of creating a 3rd model, that could combine both Venue and Products, but it feels like there must be something more sophisticated that could done. class Venue(models.Model): name = models.CharField(verbose_name="Name",max_length=100, null=True, blank=True) class Product(models.Model): name = models.CharField('Product Name', max_length=120, null=True) venue = models.ForeignKey(Venue, blank=True, related_name="venue", on_delete=models.CASCADE) -
Drf: Update or create a model instance
i have an attendance model that has a unique together constraint for date and user fk field, right now my implimentation of the createorupdate is an if else that doesn't look nice def create(self, validated_data): user = validated_data.get('user', None) date = validated_data.get('date', None) if date is not None: user = Attendance.objects.filter(user=user, date=date).first() if user is not None: instance = Attendance.objects.update( user=validated_data['user'], presence=validated_data['presence'], leave_reason=validated_data['leave_reason'], date=validated_data['date'], ) return instance else: instance = Attendance.objects.create( user=validated_data['user'], presence=validated_data['presence'], leave_reason=validated_data['leave_reason'], date=validated_data['date'], ) return instance this works the only issue is that the returned object from the update is null for all the fields and i need a better implimentation example the full serializer: class AttendanceSerializer(serializers.ModelSerializer): date = serializers.HiddenField(default=timezone.now) leave_reason = serializers.CharField(required=False, default="") class Meta: model = Attendance fields = ['user', 'presence', 'leave_reason', 'date'] #all the fields except pk extra_kwargs = { 'user': {'required': True}, 'presence': {'required': True}, 'leave_reason': {'required': False}, } # validators = [ # UniqueForYearValidator( # queryset=Attendance.objects.all(), # field='user', # date_field='date', # message=("You have already taken the attendance") # ) # ] def create(self, validated_data): user = validated_data.get('user', None) date = validated_data.get('date', None) if date is not None: user = Attendance.objects.filter(user=user, date=date).first() if user is not None: instance = Attendance.objects.update( user=validated_data['user'], presence=validated_data['presence'], leave_reason=validated_data['leave_reason'], date=validated_data['date'], … -
Django with Bootstrap Carousel
My code it's displaying image but not changing the image in the bootstrap carousel when I click the button to pass {% if variation.extravariationproductpicture_set.all %} <div id="carouselExampleControls" class="carousel slide" data-ride="carousel"> <div class="carousel-inner"> {% for picture in variation.extravariationproductpicture_set.all %} <div class="carousel-item {% if forloop.first %} active {% endif %}"> <img class="d-block w-100" src="{{picture.image.url}}" alt="First slide"> </div> {% endfor %} </div> <a class="carousel-control-prev" href="#carouselExampleControls" role="button" data-slide="prev"> <span class="carousel-control-prev-icon" aria-hidden="true"></span> <span class="sr-only">Previous</span> </a> <a class="carousel-control-next" href="#carouselExampleControls" role="button" data-slide="next"> <span class="carousel-control-next-icon" aria-hidden="true"></span> <span class="sr-only">Next</span> </a> </div> {% endif %} -
Is there anyway i can play an audio and then make theHttpResponseRedirect in django?
Like i made this blog in Django where you can like and unlike posts etc..., but when you press unlike I would like to play a sound and then make the request to remove the like. Is it possible to do that? I tried to wrap my head in an if statement, but I'm kinda new to Django so I'm lost MY Postdetail view class PostDetailView(DetailView): model = Post template_name = "post_detail.html" context_object_name = 'detail' def get_context_data(self, *args, **kwargs): context = super(PostDetailView, self).get_context_data() total = get_object_or_404(Post, id=self.kwargs['pk']) total_likes = total.total_likes() liked = False if total.likes.filter(id=self.request.user.id).exists(): liked = True context['total_likes'] = total_likes context['liked'] = liked return context My like function def LikeView(request, pk): post = get_object_or_404(Post, id=request.POST.get('post_id')) liked = False if post.likes.filter(id=request.user.id).exists(): post.likes.remove(request.user) liked = False else: post.likes.add(request.user) liked = True return HttpResponseRedirect(reverse('detail-post', args=[str(pk)])) Where the function with the audio is called <button type="submit" onclick="play()" name="post_id" value="{{ object.id }} " class="btn mb-3 mx-2 btn-outline-danger">unlike </button> | {{ total_likes }} The audio function <script> function play() { var audio = document.getElementById("audio"); audio.play(); } </script> <audio id="audio" src="https://res.cloudinary.com/volendam/video/upload/v1664620564/memesong_dzacbp.mp3"></audio> -
django template is not showing python variables anymore
so I'm trying to build a website with Django (TAPP.GE), I'm getting texts for the website from the database, but after 39 variables, the 40th one and every variable after that is not showing up on the website. all the texts above (get endless possibilities, etc are exactly the same type of variables as others but others are not showing up below, with 4 different icons.) [1]: https://i.stack.imgur.com/uCTwK.png here, red ones work perfectly, but green ones do not show up [2]: https://i.stack.imgur.com/DU3qH.png Views.py [3]: https://i.stack.imgur.com/OjJrA.png also, if I try to put green variables above in HTML, then it works so I wonder does Django templates have any limit on variables or is there any other problem? -
Error connecting Django with MongoDB using Djongo
I am building a simple web app using django as my backend and mongodb as a database. I have set up the settings.py file correctly like so: Image of my settings.py The error i get when i try to migrate my data to database: Error Traceback (most recent call last): File "C:\Users\dZoNi\AppData\Local\Programs\Python\Python39\lib\site-packages\djongo\database.py", line 10, in connect return clients[db] KeyError: 'django' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Web\ToDo Projekat\ToDoList\Back\toDo\manage.py", line 22, in <module> main() File "C:\Web\ToDo Projekat\ToDoList\Back\toDo\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\dZoNi\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\__init__.py", line 446, in execute_from_command_line utility.execute() File "C:\Users\dZoNi\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\__init__.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\dZoNi\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\base.py", line 402, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\dZoNi\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\base.py", line 448, in execute output = self.handle(*args, **options) File "C:\Users\dZoNi\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\base.py", line 96, in wrapped res = handle_func(*args, **kwargs) File "C:\Users\dZoNi\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\commands\migrate.py", line 114, in handle executor = MigrationExecutor(connection, self.migration_progress_callback) File "C:\Users\dZoNi\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\migrations\executor.py", line 18, in __init__ self.loader = MigrationLoader(self.connection) File "C:\Users\dZoNi\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\migrations\loader.py", line 58, in __init__ self.build_graph() File "C:\Users\dZoNi\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\migrations\loader.py", line 235, in build_graph self.applied_migrations = recorder.applied_migrations() File "C:\Users\dZoNi\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\migrations\recorder.py", line 81, in applied_migrations if self.has_table(): File "C:\Users\dZoNi\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\migrations\recorder.py", line 57, in has_table with self.connection.cursor() as cursor: File "C:\Users\dZoNi\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) File "C:\Users\dZoNi\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backends\base\base.py", line 323, in …