Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Get Old Objects, Update, and then return old objects
I have an APIView that looks like this: class GetNotifications(ListAPIView): serializer_class = NotificationSerializer def get_queryset(self): notifications = Notification.objects.select_related().filter(user=self.request.user).order_by("-created_at") Notification.objects.select_for_update().filter(is_read=False, user=self.request.user).update(is_read=True) return notifications What I'm trying to do is get all notifications that the user has. These include notifications that have been read and that have been not read yet (hence the is_read field). I'd like to return both the is_read and the not is_read notifications.Once those objects are received then an update will happen to change the not read notifications to is read. What this means is that any user who accesses this API through the site will mean that they've read their notifications so we can set is_read=True...however, my current code returns the objects after updating them. I want to return the old objects prior to updating hence me assigning notifications to the old objects before updating. I believe this is due to lazy loading on Django's part. Is there a way/better way to solve this? -
Issue With Nested Comments Using MPTT in Django and Django Rest Framework API - Result In Detail Not Found
I'm trying to create a nested comment system using MPTT but using Django Rest Framework to serialize MPTT tree. I got the nested comments to work - and these comments are added, edited, and deleted by calling Django Rest Framework API endpoints only - not using Django ORM DB calls at all. Unfortunately, there is a bug I couldn't figure out! Although the comments are added, edited, and deleted fine - but when a seventh or eighth comment is nested - suddenly the first-in comment or first-in nested comments would become [detail: Not found.] - meaning it will return an empty result or throw an unknown validation error somewhere which I couldn't figure out why. This results in when clicking on edit or delete the buggy comments becoming impossible - but the GET part is fine since these buggy comments do show up in the comment section (or should I say the list part returns fine). The image I'll attach will show that when I entered comment ggggg, the comment aaaa and bbbb will throw errors when trying to edit or delete them. If I delete comment gggg, comment hhhh will also be deleted (as CASCADE was enabled) - and … -
'Django OperationalError: no such table: users_portal' in Django
I'm creating a webapp and I am attempting to access the 'Portal' page (created by myself) in the User's section on the in-built Django Admin backend page. However, when I try to access this page, the following error is outputted onto the terminal: django.db.utils.OperationalError: no such table: users_portal This error has stopped my from accessing the 'Portal' page and therefore, has hindered me from progressing with my webapp. Any suggestions on how to get rid of this error? Would be highly grateful and open to all suggestions! I have already tried to make the migrations, and have them migrated. I have also attempted the --fake migrations and unfortunately none of them have yielded to the result I expected. -
AttributeError at /sign-up and /sign-in 'WSGIRequest' object has no attribute 'is_ajax'
I am getting this problem, any help will appreciated, Im getting an arror trying to sign-in or sign-up.Error bellow. AttributeError at /sign-up 'WSGIRequest' object has no attribute 'is_ajax' I know that function is depreciated now, but i can't seem to fix the issue. mixins.py class AjaxFormMixin(object): ''' Mixin to ajaxify django form - can be over written in view by calling form_valid method ''' def form_invalid(self, form): response = super(AjaxFormMixin, self).form_invalid(form) if self.request.is_ajax(): message = FormErrors(form) return JsonResponse({'result': 'Error', 'message': message}) return response def form_valid(self, form): response = super(AjaxFormMixin, self).form_valid(form) if self.request.is_ajax(): form.save() return JsonResponse({'result': 'Success', 'message': ""}) return response views.py def profile_view(request): ''' function view to allow users to update their profile ''' user = request.user up = user.userprofile form = UserProfileForm(instance=up) if request.is_ajax(): form = UserProfileForm(data=request.POST, instance=up) if form.is_valid(): obj = form.save() obj.has_profile = True obj.save() result = "Success" message = "Your profile has been updated" else: message = FormErrors(form) data = {'result': result, 'message': message} return JsonResponse(data) else: context = {'form': form} context['google_api_key'] = settings.GOOGLE_API_KEY context['base_country'] = settings.BASE_COUNTRY return render(request, 'users/profile.html', context) class SignUpView(AjaxFormMixin, FormView): ''' Generic FormView with our mixin for user sign-up with reCAPTURE security ''' template_name = "users/sign_up.html" form_class = UserForm success_url = "/" … -
django channel image serializing error says You cannot call this from an async context - use a thread or sync_to_async
i have a Invoice serializer which include a image serilaizer as a invoice has relation one to many with image i got this error when i enable many=True in images field in invoice serializer Exception inside application: You cannot call this from an async context - use a thread or sync_to_async. Traceback (most recent call last): File "D:\projects\TaxiTR\env\lib\site-packages\django\contrib\staticfiles\handlers.py", line 101, in __call__ return await self.application(scope, receive, send) File "D:\projects\TaxiTR\env\lib\site-packages\channels\routing.py", line 62, in __call__ return await application(scope, receive, send) File "D:\projects\TaxiTR\env\lib\site-packages\channels\security\websocket.py", line 37, in __call__ return await self.application(scope, receive, send) File "D:\projects\TaxiTR\core\middleware.py", line 57, in __call__ return await super().__call__(scope, receive, send) File "D:\projects\TaxiTR\env\lib\site-packages\channels\middleware.py", line 24, in __call__ return await self.inner(scope, receive, send) File "D:\projects\TaxiTR\env\lib\site-packages\channels\sessions.py", line 47, in __call__ return await self.inner(dict(scope, cookies=cookies), receive, send) File "D:\projects\TaxiTR\env\lib\site-packages\channels\sessions.py", line 263, in __call__ return await self.inner(wrapper.scope, receive, wrapper.send) File "D:\projects\TaxiTR\env\lib\site-packages\channels\auth.py", line 185, in __call__ return await super().__call__(scope, receive, send) File "D:\projects\TaxiTR\env\lib\site-packages\channels\middleware.py", line 24, in __call__ return await self.inner(scope, receive, send) File "D:\projects\TaxiTR\env\lib\site-packages\channels\routing.py", line 116, in __call__ return await application( File "D:\projects\TaxiTR\env\lib\site-packages\channels\consumer.py", line 94, in app return await consumer(scope, receive, send) File "D:\projects\TaxiTR\env\lib\site-packages\channels\consumer.py", line 58, in __call__ await await_many_dispatch( File "D:\projects\TaxiTR\env\lib\site-packages\channels\utils.py", line 50, in await_many_dispatch await dispatch(result) File "D:\projects\TaxiTR\env\lib\site-packages\channels\consumer.py", line 73, in dispatch await handler(message) … -
The view post.views.view didn't return an HttpResponse object. It returned None instead
I want to create a new post using PostCreateView and go to the details page of the new post in the next step, but I get this error: (The view post.views.view didn't return an HttpResponse object. It returned None instead.) views class PostDetailView(View): """see detail post""" def get(self, request, post_id, post_slug): post = Post.objects.get(pk=post_id, slug=post_slug) return render(request, "post/detail.html", {"post": post}) class PostCreateView(LoginRequiredMixin, View): form_class = PostCreateUpdateForm def get(self, request, *args, **kwargs): form = self.form_class return render(request, "post/create.html", {"form": form}) def post(self, request, *args, **kwargs): form = self.form_class(request.POST) if form.is_valid(): new_post = form.save(commit=False) new_post.slug = slugify(form.cleaned_data["body"][:20]) new_post.user = request.user new_post.save() messages.success(request, "you created a new post", "success") return redirect("post:post-detail", new_post.id, new_post.slug) models class Post(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) body = models.TextField() slug = models.SlugField() img = models.ImageField(upload_to="%Y/%m/%d/") created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) urls app_name = 'post' urlpatterns = [ path('', views.BlogView.as_view(), name="home"), path('detail/<int:post_id>/<slug:post_slug>/', views.PostDetailView.as_view(), name="post-detail"), path('delete/<int:post_id>/', views.PostDeleteView.as_view(), name="post-delete"), path('update/<int:post_id>/', views.PostUpdateView.as_view(), name="post-update"), path('create/', views.PostCreateView.as_view(), name="post-create"), ] -
Django FieldError: Unsupported lookup 'kategorie' for IntegerField or join on the field not permitted
I have a Django Table with Crispy Filter and I would like to filter in Data table based on Category. But I am getting FieldError. I tried to define my filter field by this way in filters.py: kategorie = django_filters.CharFilter(label="Kategorie", field_name="ucet__cislo__kategorie__jmeno", lookup_expr='icontains') And I have following structure of models in models.py: class Data(models.Model): ucet = models.ForeignKey(Ucty, on_delete=models.CASCADE, null=True, blank=True) class Ucty(models.Model): cislo = models.IntegerField("Účet", blank=True, null=True) class Mustek(models.Model): ucet = models.ForeignKey(Ucty, on_delete=models.CASCADE) kategorie = models.ForeignKey(Kategorie, on_delete=models.CASCADE) class Kategorie(models.Model): jmeno = models.CharField("Kategorie", max_length=20, blank=True, null=True) Any idea how to correct field_name definition in filter? -
Field value is not displayed for editing in the form Django?
views.py dicfacultets = DicFacultets.objects.all() disfacultetsedit = DicFacultets.objects.get(id=id) form = FacultetsForm(request.POST, instance=disfacultetsedit) if request.method == 'GET': return render(request, 'tao/dicfacultetsedit.html', {'dicfacultets': dicfacultets, 'form': FacultetsForm(), }) else: try: if form.is_valid(): disfacultetsedit = form.save(commit=False) title = request.POST.get('title') disfacultetsedit.title = title disfacultetsedit.save() return redirect('dicfacultets') except TypeError: return render(request, 'tao/dicfacultets.html', {'dicfacultets': dicfacultets, 'error': 'error', 'form': form, }) return render(request, 'tao/dicfacultets.html', {'dicfacultets': dicfacultets, }) html {% for fac in dicfacultets %} ... # *call modal window for editing* <a href="facultetsedit/{{ fac.id }}" class="on-default edit-row" data-toggle="modal" data-target="#facultetsedit{{fac.id}}"><i class="fa fa-pencil"></i></a> # next call form method="POST" action="{% url 'facultetsedit' id=fac.id %}"> {{ form }} form in modal window when a modal window is called, the field is empty, but editing and saving work -
reverse lazy error NoReverseMatch at django DeleteView
I'm trying to return back to patient analyses list after deleting 1 analysis. But can't manage proper success url So this is my model: class PatientAnalysis(models.Model): patient = models.ForeignKey(Patient, on_delete=models.CASCADE) analysis_date = models.DateTimeField(help_text = "Разделяйте даты точками! Используйте '/' или '-'") # analysis_type = models.IntegerField(choices = ANALYSIS_CHOICES) #перевести в таблицу analysis_type = models.ForeignKey(AnalysisType, on_delete=models.CASCADE, default=1) analysis_data = models.DecimalField(max_digits=5, decimal_places=2) def __str__(self): return f"{self.patient}" def get_analysis_type(self): return f"{self.analysis_type}" def get_absolute_url(self): return reverse('journal:patient_analysis', kwargs={'hist_num_slug':self.patient.pk}) class Meta: unique_together = ('analysis_date','analysis_type',) Here's the class for list all analyses per patient class PatientAnalysisListView(ListView): model = PatientAnalysis template_name = 'journal/patient_analysis.html' context_object_name = 'analysis' def get_context_data(self, *, object_list=None, **kwargs): <...> return context def get_queryset(self): return PatientAnalysis.objects.filter(patient__hist_num=self.kwargs['hist_num_slug']).order_by('-analysis_date') And here i stuck with next code: lass PatientAnalysisDeleteView(DeleteView): # Form --> Confirm Delete Button # model_confirm_delete.html model = PatientAnalysis success_url = reverse_lazy('journal:patient_analysis', kwargs={'key': model.patient}) And getting error: `NoReverseMatch at /journal/patientanalysis_delete/49 Reverse for 'patient_analysis' with keyword arguments '{'key': <django.db.models.fields.related_descriptors.ForwardManyToOneDescriptor object at 0x7fb88b8c0d90>}' not found. 1 pattern(s) tried: ['journal/patient_analysis/(?P<hist_num_slug>[-a-zA-Z0-9_]+)\Z'] Request Method: POST Request URL: http://127.0.0.1:8000/journal/patientanalysis_delete/49 Django Version: 4.1.3 Exception Type: NoReverseMatch Exception Value: Reverse for 'patient_analysis' with keyword arguments '{'key': <django.db.models.fields.related_descriptors.ForwardManyToOneDescriptor object at 0x7fb88b8c0d90>}' not found. 1 pattern(s) tried: ['journal/patient_analysis/(?P<hist_num_slug>[-a-zA-Z0-9_]+)\Z'] Exception Location: /home/verts/.local/lib/python3.10/site-packages/django/urls/resolvers.py, line 828, in _reverse_with_prefix Raised during: journal.views.PatientAnalysisDeleteView Python Executable: … -
Add menu items in wagtail ModelAdminGroup
I want to add non ModelAdmin items in a ModelAdminGroup as for example a MenuItem, like this: MenuItem('A title', '/some_url/', icon_name='doc-full-inverse', order=1) But I could not found any hints neither in Wagtail documentation nor on stackoverflow. My ModelAdminGroup looks like this class MyModelAdminGroup(ModelAdminGroup): menu_label = "Some stuff" menu_icon = "fa-suitcase" menu_order = 1 items = (Model1Admin, Model2Admin) I try to do this: class MyModelAdminGroup(ModelAdminGroup): menu_label = "Some stuff" menu_icon = "fa-suitcase" menu_order = 1 items = (Model1Admin, Model2Admin, MenuItem('A title', '/some_url/', icon_name='doc-full-inverse', order=1)) Ad some other idiotic stuff But all all crashed ... I finally found an easy solution. I just write it bellow just in case it could help the community other people -
Responding with a custom non simple object from a Django/Python API to the front
I'm a newbie building APIs with django/python I built a dictionary object (it has lists in it), and I want to send it to the front through one of the responses: JsonResponse, HttpResponse, etc. What could be the way to do it? I tried with several of them without a good response, or I get an error, or a bad response Thanks in advance Rafael -
how can I response to the front a custom-built object in Django/Pyton
I’m newbie in building APIs with Django/Python I built an object in the server side, and I want to send it to the front. I built it on the fly, without a class. it's a dictionary object with arrays in it def whole_menu(request, restaurant_id): menu = {} menu["restaurant"] = Restaurant.objects.get(id=restaurant_id) menu["categories"] = [] category_serializer = Category.objects.filter(restaurant=restaurant_id) category_index = 0 for category in category_serializer: menu["categories"].append({}) menu["categories"][category_index]["name"] = category.name menu["categories"][category_index]["description"] = category.description menu["categories"][category_index]["image_url"] = category.image_url menu["categories"][category_index]["dishes"] = [] dish_serializer = Dish.objects.filter(category=category.id) dish_index = 0 for dish in dish_serializer: menu["categories"][category_index]["dishes"].append({}) menu["categories"][category_index]["dishes"][dish_index]["name"] = dish.name menu["categories"][category_index]["dishes"][dish_index][ "description" ] = dish.description menu["categories"][category_index]["dishes"][dish_index][ "price" ] = dish.price menu["categories"][category_index]["dishes"][dish_index][ "image_url" ] = dish.image_url dish_index = dish_index + 1 category_index = category_index + 1 print(menu) return HttpResponse(menu) I tried sending the object with JsonResponse, HttpResponse and even rest_framework.response.Response, but it won’t work Whit this approach I get restaurantcategories (???) What could be the way to send a custom-built object to the front? -
on_delete oprator in Django framework
i want to build a ModelViewSet class that recive an id from url for instance localhost/id and based on that id i can either show the object with matching id or delete the object but im having trouble passing the id in the url my view is like this: class delete_or_show_View(viewsets.ModelViewSet): serializer_class = ObjectSerializer permission_classes = [permissions.IsAuthenticated] http_method_names = ['get', 'delete'] def get_queryset(self,mid): #Show the object def destroy(self, mid=None): #delete the object and my url is like this router.register('(?P<object_id>\d+)', views.delete_or_show_View, basename='do_stuff') Im getting errors for missing aruguments or that the delete method is not allowed please if someone can guide me how i can do this properly and explain it will be great thank you -
what does .models mean in djagno?
I am trying to import a class named 'Questions' from my models.py to admin.py from .models import Questions I don't understand why we have to use a period in '.models', what does it mean and what exactly is it pin pointing to? I tried this combinations but it was no avail from models import Questions from Model.models import Questions -
How to save all incoming emails to a model
I want to save all incoming emails to a django model. django-mailbox has an email table but is inactive. django-anymail's AnymailInboundMessage looks like it would work well but it is not a django model class, just a generic python object for processing incoming emails, not storing them. I know I could cut and paste the source from AnymailInboundMessage into a django model class and then turn the members into Django fields, but I am wondering if there is a way to wrap or subclass a python class such as AnymailInboundMessage into a django model. TIA -
Is there a way to run a discord bot and django code through heroku?
Everything seems to work until i get to the build part on heroku, -----> $ python manage.py collectstatic --noinput Starting up None shards... 130 static files copied to '/tmp/build_a4988370/staticfiles', 8 unmodified, 361 post-processed. Connected to shard 0 Shard 0 ready -----> Timed out running buildpack Python ! Push failed This is what happens it runs the website code and it starts by bot (shard-ed bot), and then it wont continue the build and it just fails, does anyone have any ideas, here is some of my code #!/usr/bin/env python """Django's command-line utility for administrative tasks.""" import os import sys import asyncio from threading import Thread def main(): """Run administrative tasks.""" os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'settings.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) if __name__ == '__main__': from discordbot.main import _main loop = asyncio.new_event_loop() loop.create_task(_main()) Thread(target=loop.run_forever).start() ^manage.py def main(): """Run administrative tasks.""" os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'settings.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? … -
Django show loading indicator if no validation errors
Im doing a webapp with Django and I want to display a loading indicator while I wait for my Python function to do its calculations. However, the loading indicator gets displayed (forever) if there are input validation errors. How do I check if there are validation on submit and avoid the loading indicator displaying if there are input errors? My code below. HTML template: <div class="loader" style="display:none"></div> <form method="POST" id="content" ...> ... <div>{{ form.visible_fields.0 }} </div> <div class="form-errors errorlist"> {% for error in form.visible_fields.0.errors %} <div>{{error}}</div> {% endfor %} </div> ... <button type="submit" onclick="loading()">Submit</button> JS function in template: function loading(){ $(".loader").show(); $("#content").hide(); } -
Select from a dropdown list of users to assign them to a certain Room
I'm trying to create a dropdown list of users that can be changed and updated if the admin user desires. I am able to see the dropdown list of users but when I go to create the Room and try to select a user, it doesn't get saved and that field remains blank. I used a ModelChoiceField in my forms.py file to create the dropdown list of users. I think its because I didn't call it correctly in the views.py but I'm not sure how to proceed. Any help is much appreciated Here is my code so far forms.py class RoomForm(ModelForm): userList = forms.ModelChoiceField(queryset=User.objects.all()) class Meta: model = Room fields = '__all__' exclude = ['host', 'participants'] views.py @login_required(login_url='login') def createRoom(request): form = RoomForm() topics = Topic.objects.all() if request.method == 'POST': topic_name = request.POST.get('topic') topic, created = Topic.objects.get_or_create(name=topic_name) Room.objects.create( host=request.user, topic=topic, userList = request.POST.get('userList'), name=request.POST.get('name'), status=request.POST.get('status'), priority=request.POST.get('priority'), type=request.POST.get('type'), description=request.POST.get('description'), ) return redirect('home') context = {'form': form, 'topics': topics} return render(request, 'room/room_form.html', context) @login_required(login_url='login') def updateRoom(request, pk): room = Room.objects.get(id=pk) form = RoomForm(instance=room) topics = Topic.objects.all() if request.user != room.host: return HttpResponse('You are not allowed here!!') if request.method == 'POST': topic_name = request.POST.get('topic') topic, created = Topic.objects.get_or_create(name=topic_name) room.name = request.POST.get('name') room.topic = … -
Django ORM. Check that sum of additional field of m2m relation model equals 100
I want to implement a check on this relation, to ensure that all ticket's weight in sum gives me 100. class PortfolioTicker(models.Model): """ Helper model for M2M relationship between Tickers and Portfolios """ portfolio = models.ForeignKey(Portfolio, models.PROTECT, related_name="tickers") ticker = models.ForeignKey(Ticker, models.PROTECT) weight = models.FloatField(null=False) def __str__(self) -> str: return f"{self.portfolio} {self.ticker} {self.weight}" -
Django on Railway
I have fully tested on localhost Django app. When hosted on Railway I cannot login to app or admin. It is showing all migration ok, no database configuration errors, but when trying to login it is showing wrong user/password. Any ideas, please? Checked for errors but it is not showing any. -
Calculating functions with python / django
I'm building a python / django portfolio and i'm having a very hard time with one of my Gym / BMI calculator. I'm trying to have a user input their current Weight and Height, so they can have a BMI result that will be visible from the frontend, and then POST and saved from the Backend models. I just don't know how to include a .py class that i created that will allow the user to input those details from the models and have calculation done in the frontend from the input textfield. Please help...:-) ` from django.db import models # Create your models here. (<-- This is my Model, where i'll save the calculation) class BMI(models.Model): Name = models.CharField(max_length=50) Surname = models.CharField(max_length=50) Weight = models.IntegerField() Height = models.IntegerField() def __str__(self): return self.Name # Create your forms here. (<-- This is my form, where user will be inputting their Weight and Height) from django import forms from django.forms import ModelForm from . models import BMI class BMIForm(ModelForm): class Meta: model = BMI fields = ['Weight', 'Height'] ` from django.shortcuts import render from . models import BMI from . forms import BMIForm # Create your views here. def Home(request): BMIOutcome = … -
How can I acces to my AWS S3 bucket in django?
I am working for the first time with aws s3, where I have images to upload from the django admin, everything works perfect on localhost, but once deployed the images are uploaded but not displayed on the web My setting.py AWS_ACCESS_KEY_ID = 'my acceskey' AWS_SECRET_ACCESS_KEY = 'my secret key' AWS_STORAGE_BUCKET_NAME = 'mybucketname' AWS_DEFAULT_ACL = None AWS_S3_CUSTOM_DOMAIN = f'{AWS_STORAGE_BUCKET_NAME}.s3.amazonaws.com' AWS_S3_OBJECT_PARAMETERS = {'CacheControl': 'max-age=86400'} STATIC_LOCATION = 'static' PUBLIC_MEDIA_LOCATION = 'media' MEDIA_URL = f'https://{AWS_S3_CUSTOM_DOMAIN}/{PUBLIC_MEDIA_LOCATION}/' DEFAULT_FILE_STORAGE = 'portfolio.storages.MediaStore' My models class Project(models.Model): name = models.CharField(max_length=100) description = models.CharField(max_length=200) link = models.CharField(max_length=250) another_link= models.CharField(max_length=250, null= True, blank=True) image = models.ImageField(upload_to='media/') My views def project(request): projects = Project.objects.all().order_by('-id').values() return render(request, "works.html", {"projects": projects}) My template {% for project in projects %} {% csrf_token %} <div class="row"> <div class="col-md-12 col-md-offset-1"> <div class="row"> <div class="col-xs-12 col-md-6"> <h3>{{project.name}}</h3> <p style=> {{project.description}} </p> <a href="{{project.link}}" target="_blank" class="btn btn-default">Source Code</a> <a href="{{project.another_link}}" target="_blank" class="btn btn-default">See Live</a> </div> <div class="col-xs-6 col-md-4"> <img src="{{project.image.url}}" width="360" height="200" > </div> </div> </div> </div> {% endfor %} In the Html not return a asw link, return this <img src="" width="360" height="200"> Images are loaded perfectly in the S3 bucket but are not displayed in the HTML. -
How to convert excel file to json in specific format
I need a specific JSON output from excel in order to insert data to my database. Right now, the input must come from an Excel table. This is the output I want [ { "model": "client.Restaurant", "pk": 1, "fields": { "name": "KOPITAN CLASSIC WHITE COFFEE", "description": "An ideal place for students and employees to release stress.", "location_lon": 100.481, "location_lat": 5.17818, "operating_hours_start": "10AM", "operating_hours_end": "10PM", "owner_id": 18, "image_url": "kopitanClassic.jpg" } } ] This is the output that I get from using online excel to json converter. [ { "name": "KOPITAN CLASSIC WHITE COFFEE", "description": "An ideal place for students and employees to release stress.", "location_lon": 100.481, "location_lat": 5.17818, "operating_hours_start": "10AM", "operating_hours_end": "10PM", "owner_id": 18, "image_url": "kopitanClassic.jpg" } ] -
how to set foreign by post method in django?
models.py class Courses(models.Model): course_name=models.CharField(max_length=50) course_price=models.IntegerField() class Exam(models.Model): exam_name=models.CharField(max_length=101) course=models.ForeignKey(Courses,on_delete=models.CASCADE,default='python') exam_time=models.DateTimeField() views.py def Examadd(request): mycourses = Courses.objects.all() context = {'mycourses': mycourses} if request.method == 'POST': newexam = request.POST.get('examname') course = request.POST.get('courses') examtime = request.POST.get('time') new = Exam.objects.create(exam_name=newexam,course=course,exam_time=examtime) new.save() messages.success(request, "Course created successfully") return redirect('Courselist') return render(request,'addexam.html',context addexam.html <!DOCTYPE html> <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"> <title>Document</title> </head> <body> <h1>Add New Exam</h1> <form method="post"> {% csrf_token %} <label>Examname:</label> <input type="text" name="examname"> <label>Course:</label> <select name="courses"> {% for i in mycourses %} <option value={{i.id}}>{{i.course_name}}</option> {% endfor %} </select> <label>Exam time and date:</label> <input type="text" name="examtime"> <button type="submit">Add</button> </form> </body> </html> I am doing a project elearning.I want a dropdown list with courses and pass its ids to Exam table.course id is a foreign key.I want to pass the courseid to course column in Exam table.By this code I gets error as,Cannot assign "'1'": "Exam.course" must be a "Courses" instance. -
How to save a wish icon checked after page refresh -Django
Trying to keep selected icon in product cards active after page refresh when the user refresh the page I want that the icon to remain a full heart and not an empty heart. How could I do that? views.py @login_required def add_wishlist (request): if request.is_ajax() and request.POST and 'attr_id' in request.POST: if request.user.is_authenticated: data = Wishlist.objects.filter(customer = request.user,product_id= int(request.POST['attr_id'])) if data.exists(): data.delete() else: Wishlist.objects.create(customer= request.user,product_id = request.POST['attr_id']) else: print("No Product is Found") return redirect("products:product_all") product_all.html <div id='alCarrito'class="like-container"> {% if product in wishlisted_list %} <span class="like heart " id="id" attr_id="{{product.id}}" action_url="{% url 'products:add_wishlist' %}"> <i class="fas fa-heart"></i> </span> {% else %} <span class="like" id="id" attr_id="{{product.id}}" action_url="{% url 'products:add_wishlist' %}"><i class="far fa-heart"></i></span> {% endif %} </div> wishlist.js $(document).ready(function(){ $(".like").click(function(){ var attr_id = $(this).attr('attr_id') var action_url = $(this).attr('action_url') var that = $(this) $.ajax({ url: action_url, type: "POST", data: {'attr_id': attr_id }, headers: { "X-CSRFToken": $.cookie("csrftoken") }, success: function (response) { console.log("Success") that.toggleClass("heart"); }, }); }); });