Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Related to foreign key , Django
I am a new user to Django, I have two models, one is Department and the other is Employee. I need to link these two tables so that I would be able to view the details under each department in a table. But I am getting an error as "NOT NULL constraint failed: pom_employee.department_id". I am not using forms in this project. Kindly help me models.py : class Department(models.Model): name = models.CharField(max_length=50) def __str__(self): return self.name class Employee(models.Model): name = models.CharField(max_length=124) age = models.IntegerField() department = models.ForeignKey(Department,on_delete=models.CASCADE,null=True) def __str__(self): return self.name views.py def empdata(request): if request.method == "POST": name = request.POST.get('empname',False) age = request.POST.get('empage',False) try: Employee.objects.create(name=name, age=age) return redirect('/showemp') except Employee.DoesNotExist: print("I am in except") Employee.objects.get(name=name,age=age).save() return render(request,'showempdetails.html') -
Is there a way to have an image expand the entire page on my Django based website?
I have a django based website and am having trouble with images filling up the entire screen or fitting to the screen size. Attatched is a photo of my issue. I've checked all my margin and border settings and everything is set to 0, yet the picture doesn't fill up the entirety of the screen. Anyone know a solution to this? Much appreciated. I'm trying to get the left and right borders on the side of the image to not exist, and to be covered by the image instead. <img class="image1" src="xxx" style="width:100%; margin-top:-25px;"/> <div class="image2" style="height: 725px;"><form action="/order"><input type="submit" value="Order Online"/ style="position:absolute; bottom:0; margin-bottom: 265px; margin-left: 383px; background-color: #262626; color:white; width:275px; height:70px; font-size:26px; font-family: Lucida Console"> </div>``` -
Docker image when run drops meinside an interactive shell
I have a Django application that I have containerized . It builds successfully. When I run it using the 'docker-compose up', I can access the application svcs' no problem. However, when I use the 'docker run -it -p 8000:8000 'imagename', I get an interactive shell. Why is this happening? My Dockerfile looks like: FROM python:3.9-alpine ENV PYTHONBUFFERED 1 ENV PYTHONWRITEBYCODE=1 WORKDIR /app # install psycopg2 dependencies RUN apk update \ && apk add postgresql-dev gcc python3-dev musl-dev RUN pip install psycopg2-binary RUN apk add zlib-dev jpeg-dev gcc musl-dev #install pip for the docker image RUN pip install --upgrade pip COPY requirements.txt /app/requirements.txt RUN pip install -r requirements.txt COPY . /app my docker-compose.yml file looks like: version: '3.8' services: backend: build: context: . dockerfile: Dockerfile command: 'python manage.py runserver 0.0.0.0:8000 --no-input' ports: - 8000:8000 volumes: - .:/app depends_on: - db db: image: postgres:13-alpine volumes: - postgres_data:/var/lib/postgresql/data/ expose: - 5432 environment: - POSTGRES_USER=user - POSTGRES_PASSWORD=passwd - POSTGRES_DB=db volumes: postgres_data: -
How to redirect superuser to specific page in Django?
I want to send the superuser to the dashboard (home) after login. But a normal user will redirect to the store page so how can I do it? This is the logic I am using in the views.py file so what changes do I need to do? views.py @unauthenticated_user def loginPage(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') user = authenticate(request, username = username, password = password) if user is not None: login(request, user) return redirect('store') else: messages.info(request, 'Username OR Password is incorrect') context = {} return render(request, 'store/login.html', context) urls.py urlpatterns = [ path('register/', views.registerPage, name="register"), path('login/', views.loginPage, name="login"), path('logout/', views.logoutUser, name="logout"), path('dashboard/', views.home, name='dashboard'), path('products/', views.products, name='products'), path('customer/<str:pk>/', views.customer, name='customer'), path('profile/', views.profilePage, name="profile"), path('cart/', views.cart, name='cart'), path('checkout/', views.checkout, name='checkout'), path('', views.store, name='store'), path('update_item/', views.updateItem, name='update_item'), path('process_order/', views.processOrder, name='process_order'), ] -
javascript btnAtt, att_zone
In the Django template, using JavaScript, a button has been created to display a preview of a photo and delete the preview. As applied to DetailImage, I want to apply the same to Thumbnail, but a red line appears because of the duplicate btnAtt and att_zone names, so it is impossible to proceed. How can I solve this? Any help would be greatly appreciated. We will adopt it as soon as it is resolved. -
I got django.core.exceptions.SuspiciousFileOperation after collectstatic command
I want to deploy my django project on Heroku. When I try to collect static using python manage.py collectstatic I got this Traceback: (venvecosite) (base) cristian@FInch:~/Desktop/GreatEcology my project/ecosite/ecowebsite$ python manage.py collectstatic You have requested to collect static files at the destination location as specified in your settings: /home/cristian/Desktop/GreatEcology my project/ecosite/ecowebsite/staticfiles This will overwrite existing files! Are you sure you want to do this? Type 'yes' to continue, or 'no' to cancel: yes Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/cristian/Desktop/GreatEcology my project/ecosite/venvecosite/lib/python3.8/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/home/cristian/Desktop/GreatEcology my project/ecosite/venvecosite/lib/python3.8/site-packages/django/core/management/__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/cristian/Desktop/GreatEcology my project/ecosite/venvecosite/lib/python3.8/site-packages/django/core/management/base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "/home/cristian/Desktop/GreatEcology my project/ecosite/venvecosite/lib/python3.8/site-packages/django/core/management/base.py", line 398, in execute output = self.handle(*args, **options) File "/home/cristian/Desktop/GreatEcology my project/ecosite/venvecosite/lib/python3.8/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 187, in handle collected = self.collect() File "/home/cristian/Desktop/GreatEcology my project/ecosite/venvecosite/lib/python3.8/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 128, in collect for original_path, processed_path, processed in processor: File "/home/cristian/Desktop/GreatEcology my project/ecosite/venvecosite/lib/python3.8/site-packages/whitenoise/storage.py", line 148, in post_process_with_compression for name, hashed_name, processed in files: File "/home/cristian/Desktop/GreatEcology my project/ecosite/venvecosite/lib/python3.8/site-packages/whitenoise/storage.py", line 88, in post_process for name, hashed_name, processed in files: File "/home/cristian/Desktop/GreatEcology my project/ecosite/venvecosite/lib/python3.8/site-packages/django/contrib/staticfiles/storage.py", line 399, in post_process yield from super().post_process(*args, **kwargs) File "/home/cristian/Desktop/GreatEcology my project/ecosite/venvecosite/lib/python3.8/site-packages/django/contrib/staticfiles/storage.py", … -
Django set boolean after opening record
I have been googling for a good hour and I can't for the live of me figure out how to do this. In my applicants model I have this field viewed = models.BooleanField(verbose_name="Nieuw", default=False) which gets shown on the admin page table for this model list_display = ('viewed', 'custom_status', 'updated_at', 'first_name', 'last_name', 'vacancy', 'created_at', 'applicant_actions') But how do I set that boolean to true when a user opens the applicant's detail page? Thanks in advance -
return django object with it's related instance as json
i've a Comment model and author ForeignKey i want to return it in json with it's author profile picture i tried using manager but idk if something is wrong with it or it's the wrong approach class CommentManager(models.Manager): def get_author_url(self, author): return self.get(url = author.pic.url) class Comment(models.Model): post = models.ForeignKey(Post, related_name='comments', on_delete=models.CASCADE, blank=True, null=True) author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) content = models.TextField() DatePublished = models.DateTimeField(auto_now_add=True) objects = CommentManager() but what i get: [{"id": 24, "post_id": 146, "author_id": 5, "content": "sb7", "DatePublished": "2021-07-29T06:40:38.752Z"}] -
How to change the url of an app in Django to custom url
I have an app in my Django project that called Stressz. So the url of my app is: http://localhost:8000/stressz/ http://localhost:8000/stressz/siker http://localhost:8000/stressz/attitud How can I change the url without changing the name of the app from the above url to something like this: http://localhost:8000/mpa http://localhost:8000/mpa/siker http://localhost:8000/mpa/attitud urls.py app_name = 'stressz' urlpatterns = [ path('', views.index, name='index'), path('siker', views.siker, name='siker'), path('attitud', login_required(views.AttitudCreateView.as_view()), name='attitud_item'), ... -
How I can check current page is home or a special page in template django?
I want to check that current page is home page or not in django template. How I can do this? -
how to get all fields with group by in django
I am trying to get all fields from the query set with the group by in Django(3.2). and using the PostgreSQL database. while I using Model.objects.filter().values().annotate(count=Count('name')).order_by('name') it not gives unique record. and I also try with Model.objects.filter().distinct('name') it also not work. how can I fetch unique records with all fields through the group by field? -
DRF Update or Create TypeError
I'm trying to create a structure where a list of books read is kept. I had set up a structure, but if the read finished statement is checked, it adds a new record. What I want to do is to create only 1 record according to that user and book id value and constantly update this record. When I want to do this, I get the following error, I cannot access the book id value. There are many similar questions, but I couldn't make the right application, I need suggestions. Traceback (most recent call last): File "E:\!Staj\bookorbooks\env\lib\site-packages\django\db\models\fields\__init__.py", line 1823, in get_prep_value return int(value) TypeError: int() argument must be a string, a bytes-like object or a number, not 'Book' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "E:\!Staj\bookorbooks\env\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "E:\!Staj\bookorbooks\env\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "E:\!Staj\bookorbooks\env\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "E:\!Staj\bookorbooks\env\lib\site-packages\django\views\generic\base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "E:\!Staj\bookorbooks\env\lib\site-packages\rest_framework\views.py", line 509, in dispatch response = self.handle_exception(exc) File "E:\!Staj\bookorbooks\env\lib\site-packages\rest_framework\views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "E:\!Staj\bookorbooks\env\lib\site-packages\rest_framework\views.py", line 480, in raise_uncaught_exception raise exc File "E:\!Staj\bookorbooks\env\lib\site-packages\rest_framework\views.py", line … -
How to access a class constant inside class Meta?
class MyClass(models.Model): CONSTANT = "value" ... class Meta: # I want to Access CONSTANT here I know a simple solution of hardcoding the "value" inside class Meta, but is there a way to access the outer class CONSTANT. I tried CONSTANT and MyClass.CONSTANT inside class Meta, but these two ways did not work. -
Django static files not loading properly
I tried to get my project set up with static files and I do not seem to be successful. I want a global static files instead of an in-app one and so my settings.py is STATIC_URL = '/static/' STATICFILES_DIRS =[os.path.join(BASE_DIR, 'static')] STATIC_ROOT = os.path.join(BASE_DIR, 'assets') And as such my directory is The issue I face is that my vendor folders will not load. Only images do and my custom css file. But, even if I change the static folder's name to something else images still load which I find weird as they should not load. -
Facing issue with setting up http only cookie while using react js for frontend and django rest framework for backend
I started building a basic Authentication system with JWT token authentication using rest API and react js. But, I was facing an issue while setting my cookie from the Django views sent using rest_framework.response.Response object. Now, the problem is that in the Django server the cookie is set, but in this case, while integrated with react js it fails. Django server is running on port 8000 and react js on 3000. @api_view(['POST']) def login(request): try: username = request.data['username'] password = request.data['password'] user = authenticate(request=request, username=username, password=password) if user: refresh = RefreshToken.for_user(user) response = Response() response.data = { "status": True, "Access": str(refresh.access_token) } response.set_cookie(key='refreshtoken', value=(refresh), httponly=True) return response else: return Response(FALSE_RESPONSE) except Exception as e: print(e) return Response(FALSE_RESPONSE) This is the axios request, I was making from the frontend side. axios({ method: "POST", url: "http://localhost:8000/user-api/login/", data: { username:username, password:password }, credentials: 'include', withCredentials: true }) .then(response => { console.log(response) if(response.data['status']) { setAccessToken(response.data['Access']) setIsAuthenticated(true) setLoginModal(false) } else { alert("Error! Credentials doesn't match.") } }) .catch(error => { console.log(error) }) This axios request generates no errors and I was successfully getting the token, but the refresh token was not getting saved in the cookies. # settings.py CORS_ALLOWED_ORIGINS = [ "http://localhost:3000", "http://127.0.0.1:3000" ] CORS_ALLOW_CREDENTIALS … -
"detail": "Authentication credentials were not provided." for general views
I have created a custom user model and apply djoser authentication and jwt. But after this when I tried to get request for products views , I get this error ` "detail": "Authentication credentials were not provided." here is the screenshot: here is the product_views.py: from rest_framework.decorators import api_view, permission_classes from rest_framework.permissions import IsAuthenticated, IsAdminUser from rest_framework.response import Response from base.serializers import ProductSerializer ,ProductCategorySerializer from base.models import Product, ProductCatogory, Review from rest_framework import status @api_view(['GET']) def getProducts(request): query = request.query_params.get('keyword') if query is None: query = '' products = Product.objects.filter( name__icontains=query) serializer = ProductSerializer(products, many=True) return Response(serializer.data) @api_view(['POST']) @permission_classes([IsAdminUser]) def createCategory(request): new_category = ProductCatogory.objects.create() new_category.save() return Response('new category created successfully') @api_view(['PUT']) @permission_classes([IsAdminUser]) def editCategory(request, pk): data = request.data category = ProductCatogory.objects.get(id=pk) category.product_category = data['product_category'] category.save() serializer = ProductCategorySerializer(category, many=False) return Response(serializer.data) @api_view(['DELETE']) @permission_classes([IsAdminUser]) def deleteCategory(request, pk): product_Catogory = ProductCatogory.objects.get(id=pk) product_Catogory.delete() return Response('Category is deleted successfully') @api_view(['GET']) def getCategorys(request): product_category = ProductCatogory.objects.all() serializer = ProductCategorySerializer(product_category, many=True) return Response(serializer.data) @api_view(['GET']) def productsByCategory(request,pk): category = ProductCatogory.objects.get(id=pk) products = category.product_set.all() serializer = ProductSerializer(products, many=True) return Response(serializer.data) @api_view(['PUT']) def updateProductCategory(request,pk): data = request.data product_id = data['product_id'] product = Product.objects.get(_id=product_id) category = ProductCatogory.objects.get(id=pk) product.category = category product.save() return Response('category added successfully') @api_view(['GET']) def getTopProducts(request): products = … -
Django model delete method not overriding
I'm currently working on a Django blog app where I have a Post connecting to a Category. The Category has both name and times_used fields. times_used will be incremented by 1 after a Post is created and I have achieved this overriding the save() method on the Post model. I'm trying to override the delete() method to decrement the current post's category by 1 but it's not actually reaching the overridden delete() method it seems, because the category still has the incremented value even after the post got deleted. See my code below... model.py class Category(models.Model): name = models.CharField(max_length=150, unique=True) times_used = models.IntegerField(default=0) class Post(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE) # This increments this category by 1 then saves the post - Works well! def save(self, *args, **kwargs): self.category.times_used += 1 self.category.save() super(Post, self).save(*args, **kwargs) # This decrements this category by 1 then deletes the post - Which is not working... def delete(self, *args, **kwargs): self.category.times_used -= 1 self.category.save() super(Post, self).delete(*args, **kwargs) Any suggestions how to accomplish this? -
DRF: Programmatically get default choice from TextChoices field
Our site is a Vue frontend / DRF backend. In a serializer.validate() method, I need to programmatically determine which option from a TextChoices class has been specified as the default value for a model field. TextChoices class (abbreviated example): class PaymentMethod(models.TextChoices): BANK_TRANSFER = 'Bank Transfer' CREDIT_CARD = 'Credit Card' PAYPAL = 'PayPal' OTHER = 'Other' The model: class InvoicePayment(CommonFieldsModelMixin, StatusFieldModelMixin, models.Model): ...other fields omitted... payment_method = models.TextField( verbose_name=_('Method'), choices=PaymentMethod.choices, default=PaymentMethod.OTHER, ) payment_method_other = models.TextField( verbose_name=_('Payment Method Other'), default='', ) Our users are able to bypass the frontend and post directly to the API, which means they may omit fields from the POST data - either from negligence or because the fields have default values. For the above model, though, payment_method_other is required only if payment_method is "Other". That check is done in the serializer.validate() method. If "Other" is selected on a form in the frontend, there's no problem because that value is present in validated_data passed to the validate() method. But if a user posts directly to the API and omits payment_method, the default value process is done at the database level (more or less), after the validate() method has executed. To keep it DRY, and to avoid having mismatched … -
how to properly do aggregate functions in django ORM for a case where a reference in a table is more than once
I have a table in django. Everytime a user leaves a tip a entry in that table is created. I am trying to create a query that does the following. gets the user reference to the FK user of a user. but only once. So even if there are more than 1 rows with that user FK (because they left more than one tip) I still only want it once. then the total number of tips a user has left. This is why I only want the user FK object once, regardless of how many times it shows in the table. As the total number of tips is to determine the number of tips a user has left. The total dollar amount of all the tips they have left. so if they left a tip of $5 $15 $ 25 the total amount in this field would be $45 Here is my query set and my serializer and my payload. the shochattotalminutes and totalmoney are unrelated to this question. userlist = ShoChatEntityShoChatTips.objects.annotate( numberofshochats=Count('user')).annotate(totaltips=Sum('tipamount')).filter(shochatentity= shochatentity).order_by('totaltips') serializeduserlist = ContentCreatorTopTippersSerializer(userlist, many=True) payload = { 'userList': serializeduserlist.data, 'shochattotalminutes': shochattotalminutes, 'totalmoney': totalmoney } return Response(payload) however please notice the output in the screen shot below. … -
How to access one to many field on django admin page
I make a table with one to many relationship (One Customer can have many Order). How to make one to many field so we can access it on django admin page? My code: class Customer(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) # How can i make and show this field in admin site? # order = This is field which contains all customer order class Order(models.Model): customer = models.ForeignKey(Customer, on_delete=models.CASCADE) I've been trying to find the answer but mostly the answer is using prefetch_related and show it on template or view. How can i see it on admin site? Thank you. -
Add custom logic in CreateView to not show the add form if a condition is met
How do I add custom logic in a class based view ? urls.py: path('books/add', views.AddBook.as_view(), name='add_book'), models.py class Book(models.Model): title = models.CharField(max_length=255) summary = models.TextField(max_length=2048) created = models.DateTimeField(auto_now_add=True) user = models.ForeignKey(User, on_delete=models.CASCADE) views.py MAX_BOOKS = 5 class AddBook(LoginRequiredMixin, generic.CreateView): model = Book """ if user has reached MAX_BOOKS books = Book.objects.filter(user=request.user) if len(books) == MAX_BOOKS template_name = 'books/restrict_book.html' and send in some data like { 'error_msg': 'You cannot add further books' } """ form_class = BookForm # fields = ['title'] template_name = 'books/add_book.html' success_url = reverse_lazy('dashboard') def form_valid(self, form): form.instance.user = self.request.user super(AddBook, self).form_valid(form) return redirect('dashboard') -
upload contacts from iphone/mac to django app
I am trying to understand if there is a way to upload/sync all my contacts on the contacts app of my mac/iphone with my django app. Any help? -
Forms not working as expected. After submitting, it just refresh a same page of form to me
Im facing a issue where the my input data is not pass on at all in python django code. Im doing a simple testing from the lots of other task I have to put in the code but it is not printing valid on my powershell. My code are: views.py: def device_add(request): if request.method == "POST": device_frm = DeviceForm(request.POST) if device_frm.is_valid(): print("valid") #return render(request, 'interface/device_display.html',{'devices':devices}) #dd_frm = DeviceDetailForm(request.POST) #di_frm = DeviceInterfaceForm(request.POST) #if dd_frm.is_valid() and di_frm.is_valid(): #if dd_frm.is_valid(): #dd_frm.save() #devicedetail = dd_frm.save(commit=False) #devicedetail.save() #dd_frm.save_m2m() #deviceinterface = di_frm.save(commit=False) #deviceinterface.hostname = devicedetail.hostname #deviceinterface.save() else: device_frm = DeviceForm() return render(request, 'interface/device_add.html',{'form':device_frm} ) #dd_frm = DeviceDetailForm() #di_frm = DeviceInterfaceForm() #context = {'dd_frm':dd_frm, 'di_frm':di_frm, 'title':'Device Add'} return render(request, 'interface/device_add.html',{'form':device_frm}) In forms.py class DeviceForm(ModelForm): class Meta: model= Device fields= '__all__' In models.py class Device(models.Model): hostname = models.CharField(max_length=50) ipaddr = models.CharField(max_length=15) date_added = models.DateTimeField(default=timezone.now) #date_updated = models.DateTimeField(auto_new=True) #created_by = models.ForeignKey(User, on_detele=models.CASCADE) #updated_by = models.ForeignKey(User, on_detele=models.CASCADE) def __str__(self): return self.hostname -
Which is a better way to enforce OneToOne Relationship in Django?
Were wondering which would be the effective way to enforce OneToOne relationship in Django. Here is what we have encountered and wanted opinion. class Address(models.Model): phone = models.OneToOneField(Phone, related_name='phoneNumber') class Phone (models.Model): phone = models.PositiveIntegerField(min_length=9) the other was using ForeignKey with unique_together - class Phone(models.Model): address = models.ForeignKey(Address, related_name='phoneAddress',on_delete=models.CASCADE) phone = models.PositiveIntegerField(min_length=9) class Meta: unique_together = ['phone','address',] or by creating a Subclass - class Address(models.Model): .... class Phone (Address): phone = models.PositiveIntegerField(min_length=9) your expertise and insights appreciated. Cheers! -
Django: Even after setting AUTH_USER_MODEL = 'custom_user.User' I get clashes with reverse accessor
I have added a custom_user app to my project and in that I have a model User which extends the AbstractUser model the models.py from django.db import models # Create your models here. from django.contrib.auth.models import AbstractUser class User(AbstractUser): pass I have also AUTH_USER_MODEL = 'custom_user.User' in the settings.py file and also added the app in the INSTALLED_APPS. INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'custom_user' ] Still when I run the server I get ERRORS: auth.User.groups: (fields.E304) Reverse accessor for 'User.groups' clashes with reverse accessor for 'User.groups'. HINT: Add or change a related_name argument to the definition for 'User.groups' or 'User.groups'. auth.User.user_permissions: (fields.E304) Reverse accessor for 'User.user_permissions' clashes with reverse accessor for 'User.user_permissions'. HINT: Add or change a related_name argument to the definition for 'User.user_permissions' or 'User.user_permissions'. custom_user.User.groups: (fields.E304) Reverse accessor for 'User.groups' clashes with reverse accessor for 'User.groups'. HINT: Add or change a related_name argument to the definition for 'User.groups' or 'User.groups'. custom_user.User.user_permissions: (fields.E304) Reverse accessor for 'User.user_permissions' clashes with reverse accessor for 'User.user_permissions'. HINT: Add or change a related_name argument to the definition for 'User.user_permissions' or 'User.user_permissions'. What is the mistake I am doing