Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 … -
Fetching data from django restframewok using js fetch [closed]
index.html:401 POST http://127.0.0.1:8000/predict/ 415 (Unsupported Media Type) -
Unable to create migration in django
About issue There is no migration folder Unable to create migration of model Steps to replicate the issue Created the project using this command: django-admin startproject practice1 I did not create any app using command: python manage.py startapp app_name configured mysql in settings.py DATABASES = { 'default': { #'ENGINE': 'django.db.backends.sqlite3', "ENGINE": "django.db.backends.mysql", "NAME": "backend", "USER": "root", "PASSWORD": "", "HOST": "localhost", "PORT": "3306" #'NAME': BASE_DIR / 'db.sqlite3', } } Since there was no models.py file so I created it inside the directory where settings.py exists models.py contents from django.db import models class Roles(models.Model): role = CharField(max_length=10) is_active = BooleanField(default=False) now, in console, type python manage.py makemigrations it says - No changes detected -
why would I use django-rest-framework , when I can build APIs without it? [closed]
why do I have to use api_view (coming from the django-rest-framework) api_view(['POST']) def signUp(request): ip = request.META.get('REMOTE_ADDR') jned = json.loads(request.body) try: connection = psycopg2.connect(user="postgres", password="0000", host="127.0.0.1", port="5432", database="test") except: print('error in connection ') when I can just do this ? (I am using csrf_exempt because the API that I am building will be called by a python script, and not by a web browser) @csrf_exempt def signUp(request): ip = request.META.get('REMOTE_ADDR') jned = json.loads(request.body) try: connection = psycopg2.connect(user="postgres", password="0000", host="127.0.0.1", port="5432", database="test") except: print('error in connection ') -
Media files showing 404 debug is false using Django development server
I have been trying to test my Django project before deploying it on a cpanel #settings.py STATIC_URL = '/static/' MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] -
Django navigation as POST input for dynamcial view
I am building an django app that displays real estate data of different cities. The city info is saved in the django model. I have one view that displays all data of a particular city, I only need a way to get the user input of which city data he wants to see. In the navbar are the names of the cities, how do I save the user choice in the navigation in the session info and use it as input for the view? In a form of a POST? base.html <div class="navigation"> <ul> <li> <a href="#"> <span class="title">City 1</span> </option> </a> </li> <li> <a href="#"> <span class="title">City 2</span> </a> </li> <li> <a href="#"> <span class="title">City 3</span> </a> </li> <li> <a href="#"> <span class="title">City 4</span> </a> </li> </ul> </div> -
Django views.py function doesn't get called
I want the function login_user() to be called when the user clicks the Log In Button. But the function never gets called. I think I have setup all the URLConfs correctly. Can you spot my mistake? views.py from django.shortcuts import render, redirect from django.contrib.auth import authenticate, login, logout from django.contrib import messages # Create your views here. def login_user(request): if request.method == "POST": # if user goes to webpage and fills out form, do something email = request.POST['email'] password = request.POST['password'] user = authenticate(request, email=email, password=password) if user is not None: login(request, user) return redirect('home') # Redirect to a success page. else: messages.success(request, "There was an Error Logging In, please try again.") return redirect('login') else: return render(request, 'registration/login.html', {}) urls.py (main config) from django.contrib import admin from django.urls import include, path urlpatterns = [ path('admin/', admin.site.urls), path('accounts/', include('loginForm.urls')), path('accounts/', include('django.contrib.auth.urls')), ] urls.py from django.urls import path from . import views urlpatterns = [ path('login', views.login_user, name='login'), ] login.html <h2>Log In</h2> <form method="POST"> {% csrf_token %} <div class="mb-3"> <label for="email" class="form-label">Email address</label> <input type="email" class="form-control" name="email" aria-describedby="emailHelp"> </div> <div class="mb-3"> <label for="exampleInputPassword1" class="form-label">Password</label> <input type="password" class="form-control" name="password"> </div> <input type="submit" value="Log In" class="btn btn-secondary"> </form> Note: Even if I print something … -
Show product page by category - send 2 var in url
You fetch products by category in this function Urls path('category/<str:slug>', views.categoryslug, name="categoryslug"), Views def categoryslug(request, slug): category = Category.objects.get(slug=slug) context = { 'category': category, 'products': category.product_set.all(), } #return render(request, 'pages/catpro.html', context) But I want to open a product through this link http://127.0.0.1:8000/category/phone/redmi-8-pro Template {% url 'catproslug' product.slug d.slug %} Urls path('category/<str:slug>/<str:proslug>', views.catproslug, name="catproslug") Views def catproslug(request, slug, proslug): d = Product.objects.get(slug=proslug) context = { 'd': d, 'category':category } return render(request, 'pages/catpro.html', context) -
django model to yeild specific HTML output without redundancy in the model
I have 3 models (supervisor, students, and allocation) I am building an allocation system where multiple students can be allocated to one supervisor Now I want my model to be able to yeld this output Example of how i want the output to come out Here are the structure of my model class StudentProfile(models.Model): stud_id = models.UUIDField(default=uuid.uuid4, primary_key=True, unique=True) user_id = models.OneToOneField(User,blank=True, null=True, on_delete=models.CASCADE) programme_id = models.ForeignKey(Programme, on_delete=models.CASCADE) session_id = models.ForeignKey(Sessi`**enter code here**`on, on_delete=models.CASCADE) type_id = models.ForeignKey(StudentType, on_delete=models.CASCADE) dept_id = models.ForeignKey(Department, on_delete=models.CASCADE) class SupervisorProfile(models.Model): super_id = models.UUIDField(default=uuid.uuid4, primary_key=True, unique=True) user_id = models.ForeignKey(User, on_delete=models.CASCADE) dept_id = models.ForeignKey(Department, on_delete=models.CASCADE) class Allocate(models.Model): allocate_id = models.UUIDField(default=uuid.uuid4, primary_key=True, unique=True) stud_id = models.ForeignKey(StudentProfile, on_delete=models.CASCADE) super_id = models.ForeignKey(SupervisorProfile, on_delete=models.CASCADE) now my main focus is the Allocate model where the allocation is made, and there is a lot of redundancy any suggestions on how to improve my model to remove redundancy in yielding the expected HTML output would be appreciated 🙏 -
How to solve No module named 'django.contrib.staticfilespages' in Django?
I was studying from the book "Django for Beginners" by William S. Vincent. Whenever I try to run the code from chapter 2, Hello World App, I get "No module named 'django.contrib.staticfilespages' " This question has already been asked by someone else on Django.fun but no answers there. I can't find anyone else having a similar problem on the internet. Also Pycharm is not showing any error to help me with this. File "C:\Users\rexze\PycharmProjects\djangoProject\manage.py", line 22, in <module> main() File "C:\Users\rexze\PycharmProjects\djangoProject\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\rexze\PycharmProjects\djangoProject\venv\lib\site-packages\django\core\management\__init__.py", line 446, in execute_from_command_line utility.execute() File "C:\Users\rexze\PycharmProjects\djangoProject\venv\lib\site-packages\django\core\management\__init__.py", line 420, in execute django.setup() File "C:\Users\rexze\PycharmProjects\djangoProject\venv\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\rexze\PycharmProjects\djangoProject\venv\lib\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) mod = import_module(mod_path) File "C:\Users\rexze\AppData\Local\Programs\Python\Python310\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 992, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 1004, in _find_and_load_unlocked ModuleNotFoundError: No module named 'django.contrib.staticfilespages' (venv) PS C:\Users\rexze\PycharmProjects\djangoProject> python manage.py startserver Traceback (most recent call last): File "C:\Users\rexze\PycharmProjects\djangoProject\manage.py", line 22, in <module> …