Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to combine two querysets from two models? Django Rest Framework
I have two models class Answer(models.Model): answer = models.TextField() created_at = models.DateTimeField(editable=False, default=timezone.now) updated_at = models.DateTimeField(default=timezone.now) user = models.ForeignKey('users.CustomUser', on_delete=models.PROTECT) question = models.ForeignKey('Question', on_delete=models.PROTECT) number_of_points = models.IntegerField(default=0) moderate_status = models.BooleanField(default=False) and class Question(models.Model): question_subject = models.TextField() question_text = models.TextField(default=None, null=True, blank=True) slug = models.SlugField(max_length=128, unique=True, null=False, editable=False) created_at = models.DateTimeField(editable=False, default=timezone.now) updated_at = models.DateTimeField(default=timezone.now) user = models.ForeignKey('users.CustomUser', on_delete=models.PROTECT) animal = models.ForeignKey('animals.Animal', on_delete=models.PROTECT) serializers.py class QuestionDetailSerializer(serializers.ModelSerializer): answers = serializers.PrimaryKeyRelatedField(many=True, read_only=True) class Meta: model = Question fields = '__all__' views.py class QuestionsDetailView(generics.ListAPIView): queryset = Question.objects.all() serializer_class = QuestionsSerializer def get_queryset(self): return super().get_queryset().filter( id=self.kwargs['pk'] ) url.py path('questions/<int:pk>', QuestionsDetailView.as_view()), And i want to combine 2 queryset, one being already that filters the question by pk provided in the url, and the other queryset i'd like to give is Answer.objects.all().filter(question__id='pk'). Essentially i want to show all the questions with answers to a particular question. -
How do I auto create pages for each element with Wagtail?
I'm learning Wagtail, and I'm struggling to understand auto page creation. Say I have a website where users can fill a form to become a "fan". I have a page where all the fan names are listed, e.g. fanlist = Fan.objects.order_by( "-timestamp") When a user submits the form and becomes a fan, they are added to the page with the fan list. Now I want to be able to create a page for each fan, so that the names in the fan list page link to a page for that specific fan. How can I do this programmatically and dynamically, so that each time a new fan signs up, the websites auto creates a page for this fan? -
How to execute custom function when I'm clicking on object in django admin?
I want to create function, that will be execute every time when Admin click on this object in Django Admin. Do you have some ideas? My function is trivial, I have just override save, but I want to execute this function without saving object: def save(self, *args, **kwargs): if self.corp_goal: print('We have corporate goal!') for i in self.corp_goal.all(): if i.corp_factor_rate: print('we have rated goal!') print('Corporate goal {} : factor {}'.format(i.corp_goal_title, i.corp_factor_rate * i.corp_factor_weight)) else: print('we dont have rated goal') else: print('we dont have asigned goals') -
Django edit the owner of Object
When an object is called via URL, I want to change the owner(user) of the object. The owner in my case is a ForeignKey. I tried it with something like this, which of course doesn't work def ChangeField(request, title_id): user_title = Field.objects.filter(id=title_id, user=request.user) if user_title: user_title.user = 'Admin' user_title.save() else: return redirect('https://example.com') return HttpResponseRedirect('/another') When the user of object ID 11 for example calls the URL /11, I want to change the owner of object 11 to the superuser, I mey case the superuser is called 'Admin' Models File class Field(models.Model): user = models.ForeignKey( settings.AUTH_USER_MODEL, default=None, null=True, on_delete=models.CASCADE, ) .... -
Serving user uploaded images in development
I have a Profile model that should allow a user to upload a profile image. In the browser the form where I allow a user to edit their profile displays the "Browse Images" input field, but upon submission the image is not saved and no "media/" directory is created, though the rest of the fields update properly. models.py: from django.db import models from django.contrib.auth.models import User from django.conf import settings class Profile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) date_of_birth = models.DateField(blank=True, null = True) photo = models.ImageField(upload_to='users/%Y/%m/%d/', blank = True) forms.py: from django import forms from django.contrib.auth.models import User from .models import Profile class UserEditForm(forms.ModelForm): class Meta: model = User fields = ('username', 'first_name', 'last_name', 'email') class ProfileForm(forms.ModelForm): class Meta: model = Profile fields = ('date_of_birth', 'photo') views.py: from django.shortcuts import render from .forms import UserEditForm, ProfileForm def edit(request): if request.method == 'POST': user_edit_form = UserEditForm(request.POST, instance=request.user) profile_edit_form = ProfileForm(data = request.POST,files = request.FILES, instance=request.user.profile) if user_edit_form.is_valid() and profile_edit_form.is_valid(): user_edit_form.save() profile_edit_form.save() else: user_edit_form = UserEditForm(instance = request.user) profile_edit_form = ProfileForm(instance = request.user.profile) return render(request, 'account/edit.html', {'user_edit_form':user_edit_form, 'profile_edit_form': profile_edit_form}) the template: <h2>Edit Your Profile</h2> <form class="" action="." method="post"> {{user_edit_form.as_p}} {{profile_edit_form.as_p}} {% csrf_token %} <input type="submit" name="" value="Change Profile"> </form> as for image specific … -
How to access a field inside a nested Serializer and make post request work?
I am working on a POST request where first a Tag is saved and then a Tagging - these are text labels relating to a picture (Resource). These are the two serializers: serializers.py class TagSerializer(serializers.ModelSerializer): class Meta: model = Tag fields = ('name', 'language') def create(self, validated_data): tag_data = validated_data.pop('tag') Tag.objects.create(**tag_data) return tag_data def to_representation(self, data): data = super().to_representation(data) return data class TaggingSerializer(serializers.ModelSerializer): tag_id = serializers.PrimaryKeyRelatedField(queryset=Tag.objects.all(), required=False, source='tag', write_only=False) # tag = TagSerializer(required=False, write_only=False).data.get('name') resource_id = serializers.PrimaryKeyRelatedField(queryset=Resource.objects.all(), required=True, source='resource', write_only=False) gameround_id = serializers.PrimaryKeyRelatedField(queryset=Gameround.objects.all(), required=False, source='gameround', write_only=False) user_id = serializers.PrimaryKeyRelatedField(queryset=CustomUser.objects.all(), required=False, source='user', write_only=False) class Meta: model = Tagging fields = ('id', 'user_id', 'gameround_id', 'resource_id', 'tag_id', 'created', 'score', 'origin') depth = 1 def create(self, validated_data): """Create and return a new tagging""" tagging = Tagging( user=validated_data.get("user"), gameround=validated_data.get("gameround"), resource=validated_data.get("resource"), tag=validated_data.get("tag"), created=datetime.now(), score=validated_data.get("score"), origin=validated_data.get("origin") ) tagging.save() return tagging def to_representation(self, data): data = super().to_representation(data) return data This is the post request in the view: views.py def post(self, request, *args, **kwargs): if not isinstance(request.user, CustomUser): current_user_id = 1 else: current_user_id = request.user.pk gameround = request.data.get('gameround', '') random_resource = request.data.get('resource', '') created = datetime.now() score = 0 origin = '' name = request.data.get('name', '') language = request.data.get('language', '') tag_serializer = TagSerializer(data=request.data) tagging_serializer = TaggingSerializer(data=request.data) if Tag.objects.all().filter(name=name, language=language).exists(): … -
Online pricing/ordering web with django: display/show a button aftern form submitted
I am working on a online pricing/ordering web. after user input some required data and click "get price", the form is submitted and the page will show the price at the bottom of the page (currently achieved as shown in below demo code). Next, I want the page also display a button called "order now" on the right side of the price. If user click it, the page will navigate to another page where user can input more data for order information, and also auto-display the price and other already inputed data shown in the previous page. Main html: <html> <body> <form method="POST" hx-post="{% url 'blog:post_list' %}" hx-target="#num_1" hx-target="#num_2" hx-target="#result"> {% csrf_token %} <div> <label>num_1:</label> <input type="text" name="num_1" value="" placeholder="Enter value" /> </div> <div> <label>num_2:</label> <input type="text" name="num_2" value="" placeholder="Enter value" /> </div> <br /> <div id="num_1">{{ num_1 }}</div> <br /> <div id="num_2">{{ num_2 }}</div> <br /> <div id="result">{{ result }}</div> <br> <button type="submit">Submit</button> </form> <script src="https://unpkg.com/htmx.org@1.6.1"></script> </body> </html> Child html: <div> <label>first_number:</label> <span id="num_1"> {{ num_1 }} </span> </div> <div> <label>second_number:</label> <span id="num_2"> {{ num_2 }} </span> </div> <div> <label>calculation_result:</label> <span id="result"> {{ result }} </span> </div> view.py: def post_list(request): result = "" num1 = "" num2 = "" … -
How to show a django form for many to many with through field?
I have created 3 model: class PropertyExtra(models.Model): type = models.CharField(choices=ExtrasType.choices, max_length=7) property_type = models.IntegerField(choices=PropertyType.choices) title = models.CharField(max_length=100) identifier = models.CharField(max_length=20, unique=True) class Property(models.Model): extras = models.ManyToManyField(PropertyExtra, through="PropertyExtraData") class PropertyExtraData(models.Model): value = models.CharField(blank=True, null=False, max_length=300) property_extra = models.ForeignKey(PropertyExtra, on_delete=models.CASCADE) property = models.ForeignKey(Property, on_delete=models.CASCADE) In PropertyExtra an admin user can add items like Electricity, Gas, Central Heating, etc. Some values will be boolean and some int which depends on the ExtrasType enum in the PropertyExtra. The specific value per property will be saved within the PropertyExtraData.value. Currently I'm have a form wizard to create a new Property using django-formtools and I'd like one of the steps to include a form that shows all the available PropertyExtras for a specific property_type. Basically if I have the above mentioned Electricity, Gas, Central Heating records in PropertyExtra - for a specific property_type I want to render 3 checkboxes where the user can mark them. Preferably would like to use ModelForm or ModelFormSet in order to simplify editing and saving but it's not possible - I'm looking for suggestions or 3rd party packages. -
Django template to Vue component
So I need to turn some of my templates to Vue components but I am currently using server-side rendering with Jinja how can I turn Jinja render into Vue? I am new to Vue.js so I apologies if that is a terrible question. -
Django Rest Framework - Doesn't appear to be paginating queryset correctly causing a long wait time before displaying on front end
I am experiencing an issue where it is taking upwards of 30 seconds to receive 25 items in a paginated response. This happens on original load of the page as well as any subsequent page requests via the datatables previous and next buttons. The model in question has roughly 600k records in it with the request to the api providing a query parameter to filter this by listing type (Letting or Sale). There are other filters applied to the queryset to ignore items that don't fall into the queue leaving 37k records on the Sales side and 90k on lettings that are returned. My model structue is as follows: class Listing(models.Model): date_added = models.DateField(verbose_name='Date Added', auto_now_add=True, auto_now=False) listing_id = models.CharField(max_length=15, blank=False, primary_key=True) portal = models.CharField(max_length=30, blank=False) url = models.URLField(max_length=200, blank=False) date = models.DateField(verbose_name='Listing Date', auto_now_add=False, auto_now=False, null=True, blank=True) listing_status = models.CharField(max_length=30, blank=False) outcode = models.ForeignKey( 'postcode_data.Outcode', blank=True, null=True, default=None, on_delete=models.CASCADE, related_name='+') sector = models.ForeignKey( 'postcode_data.Sector', blank=True, null=True, default=None, on_delete=models.CASCADE, related_name='+') address = models.CharField(max_length=200, blank=False) postcode = models.CharField(max_length=15, blank=False) description = models.TextField(blank=True) price = models.DecimalField(max_digits=9, decimal_places=1, default=Decimal(0.0)) property_type = models.CharField(max_length=30, blank=False) beds = models.PositiveIntegerField(default=0) baths = models.PositiveIntegerField(default=0) agent = models.CharField(max_length=150, blank=False) agent_company = models.CharField(max_length=100, blank=False) agent_branch = models.CharField(max_length=50, blank=False) available = … -
Django DeleteView Not Saving Changes
I'm using django DeleteView to delete user account. when i set the user's is_active property to False, it doesn't get saved in the database. it's still set to True here's my views.py from django.shortcuts import get_object_or_404 from django.urls import reverse_lazy from django.http import HttpResponseRedirect from django.views.generic.edit import DeleteView from django.contrib.auth.mixins import LoginRequiredMixin from django.contrib.messages.views import SuccessMessageMixin class DeleteAccount(LoginRequiredMixin, SuccessMessageMixin, DeleteView): """ DeleteAccount: view to delete user account """ model = User template_name = 'registration/delete_account.html' success_url = reverse_lazy('core:index') success_message = 'Account Successfully Deleted!' def form_valid(self, form): """ Delete account and logout current user """ account = self.get_object() # verify if user is the rightful owner of this account if not account.id == self.request.user.id: return HttpResponseRedirect(reverse_lazy('accounts:index')) account.is_active = False # DOESN'T GET SAVED account.save() # EVEN AFTER CALLING MODEL.SAVE() METHOD logout(self.request) return super().form_valid(form) def get_object(self): return get_object_or_404(User, pk = self.request.user.id) -
Manytomany relationship with through field doesn't show up in admin edit panel
I am trying to add new functionality to an existing project, where users can add multiple country locations with cities. Here are the models: class OfferCountries(models.Model): country = models.ForeignKey("Country", on_delete=models.CASCADE) cities = models.ManyToManyField("City", related_name="offer_cities", blank=True) offer = models.ForeignKey("Offer", related_name="offer_id",on_delete=models.CASCADE) class Offer(BaseModel): ... offer_country = models.ManyToManyField('Country', through='OfferCountries', related_name='offer_countries',blank=True) Now when I try to add a new Offer instance in admin there is no field of offer_country. Any ideas on how can I fix it? -
python: How can I import my own module? ModuleNotFoundError in python
I'm going to import my own module to my main.py. I made some python files in my scripts directory.(DataExtractor~KorTextPreProcessor) enter image description here I wrote my code like this... import DataExtractor import KoreTextPreprocessor and so on... Pycharm doesn't show me any errors, but my ec2 command errors... which says :: "No module named 'DataExtractor" << I want to import them all in main.py. Someone recommends to write this way from FileTransformer import method but it still shows error... how can I fix it? Maybe shoud I wrote somethin in my init.py? -
Invalid command 'PassengerPython', perhaps misspelled or defined by a module not included in the server configuration IN Django godaddy
Internal Server Error The server encountered an internal error or misconfiguration and was unable to complete your request. Please contact the server administrator at webmaster@example.com to inform them of the time this error occurred, and the actions you performed just before this error. More information about this error may be available in the server error log. Additionally, a 500 Internal Server Error error was encountered while trying to use an ErrorDocument to handle the request. -
Using Django template tags and filters in javascript
I am building a search engine using Algolia in a client's Django project. In the html section of the template the client uses this line to format the date correctly. <span><em>posted</em> <strong>{{ dealer_announcement.publish_date|date:"F jS, Y" }}</strong></span> In the script on the template I define what each hit on the search engine should look like in a template like so. {% verbatim %} const hitTemplate = '' + '<span><em>posted</em> <strong>{{ publish_date }}</strong></span>' + '</div>' + ''; {% endverbatim %} This works fine, however the date is not formatted correctly so I tried to match the same format like so. {% verbatim %} const hitTemplate = '' + '<span><em>posted</em> <strong>{{ publish_date|date:"F jS, Y" }}</strong></span>' + '</div>' + ''; {% endverbatim %} but then nothing shows up. How can I use the same filters and tags within the script to have it match the original output. -
How to cleanly and efficiently delete an app from django
I have rewritten and renamed an entire app. It has now passed my tests, so it is time to delete the old version. To my surprise, this is either much harder than it should be, or I just haven't found the right answer. Where is 'python manage.py delete app 'appname'? I looked at this How to delete a record in Django models? and at the docs https://docs.djangoproject.com/en/4.0/topics/migrations/#workflow. First I tried just removing the entire app from the filesystem, but migrations complained: File "/home/malikarumi/.virtualenvs/LogBook/lib/python3.9/site-packages/django/db/models/base.py", line 113, in new raise RuntimeError( RuntimeError: Model class uppergi.models.Food doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. (LogBook) malikarumi@Tetuoan2:~/Projects/LogBook$ python manage.py delete uppergi Unknown command: 'delete' Type 'manage.py help' for usage. (LogBook) malikarumi@Tetuoan2:~/Projects/LogBook$ manage.py help manage.py: command not found (LogBook) malikarumi@Tetuoan2:~/Projects/LogBook$ git revert 8bb60951 So I put it back and tried deleting one model at a time. Migrations complained about that, too. (LogBook) malikarumi@Tetuoan2:~/Projects/LogBook$ python manage.py makemigrations Traceback (most recent call last): ... File "/home/malikarumi/Projects/LogBook/uppergi/admin.py", line 6, in from . models import Grocer, Food, ShoppingTrip, Cook, Eaten ImportError: cannot import name 'Eaten' from 'uppergi.models' (/home/malikarumi/Projects/LogBook/uppergi/models.py) and specifying the app: (LogBook) malikarumi@Tetuoan2:~/Projects/LogBook$ python manage.py makemigrations uppergi Traceback (most recent call last): File "/home/malikarumi/Projects/LogBook/manage.py", … -
AttributeError: 'list' object has no attribute 'lower' django/utils/http.py
I've been getting an exception from the site-packages/django/utils/http.py module when ALLOWED_HOSTS in my settings is a list. File "/home/xxxx/.local/lib/python3.8/site-packages/django/utils/http.py", line 292, in is_same_domain pattern = pattern.lower() AttributeError: 'list' object has no attribute 'lower' Usually fires from module from django.test.Client To solve, I left only one item in ALLOWED_HOSTS. Does anyone know why? Thanks! -
How to make a field the same as int:pk in django rest framework?
I have a serializer class AnswerQuestionsSerializer(serializers.ModelSerializer): user = serializers.PrimaryKeyRelatedField(read_only=True, default=serializers.CurrentUserDefault()) class Meta: model = Answer fields = ('answer', 'user', 'question', 'number_of_points', 'moderate_status',) And the view class AnswerQuestions(generics.CreateAPIView, generics.GenericAPIView): queryset = Answer.objects.all() serializer_class = AnswerQuestionsSerializer def perform_create(self, serializer): return serializer.save(user=self.request.user) def get_queryset(self): return super().get_queryset().filter( question_id=self.kwargs['pk'] ) The model looks like this answer = models.TextField() created_at = models.DateTimeField(editable=False, default=timezone.now) updated_at = models.DateTimeField(default=timezone.now) user = models.ForeignKey('users.CustomUser', on_delete=models.PROTECT) question = models.ForeignKey('Question', on_delete=models.PROTECT) number_of_points = models.IntegerField(default=0) moderate_status = models.BooleanField(default=False) And i set the url to answerQuestions/int:pk, so when i use post request lets say answerQuestions/3 i still need to put "question": "3" in body because it won't read it automatically. Do you have any idea how to make it automatically hit the question of the id provided in the url? Which in this case would be 3. -
React VS NextJS for Django
I am still quite new to React, and I am currently working on a Django-React app. I read a bit about Next JS and it seems quite useful and interesting (especially for SEO), but I've heard various opinons about it. I am considering using it for the front end and rendering only. Therefore I was wondering, would it be worth it to learn and implement NextJS (and re do some of the work I did with react), or is the effort to great for a minimal result? Will NextJS allow me to do more than react (in terms of SEO and rendering)? Does the complexity of a project really increases when implementing Nextjs + React-Django? Lots of people are talking about NextJs and I was wondering if it was just "another framework" or really something more. Have a good day -
get none object in upload file in Apollo graphql
After uploading a file to the server returning an none object. client setup apollo.use apollo-upload-client module and set graphql uri const apolloLink = createUploadLink({ uri: API_URL, credentials: "same-origin", }); export const apolloFetch = createApolloFetch({ uri: API_URL }); const apolloCache = new InMemoryCache(); const authLink = setContext((_, { headers }) => getAuth().then(jwt => ({ headers: { ...headers, Authorization: jwt?.token ? `JWT ${jwt.token}` : "", }, })) ); const refreshTokenLink = new ApolloLink((operation, forward) => { operation.setContext((_: any) => isAuthenticated().then(is => { !is && getAuth().then(rt => { rt != null && apolloFetch({ query: gqlPrint(mutations.REFRESH_TOKEN), variables: { token: rt?.token }, }).then( ({ data: { user: { refreshToken }, }, }: any) => { if (refreshToken.success) setAuth(refreshToken.token); else clearAuth(); } ); }); }) ); return forward(operation); }); export const gplClient = new ApolloClient({ link: from([refreshTokenLink, authLink, apolloLink]), cache: apolloCache, }); and setup mutation upload file .I sure this part is right and think set apollo link is wrong import React, { useCallback } from "react"; import { useDropzone } from "react-dropzone"; import gql from "graphql-tag"; import { useMutation } from "@apollo/react-hooks"; import { filesQuery } from "./Files"; const uploadFileMutation = gql` mutation UploadFile($file: Upload!) { uploadFile(file: $file) } `; export const Upload = () … -
Django {% include %} TemplateDoesNotExist at / blog/includes/post.html
Hello,good day to you, I'm currenttly taking a Django course where im building a blog . i keep getting a: TemplateDoesNotExist at / blog/includes/post.html which i can not seem to solve. but i think it has something to do with the {%include%} template tag i have two files: 1)post.html and 2)index.html i am trying to {%include%} the post.html in the index.html but when i do i get this: TemplateDoesNotExist at / blog/includes/post.html template does not exist error but i have tested the path several times i have checked settings.py and my path is correct {% include "blog/includes/post.html" %} ### HERE IS THE PROBLEM in index.html {% include "blog/post.html" %} {% include "blog/templates/blog/includes/post.html" %} i have tried all paths none work. the only way i can make it work is by not using the the {% include%} and instead copying and pasting the post.html directly but this is impractical and does not let me move on with my project ##### index.html ###### {% extends "templates/base.html" %} {% load static %} {% block title %} My Blog {% endblock %} {% block css_files %} <link rel="stylesheet" href="{% static "blog/post.css" %}" /> <link rel="stylesheet" href="{% static "blog/index.css" %}" /> {% endblock %} {% … -
django missing csrf token in javascript .submit() function (non ajax)
I am using a javascript to send an html form to django. js looks like this: document.getElementById("fooform").submit(); and the html form looks like this: <form class="form-inline" id="fooform" action ="{% url 'foo:doo' %}" method="post"> {% csrf_token %} <input type="hidden" id="fooinput" value="" /> </form> the js can write the data into the input field without any problems and also carry out the submit. my problem is using the crsf token. I have already put the token {% csrf_token %} in every conceivable place. (Before the form, before the js...). in the html code is the token also correct. django gives me the error: Reason given for failure: CSRF token missing or incorrect. In general, this can occur when there is a genuine Cross Site Request Forgery, or when Django's CSRF mechanism has not been used correctly. For POST forms, you need to ensure: Your browser is accepting cookies. The view function passes a request to the template's render method. In the template, there is a {% csrf_token %} template tag inside each POST form that targets an internal URL. If you are not using CsrfViewMiddleware, then you must use csrf_protect on any views that use the csrf_token template tag, as well as … -
Invalid address when sending mail via Django
I am trying to send mail via Django, but have an error: (501, b'5.1.7 Invalid address', '"emea\\\\sss1ss1"') My EMAIL_HOST_USER = r'emea\xss1ss1'. As you can see my user consist \x so I am using r''. How to fix it, the real EMAIL_settings are correct. my view.py def home(request): subject = 'Test mailing' message = 'Hello world!!!' email_from = settings.EMAIL_HOST_USER recipient_list = ['smth@smth.com'] send_mail(subject,message,email_from,recipient_list) return HttpResponse('Test mailing') -
Django: how to update a ManyToManyField in a custom Django management task?
In Django I have a model where one of the fields (tags) is a ManyToManyField: class MyModel(models.Model): id = models.CharField(max_length=30, primary_key=True) title = models.CharField(max_length=300, default='') author = models.CharField(max_length=300) copy = models.TextField(blank=True, default='') tags = models.ManyToManyField(Tag) I have a custom management task below where I'm getting all of the instances of the MyModel table on a server and using that to replace the instances of the MyModel table on my local server. (I'm running this custom management task from my local) Here's what I'm trying so far. However I'm getting this error: CommandError: Direct assignment to the forward side of a many-to-many set is prohibited. Use tags.set() instead. How can I update the tags field that's a ManyToMany field? from bytes.models import MyModel class Command(BaseCommand): def handle(self, *args, **options): try: // get queryset of MyModel instances from server queryset = MyModel.objects.using('theserver').all() // loop through that queryset and create a list of dictionaries mymodel_list = [ { 'id': mymodel['id'], 'title': mymodel['title'], 'author': mymodel['author'], 'copy': mymodel['copy'], 'tags': mymodel['tags'] } for mymodel in queryset ] //delete all objects in the local MyModel table MyModel.objects.all().delete() //replace with MyModel instances from server new_mymodel = [ MyModel( id=mymodel['id'], title=mymodel['title'], author=mymodel['author'], copy=mymodel['copy'], tags=mymodel['tags'] <--- causing error ) for … -
How to go to a form section which is in a bootstrap modal by using another button which is located in the navbar section of my website?
So I'm building a Ecommerce website, I've made different categories for different product so here an admin can add new products in the category section by clicking this + icon. Now I've added a new button in the navbar section which is Add Items (navbar section is in base.html), I also want that an admin can add products by clicking that button and I want that the same modal will pop up after clicking that button but I'm getting 404-Not Found which is obvious because in the views.py I've written only if the method is post I will allow this request and now I'm trapped how do I handle this navbar button? What condition's should I use here? views.py def add_product(request): if request.method=='POST': product_name = request.POST['product_name'] product_category = request.POST['product_category'] product_price = request.POST['product_price'] product_photo = request.FILES['product_photo'] product_description = request.POST['product_description'] add_product = Product(product_name=product_name,category=product_category,price=product_price,description=product_description, pub_date=datetime.today(),image=product_photo) add_product.save() messages.success(request, 'Product has been added successfully!!!') return render(request,'index.html') else: return HttpResponse("404-Not Found") Here is the photo of my Add product modal which will pop up after clicking + button This is the code for Add Item inside modal which is located in vegetable.html <div class="modal-body"> <form action="/add_product" method="post" enctype="multipart/form-data"> {% csrf_token %} <div class="mb-3"> <label for="exampleFormControlInput1" class="form-label">Product …