Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
TypeError: Object of type Vehicle is not JSON serializable
when I try to filter my model I got this error TypeError: Object of type Vehicle is not JSON serializable my model class Vehicle(models.Model): driver_id = models.ForeignKey(Driver,on_delete=CASCADE,unique=True,null=True, blank=True) make = models.CharField(max_length=150) model = models.CharField(max_length=150) plate_number = models.CharField(max_length=10,validators = [validate_plate_numberLATIN,validate_plate_numberCYRYLLIC], unique=True) created_at = models.DateTimeField(default=NOW) updated_at = models.DateTimeField(default=NOW) def __str__(self): return self.make -
what causes Unhandled exception in wfastcgi.py: Traceback (most recent call last) in django +IIS
I create web app by django and IIS 10 web service on windows serevr 2019. I have problem in log file of wfastcgi log file that configured in web.config. text of log and problem is: 2021-12-10 16:26:35.568572: Unhandled exception in wfastcgi.py: Traceback (most recent call last): File "c:\python37\lib\site-packages\wfastcgi.py", line 774, in main record = read_fastcgi_record(fcgi_stream) File "c:\python37\lib\site-packages\wfastcgi.py", line 158, in read_fastcgi_record data = stream.read(8) # read record OSError: [Errno 22] Invalid argument 2021-12-10 16:26:35.615397: Running on_exit tasks 2021-12-10 16:26:35.646693: wfastcgi.py 3.0.0 closed 2021-12-10 16:59:42.309400: wfastcgi.py will restart when files in C:\inetpub\wwwroot\ are changed: .*((\.py)|(\.config))$ 2021-12-10 16:59:42.340650: wfastcgi.py 3.0.0 initialized each 1 hour wfastcgi raise OSError: [Error 22] and run exit task and after minutes restart again. I added follow line to web.config but no any impact on this error: <add key="SCRIPT_NAME" value="/Music_backend" /> whole web.config text is as bellow: <?xml version="1.0" encoding="utf-8"?> <configuration> <system.webServer> </system.webServer> <appSettings> <add key="PYTHONPATH" value="C:\inetpub\wwwroot\Music_backend" /> <add key="WSGI_HANDLER" value="Music_backend.wsgi.application" /> <add key="DJANGO_SETTINGS_MODULE" value="Music_backend.settings" /> <add key="SCRIPT_NAME" value="/Music_backend" /> <add key="WSGI_LOG" value="c:\wfastcgi.log"/> </appSettings> <location path="" overrideMode="Deny"> <system.webServer> </system.webServer> </location> <location path="" overrideMode="Allow"> <system.webServer> <handlers> <add name="Python FastCGI" path="*" verb="*" modules="FastCgiModule" scriptProcessor="c:\python37\python.exe|c:\python37\lib\site-packages\wfastcgi.py" resourceType="Unspecified" requireAccess="Script" /> </handlers> </system.webServer> </location> </configuration> in addition i active Django.server , Django.request, Django.db.Backend LOGGING … -
Django migration- How to fix uniqueness=True on migration (backwards)?
A field in my model used to have no constraints. But in order to avoid problems in the future i need to make the field unique=True. This will obviously raise a Key (field)=(foo) is duplicated What is the best practice to fix that migration backwards in order to not raise an error? -
comparing forloop variables to a number
<ul class="navbar-nav mr-auto"> <li class="nav-item"> <a class="nav-link" href="/">Home </a> </li> <li class="nav-item"> <a class="nav-link" href="{% url 'store' %}">Products</a> </li> {% for x in cat %} <li class="nav-item"> <a class="nav-link" href="#">{{x.name}}</a> </li> {% if forloop.counter >3%} <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" data-toggle="dropdown" href="#">More</a> <div class="dropdown-menu"> <a class="dropdown-item" href="#">{{x.name}}</a> </div> </li> {% endif %} {% endfor %} </ul> So what i want here is the objects in the for loop counter be more that three then all should come in the dropdown menu which but it is not working as of now and giving me this error what is the best way to handle this problem Could not parse the remainder: '>3' from '>3' Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 4.0 Exception Type: TemplateSyntaxError Exception Value: Could not parse the remainder: '>3' from '>3' Exception Location: C:\Users\saran\OneDrive\Desktop\e-com-test\core\hienv\lib\site-packages\django\template\base.py, line 692, in __init__ Python Executable: C:\Users\saran\OneDrive\Desktop\e-com-test\core\hienv\Scripts\python.exe Python Version: 3.9.6 Python Path: ['C:\\Users\\saran\\OneDrive\\Desktop\\e-com-test\\core', 'C:\\Users\\saran\\AppData\\Local\\Programs\\Python\\Python39\\python39.zip', 'C:\\Users\\saran\\AppData\\Local\\Programs\\Python\\Python39\\DLLs', 'C:\\Users\\saran\\AppData\\Local\\Programs\\Python\\Python39\\lib', 'C:\\Users\\saran\\AppData\\Local\\Programs\\Python\\Python39', 'C:\\Users\\saran\\OneDrive\\Desktop\\e-com-test\\core\\hienv', 'C:\\Users\\saran\\OneDrive\\Desktop\\e-com-test\\core\\hienv\\lib\\site-packages'] Server time: Fri, 10 Dec 2021 13:32:32 +0 -
How to relate multiple same models related_name in django
I have two models Movie and Actor class Actor(models.Model): id = models.UUIDField(default=uuid.uuid4, primary_key=True, editable=False) name = models.CharField(name="name", max_length=2000, blank=True, null=True) class Movie(models.Model): id = models.UUIDField(default=uuid.uuid4, primary_key=True, editable=False) name = models.CharField(name="name", max_length=2000, blank=True, null=True) actors = models.ManyToManyField(Actor, related_name='movie_actor') Now I would like to let the users to add their favourite actors like class MyUser(AbstractUser): actors = models.ManyToManyField(Actor, related_name='user_actor') Now, I would like to make the response for each movie so that the movie can tell that this movie has one/more of their favourite actors or not? -
how to send CSRF token using flutter http request
how to send CSRF token using flutter HTTP request I have a Django based project that uses django-rest-framework for API, when I send a POST request using Postman it works perfectly fine,, but when I send an HTTP.post request from my flutter application I get this response : Forbidden 403 CSRF verification failed. Request aborted. You are seeing this message because this HTTPS site requires a “Referer header” to be sent by your Web browser, but none was sent In django am using function based view to receive the requests: @api_view(['POST']) @permission_classes([AllowAny,]) @csrf_exempt def create_user(request): ...... ..... then in the URLS : path("api/v1/create_user/", api.create_user, name="create_user"), and am sending the request in flutter : http.post(Uri(myURL),header={ 'Content-Type': 'application/x-www-form-urlencoded', } ,body={ 'my_key':'my_value', }) -
Django and Python
Good afternoon, I am new to Django / Python and I am finding my way around things. I've been searching around on the internet but cant really find an answer to my question which is the following: I am trying to create a Django website that will have several pages. On each of these pages I am looking to create a Python task. One of these tasks on one of the pages might be for a user to enter an input such as a name John Smith and click search. I wish for the Python script to then go and search for all John Smith related material on the internet and return results. Firstly would the Python script be able to sit on the Django web page to do this ? Or am I misunderstanding what Django can do. Secondly will I just mix the script in with the HTML etc ? Thank you in advance. -
Accessing model data in python django
I have a a Django model: class Myvalues(models.Model): items_list = models.JSONField() I have populated this model in Django admin. I now want to access the data inside this model. However I am getting an error that says: 'Manager' object has no attribute ‘items_list' The way I am trying to access it is as follows: Print(Myvalues.objects.items_list.values()) I don’t understand why this is coming up as the class has that model in it. Out of interest I printed the all() result of Myvalues class, like so: print(Myvalues.objects.all()) this resulted in the following: <QuerySet [<Myvalues: Myvalues object (1)>]> How can I access the data that’s in my items_list model? -
Django Urls conflict
In my App urls.py i have a urls conflict, every one is pointing to a different View, they have same syntax but one have a urls.py path('dashboard/categories/<str:category_name>', views.CategoryProductsView.as_view(), name='category_products') path('dashboard/categories/add_category', views.AddCategoryView.as_view(), name='add_category'), When i disable (comment) the first one the second url works fine , that's why i think that the problem comes from a url conflict -
what kind of architecture pattern is my application?
I am trying to understand what kind of architecture my application has. I have a simple Django App which can create, read, update and delete from a MySQL database I have connected to it. This app is for one specific customer. now I would either say it is a monolithic architecture because it is all coded in the same application and if some component goes down(presentation, logic or data) the whole application will break. but I would maybe also say it was a layered(n-tier) architecture maybe? because Django it self is MVT architecture? So what is the right to say? -
django: customized primary key based on form template
I have the following model: UNIT = (("pounds","pounds"),("pcs","pcs"),("kg","kg"),("g","g")) CATEGORIES = (("finished good","finished good"),("raw material","raw material")) class Product_Hierarchy(models.Model): product_code = models.CharField(max_length=100, primary_key=True) parent_product_code = models.ForeignKey("self",on_delete=models.CASCADE) product_name = models.CharField(max_length=100) product_category = models.CharField(max_length=100,choices=CATEGORIES, default="finished good") stock_on_hand = models.FloatField(max_length=1000000) unit = models.CharField(max_length=100, choices = UNIT, default="pcs") and I am trying to set the product code to be build in accordance with the category in which the product belongs to. It does not seem possible to automatically build it after the product category selection. Because the product creation is rendered in two templates: finished good registration template and the other one is the raw material registration template. I am wondering if I could write something that detects from where the model is accessed and automatically generate the code corresponding to the category. Here is what my form look like: CATEGORY_CHOICES = [ ('finished good', 'finished good'),('raw material', 'raw material'), ] UNIT = [("pounds","pounds"),("pcs","pcs"),("kg","kg"),("g","g")] class UpdateProductForm(forms.ModelForm): product_category = forms.CharField(widget=forms.Select(choices=CATEGORY_CHOICES), label='Category') product_name = forms.CharField(label = 'Product Name') stock_on_hand = forms.CharField(label = 'Stock On Hand') unit = forms.CharField(widget=forms.Select(choices=UNIT), label='Unit') class Meta: model = Product_Hierarchy fields = ("product_name", "product_category", "stock_on_hand", "unit") I have not yet found a way to do that, the documentation does not cover it and my … -
How can we achive max of every stock valid date with foreign key name with ORM Django
model class stock(models.Model): id = models.AutoField(primary_key=True) symbol = models.CharField(max_length=30) name = models.CharField(max_length=50) sector = models.CharField(max_length=50,blank=True,null=True) validtill = models.DateTimeField() created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(blank=True,null=True) class quote(models.Model): id = models.AutoField(primary_key=True) stock = models.ForeignKey(stock, related_name='quote', on_delete=models.CASCADE) valid_till = models.DateTimeField() ... Current solution quote.objects.values('valid_till').annotate(max_date=Max('valid_till')).values('stock','valid_till','price','created_at') {'stock': 984, 'valid_till': datetime.datetime(2021, 12, 9, 19, 4, 16), 'max_date': datetime.datetime(2021, 12, 9, 19, 4, 16)} getting the result from above query but only thing I want is get the stock symbol from foreign key table instead of id I want foreign key table column value -
Multi-model RSS Feed in Django
I am trying to figure out how to have a multi-model RSS feed in Django. That is, I would like Django to serve updates of two different models under one RSS url. Here is what I have thus far class ArticleFeed(Feed): title = "Articles" link = "/articles/" description = "RSS feed of Articles" def items(self): return Article.objects.filter(is_published=1) def item_title(self, item): return item.title def item_description(self, item): return item.get_description() def item_link(self, item): return item.get_absolute_url() class VideoFeed(Feed): pass class atomFeed(Feed): feed_type = Atom1Feed In urls.py I have the following path path('rss/', ArticleFeed(), name="article_feed"), I would like rss/ to provide updates to both the Article and Video model. The Video model has similar fields but is non-verbatim. -
Django translation.override() not working
I literally copy-pasted this from the docs: class CustomerAdmin(ExportActionMixin, admin.ModelAdmin): def mail(self, request, queryset): with translation.override('nl'): print(_('Hello')) still prints Hello instead of Hallo Docs state this should work regardless of what settings or middleware you've got enabled. I tried nl, de, and dk, it's always English. I'm on Django 3.6 -
How to check if a request consists of session id and csref token in the cookie in Django rest framework?
my rest_framework authentication and permission classes "DEFAULT_PERMISSION_CLASSES": [ "rest_framework.permissions.IsAuthenticated", "rest_framework.permissions.IsAdminUser", "rest_framework.permissions.AllowAny", ], "DEFAULT_AUTHENTICATION_CLASSES": ( "rest_framework_simplejwt.authentication.JWTAuthentication", "rest_framework.authentication.SessionAuthentication", "rest_framework.authentication.BasicAuthentication" ), login view class UserLoginView(generics.RetrieveAPIView): """ View for a user to login through 1FA. The view provides a post request that accepts a email and password. Returns a jwt token as a response to authenticated user. """ throttle_scope = "login" permission_classes = (permissions.AllowAny,) serializer_class = UserLoginSerializer def post(self, request): """ POST request to login a user. """ #if session key is not present then create a session for the user serializer = self.serializer_class(data=request.data) serializer.is_valid(raise_exception=True) if not request.session.session_key: request.session.save() return Response("logged in") In my login view if user credentials are valid i am creating a user session if not created yet. For all other requests i need to ensure that user has a active session i.e. a session id in the cookie and csrf token to secure the application , is there method provided by rest framework to do that or i need to write my own permission classes for the views -
calling external API results in alert messages
I havwe a fine working script, that behaves odly: def get_info(self, env, limit = None): token = self.get_token()["access_token"] if limit == None: url = f"""{env}infos""" else: url = f"""{env}infos?limit={limit}""" payload = {} headers = {"Authorization": f"""Bearer {token}"""} response = requests.request("GET", url, headers = headers, data = payload) if response.status_code != 200: return False return json.loads(response.text) There is a simple view returning the data to the frontend: class TheView(TemplateView): template_name = "apihlp/index.html" def get_context_data(self, *args, **kwargs): context = super().get_context_data(**kwargs) data = get_data() context.update({"data": data}) return context with get_data looking like this: def get_data(): infos = get_infos("some_url", limit = 20) ORGADATA = [] counter = 0 for info in infos: name = f"""<h3 style="color:green">{counter}: {info["organization"]}</h3>""" try: owners = "".join([f"""<li>{info["mail"]}""" for info in infos["owner"]]) except: owners = "" ORGADATAHTML = f"{name}<h4>owners:</h4>{owners} ORGADATA.append({"counter": counter, "id": info["id"], "name": info["organization"], "HTML": ORGADATAHTML}) html part is even simpler: {% for item in data %} {{ item.HTML|safe }} {% endfor %} I know from doing the same call in postman, I can receive 50+ objects. When I set limit to 10 or 20 everyhing works fine (works fine in Postman with set to 10000 as well ...). But in Django I get: [![enter image description here][1]][1] and after … -
How to use count() in serializers?
I am trying to get count of article likes,but the problem is that i am facing with various errors. Here is my code: class ArticleLikeSerializer(serializers.ModelSerializer): class Meta: model = ArticleLike fields = ('id',"author","article",'timestamp') class ArticleSerializer(serializers.ModelSerializer): articlelikes_set = ArticleLikeSerializer(source='articlelikes',required=False,many=True) total_likes = serializers.SerializerMethodField(read_only=True) class Meta: model = Article fields = ('id','author','caption','total_likes','articlelikes_set') def get_total_likes(self, language): return articlelikes_set.count() Here is my error: name 'articlelikes_set' is not defined How can i solve the problem? -
python: dynamic keys in nested dictionary
i am using the django shell to try to create such a dictionary: {'SECTION ONE': {'Category One': [<Price: price element one>], 'Category Two': [<Price: price element one>, <Price: price element two>]}, 'SECTION TWO': {'Category One': [<Price: price element one>, <Price: price element two>]}} but this pieces of code: dict[section][category] = [x] change the "price element one" in "two" like the result below. dict = dict() for x in price.objects.all(): if section not in dict: dict[section] = { category: [x] } else: dict[section][category] = [x] dict[section][category].append(x) {'SECTION ONE': {'Category One': [<Price: price element two>], 'Category Two': [<Price: price element two>, <Price: price element two>]}, 'SECTION TWO': {'Category One': [<Price: price element two>, <Price: price element two>]}} how can you keep all the elements? -
How to share localhost port over local network
I created webpage on local server with django framework (python). I have acces to it under address http://localhost:8000/. Now I want to share it over local network. I try to do it with Windows firewall Inbound/outbound rules, but it seems either I do something wrong or it's not enough. -
Add filter Comment in Django
I have a problem with adding comments only spaces or enters. I don't know how filter that. If the user sends a normal comment it is transferred to the current page but if send only spaces or enters it is transferred to the URL comment. This my is code: models.py class Post(models.Model): """Post Model""" hash = models.UUIDField(default=uuid.uuid4, editable=False) title = models.CharField("Title", max_length=200) slug = models.SlugField(max_length=200, unique=True) author = models.ForeignKey( settings.AUTH_USER_MODEL, related_name="created_by", on_delete=models.CASCADE, default=current_user.CurrentUserMiddleware.get_current_user, ) category = TreeForeignKey(Category, verbose_name="Category", related_name="items", on_delete=models.CASCADE) tags = TaggableManager() image = models.ImageField("Image", upload_to=get_timestamp_path) content = RichTextUploadingField() create_at = models.DateTimeField(auto_now_add=True) def __str__(self): return f"{self.title}" def get_absolute_url(self): return reverse("main:post_detail", args=[self.slug]) def save(self, *args, **kwargs): if str(self.hash) not in self.slug: self.slug = f"{self.slug}-{self.hash}" super().save(*args, **kwargs) def get_comment(self): return self.comment_set.all() class Comment(models.Model): user = models.ForeignKey(User, verbose_name="User", on_delete=models.CASCADE) post = models.ForeignKey(Post, verbose_name="Post", on_delete=models.CASCADE) text = models.TextField(verbose_name="Comment") create_at = models.DateTimeField("Date of creating", auto_now=True) class Meta: verbose_name = "Comment" verbose_name_plural = "Comments" def __str__(self): return str(self.user) views.py class PostDetail(DetailView, MultipleObjectMixin): model = Post context_object_name = 'post' paginate_by = 10 template_name = 'main/post_detail.html' def get_context_data(self, **kwargs): comments = Comment.objects.filter(post=self.get_object()) context = super(PostDetail, self).get_context_data(object_list=comments, **kwargs) return context class AddComment(LoginRequiredMixin, CreateView): """Add Comment""" model = Post form_class = CommentForm def form_valid(self, form): form.instance.user = self.request.user form.instance.post_id … -
I want to make a simple face detection program with opencv and django
I found out how to get the webcam going in django and how to detect faces but i cant seem to find out how to combine both , any help would be appreciated face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml') def home(request): context = {} return render(request, "home.html", context) class VideoCamera(object): def __init__(self): self.video = cv2.VideoCapture(0) (self.grabbed, self.frame) = self.video.read() threading.Thread(target=self.update, args=()).start() def __del__(self): self.video.release() def get_frame(self): image = self.frame _, jpeg = cv2.imencode('.jpg', image) return jpeg.tobytes() def update(self): while True: (self.grabbed, self.frame) = self.video.read() def gen(camera): while True: frame = camera.get_frame() yield(b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n\r\n') def detection(camera): while True: _, img = gen(camera) gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) faces = face_cascade.detectMultiScale(gray, 1.1, 4) for (x, y, w, h) in faces: cv2.rectangle(img, (x, y), (x+w, y+h), (255, 0, 0), 2) k = cv2.waitKey(30) & 0xff if k==27: break return img this is how i tried to combine both @gzip.gzip_page def detectme(request): cam = VideoCamera() return StreamingHttpResponse(detect(cam), content_type="multipart/x-mixed- replace;boundary=frame") this is the home.html incase i messed something up in there {% load static %} {%load widget_tweaks %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>DJAGO_OPENCV</title> </head> <body> {% block body %} <h1></h1> <table> <tr> <td width="50%"> <img src="http://127.0.0.1:8000/detectme" style="width:1200px;" /> </td> <td width="50%"> … -
Django: count every same value in a object.filter
I have a CourseEmailPersonEven model that has this: class CourseEmailPersonEvent(models.Model): uid = models.UUIDField(primary_key=True, default=uuid.uuid4) action = models.CharField(max_length=32) is_filtered = models.BooleanField(default=False) user_agent = models.CharField(max_length=255, null=True, blank=True) ip = models.GenericIPAddressField(null=True, blank=True) ip_address = models.ForeignKey(Ip, on_delete=models.SET_NULL, null=True, blank=True) created_at = models.DateTimeField(auto_now_add=True) course_email_person = models.ForeignKey( CourseEmailPerson, related_name="events", on_delete=models.CASCADE ) In a viewset (retrieve), i'm getting CourseEmailPersonEvent's informations about one single account. But I wanna add the amount of same "ip_address" used from every accounts (even mine). And I don't know what to do: class UtilsViewSet(viewsets.ViewSet): @action(detail=False, methods=["get"], url_path="emails/events/ips") def emails_events_ip(self, request, *args, **kwargs): account = get_object_or_404(models.Account, uid=self.kwargs["account_pk"]) ips_events_count = ( models.CourseEmailPersonEvent.objects.filter( course_email_person__account=account, action="open", ip_address__isnull=False, ) .values("ip_address") .annotate(Count("ip_address")) .order_by("-ip_address__count") )............ Here the result I wanna have in final: (to add that "ip_address_used_all_account" line) [ { "ip_address": "4ead446d-28c5-4641-b44d-f1e3aa7d26f8", "ip_address__count": 1, "ip_address_used_all_account: 2, "is_filtered": false, "ip": "80.150.22.32", "country_code": "FR", "asn": "4b2698b3-bf86-4674-8d69-f4a038a8200a", "asn_name": "FREE SAS" } ] -
Show list of related objects in Django
I have an issue with displaying list of related articles in my Q&A DetailView. I have a field where user can connect an article to Q&A from admin site. What I want is to display these related article models.py class QA(models.Model): id = models.AutoField(primary_key=True) author = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True, null=True, on_delete=models.SET_NULL) #settings INSTALLED_APPS title = models.CharField(max_length=750) category = models.ForeignKey(Category, on_delete = models.CASCADE, blank=True) related_articles = models.ManyToManyField(Article, default=None, blank=True, related_name='related_article') slug = models.SlugField(unique=True, blank=True) class Article(models.Model): id = models.AutoField(primary_key=True) author = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True, null=True, on_delete=models.SET_NULL) #settings INSTALLED_APPS title = models.CharField(max_length=200) category = models.ForeignKey(Category, on_delete = models.CASCADE, blank=True) slug = models.SlugField(unique=True, blank=True) views.py class QADetailView(LoginRequiredMixin, DetailView): login_url = 'login' redirect_field_name = 'login' template_name = 'QADetailView.html' model = QA def get_context_data(self, **kwargs): categories = Category.objects.all() related_articles = Article.objects.filter(related_article=self.kwargs['id']) #No idea what to put in filter context['related_article'] = related_articles context['categories'] = categories return context QADetailView.html {% for article in related_article %} {{article.title}} {% endfor %} -
Saving dropdown menu selection as a cookie in Django
I'd like to save a user selection from a dropdown menu as a cookie. I've seen this question asked before but never fully in python. I wish to use these two cookies in running a simple piece of code so there is no need for a database to be used. Here is my current HTML code: <form role="form" method="post"> {% csrf_token %} <div class="form-group"> <label for="dog-names">Choose a dog name:</label> <select name="dog-names" id="dog-names" onchange="getSelectValue"> <option value="rigatoni">Rigatoni</option> <option value="dave">Dave</option> <option value="pumpernickel">Pumpernickel</option> <option value="reeses">Reeses</option> <option value="{{ current_name }}"> {{ current_name }}</option> </select> <br/> <label>Current dog: {{ current_name }}</label> </div> <button type="submit" value="Submit" class="btn btn-info">Submit</button> </form> Python def cookies_test(request): template_name = 'cookies.html' current_name = "Rigatoni" # default name if request.method == 'GET': if 'name' in request.COOKIES: current_name = request.COOKIES['name'] elif request.method == 'POST': current_name = request.POST.get('name') response = render(request, 'test.html', { "current_name": current_name }) response.set_cookie('name', current_name) return response The python works if I give a value to {{ current_name }} All I want is to be able to save a value from a dropdown menu in a variable so I can save it as a cookie Any advice at all would be appreciated :) -
Is there a more faster and efficient ways to send email in django so that the user does not have to wait the entire time the page loads
I am making a website where a user registers to book an instructor for a certain period of time according to a plan he chooses. There are three plans from which a user can choose namely 7days, 14days and 21days. After registering, the user needs to accept an agreement and then based on the plan he has chooses an expiration date is set from the day the user has accepted the agreement. Now after the user, has accepted the agreement, a copy of the agreement is sent to the user as well as the owners of the website through email. The owners want this system, where the copy of agreement is recieved by both the user and them. I am able to make this happen, and the site is working fine in the testing phase. So basically, two emails are sent after the user accepts and a Contract model is updated. Now, I have noticed that sending two emails takes a good of time, and the page keeps on loading until both the emails are sent, and then the redirects and all happens for the user. This waiting time may trigger some users to press back interrupting the smtp connection, …