Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Page Number in Django Template
Here is a Django template. {% for balance in balances %} {{ balance.amount }} {% endfor %} {% for price in price %} {{ price.amount}} {% endfor %} I would like to show multiple values in Django template like one after another. I also need to print the page number. For example, 1,2,3,4 page for balance and 5,6,7 is used for the price. So is there any way I can print it? -
how to make group join and leave functionality in Django?
def join_group(request,pk): group = Room.objects.get(id=pk) group.members.add(request.user) return redirect('home') urls.py path('create_group', views.create_group, name="create-group"), path('group/<str:pk>', views.group, name="group"), path('join_group/<str:pk>', views.join_group, name="join_group"), feed.html <a href="{% url 'join_group' group.id %}"> <p class="roomListRoom__topic"> Join </p> </a> I have group in my app. I wanted to make join and leave functionality. Join functionality is working properly but i want to make when ever anyone clicks on (join) then he should be redirected to that particular group when i change return redirect to ' return redirect ('group/' + str(pk)) ' then i am getting url like 127.0.0.1:8000/join_group/group/8..... and i want to make that if the user is joined to group then there should be joined instead of join and join for other users. - using if statement and i want to make leave functionality: please help me to get out of these problems.. if you need more info .. i am ready thank you in advance!!! -
Django 4 Giant Enormous Bug Report
Bug description: Page A is accessed directly, Click something on page A goes to page B, Press back button back to Page A, And simple html elements on Page A will stop working with Safari. The website link live: https://howtoback.com/ Django 3 no such bug Days of work to find the bug, Please fix in the upcoming Django releases. -
django no module named 'settings'
i inherited a python project where django is used. for my devs, i needed the transaction module of django. so i went to 'P:\file\ourLibrary\server\config\settings.py' and updated the **DATABASES = { 'default': { filled infos }** then in Powershell i set the ENV_VARIABLE DJANGO_SETTINGS_MODULE to the path specified before i then tried to use the function that uses the @transaction.atomic but i had the folowing error > You must either define the **environment variable > DJANGO_SETTINGS_MODULE** or call **settings.configure()** before > accessing settings. which i don't understand because i already setted it. i found various posts in StackOverflow that suggest to use import os os.environ.setdefault('DJANGO_SETTINGS_MODULE','P:\file\ourLibrary\server\config\settings') but now when i use the @transaction function i got ModuleNotFoundError: No module named **'P:\file\ourLibrary\server\config\settings'** what am i doing wrong here? thank you for your help, -
Django - How to make a model that when an instance of this model is created, that data is saved to a page that is unique to a user
I'm making a website where you can post jobs to an 'explore page', and I was then wondering how I would go about making it so that when a job is posted to that 'explore page', that job will also be posted to a page where the person who posted the job can manage all of the jobs they have posted i.e. edit, delete. I can post jobs to the explore page but I need to find a way for the job to save to the 'employers' page views.py from django.shortcuts import render, redirect from django.contrib.auth.decorators import login_required from base.forms import JobForm @login_required(login_url='login') def manage_jobs(request): if request.user.is_employee: return redirect('home') else: form = JobForm(request.POST) if form.is_valid(): form.save() context = {"form":form} return render(request, 'employer/manage-jobs.html', context) urls.py from django.urls import path from . import views urlpatterns = [ path('', views.manage_jobs, name='manage-jobs'), ] models.py class Job(models.Model): company = models.CharField(max_length=40, null=True, verbose_name="Company/Employer") description = models.TextField(null=True) role = models.CharField(max_length=25) area_of_filming = models.CharField(max_length=50, verbose_name="Area Of Filming", default="") contact_email = models.EmailField(verbose_name='Contact Email', max_length=60, default='') created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.company class Account(AbstractBaseUser): email = models.EmailField(verbose_name='email', max_length=60, unique=True) name = models.CharField(max_length=45, unique=False) date_joined = models.DateTimeField(verbose_name='date joined', auto_now_add=True) last_login = models.DateTimeField(verbose_name='last login', auto_now=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) … -
Django - static files not showing inside sources tab
In my folder of static files i have two images, a javascript file and a css file but when i look inside the browsers sources tab one of my images like_icon_LIKED.png does not appear. This causes errors in my javascript file when trying to change the images src path as the image cannot be found. No idea why this is happening -
how to add file path in django project
I am making an online judge in Django. I am taking user code in a file and then compile it and running it and giving the verdict. for example let say a user submitted code in c++ language so I am taking that code in a .cpp file and compile it and running it and I am doing it by giving the absolute path of my .cpp file like E:\online_judge_project\oj\language\forcpp.cpp my problem is that when I will deploy my project it will cause error because this paths are my local machine path and I can't use that in deployment so how will I access the files( like .cpp file) after the deployment. Although those files are in my project directory only and I kept them in a folder name language. my project directory structure is like: I am thinking of using os.join.path() but I am not getting how to do that. -
How can i auto increment and shorten a string as textfield?
im currently trying to do a project management app and i need to autoincrement project count and add shortened string from department. For example if Product Development add a project to site i need to show in table like this PD_1 -
profile shape not partially saved
After the first registration, it transfers to a new form - you can enter a profile email, photo, bio, links to twitter, github and other social networks, 2 models participate: ProfileUser and User. When a person wrote what he wanted and pressed the button, after the transition he clicked on the user and then he was thrown to the profile page, but there, apart from the mail, nothing from the previously entered is shown, when trying to change the profile, nothing is shown either, there is nothing in the form, I went in the admin panel in the model, only the user is also set automatically when switching to creating a profile after registration, other data is simply not entered, please tell me how to fix it The user appears to me because this is in the registration profile = ProfileUser.objects.create(user=new_user) I tried to redo it according to this article did not work models.py class ProfileUser(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True) img = models.ImageField(null=True, blank=True, upload_to='static/images/', validators=[img__size]) birthday = models.DateField(blank=True, null=True) about = models.TextField(max_length=1000, null=True) #? social media twitter = models.URLField(null=True, blank=True) facebook = models.URLField(null=True, blank=True) instagram = models.URLField(null=True, blank=True) telegram = models.URLField(null=True, blank=True) vk = models.URLField(null=True, blank=True) reddit = … -
pytest-django Use env vars in settings.py
I have an api in Django that uses quite a few environment variables. The idea is to add pytest-django to test all its functionalities (I know it would have been smarter to build the tests together with the project). Currently it is in the manage.py file where I load the environment variables as follows: def main(): dotenv.read_dotenv() And in my api settings.py file I use some of these environment variables as follows: os.environ.get('one_key') In my pytest.ini file I have correctly configured my settings.py as follows: DJANGO_SETTINGS_MODULE = api.settings The problem is that when I run pytest I get the error that it does not find those environment variables, because the manage.py has not been executed and therefore these have not been loaded. Is there any way to make pytest load an .env before running the tests and the settings.py? -
Why doesn't css styles apply to html correctly in django?
Only body styling work in django, I use static files to get css. I tried even commenting out body part css, but it still works, I don't know how, I don't know why, please help! (I've used collectstatic, so it's not because of that). I've inserted static_root and url and other things in setting to, but it didn't help either. body{ max-width: 1080px; margin: auto; background: #8D7D77; font-family:'Gill Sans', 'Gill Sans MT', Calibri, 'Trebuchet MS', sans-serif; } /* ----------------------------------------------NAV-BAR-UPPER------------------------------------------ */ .nav-bar{ display: flex; flex-direction: row; padding-top: 20px; } .nav-bar img{ max-width: 150px; margin-left: 20px; } .nav-bar ul{ list-style: none; display: flex; flex-direction: row; } .nav-bar ul li{ margin-right: 15px; } .nav-bar ul a{ text-decoration: none; color: white; font-size: 20px; margin-left: 80px; padding: 10px 20px 10px 20px; border: solid 1px; border-radius: 10px; } .nav-bar ul a:hover{ text-decoration: none; color: #8D7D77; background-color: white; } .search-bar{ width: 600px; height: 40px; margin-top: 10px; margin-left: 50px; border-radius: 5px; border-width: 1px; border-color: #C2B280; font-size: 110%; } .search-bar:focus{ border-style:none; } {% load static %} <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <link rel="stylesheet" href="{% static 'styles/main.css' %}" /> <link rel="icon" href="{% static 'images/logomogo.png' %}" /> <title>BookShelf</title> </head> <body> {% … -
how to set object admin moderation in drf
I am using python 3.8 and django 4.0.6 + drf 3.13.1 There are models class Profile(models.Model): user='US' manufacturer = 'MA' admin='AD' choice=[ (user, 'User'), (manufacturer, 'Manufacturer'), (admin, 'Admin') ] user_company = models.CharField(max_length=2, choices=choice) user = models.OneToOneField(User, on_delete=models.CASCADE) last_request = models.JSONField(null=True) class ProfileCompany(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) company = models.OneToOneField('Company', on_delete=models.CASCADE) classCompany(models.Model): id_company = models.IntegerField(null=True, unique=True) Company = models.CharField(max_length=128) Direction = models.CharField(max_length=512, blank=True) Description = models.TextField(null=True, blank=True) Categories = ArrayField(base_field=models.CharField(max_length=128), null=True, blank=True) Products = ArrayField(base_field=models.CharField(max_length=128), null=True, blank=True) Serializer class CompanySerializer(serializers.ModelSerializer): class Meta: model=Company fields = '__all__' The task is to make the pre-moderation of the creation and updating of companies by the admin. Manufacturer creates a new company or updates data in it, this data is not visible to all users, but only to the admin. The admin accepts or rejects this data with a comment (in this case, the Manufacturer receives a message with this comment, corrects the data and sends the data again for moderation) I could not connect django-moderation, because it is not suitable for REST. Are there ready-made libraries or solutions? -
Size not being displayed on productdetails page
I am doing CRUD using serializers and foreign keys and I have made a product details page which shows the details of the product that I have clicked. The problem is that the Size(SM,M,L,XL,XXL) itself isn't coming but the id is coming as shown below below is the 'productdetails' function <tr> <td>{{data.id}}</td> <td>{{data.title}}</td> <td>{{data.price}}</td> <td>{{data.sku_number}}</td> <td>{{data.product_details}}</td> <td>{{data.size}}</td> <td>{{data.quantity}}</td> <td><img src="{{data.image}}" alt="product image" width="400" height="400"></td> </tr> productdetails function def productdetails(request,id): prod = Products.objects.get(id=id) product = POLLSerializer(prod) return render(request,'polls/productdetails.html',{'data':product.data}) model class Products(models.Model): categories = models.ForeignKey(Categories,on_delete=models.CASCADE) sub_categories = models.ForeignKey(SUBCategories,on_delete=models.CASCADE) color = models.ForeignKey(Colors,on_delete=models.CASCADE) size = models.ForeignKey(Size,on_delete=models.CASCADE) image = models.ImageField(upload_to = 'media/',width_field=None,height_field=None,null=True) title = models.CharField(max_length=70) price = models.CharField(max_length=10) sku_number = models.CharField(max_length=10) product_details = models.CharField(max_length=1000) quantity = models.IntegerField(default=0) isactive = models.BooleanField(default=True) Help is greatly appreciated,thanks! -
"Page not found error" after enabling Login required (CMS_Permission)
I would like to password protect a page on my website. For this I set CMS_PERMISSION = True in settings.py. And under Page > Permission I checked login required. The following error appeared when I tried to visit the page: Page not found (404) Request Method: GET Request URL: http://localhost:8000/en/accounts/login/?next=/en/private/ Raised by: cms.views.details Using the URLconf defined in backend.urls, Django tried these URL patterns, in this order: en/ ^jsi18n/$ [name='javascript-catalog'] ^static/(?P<path>.*)$ en/ ^admin/ en/ ^ ^blog-content/\Z [name='posts-latest'] en/ ^ ^blog-content/feed/\Z [name='posts-latest-feed'] en/ ^ ^blog-content/feed/fb/\Z [name='posts-latest-feed-fb'] en/ ^ ^blog-content/(?P<year>[0-9]+)/\Z [name='posts-archive'] en/ ^ ^blog-content/(?P<year>[0-9]+)/(?P<month>[0-9]+)/\Z [name='posts-archive'] en/ ^ ^blog-content/author/(?P<username>[^/]+)/\Z [name='posts-author'] en/ ^ ^blog-content/category/(?P<category>[^/]+)/\Z [name='posts-category'] en/ ^ ^blog-content/tag/(?P<tag>[-a-zA-Z0-9_]+)/\Z [name='posts-tagged'] en/ ^ ^blog-content/tag/(?P<tag>[-a-zA-Z0-9_]+)/feed/\Z [name='posts-tagged-feed'] en/ ^ ^blog-content/(?P<year>[0-9]+)/(?P<month>[0-9]+)/(?P<day>[0-9]+)/(?P<slug>[^/]+)/\Z [name='post-detail'] en/ ^ ^blog-content/(?P<year>[0-9]+)/(?P<month>[0-9]+)/(?P<slug>[^/]+)/\Z [name='post-detail'] en/ ^ ^blog-content/(?P<category>[^/]+)/(?P<slug>[^/]+)/\Z [name='post-detail'] en/ ^ ^blog-content/(?P<slug>[^/]+)/\Z [name='post-detail'] en/ ^ ^cms_login/$ [name='cms_login'] en/ ^ ^cms_wizard/ en/ ^ ^(?P<slug>[0-9A-Za-z-_.//]+)/$ [name='pages-details-by-slug'] en/ ^ ^$ [name='pages-root'] en/ ^sitemap\.xml$ en/ ^taggit_autosuggest/ en/ ^filer/ The current path, /en/accounts/login/, didn’t match any of these. My urls.py looks like this: from django.conf.urls.i18n import i18n_patterns from django.contrib import admin from django.contrib.staticfiles.urls import staticfiles_urlpatterns from django.urls import include, re_path, path from django.views.i18n import JavaScriptCatalog from django.contrib.sitemaps.views import sitemap from cms.sitemaps import CMSSitemap from djangocms_blog.sitemaps import BlogSitemap urlpatterns = i18n_patterns( re_path(r'^jsi18n/$', JavaScriptCatalog.as_view(), name='javascript-catalog'), … -
How To Hide Form Fields When A Particular Type Of Product Is Selected Django
Please I have a project where I want to hide some fields in a form when the category selected belongs to a particular product type. The type of products is Single and Bundle products. So for instance, if I choose something like pens(Bundle) in the form category I should only see quantity in the form fields but if I select something like Desk(single) all fields should be available to fill. How do I implement this in Django? Thank you My Model TYPE =(('Single', 'Single'),('Bundle','Bundle')) class Category(models.Model): name = models.CharField(max_length=50, blank=True, null=True) pro_type = models.CharField(max_length=50, choices=TYPE, null=True) timestamp = models.DateTimeField(auto_now_add=False, auto_now=True, null=True) def __str__(self): return f'{self.name}' class Product(models.Model): pro_name = models.CharField(max_length=100, blank=True, null=True) category = models.ForeignKey(Category, on_delete=models.CASCADE, blank=True, null=True) quantity = models.IntegerField(default='0', blank=True, null=True) issue_to = models.ForeignKey('Order',default='', on_delete=models.CASCADE,blank=True, null=True) serial_num = models.CharField(max_length=100, blank=True, null=True) model_num = models.CharField(max_length=100, blank=True, null=True) storage_size = models.CharField(max_length=50, blank=True, null=True) My views def add_products(request): form = ProductCreateForm(request.POST) if request.method == 'POST': if form.is_valid(): obj = form.save(commit=False) obj.staff = request.user obj.save() return redirect('dashboard-products') else: form = ProductCreateForm() context = { 'form': form, } -
Show image next to text using CSS/Bootstrap
i want to show image next to text. But its showing below it Here is the code <div class="container"> <div class="row"> <div class="col-md-8"> <h1>This is my first post</h1> <div> <p><strong>Lorem Ipsum</strong> is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry&#39;s standard … </div> <div class="col-md-4"> <img src="/media/post/Screenshot_from_2022-07-17_23-55-13.png" class="img-thumbnail" > </div> <div><a href="/blog/first-post" >Read More..</a></div> <div class="col-md-8"> <h1>this is second post</h1> <div> <p><strong>Lorem Ipsum</strong> is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry&#39;s standard … </div> <div class="col-md-4"> <img src="/media/post/0a61bddab956.png" class="img-thumbnail" > </div> <div><a href="/blog/2nd-post" >Read More..</a></div> </div> </div> This is how it look like EDIT. I copied this from view-source and some text is cut off there. Actually i am using Django jina 2 template code {% for post in context %} <div class="col-md-8"> <h1>{{ post.title}}</h1> {{ post.content |truncatewords:20 | safe}} </div> <div class="col-md-4"> <img src="/media/{{post.image}}" class="img-thumbnail" > </div> <div><a href="/blog/{{post.slug}}" >Read More..</a></div> {% endfor %} Here is base.html file code <div class="container"> <div class="row"> {%block content %} {%endblock%} </div> </div> -
How to deploy django app on some other local network?
So i've created a django app and i've tested on my local network. Now i want to run this app on some others (customers) local network. I can't run the whole project in their customers computer. What all do i need to do? Please explain briefly. -
Django Taggit adding a list of tags to tag field by post save method
i am using Django Taggit 3.0.0 with python 3.10.5 and django 4.0.6 adding a list of tags to tag field by post save method i tried below codes which works well no error at all but the tags list is not assigned to the resource ragfield but it is getting listed in admin pannel tags model table. and i also want to add initial tags to each tagfield Model class resource(models.Model): title=models.CharField(max_length=100) size=models.CharField( max_length=20, default="") desc=models.TextField(default="") file=models.FileField(default="", blank=True) url= models.URLField(max_length=200, blank=True) Brand = models.ForeignKey(brand,on_delete=models.CASCADE, default="") Model = models.ForeignKey(model,on_delete=models.CASCADE, default="") Categories = models.ForeignKey(category,on_delete=models.CASCADE, default="") update_at=models.DateField(auto_now=True) slug=models.SlugField(default="") Tags = TaggableManager() def tag_set(sender, instance,*arg, **kwargs): ans= array_tag(instance) # print(ans) mylist = ["firmware", "download", "gsm"] instance.title='check' instance.Tags.add(*ans) post_save.connect(tag_set, sender=resource) def array_tag(instance): return [instance.title ,instance.desc,instance.size, instance.Brand.title ,instance.Model.title ,instance.Categories.title] -
Run pytest test case in thread isolation
I want to test a function wich uses thread_local variable i.e. threading.local().setattr() and threading.local().getattr() When I run my single test case it passes since it is only test using the thread but when I run pytest in the project which runs all tests in the project, it looks like other test cases are reusing the same thread and my thread_local variable is getting overwritten, Is there a simple way to keep my test case independent from other tests, either by running in a separate thread or locking thread while this test is running(less preferable solution, in this case, I'd rather delete this test case) -
Convert Image file to Base64 and store in database using django rest framework
I am trying to upload an image file and to save it as base64 in PostgreSQL using Django Rest Framework. My files are as follows: **Models.py:** from django.db import models import base64 class MyImageModel(models.Model): image_file = models.ImageField( upload_to="photos/", max_length=6000, null = True) def save(self, *args, **kwargs): if self.image_file: file = str(self.image_file) image = open(file, 'rb') image_read = image.read() self.image_64_encode = base64.encodebytes(image_read) print('This is the image in base64: ' + str(self.image_64_encode)) super(MyImageModel, self).save(*args, **kwargs) **serializers.py:** from django.forms import ImageField from drf_extra_fields.fields import Base64ImageField from .models import * from rest_framework import serializers class MyImageModelSerializer(serializers.ModelSerializer): image_file = serializers.ImageField class Meta: model = MyImageModel fields = ('image_file',) **Views.py:** from .models import * from rest_framework import status from rest_framework.views import APIView from rest_framework.response import Response import base64 from imagebase64app.serializers import MyImageModelSerializer # Create your views here. class AddImageView(APIView): def post(self, request, format=None): serializer = MyImageModelSerializer(data = request.data) if serializer.is_valid(raise_exception=True): serializer.save() return Response({'message':'Registered Successfully!'},status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) -
How to set current active user as author field to the Article model?
I have many users who can add articles from Django Admin Panel. I want the author field must be assigned to the user who is currently login. I know we can achieve it through request.user. I want to achieve the same in the Article model's save() method. class Article(models.Model): author = models.ForeignKey(CustomUser,on_delete=models.CASCADE) def save(self, *args, **kwargs): self.author = ? super(Article, self).save(*args, **kwargs) -
How to enable and configure https and get a ssl/tls certificate for a nginx/docker-compose/django site, for a .dev domain
I'd like to set up a ssl/tls certificate so that I can navigate to my site through the .dev domain I have. I don't really know the best direction to head in to enable https for my .dev domain (https://en.wikipedia.org/wiki/.dev). I figured out http won't work because .dev domains are preloaded on a http strict transport security (hsts) list (https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Strict-Transport-Security). I was thinking of going through this tutorial (https://testdriven.io/blog/django-lets-encrypt/) but I don't know if there are easier ways since my project is set up a little differently and I'm not sure what all I'd have to change to make it work. I can currently reach my site through its ipv4 public address but ipv6 is enabled. My domain is through google domains and as far as I can tell the custom records are correct, I just need the certificate working. What should I do/change to enable https? It's a Django/Wagtail site with 3 containers: nginx, web, and db. /app/docker-compose.prod.yml: version: "3.7" services: nginx: build: context: . dockerfile: ./compose/production/nginx/Dockerfile volumes: - staticfiles:/app/static - mediafiles:/app/media ports: - 80:80 - 443:443 depends_on: - web web: build: context: . dockerfile: ./compose/production/web/Dockerfile image: wagtail_bootstrap_blog_prod_web command: /start volumes: - staticfiles:/app/static - mediafiles:/app/media env_file: - ./.env/.prod depends_on: … -
Error while saving foreign key data in database using Django Model Form
I have two Models for my Project, 1. Category Model and 2. Course Model Course Model has a Foreign Key reference with my Category Model as shown below. class Category(models.Model): categoryname = models.CharField(max_length=200,null=True,blank=True, default="") class Courses(models.Model): coursename = models.CharField(max_length=200,null=True,blank=True, default="") course_category = models.ForeignKey(Category, related_name="courses", blank=True,null=True,on_delete=models.CASCADE) logo = models.ImageField(upload_to='courselogos', null=True, blank=True) Initially I was using HTML form and will be able to save the Course data under a Particular Category to the database as: def add_course(request): if request.method == 'POST': course_name = request.POST.get('coursname') categoryid = request.POST.get('category_id') category = Category.object.get(id=category_id) course_logo = request.FILES.get('logo') course = Courses(coursename=course_name, course_category=category, logo= course_logo) course.save() return redirect('/all_category') Later I decided to move on using Django Model forms and I tried to implement the code as follows class AddCourseForm(forms.ModelForm): class Meta: model = Courses fields = ('coursename', 'course_category', 'logo') widgets = { 'coursename' : forms.TextInput(attrs={'class':'form-control'}), } def __init__(self, *args, **kwargs): category_id = kwargs.pop('category_id',1) super(AddCourseForm, self).__init__(*args, **kwargs) self.fields['course_category']=forms.ModelChoiceField(widget=forms.TextInput(), queryset=Category.objects.filter(id=category_id)) Later in the view I have saved the data as def add_course(request): if request.method == 'POST': addcourse = AddCourseForm(request.POST, request.FILES) if addcourse.is_valid(): addcourse.save() return redirect('/all_category') On my HTML page I am passing the input to the 'course_category' inputfield as 1,2,3....etc as the category_id value I have rendered the field in … -
Import data from CSV file with many to many fields in Python
I would like to be able to import data into my database from a CSV file thanks to the Pandas library, I succeeded for some model data but when the model fields are in many to many I can't. Here is the model whose data I would like to import: class LnkPlantPlant(models.Model): class MAGNET_CHOICES(models.TextChoices): NONE = None IDEAL = 'ideal', GOOD = 'good', MEDIOCRE = 'mediocre', BAD = 'bad' custom_id = models.IntegerField(primary_key=True, unique=True) plant = models.ManyToManyField('perma_plants.Plant', related_name='%(class)s_plant') plant_associated = models.ManyToManyField('perma_plants.Plant', related_name='%(class)s_plant_associated') link = models.CharField(max_length=10, choices=MAGNET_CHOICES.choices, default=MAGNET_CHOICES.NONE, blank=True, null=True) description = RichTextField(max_length=255, blank=True, null=True) Here the model of the plant: class Plant(models.Model): name = models.CharField(max_length=150) def __str__(self): return self.name Here, is my function which allows to import data into the database but I would like to be able to import the name of the many to many fields of the plant and the plant_associated: class UploadLinkPlantData(generics.CreateAPIView): serializer_class = FileUploadSerializer def post(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) file = serializer.validated_data['file'] reader = pd.read_csv(file) for _, row in reader.iterrows(): LnkPlantPlant.objects.update_or_create( custom_id=row['Custom Id'], defaults={ "custom_id": row['Custom Id'], "plant": Plant.objects.get(name=row['Plant']), # doesn't work "plant_associated": Plant.objects.get(name=row['Plant associated']), # doesn't work "link": row['Link'], "description": row['Description'] }) return Response({"status": "Succès : plante(s) crée(s) ou mise(s) à … -
"detail": "Method \"POST\" not allowed." django rest framework
I am new to django so having issues with it. Post method is not allowed. I have shared below both views.py and urls.py. Please help me out with it. views.py from django.shortcuts import render from rest_framework import viewsets,generics from user.serializer import UserSerializer,RetailerSerializer,ProductSerializer,Order_ItemsSerializer,Payment_DetailsSerializer,Order_DetailsSerializer from user.models import User,Retailer,Product,Order_Items,Payment_Details,Order_Details from product.models import Cart,Shipping_Address,Track_Repairs,NFT_Details from product.serializer import CartSerializer,Shipping_AddressSerializer,Track_RepairsSerializer,NFT_DetailsSerializer class AddProduct(generics.CreateAPIView): queryset = Product.objects.all() serializer_class = ProductSerializer class Product_List(viewsets.ModelViewSet): queryset = Product.objects.all().order_by('name') serializer_class = ProductSerializer class Product_Detail(generics.RetrieveAPIView): queryset = Product.objects.all().order_by('name') serializer_class = ProductSerializer urls.py from django.urls import path,include from . import views from rest_framework import routers router = routers.DefaultRouter() router.register(r'',views.Product_List) urlpatterns = [ path('product/',include(router.urls)), path('product/<int:pk>/',views.Product_Detail.as_view()), path("product/add/", views.AddProduct.as_view()), ]