Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Dynamic exec Django
Good day people! I have 3 forms that perform 3 different operations. The task is to make a single class to handle forms dynamic. I was briefly explained that I need 2 tables. It will take the number of variables from the first table, and the names of variables from the second table. Next, it collects data in an array and passes it as an input parameter to the operation being performed. models.py from django.db import models from SqlApp import greats class DForm(models.Model): create_choices = ( ('LOAN', 'Создать кредитный договор'), ('ACC', 'Создать банковский счет'), ('DEPO', 'Создать депозитный договор') ) choose_procedure = models.CharField(max_length=4, verbose_name='Выберите процедуру', choices=create_choices) def __str__(self): return self.choose_procedure class Acc(models.Model): oper_date = models.CharField(max_length=10, verbose_name='Операционная дата') instance = models.CharField(max_length=10, verbose_name='Инстанция') iin = models.CharField(max_length=12, verbose_name='ИИН клиента') dcl_code = models.CharField(max_length=10, verbose_name='Шаблон продукта') val = models.CharField(max_length=10, verbose_name='Валюта') specfl = models.CharField(max_length=10, verbose_name='Признак спец.счета') def save(self, *args, **kwargs): greats.createAcc(self.oper_date, self.instance, self.iin, self.dcl_code, self.val, self.specfl) class Loan(models.Model): oper_date = models.CharField(max_length=10, verbose_name='Операционная дата') instance = models.CharField(max_length=10, verbose_name='Инстанция') iin = models.CharField(max_length=12, verbose_name='ИИН клиента') dcl_code = models.CharField(max_length=10, verbose_name='Шаблон продукта') pcn = models.CharField(max_length=10, verbose_name='Процентная ставка') pday = models.CharField(max_length=10, verbose_name='День месяца погашения') def save(self, *args, **kwargs): greats.createLoan(self.oper_date, self.instance, self.iin, self.dcl_code, self.pcn, self.pday) class Depo(models.Model): oper_date = models.CharField(max_length=10, verbose_name='Операционная дата') instance = … -
Why is this django test is failing?
Whenever I run my test.py I get: (blog-1rz6wx-6) λ python manage.py test Creating test database for alias 'default'... System check identified no issues (0 silenced). .F.. ====================================================================== FAIL: test_post_detail_view (blog.tests.BlogTests) ---------------------------------------------------------------------- Traceback (most recent call last): File "C:\Users\ **** \Desktop\blog\blog\tests.py", line 40, in test_post_detail_view self.assertEqual(response.status_code, 200) AssertionError: 404 != 200 ---------------------------------------------------------------------- Ran 4 tests in 0.776s FAILED (failures=1) Destroying test database for alias 'default'... My test.py code: def test_post_detail_view(self): response = self.client.get('/post/1/') no_response = self.client.get('/post/100000') self.assertEqual(response.status_code, 200) self.assertEqual(no_response.status_code, 404) self.assertContains(response, 'A good title') self.assertTemplateUsed(response, 'post_detail.html') urls.py that is in the same folder as settings.py: from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('',include('blog.urls')), ] And the urls.py that is located in the same folder as views.py: from django.urls import path from .views import BlogListView, BlogDetailView urlpatterns = [ path('post/<int:pk>', BlogDetailView.as_view(), name = 'post_detail'), path('',BlogListView.as_view(),name = 'home') ] I have no Idea, and when I changed the response to response = self.client.get(''), it does come up with code 200, but the TemplateUsed obviously becomes 'home.html. Thanks beforehand. -
Which frameworks to generate CRUDs on mobile?
I'm building a web app to manage inventory. The simplified model looks like: Client(clientId, name, address, email, etc) Auditor(auditorId, email, etc) Product(productId, name, description, unit, cost, etc) InventoryDataEntry(entryId, productId, nbUnits, inputDate) A Client needs to input entry in his inventory daily: "as of today, I have 10 kg of apples" An Auditor need to verify the inventory stock monthly: "as of today, clientId 123ABC has 10 kg of apples" I need a role-based system: a client can only input data in his own inventory while an auditor can input data for any client. I will need to display graphs to show the evolution of stocks over time. I'm thinking of using Django for the back-end and services. I like the django-admin interface. HOWEVER, I need to make the web app usable thru mobile and I'm very rubbish at front-end dev. I looked at solutions such as react-native which looks great. I'm wondering if there were any solutions that could provide a django-admin like interface (generating all the CRUDs + permissioning) for a mobile web app. -
django modelformset_factory not validating because * id * Select a valid choice, That choice is not one of the available choices
MY view receives a model modelformset_factory from the template, but it doesn't pass validation, claiming that * id * Select a valid choice. That choice is not one of the available choices. Here is a simplified version of my view: def menuuser(request): user_role = DesignationForm() #formset = modelformset_factory(SbTitle, fields=('title', 'permission'), max_num=0) sbtitle_form = SbTitleForm(queryset=SbTitle.objects.all()) sbitleelement_form = SbTitleElementForm(queryset=SbTitleElement.objects.all()) if request.method == 'POST': user_role_id = request.POST['designation_selection'] sbtitle_form = SbTitleForm(request.POST, queryset=SbTitle.objects.all()) sbitleelement_form = SbTitleElementForm(request.POST, queryset=SbTitleElement.objects.all()) if sbtitle_form.is_valid() and SbTitleElementForm.is_valid(): bla...... context = { 'user_role':user_role, 'sbtitle_form':sbtitle_form, 'sbitleelement_form':sbitleelement_form, } return render(request, 'admins/user_role/user_permission.html', context) And here is my template: {% extends 'base/base.html' %} {% load static %} {% block content %} <div class="card"> <form class="form-horizontal" action="" method="post"> {% csrf_token %} {{ sbtitle_form.management_form }} {{ sbitleelement_form.management_form }} <div id="DataTables_Table_2_wrapper" class="dataTables_wrapper no-footer"> <div class="datatable-header"> <div class="form-group row"> <label class="col-md-4 col-form-label"><span><h5>Select User Role For Menu Permission:</h5></span></label> <div class="col-md-5">{{ user_role.designation_selection }}</div> </div> </div> <div class="datatable-scroll"> <table class="table table-bordered table-hover datatable-highlight dataTable no-footer" id="DataTables_Table_2" role="grid" aria-describedby="DataTables_Table_2_info"> <thead> <tr role="row" class="bg-teal-400"> <th class="sorting text-center h5" tabindex="0" aria-controls="DataTables_Table_2" rowspan="1" colspan="1" aria-label="Job Title: activate to sort column ascending">Sidebar Title</th> <th class="sorting text-center h5" tabindex="0" aria-controls="DataTables_Table_2" rowspan="1" colspan="1" aria-label="DOB: activate to sort column ascending">Sidebar Title Element</th> </tr> </thead> <tbody> {% for field in sbtitle_form %} … -
How do I connect a model instance to a user in django?
Im looking to make it so the logged in user that creates a profile is linked to their guestprofile model when they create their profile. When I create the guest profile while logged in, it successfully creates the guest profile, but in the guest profile admin screen there is no user connected to the guest profile model created. Instead there is a dropdown menu listing all users, which makes the connection process manual. Thanks. views.py class AddProfileView(CreateView): model = GuestProfile form_class = AddProfileForm template_name = 'profilemanip/addprofile.html' success_url = reverse_lazy('home') def get_object(self): return self.request.user Forms.py class AddProfileForm(forms.ModelForm): name = forms.CharField(max_length=50, widget=forms.TextInput(attrs={'class': 'form-control'})) location = forms.CharField(max_length=100, widget=forms.TextInput(attrs={'class': 'form-control'})) summary = forms.CharField(max_length=500, widget=forms.Textarea(attrs={'class': 'form-control'})) profile_pic = forms.ImageField() class Meta: model = GuestProfile fields = ('name', 'location', 'summary', 'profile_pic') Models.py class GuestProfile(models.Model): user = models.ForeignKey(User, null=True, on_delete=models.CASCADE) name = models.CharField(max_length=100) location = models.CharField(max_length=100) summary = models.TextField(max_length=350) profile_pic = models.ImageField(null=True, blank=True, upload_to="images/") def __str__(self): return str(self.user) -
Run functions inside model.py - Django
I want to execute the function named Average_Health() inside models.py to insert it's i.e. Average_Health()returned value. I don't want to execute the function inside views.py because there's such a condition that several views.py will this same task. It's just a sample code to understand: class myModal(models.Model): name = models.CharField(max_length=150, null=True) earning = models.IntegerField(max_length=150, default=1600) def Average_Health(): return (earning-2500) health = models.IntegerField(max_length=1000, default=Average_Health()) -
Django renders an "in exception" page instead of a page that can help debugging
I don't know why but recently whenever I get an error I don't see any helping messages in the terminal and all what I see in my browser is an empty page with "in exception" text And now my only way of debugging is to through multiple print statements and see where my code crashed. Does anyone know why Django suddenly became very useless?! The page I get when an error occures look like this I spend literally 2 hours trying to find out why my page wasn't rendering to find out that I forgot to place ".html" extension at the end of rendering! Why Did Django Suddenly Became Useless?! -
Nested Json is not being serialized while using Multipart Parser
I will try to give a small example and tell where it's not working. The models are as follows, class Address(models.Model): name = models.CharField(db_column='name', max_length=200, blank=False, null=False, unique=True) class Meta: managed = True db_table = 'Address' class Product(models.Model): title = models.CharField(db_column='title', max_length=200, blank=False, null=False) imageUrl = models.ImageField(db_column='image_url', blank=True, null=True, upload_to='deals/%Y/%m/') addresses = models.ManyToManyField(Address, related_name='product_addresses') class Meta: managed = True db_table = 'Product' The serializers class AddressSerializer(BaseSerializer): id = serializers.IntegerField(required=False) name = serializers.CharField(required=False) class Meta: model = Address fields = ['id', 'name'] class ProductSerializer(serializers.ModelSerializer): id = serializers.IntegerField(required=False) title = serializers.CharField(required=False) addresses = AddressSerializer(many=True, required=False) def create(self, validated_data): locationData = get_popped(validated_data, 'addresses') instance = Product.objects.create(**validated_data) self.createLocation(locationData, instance) return instance def createLocation(self, locationData, instance): location_ids = [] if locationData is not None: for item in locationData: if 'id' in item: location_ids.append(item.get('id')) addresses = Address.objects.filter(id__in=location_ids) for loc in addresses: instance.addresses.add(loc) instance.save() def update(self, instance, validated_data): print(validated_data) addressData = get_popped(validated_data, 'addresses') if addressData is not None: instance.addresses.clear() self.createLocation(addressData, instance) super(self.__class__, self).update(instance, validated_data) return instance class Meta: model = Product fields = ['id', 'addresses', 'title', 'imageUrl'] My views, class ProductViewSet(viewsets.ModelViewSet): pagination_class = CustomPagination serializer_class = ProductSerializer parser_classes = (MultipartJsonParser, parsers.JSONParser) queryset = Product.objects.all() class AddressViewSet(viewsets.ModelViewSet): pagination_class = CustomPagination serializer_class = AddressSerializer queryset = Address.objects.all() And the … -
How to Create a Dependent dropdown in django without form or ajax
I want to create a dependent dropdown in django restframework without using forms and ajax. -
Django DRF AttributeError: Got AttributeError when attempting to get a value for field `added_email` on serializer `UserMailListSerializer`
ps. I'm sorry that the sentences are weird because I'm not familiar with English. An error occurs when you add an email to your mailing list. error message AttributeError: Got AttributeError when attempting to get a value for field `added_email` on serializer `UserMailListSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `str` instance. Original exception text was: 'str' object has no attribute 'added_email'. After AttributeError, the database contains the values you want to save correctly, and after refresh, check the mailing list with Get to get the values. Errors seem to occur only when added to the list. Model.py class UserAccountManager(BaseUserManager): """ model manager """ def create_user(self, email, name, password=None): """ create user """ if not email: raise ValueError("valid email") user = self.model(email=self.normalize_email(email), name=name) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, name, password=None): """ create admin """ user = self.create_user(email, name, password) user.is_superuser = True user.is_staff = True user.save(using=self._db) return user class UserAccount(AbstractBaseUser, PermissionsMixin): """ user account model """ email = models.EmailField(unique=True, verbose_name='email') name = models.CharField(max_length=20, verbose_name='username') created_at = models.DateTimeField(auto_now_add=True, verbose_name='subscription_date') is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) objects = UserAccountManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['name'] class Meta: db_table = 'accounts' def … -
How do I make all posts that share a category appear on a page in Django
How do I make the page list all posts that that share the same category id. I have the category titles as a separate "foreign key" model. My goal is to be able to type in my url so that I have the category id at the end and it shows me all the posts that have the specific category id. """models.py""" class Category(models.Model): name = models.CharField(max_length=200) slug = models.SlugField() def __str__(self): return self.name def get_absolute_url(self): return reverse('post-category', kwargs={'pk': self.pk}) class HelpPage(models.Model): title = models.CharField(max_length=100) content = models.TextField(default="test") date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) product = models.CharField(max_length=100) category = models.ForeignKey('Category', null=True, blank=True, on_delete=models.CASCADE) def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail', kwargs={'pk': self.pk}) """views.py""" class CategoryDetailView(DetailView): model = Category context_object_name = 'category' template_name = 'blog/categories.html' """urls.py""" from .views import ( CategoryDetailView,) urlpatterns = [ path('category/<int:pk>', CategoryDetailView.as_view(), name='post-category'),] """categories.html""" {% extends "blog/base.html" %} {% block content %} Category name: {{ category.name }} {% for post in category.post_set.all %} post: {{ post.title }} {% endfor %} {% endblock content %} categories.html -
How to sort cart items in order
I am building a Django e-commerce website and as I was working on my cart functionality I noticed that every time I try to change the quantity of a specific item in the cart, all the items in the cart are re-sorted in a different order. I was wondering if there's any way I can sort the items in the backend before they are displayed. ** I am getting this error only when the user is "Authenticated" ** Guest checkout is working correctly This is my cart Views.py def cart(request): # Authenticated Checkout if request.user.is_authenticated: customer = request.user.customer order, created = Order.objects.get_or_create(customer=customer, complete=False) cartItems = order.get_cart_items items = order.orderitem_set.all() if cartItems == 0: context = {"items": items, "order": order, "cartItems": cartItems} return render(request, "cart_empty.html", context) #Guest Checkout else: data = cartData(request) cartItems = data["cartItems"] order = data["order"] items = data["items"] if cartItems == 0: context = {"items": items, "order": order, "cartItems": cartItems} return render(request, "cart_empty.html", context) context = {"items":items, "order": order, "cartItems":cartItems} return render(request, "cart.html", context) def update_cart(request): data = json.loads(request.body) productId = data["productId"] action = data["action"] customer = request.user.customer product = Product.objects.get(id=productId) order, created = Order.objects.get_or_create(customer=customer, complete=False) orderItem, created = OrderItem.objects.get_or_create(order=order, product=product) if action == "add": orderItem.quantity = (orderItem.quantity … -
RelatedObjectDoesNotExist at /register/ User has no schoolprofile
hello am trying to create a school profile when a user( schooluser) registers,the profile is created but giving the error RelatedObjectDoesNotExist at /register/User has no schoolprofile.and the strange thing is that in the admin the model fields when you try to edit any field of the created school profile they are empty. help. models.py class SchoolProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE,related_name='schoolprofile') schoolname = models.CharField(max_length=200) region = models.CharField(max_length=200) district = models.CharField(max_length=200) code = models.CharField(max_length=20) logo = models.ImageField(default='default.jpg', upload_to='logos') def __str__(self): return f'{self.user.username} Profile' def save(self, *args, **kwargs): super().save(*args, **kwargs) forms.py from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from .models import SchoolProfile class SchoolRegisterForm(UserCreationForm): email = forms.EmailField() class Meta: model = User fields = ['username', 'email', 'password1', 'password2'] class SchoolProfileForm(forms.ModelForm): class Meta: model = SchoolProfile fields = ['schoolname', 'code', 'region'] views.py from .forms import SchoolRegisterForm,SchoolProfileForm def register(request): if request.method == 'POST': form = SchoolRegisterForm(request.POST) s_profile_form = SchoolProfileForm(request.POST) if form.is_valid() and s_profile_form.is_valid(): form.save() request.user.refresh_from_db() s_profile_form = SchoolProfileForm(request.POST, instance=request.user.schoolprofile) s_profile_form.full_clean() s_profile_form.save() username = form.cleaned_data.get('username') messages.success(request, f'Your account has been created! You are now able to log in!') return redirect('dashboard') else: form = SchoolRegisterForm() s_profile_form = SchoolProfileForm() return render(request, 'accounts/register.html', {'form': form,'s_profile_form':s_profile_form}) -
It is possible send a http request of a view in another view?
I would want to send a http request in a view. The request URL has relation to another view. Somthing like this: class View_A(APIView): def get(self, request): return Response({'foo':'bar'}) class View_B(APIView): def post(self, request): # Here I would want to send a request to View_A, something like this: request_view_A = View_A.as_view().get('URL_FROM_VIEW_A') # ... return Response({'foo2':'bar2'}) I have seen this question which has a different focus, however don't working for me because http method from View_A (get) is different to http method from View_B (post). -
Crypting/decrypting user passwords used for basic auth in Django
I have a Django application. Via the app, users can access a third party API which uses basic auth credentials. I was planning on adding a section where user can add their credentials to said Api, which would then be stored to the database as a basic auth header. But then I facepalmed as obviously encoding them as base64 can be decoded to plain text. What would be the best way to achieve a encrypting/decrypting mechanism in Django for this purpose? In this case, the credentials would be encrypted when saved to the database and encrypted when they are fetched from there. -
Render personalized data in template against django.contrib.auth.models.User
When my users answer a challenge, I want it to be stored against their profile. When they log in, they will see an index of challenges and it will show which ones have been answered. Like this: Trivia What is the capital of France? - answered How high is the Empire State building? Maths What is 2+2 - answered My model for the above contains Category and Challenge. I am also using Django auth User for log-in. To get the 'answered' bit, I thought I could add a User_Challenge model in models.py: class User_Challenge(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) challenge = models.ForeignKey(Challenge, on_delete=models.CASCADE, null=True) answered = models.BooleanField(default=False) But because you can't do filtering in a template, I am finding this really cumbersome. Is there a simpler way to associate challenge status against a user profile without introducing another table? I find that passing Category, Challenge, User and User_Challenge from my view to my template too complicated since you can't execute functions in templates. Thanks in advance! -
is there performance difference in using model name istead of object in ForeignKey?
Well Django docs do not say anything about performance or particular situations when to use model name class SomeModel(Model): related_model = ForeignKey('RelatedModel') or the class itself class SomeModel(Model): related_model = ForeignKey(RelatedModel) in my experience is much better to use the model name to avoid import loops but does it have any particular impact on app's live peformance or just server startup takes longer? Can't really think of a test that would reliably check the performance thus the quetion PS I know the similar answer was asked but it says nothing about real performance. -
Getting RelatedObjectDoesNotExist error accessing field on custom form
I'm relatively new to Django (and python in general) and I'm working on project I have not coded myself. Specifically I'm trying to save some information from a form via POST but I get a RelatedObjectDoesNotExist error when accessing the user field defined in my custom Profile model and I don't get why. Here is my views.py: def conferma(request): family = request.user.profile.family # cannot be null already_confirmed = request.user.profile.conferma_inviata if(already_confirmed == False): ProfileFormSet = modelformset_factory( Profile, form=ConfirmForm, extra=0) if request.method == 'POST': formset = ProfileFormSet( request.POST, queryset=Profile.objects.filter(family=family)) if formset.is_valid(): for form in formset: f = form.save(commit=False) f.conferma_inviata = True f.save() If I try to access f.user I get a RelatedObjectDoesNotExist error and I need that information in order to save the form. Here is my forms.py: class ConfirmForm(forms.ModelForm): class Meta: model = Profile fields = ('user', 'conferma_pranzo', 'conferma_sera', 'conferma_inviata',) def __init__(self, *args, **kwargs): super(ConfirmForm, self).__init__(*args, **kwargs) self.fields['user'].required = False self.fields['conferma_inviata'].required = False Here is my models.py: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) full_day = models.BooleanField(default=True) family = models.TextField(max_length=100, blank=True) conferma_pranzo = models.BooleanField(default=False) conferma_sera = models.BooleanField(default=False) conferma_inviata = models.BooleanField(default=False) def __str__(self): return self.user.first_name + ' ' + self.user.last_name I have already checked the Database but the Profile records are correctly stored … -
drf-spectacular is using the wrong AutoSchema to generate Swagger
Previously I was using drf-yasg but want to update to use OpenAPI 3. I am trying to switch over to drf-spectacular. Following the instruction, I ran pip install drf-spectacular, I've removed all references to the drf-yasg package, and updated Settings.py as follows: INSTALLED_APPS = [ ... "drf_spectacular", ] REST_FRAMEWORK = { "DEFAULT_SCHEMA_CLASS": "drf_spectacular.openapi.AutoSchema", } When I use the CLI to generate the schema, I get the bellow AssertionError. If anyone has run into this problem before and has any insight, it would be much appreciated! I'm using Python 3.7, Django 3.0, Django Rest Framework 3.11, and DRF Spectacular 0.10.0. Traceback (most recent call last): File "manage.py", line 23, in <module> main() File "manage.py", line 19, in main execute_from_command_line(sys.argv) File "/opt/anaconda3/envs/dev/lib/python3.7/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/opt/anaconda3/envs/dev/lib/python3.7/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/opt/anaconda3/envs/dev/lib/python3.7/site-packages/django/core/management/base.py", line 328, in run_from_argv self.execute(*args, **cmd_options) File "/opt/anaconda3/envs/dev/lib/python3.7/site-packages/django/core/management/base.py", line 369, in execute output = self.handle(*args, **options) File "/opt/anaconda3/envs/dev/lib/python3.7/site-packages/drf_spectacular/management/commands/spectacular.py", line 50, in handle schema = generator.get_schema(request=None, public=True) File "/opt/anaconda3/envs/dev/lib/python3.7/site-packages/drf_spectacular/generators.py", line 187, in get_schema paths=self.parse(request, public), File "/opt/anaconda3/envs/dev/lib/python3.7/site-packages/drf_spectacular/generators.py", line 160, in parse 'Incompatible AutoSchema used on View. Is DRF\'s DEFAULT_SCHEMA_CLASS ' AssertionError: Incompatible AutoSchema used on View. Is DRF's DEFAULT_SCHEMA_CLASS pointing to "drf_spectacular.openapi.AutoSchema" or any other drf-spectacular compatible … -
How to use wkHTMLtoPDF with docker-compose and Django
I need help to understand how to use wkHTMLtoPDF with docker-compose and then apply it in Django. I tried to build docker-compose: version: '3.7' services: db: image: postgres:13.0 restart: always environment: POSTGRES_PASSWORD: trytofindme ports: - 15432:5432 adminer: image: adminer restart: always ports: - 8020:8080 wkhtmltopdf: image: diegovieira/wkhtmltopdf:latest volumes: - .:/data It was the first image of wkhtmltopdf, that I found and it was working. When I type docker-compose up - everything runs correctly, but at least i see that message: server_wkhtmltopdf_1 exited with code 1 Does someone know how to solve this problem? And then how to use it in Django. For example: I need to convert HTML to PDF simple page with text and need to save it in "../project-name/media/pdf. I will be insanely grateful for your help. -
Django ModelMultipleChoiceField - Can't unselect all checkboxes
I'm passing a checklist form to my template. When no items are selected, there is no request.POST object passed to the view. This means I can't deselect all existing checkboxes and hit save. How can the view detect that the request.method is "POST" when no data is submitted? Code below: View.py if request.method == "POST": form = AssignedUsersForm(request.POST, instance=assignment) if form.is_valid(): assignment = form.save(commit=False) assignment.save() form.save_m2m() return redirect('assignment', id) -
Method Not Allowed (POST): /profiles/flash/ Method Not Allowed: /profiles/flash/
Well here i am simply trying to add follow toggle button in django tmeplate with django and jqeury ajax but its showing me an error Method Not Allowed (POST): /profiles/flash/ Method Not Allowed: /profiles/flash/. I dont get it where i am making mistake. Even i triple check my code. html <form method='post'> <button class="btn {% if is_following %}btn-warning{% else %}btn-primary{% endif %}" id="like-button" toggle="{{user.userprofile}}">{% csrf_token %} {% if is_following %}Unfollow {% else %}Follow{% endif %} </button> </div> </form> jquery,ajax <script> var user = $('#test').attr('user'); console.log(user,'test purpose'); $(document).on('click', '#follow-button', function (e) { e.preventDefault(); $.ajax({ type: 'POST', url: '{% url "profiles:follow" %}', data: { user_toggle: user, csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val(), action: 'post' }, success: function (json) { document.getElementById("is_following").innerHTML = json['is_following'] }, error: function (xhr, errmsg, err) { } }); }) </script> urls.py app_name = 'profiles' urlpatterns = [ path('follow/',follow,name = 'follow'), ] views.py def follow(request): if request.POST.get('action') == 'post': result = '' profile_ = UserProfile.objects.get(user__username__iexact=request.user.username) is_following = False username_to_toggle=request.POST.get('user_toggle') follower = profile_.follower.filter(username__iexact=username_to_toggle).first() if follower: profile_.follower.remove(follower.id) else: new_follower = User.objects.get(username__iexact=username_to_toggle) profile_.follower.add(new_follower.id) is_following = True return JsonResponse({'is_following': is_following, }) if more information is require than tell me in a comment section. will update my question with that information. -
Jinja Statement ( {% for loop%}) cannot be read on line server
I deployed an ecommerce website on the live server using heroku but having issue with product images as they are not being displayed. The website is working fine on the local host but causing problem when being deployed online. I inspected the html code and found out that the live website doesn't show the jinja for loop template which is added to the html file. Can anyone please guide me on how to solve this issue? Here is the link to the website,https://ahad-ecommerce-website.herokuapp.com/ and also the code snippet for the html file main.html {% load static %} <!DOCTYPE html> <html> <head> <title> Ecom </title> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css" integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous"> <link rel="stylesheet" type="text/css" href="{% static 'css/main.css'%}"> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1" /> <script type="text/javascript"> var user = '{{request.user}}' function getToken(name) { var cookieValue = null; if (document.cookie && document.cookie !== '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = cookies[i].trim(); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } var csrftoken = getToken('csrftoken'); function getCookie(name) { … -
purchased_products = validated_data.pop("products") KeyError: 'products'
I have a M2M relationship between Product and Purchase. What I am trying to achieve is when a purchase is made, to also fill the PurchasedProduct(the through model) model. But every time I send the data to the API and I try to access the products key in the serializer from the validated_data a keyError exception is thrown but if I return the validated_data for the purpose of debugging the product key is part of the response. djangorestframework==3.11.0 django==2.2.10 class Product(Model): name = CharField(max_length=20, unique=True) date_added = DateTimeField(default=now) models.py class Purchase(Model): manager = ForeignKey('users.User', on_delete=PROTECT, related_name='purchases') quantity = DecimalField(max_digits=6, decimal_places=2) products = ManyToManyField('branches.Product', through='PurchasedProduct', through_fields=('purchase', 'product')) amount_fc = IntegerField(default=0) amount_usd = IntegerField(default=0) total_amount = IntegerField(default=0) date_purchased = DateTimeField(default=now) class PurchasedProduct(Model): purchase = ForeignKey('Purchase', on_delete=CASCADE, related_name="to_products", blank=True) product = ForeignKey('branches.Product', on_delete=CASCADE, related_name='purchases') unit_price = DecimalField(max_digits=12, decimal_places=4, default=0.00) quantity = DecimalField(max_digits=5, decimal_places=2) amount_fc = DecimalField(max_digits=10, decimal_places=2) date_purchased = DateTimeField(default=now) serializer.py class PurchasedProductSerializer(ModelSerializer): class Meta: model = PurchasedProduct fields = [ "id", "purchase", "product", "unit_price", "quantity", "amount_fc", "date_purchased" ] class PurchaseSerializer(ModelSerializer): # https://github.com/encode/django-rest-framework/issues/5403 products = PurchasedProductSerializer(source="to_products", many=True) class Meta: model = Purchase fields = [ "id", "manager", "quantity", "amount_fc", "amount_usd", "total_amount", "products", "date_purchased" ] def create(self, validated_data): purchased_products = validated_data.pop("products") manager = validated_data.pop('manager') … -
How do I implement a simple Python program in my Django web app?
I have this simple Python code: import random a = random.randint(0,101) if a >= 0 and a <= 10: return(a, "There is a 10% chance a is between 0, 10") else: return(a, "There is a 90% chance a is between 11, and 100") I want to be able to run and display the output from the program on a web app made with Django? For example that I have a Web page with a button. And when I click the button the programm is being run and the return is displayed next to the button.