Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to add a select element to a table (add object to m2m relation)
I have two manytomany related models Projects and Users. I would like that when selecting a user from the list, it would be added to the table, that is (user.member.add(project)). Would UpdateView help me? How? [enter image description here](https://i.stack.imgur.com/Be5w2.png) I thought about doing it by editing the psot method of UpdateView to add the relationship but I don't need data to be loaded in any form, I just want it to be inserted into the table and transparent to the user -
why Index error at / list index out of range?
hello im having a problem with the index code in my views.py, aparrently the HTML index is out of range for some reason i dont understand, because before i wanted to make the page to add images as avatars work perfectly fine the index .html is in a templates folder , inside the APP folder, and i created a media folder outside of the APP for storage of media this is the views.py from django.http import HttpResponse from django.shortcuts import render from django.views.generic import ListView from django.views.generic.detail import DetailView from django.views.generic.edit import UpdateView, DeleteView, CreateView from django.contrib.auth.views import LoginView, LogoutView from django.contrib.auth.decorators import login_required from django.contrib.auth.mixins import LoginRequiredMixin from .forms import PosteoForm, SignUpForm, UserEditForm from .models import Posteo, Avatar from django.urls import reverse_lazy # Create your views here. def mostrar_index(request): imagenes = Avatar.objects.filter(user=request.user.id) return render(request, 'index.html', {'url': imagenes[0].images.url}) def mostrar_gallery(request): return render(request,'gallery.html') def mostrar_contact(request): return render(request,'contact.html') def cursoPost(request): return render(request,'Posts.html') @login_required def crear_post(request): if request.method == 'POST': posteo = PosteoForm(request.POST) print('posteo') if posteo.is_valid(): data = posteo.cleaned_data posteo = Posteo (titulo=data['titulo'], texto=data['texto']) posteo.save() return render(request,'index.html') else: posteo = PosteoForm() print('formulario') return render(request,'Posts.html',{'posteo':posteo}) def buscar_post(request): return render(request,'buscador.html') def buscador (request): if request.GET.get ('titulo', False): titulo = request.GET ['titulo'] post = Posteo.objects.filter(titulo__icontains=titulo) return … -
Upload picture with ajax in django application
I'm stuck with a problem in a django application. I have an ajax function to upload a single image to a model but, so far, I wasn't able to succeed in my goal. What I basically achieve is that I get the file from Ajax but, when I try to send it on my Django request in the view, the result is None object. Let me post some code to be more clear: HTML: {% for question in questions %} <tr> <td>{{forloop.counter}}</td> <td>{{question.id}}</td> <td>{{question}}</td> <td> <a title="{% trans "Edit Question" %}" class="btn btn-warning btn-sm" href="{% url 'administration:edit_question' pk=question.id %}"><i class="fas fa-edit"></i></a> <a title="{% trans "See Details" %}" class="btn btn-primary btn-sm ms-3" href="{% url 'administration:question_details' pk=question.id %}" ><i class="fas fa-eye"></i></a> <a title="{% trans "Delete Question" %}" href="{% url 'administration:delete_question' pk=question.id %}" id="delete_question" class="btn btn-sm btn-danger ms-3"><i class="fas fa-trash"></i></a> <button title="{% trans "Add Image" %}" class="btn btn-sm btn-success ms-3" data-bs-toggle="modal" data-bs-target="#addImageModal{{question.id}}"><i class="fas fa-file-image"></i></button> {% if question.explanation %} <a title="{% trans "Edit Explanation" %}" href="{% url 'administration:edit_explanation' pk=question.explanation.id %}" class="btn btn-sm btn-info ms-3"><i class="fas fa-edit"></i></a> <button title="{% trans "Add Explanation Image" %}" data-bs-toggle="modal" data-bs-target="#addExplanationImageModal{{question.id}}" data-questionId="{{question.id}}" class="btn btn-sm btn-secondary explanationModals ms-3"><i class="fas fa-plus"></i></button> {% else %} <a title="{% trans "Add Explanation" %}" href="{% url … -
Django saving nested formsets that are related to each other column cannot be null error
There are two nested formsets and they are related to each other. When I increase the extra field in the second formset, I get the error column cannot be null. I have no problem saving both forms as one. Here is my error : The error Here is my forms : class UserTaskForm(forms.ModelForm): class Meta: model = UserTask fields = ['user_id','task_types_id','store_house_id','description'] class TaskSourcesForm(forms.ModelForm): class Meta: model = TaskSources fields = ['product_id', 'product_amount'] TaskSourcesFormSet = modelformset_factory( TaskSources, fields=('product_id', 'product_amount',), extra=2, ) UserTaskFormFormSet = modelformset_factory( UserTask, fields=('user_id','task_types_id','store_house_id','description',), extra=1, ) here is my views : @login_required(login_url="login") def addUserTask(request): user_task_form = UserTaskFormFormSet(queryset=UserTask.objects.none(),initial=[{'user_id': request.user}]) formset = TaskSourcesFormSet(queryset=TaskSources.objects.none()) if request.method == 'POST': user_task_form = UserTaskFormFormSet(request.POST) formset = TaskSourcesFormSet(request.POST) if user_task_form.is_valid(): for form in user_task_form: user_task = form.save(commit=False) user_task.author = request.user user_task.save() if formset.is_valid(): for form_data in formset: task_sources = form_data.save(commit=False) task_sources.user_task_id = UserTask(id = user_task.id) task_sources.save() messages.success(request,"Task added successfully!") return redirect(".") context = { "user_task_form" : user_task_form, "formset" : formset, } return render(request,"user/addtask.html",context) How to save two model formsets together(relates to each other) in one view? what is the wrong part when i do it? -
Multiple queries and chart js problem - Optimize Django hardcode
Hello mates. I have an project with patient laboratory analyses. The problem is my hardcoding but i didn't find the solution to make it simplier. My aim was to make a dataframe for each analysis group and draw chartjs. So let me explain what i did /w code: I have a patient analysis model: class PatientAnalysis(models.Model): patient = models.ForeignKey(Patient, related_name='analyses', on_delete=models.CASCADE) analysis_date = models.DateTimeField(default=datetime.now, 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_all_info', kwargs={'hist_num_slug':self.patient.pk}) class Meta: unique_together = ('analysis_date','analysis_type',) It has analysis type: class AnalysisType(models.Model): a_name = models.CharField(max_length=16) a_measur = models.CharField(max_length=16) a_ref_min = models.DecimalField(max_digits=5, decimal_places=2, null=True, blank=True) a_ref_max = models.DecimalField(max_digits=5, decimal_places=2, null=True, blank=True) analysis_group = models.ManyToManyField(AnalysysGroup) def __str__(self): return f"{self.a_name}" Which comes with Analysis group: class AnalysysGroup(models.Model): group_name = models.CharField(max_length=32) # analysis = models.ManyToManyField(AnalysisType, blank=True) def __str__(self): return f"{self.group_name}" I tried to show analyses for 1 person for each day and group it by type then draw chartjs multi table: def patient_filtered_analysis(request, pk, ag): patient_info = Patient.objects.get(pk=pk) analysis_group_list = AnalysysGroup.objects.all() analysis_group = AnalysysGroup.objects.filter(id=ag)[0] analysis_types_in_group = AnalysisType.objects.filter(analysis_group=ag) patient_filtered_analysis = PatientAnalysis.objects.filter(patient__hist_num=pk).filter(analysis_type__analysis_group=ag).order_by('analysis_type','-analysis_date') analysis_date_list … -
Consume a docker container inside Django docker container? Connecting two docker containers
I have a Django container and I want to consume another DL container inside it? For example, I have a Django app that predicting images classes and I want to make the prediction using a docker container and not a python library. That Django app will be containerised as well. In production, I will have three docker containers: Django container + Postgres container + YoloV5 container. How can I link the Django with the YoloV5 so that the prediction inside the Django will be done using the YoloV5? I want to connect a deep learning container with Django container to make prediction using the DL container and not a python package. -
Why swagger loading so long time and not answer
enter image description here views @swagger_auto_schema(request_body=BoardDetailSerializer, operation_summary="update method") def patch(self, request, pk): board = self.get_object(pk) serializer = BoardDetailSerializer(board, data=request.data, partial=True) if serializer.is_valid(): serializer.update() return Response(serializer.data, status=status.HTTP_200_OK) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) serializers class BoardSerializer(serializers.Serializer): id = serializers.IntegerField(read_only=True) title = serializers.CharField(max_length=30) background = serializers.ImageField(required=False, default=None) def create(self, validated_data): board = Board( title=validated_data['title'], background=validated_data['background'], ) board.save() return board def to_representation(self, instance): representation = super().to_representation(instance) representation['column'] = ColumnSerializer(instance.column.all(), many=True, context=self.context).data return representation [ 1. - --- ](https://i.stack.imgur.com/A4yjf.png) Idk what to do. I removed the 'Partial = True', and restarted patch request many time, but this is not workin. -
Django: Quizapp with Question and Answer Model
I would like to create a Quiz app with Django. Where the Questions can be stored in a DB and more users can add more questions in Admin. and each question can have an answer from the user input. This is a basic version of what I tried so far, Simple example of My Models: QuestionModel ID question author AnswerModel ID Answer question_id author So, When I create an AnswerForm(): it shows the form, but the question shows up as a dropdown instead of labels. and it is not creating fields for each question. It just creates one input field and a dropdown for the question. I know it does that because I have question_id as FK in the Answer Model. Is there a better way to get this done? I am new to Django -
Execute task at specific times django
I am in the process of writing my own task app using Django and would like a few specific functions to be executed every day at a certain time (updating tasks, checking due dates, etc.). Is there a way to have Django run functions on a regular basis or how do I go about this in general? Does it make sense to write an extra program with an infinite loop for this or are there better ways? -
Django convert InMemoryUploadedFile PDF to images
I need to convert uploaded PDF to images. I'm using pdf2image function convert_from_path() to convert the image but am getting an error Unable to get page count. My code looks somewhat like this: pages = convert_from_path(request.FILES['file'].read()) And the error: Error message Code line with error Is there a better way to do this? -
hey I want to create a freelancing web app like fiverr i want to know how to save payments on the website than withdraw them to visa or baknk
hey I want to create a freelancing web app like fiverr i want to know how to save payments on the website than withdraw them to visa or baknk hey I want to create a freelancing web app like fiverr i want to know how to save payments on the website than withdraw them to visa or baknk -
djangorestframework_camel_case (django parser library) does not work with multipart nested data
for eg. if post data is like: Postman Input then in view we get parsed data like: Output in Viewset settings.py: settings parameter I tried using parser_classes NestedMultiPartParser and CamelCaseMultiPartParser in ViewSet but no solution. -
how to compare two dictionaries and display the values that differs in template?
I try to compare two dictionaries and if on key, value differs from the other dictionary then print the difference key, value in red. I think my views.py is correct. But how to show the difference in the template? So I have views.py: def data_compare(): fruits = { "appel": 3962.00, "waspeen": 3304.07, "ananas": 24, } set1 = set([(k, v) for k, v in fruits.items()]) return set1 def data_compare2(): fruits2 = { "appel": 3962.00, "waspeen": 3304.07, "ananas": 30, } set2 = set([(k, v) for k, v in fruits2.items()]) return set2 def data_combined(request): data1 = data_compare() data2 = data_compare2() diff_set = list(data1 - data2) + list(data1 - data2) return render(request, "main/data_compare.html", context={"diff_set": diff_set}) and template: <!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> <div class="container center"> {% for key, value in diff_set.fruits.items %} <span {% if key in data1.condition %} style="color: red;" {% endif %}>{{ key }}: {{value}}</span><br> {% endfor %} </div> <div class="container center"> {% for key, value in diff_set.fruits2.items %} <span {% if key in data2.condition %} style="color: red;" {% endif %}>{{ key }}: {{value}}</span><br> {% endfor %} </div> </body> </html> But nothing is returned. Question: how to return the key, … -
Serialize same level object from Many to many field
I have to serialize spare instance from spare variety many to many field. Models.py class SpareVariety(models.Model): quality = models.ForeignKey(Quality, max_length=255, on_delete=models.CASCADE, null=True, blank=True) variety_name = models.CharField(max_length=255, null=True, blank=True) property = models.ForeignKey(SpareProperty, null=True, blank=True, on_delete=models.CASCADE) purchase_price = models.PositiveIntegerField(help_text="in INR", blank=True, null=True) retail_price = models.FloatField(help_text="All values in INR", blank=True, null=True) dealer_price = models.FloatField(help_text="All values in INR", blank=True, null=True) stock_available = models.PositiveIntegerField(blank=True, null=True,default=True) spare_costing = models.ForeignKey(SpareCosting, on_delete=models.CASCADE, blank=True, null=True) spare_discount = models.ForeignKey(Discount, on_delete=models.CASCADE, blank=True, null=True) is_available = models.BooleanField(default=False) date_added = models.DateTimeField(auto_now=True) date_updated = models.DateTimeField(auto_now_add=True) class Spare(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) spare_variety = models.ManyToManyField(SpareVariety, related_name='spare_varieties', null=True, blank=True) name = models.CharField(max_length=255, help_text="Enter the name of spare (Ex:Display, Speakers)") type = models.ForeignKey(Type, blank=True, null=True, on_delete=models.CASCADE) date_added = models.DateTimeField(auto_now=True) date_updated = models.DateTimeField(auto_now_add=True) def __str__(self): return '%s - %s' % (self.product.name, self.name) Serialize the spare model from spare variety serializer serializers.py class SpareVarietySerializer(serializers.HyperlinkedModelSerializer): spare_costing= SpareCostingSerializer(many=False, read_only=False) spare_discount = DiscountSerializer(many=False, read_only=False) quality = QualitySerializer(many=False, read_only=False) property = SparePropertySerializer(many=False, read_only=False) spare_name = serializers.CharField(read_only=True, source="spare.name") class Meta: model = SpareVariety fields = ['id','quality','variety_name','purchase_price','spare_name','retail_price','property', 'dealer_price', 'stock_available','spare_costing','spare_discount','is_available', 'date_added', 'date_updated',] -
Save nested objects in Django from a dictionary
I have a small problem with repeating myself by creating nested related objects. I get a JSON from an API call which I convert it to a nested dictionary. This nested dict has a lot of related objects which I have to check if their fields have a related_model in order to create the related object before creating the actual object... I have 3 functions that are the same, but with different name: get_or_create_object get_or_create_related_object get_or_create_subrelated_object Here is the code: def get_or_create_object(object_dict:dict, Klass): # Main object just_fields_dict = object_dict just_related_objects_dict = {} for key in object_dict.copy().keys(): key = _validate_field_name(key) related_model = getattr(Klass, key).field.related_model if related_model: if isinstance(object_dict[key], list): print(object_dict[key]) else: value = _clean_object_dict(object_dict[key]) obj = get_or_create_related_object(object_dict=value, Klass=related_model) just_related_objects_dict[key] = obj just_fields_dict.pop(key, None) composed_object_dict = {**just_fields_dict, **just_related_objects_dict} obj, _ = Klass.objects.get_or_create(**composed_object_dict) return obj def get_or_create_related_object(Klass, object_dict): # Related object to main object just_fields_dict = object_dict just_related_objects_dict = {} for key in object_dict.copy().keys(): related_model = getattr(Klass, key).field.related_model if related_model: object_dict = _clean_object_dict(object_dict[key]) obj = get_or_create_subrelated_object( Klass=related_model, object_dict=object_dict ) just_related_objects_dict[key] = obj just_fields_dict.pop(key, None) composed_object_dict = {**just_fields_dict, **just_related_objects_dict} obj, _ = Klass.objects.get_or_create(**composed_object_dict) return obj def get_or_create_subrelated_object(Klass, object_dict): # Related object to "Related object to main object" # In other words: subrelated object just_fields_dict … -
Make form input searchable for items from a different model
I have a form that will be used to add a drinks recipe to my database. The form allows for up to 10 ingredients plus their amount to be added as well as information, name and a picture of said drink. I now want to make the text input blocks to be linked to a model that contains all possible ingredients in my database. I would like these text blocks to work as a searchbar for the ingredients. Is there a way to make this work? see my setup below: Template view so far: {% extends 'base.html' %} {% block content %} <div class='container'> <div class='row'> <form method="POST" enctype='multipart/form-data'> {% csrf_token %} <div class='row'> <div class='col'> <div class='mb-5'> {{form.drink_name.label_tag}} <br> {{form.drink_name}} </div> {% for ingredients in form %} {% if forloop.counter < 21 %} {{ingredients.label_tag}} <br> {{ingredients}} <br> {% endif %} {% endfor %} </div> <div class='col'> {% for ingredients in form %} {% if forloop.counter > 21 %} {{ingredients.label_tag}} <br> {{ingredients}} <br> {% endif %} {% endfor %} </div> <div class='row my-4'> <input type='submit' value='submit' class='my-2'> </div> </form> </div> {% endblock content %} Models: ingredient model: class Bottle(models.Model): category_name = models.ForeignKey('Category', on_delete=models.SET_NULL,null=True,blank=True) brand = models.ForeignKey('Brand', on_delete=models.CASCADE) bottle_name = models.CharField(max_length=255) … -
Python: Delete a rows in db if it is not in the API
In my database, I have a Trader and Position table. For each position retrieved via the API url, I look if it exists in my table. If the position does not exist, I create it. I would like to delete the Position in my database if it does not exist in the API. I can't modify the data coming from the url because it comes from an external API. Only the data (encryptedUid, symbol) are fixed, the others are data related to the price of a cryptocurrency Here is what the JSON data from the url looks like: { 'symbol': 'BTCUSDT', 'encryptedUid': '08F22AF1161739C74509F9F38F188A8D', '......': ......, } My code (Django Command) def handle(self, *args, **kwargs): traders = Trader.objects.all() for t in traders: uid = t.encrypted_uid payload = {'encryptedUid': uid, 'tradeType': 'PERPETUAL'} positions = requests.post(self.URL_POSITION, json=payload).json()['data']['otherPositionRetList'] if positions is not None: for p in positions: p['uid'] = uid find_positions = Position.objects.filter(trader=t).filter(symbol=p['symbol']) if not find_positions: trader = Trader.objects.get(encrypted_uid=p['uid']) self.save(trader, p) Data from my db <QuerySet [{'id': 117, 'trader_id': 1, 'symbol': 'BNBUSDT', 'entry_price': 342.966434, 'amount': 350.0, 'direction': '', 'leverage': 25.0, 'closed': False}]> I tried to make a loop on all the Positions. To loop over the API to find the matches with (encryptedUid & … -
Django querysets being cached when using custom manager and properties
I have a Django model that uses properties to derive "fields" whenever called. I did this rather than creating these as database values as these "fields" are all calculable from model fields and should be calculated on the fly when required. As these do not exist at the database-level and can't be accessed via queryset I created a custom manager with methods that look-up all the ids of a queryset with the condition of a property or properties required and then re-lookup a queryset for those ids. What is happening is that the resulting querysets are completely cached and any updates to the underlying database is not reflected when refreshing the views. I am using djange-tables2 and filters so the views are mostly based of generic form views calling the custom manager methods as input into the queryset variable. Does anyone have any ideas as to what I am doing wrong? Any pointers will be greatly appreciated. The models.py is as follows: from django.db import models from datetime import date import datetime from business.calendar import Calendar from django.urls import reverse from simple_history.models import HistoricalRecords from taggit.managers import TaggableManager from contacts.models import Contact # ToDo: Move calendars to global yml and … -
Django Pylint failed to parse the output
I am running a django server on Linux environment. When running pylint from commandline there is no error. Versions pylint 2.15.5 astroid 2.12.12 Python 3.10.6 (main, Nov 2 2022, 18:53:38) [GCC 11.3.0] pylint_django 2.5.3 VSCode: Version: 1.73.1 (system setup) Commit: 6261075646f055b99068d3688932416f2346dd3b Date: 2022-11-09T04:27:29.066Z Electron: 19.0.17 Chromium: 102.0.5005.167 Node.js: 16.14.2 V8: 10.2.154.15-electron.0 OS: Windows_NT x64 10.0.22000 Sandboxed: No pylint --load-plugins=pylint_django --django-settings-module=server.settings /root/server/app/test.py But when .pylintrc file is editted and I add these values to the config. I get the following error. ##########Linting Output - pylint########## [ERROR 2022-10-30 19:15:36.361]: Linter 'pylint' failed to parse the output '. SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) at s.parseMessages (/root/.vscode-server/extensions/ms-python.python-2022.18.2/src/client/linters/pylint.ts:48:39) at s.run (/root/.vscode-server/extensions/ms-python.python-2022.18.2/src/client/linters/baseLinter.ts:99:31) at runMicrotasks (<anonymous>) at process.messages (node:internal/process/task_queues:96:5) at s.runLinter (/root/.vscode-server/extensions/ms-python.python-2022.18.2/src/client/linters/pylint.ts:21:15) Anyone who has encountered the same problem and knowns how to fix this issue. Tried running the command and that worked, but when it's run from the default python extension it gives an error. -
CSS files not loading in django
This is my first Django project. I cannot load CSS files onto my website. i've done everything possible. Project Directries firstproject/ static/ css/ <CSS files> Settings.py/ static files STATIC_URL = 'static/' STATICFILE_DIRS = [ os.path.join(BASE_DIR, "static") ] STATIC_ROOT = os.path.join(BASE_DIR,'assets') urls.py urlpatterns += static(settings.STATIC_URL,document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT) HTML file <link rel="stylesheet" href="{% static 'css/bootstrap-grid.css' %}"> -
How to create a ModelViewset when model has OneToOneField?
The idea is to have a model like this: class Object(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) name = models.CharField(max_length=256) def __str__(self): return self.name and then create a serializer and a ModelViewSet related to it. The problem is that ModelViewSet must return a queryset but I want to work with single objects due to the one-to-one relation. How should I proceed? -
Django : How to create a Task with Subtask system
I am trying to develop something that allows me to create Tasks to complete in a project and then you can add subtasks so each task etc. Example : The project is to build a house, the main tasks are let's say, the plumbing, then the roof and finally the rest of the architecture. For the plumbing, you then need to do the sketches first, then to figure out what kind of pipes, etc. So for each task you have subtasks and so on. class Project(models.Model): project_name = models.CharField(max_length=100) class Task(models.Model): task_name = models.CharField(max_length=100) task_project = models.ForeignKey('Project', on_delete=models.SET_NULL, null=True) class SubTask(models.Model): subtask_name = models.CharFiedl(max_length=100) subtask_parent = models.ForeignKey('Task', on_delete=models.SET_NULL, null=True) So here in my code, each Project have like several Main Tasks and then we get the Subtasks. The goal is that I can keep on creating Subtasks that then belong to a parent Subtask if that makes sense. I can't figure out what type of connection that is or how to approach the issue. Many thanks ! -
How can I get all objects of a model and it's fields?
I have a Product Model and I want to be able to count all it's objects in a method so I can render the total number in a template, same for each category but I can only do that with the number_of_likes method. class Category(models.Model): name = models.CharField(max_length=45) ... class Product(models.Model): author = models.ForeignKey(User, default=None, on_delete=models.CASCADE) title = models.CharField(max_length=120, unique=True) category = models.ForeignKey(Category, default=None, on_delete=models.PROTECT) product_type = models.CharField(max_length=30, choices=TYPE, default='Physical') likes = models.ManyToManyField(User, related_name='like') ... def number_of_likes(self): return self.likes.count() def number_of_products(self): return self.all.count() def number_of_products_for_category(self): return self.all.category.name.count() def __str__(self): return str(self.title) + ' from ' + str(self.author) -
How to create a function that change is_active=False to True?
How to create a function that change is_active=False to True? The case is that I want to create a function that change the value in an user case from "is_active=False" to "is_active=True". At my final point I want to create "an email verification" when someone registered. If someone registered on my website, he receive an email with the verification. I guess I have to create a function that change "is_active=false" on "is_active=true" when someone clicked the link that call the function? Mean I well? Thanks! def activateEmail(request, user, email, first_name): send_mail( #email subject f"Activate your user account, {user.first_name} !", #email content f"Hi {user.first_name}!\nPlease click on the link below to confirm your registration\n{SITE_URL}\nhttps://patronite.pl/wizard/autor/profil?step=3", #email host user EMAIL_HOST_USER, #email to [user.email], #if error True is better. fail_silently=False, ) The case is that I want to create a function that change the value in an user case from "is_active=False" to "is_active=True". At my final point I want to create "an email verification" when someone registered. If someone registered on my website, he receive an email with the verification. -
How to combine data from different functions in one function?
I have a django application. And I try to combine two dictionaries in one function? So that both dictionaries will render in the same template. So I have the views.py: def data_compare(): fruits = { "appel": 3962.00, "waspeen": 3304.07, "ananas": 24, } condition = ["ananas"] context = {"fruits": fruits, "condition": condition} return context def data_compare2(): fruits2 = { "appel": 3962.00, "waspeen": 3304.07, "ananas": 30, } condition = ["ananas"] context = {"fruits2": fruits2, "condition": condition} return context def data_combined(request): context = data_compare(), data_compare2() return render(request, "main/data_compare.html", context) And template looks: {% extends 'base.html' %} {% load static %} {% block content %} <!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> <div class="container center"> {% for key, value in fruits.items %} <span {% if key in condition %} style="color: red;" {% endif %}>{{ key }}: {{value}}</span><br> {% endfor %} </div> <div class="container center"> {% for key, value in fruits2.items %} <span {% if key in condition %} style="color: red;" {% endif %}>{{ key }}: {{value}}</span><br> {% endfor %} </div> </body> </html> {% endblock content %} But then I get this error: TypeError at /data_combined context must be a dict rather than tuple. Question: …