Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
adding required files to custome user when registration in django
I’m really new in Django and I would like to create a register form to login user. I would like this form have additional and required fields. the problem is when I try to fill the sign up registration directly on the web, the user is not registered, but if I do it in /admin section, the user is saved, so I have used custom user So first I have created class in model.py file: class Account (AbstractBaseUser): email = models.EmailField(verbose_name="email", max_length=60, unique=True) username = models.CharField(max_length=30, unique=True) date_joined = models.DateTimeField( verbose_name='date joined', auto_now_add=True) last_login = models.DateTimeField(verbose_name='last login', auto_now=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) phone_regex = RegexValidator( regex=r'^\+?1?\d{9,15}$', message="Phone number must be entered in the format: '+999999999'. Up to 15 digits allowed.") phone_number = models.CharField( validators=[phone_regex], max_length=17, blank=True) # validators should be a list role = models.CharField(max_length=50) store = models.CharField(max_length=50) aisle = models.CharField(max_length=50, unique=True) user_identification = models.CharField(max_length=30, unique=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username', 'first_name', 'last_name', 'phone_number', 'role', 'store', 'aisle', 'user_identification'] objects = MyAccountManager() def __str__(self): return self.email # if user is admin, can chenge def has_perm(self, perm, obj=None): return self.is_admin def has_module_perms(self, app_label): return True @property def … -
How to pass dynamic lookups from the request.GET right to filter?
Sending query like this /?field1=value1 in the request.GET i have {'field1': ['value1']}. So doing .filter(**request.GET) i send to it (field1=['value1']) instead of (field1='value1'). How i can take strings instead of arrays? -
React front-end to receive updates from a running process in Django back-end
I'm trying to generate a large PDF file that isn't feasible to do client-side. From the React FE, the user can select a category they want to run, and submit it to the Django BE. Django will then iterate through all of the items in that category to produce the PDF server-side, then send it to the FE when it is done. That much I pretty much have sorted out. However, what I want to implement is that as it is iterating through the items in the category, it is updating FE with which item is currently at, where it is in the queue, and how many total items are in the queue. From that, a percentage completed and an estimated time remaining can be calculated. A regular axios HTTP request doesn't seem like it would do the trick because it is terminated when it receives a response. Unless I iterate through the items in the FE and make an HTTP request for each item, but that doesn't seem like the best way to go about this. I'm just not sure what libraries I will need or what tech I need to be looking at to implement this, so that … -
Add a foreign key to AbstractUser
I have this two models: class User(AbstractUser): pass class Listing(models.Model): listing_id = models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID') title = models.CharField(max_length=64) owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="listing") I would like to do the following in the User model: class User(AbstractUser): listing = models.ForeignKey(Listing, on_delete=models.CASCADE) But i'm getting the following error: NameError: name 'Listing' is not defined Is it possible to add a foreign key to abstractuser? -
Django Beginner: Display value of RawQuerySet
I am using a RAW SQL query to get the record of each week's sale and then sum it up and show it on the web page. Here's my query: sales = addCustomer.objects.raw("SELECT SUM(productPrice) FROM cms_addcustomer WHERE date <= %s and date >= %s", [startdate, weekDate]) Already using the datetime library to get the date and everything is working fine on this end. When I try to display the result I get this message on my webpage: Total Sales: Rs.<RawQuerySet: SELECT SUM(productPrice) FROM cms_addcustomer WHERE date <= 2020-07-29 and date >= 2020-07-23> Here is a screenshot. I just want to display the sum of the Sales on my webpage but I am not sure how to do it. I have read most of the answers on StackOverFlow but I was unable to understand them as I am complete beginner. Please help. Thank you. -
Django ForeignKey only delete "child" element
I've followed the starting tutorial and my admin page looks like this I am trying to delete a choice by selecting the "Delete?" option and clicking "Delete", but after doing so it prompts me to delete the entire question and its corresponding choices. How can I only delete individual choices? I've found that on_delete=models.CASCADE is most likely the culprit, and I've found the alternatives, but none of these seem to just simply remove the Choice and revert the question to the state it was before I added the Choice. I am a complete beginner and any help is much appreciated. -
How to use Pycharm with Virtual Environment / Django?
Good afternoon everyone, I recently finished working with pygame and now I'm starting to learn Django because I've always wanted to make my own website. Everyone who teaches Django tells their viewers they need a "virtual environment". I spent a whole day understanding what it is and how to create one, activate it, deactivate, install packages, pip freeze, etc etc etc.... I understood that part atleast the basics. I'm going to be using Pythons built in "venv" and not "virtualenv", "pipenv" or any other virtual environment tool. From what I learned about virtual environments, they recommend NOT to place stuff inside the virtual environment. Ok that I got... I've been using Pycahrm as my IDE and has helped me a lot to learn programming. My main question is: Will the way I use Pycharm change NOW that I'm getting into Django and virtual environments? With pygame or tkinter I just opened a new project (example: "robot_game") in Pycharm, a new directory was created with the name of "robot_game" and inside that folder another folder called "venv" was created. All my images, sounds and .py files where inside "robot_game", not inside "venv" folder. That was my normal rutine. ...but I remember … -
Django API does not accept data since its not recognized as a file
I have an ionic 5 project with Angular 9 that I want to connect with an Django rest api. I have problems when it comes to upload images and other stuff with it. I want to upload posts with other information like position, hashtags and so on. The data consists of a file, bools, numbers and strings. The api docs says its not JSON its multipart. When I try to post the payload it gives me this error: {"src":["The submitted data was not a file. Check the encoding type on the form."],"lon":["A valid number is required."],"lat":["A valid number is required."]} What is really strange is, that it says my data wouldn't be a file since I converted it to a file and the console actually also tells me it would be a file. This is what the form contains: image: ZoneAwarePromise __zone_symbol__state: true __zone_symbol__value: File {name: "picture.jpeg", lastModified: 1569954025000, lastModifiedDate: Tue Oct 01 2019 20:20:25 GMT+0200 (Mitteleuropäische Sommerzeit), webkitRelativePath: "", size: 274100, …} Symbol(Symbol.toStringTag): (...) __proto__: Object position_lat: ZoneAwarePromise {__zone_symbol__state: true, __zone_symbol__value: 10} position_lon: ZoneAwarePromise {__zone_symbol__state: true, __zone_symbol__value: 5} Here my code: camera.ts // convert base64 image into a file function base64toBlob(base64Data, contentType) { contentType = contentType || ''; const … -
Only check Django form if radio button is selected
I got one form in a Django checkout page where the user can select if their product is gonna be shipped to the regular address ou another one he/she desires. The case is: if the user uses the regular address, some fields do not need to be filled. Otherwise, if the costumer selects to be shipped to another address, Django must check if all form fields are properly filled. My form.py: class ProfileRegistrationForm(forms.ModelForm): class Meta: model = Profile fields = ('date_of_birth', 'cep', 'rua', 'numero', 'bairro', 'complemento', 'cidade', 'estado') labels = {'date_of_birth': 'Data de nascimento', 'cep': 'CEP', 'numero': 'Nº'} widgets = {'date_of_birth': forms.TextInput(attrs={'id': 'date_of_birth', 'OnKeyPress': 'formatar("##/##/##", this)', 'maxlength': "8", 'placeholder': '__/__/__', 'class': 'form-control'}), 'cep': forms.TextInput(attrs={'id': 'cep', 'onblur': 'pesquisacep(this.value)', 'OnKeyPress': 'formatar("#####-###", this)', 'placeholder': '______-___', 'class': 'form-control'}), 'rua': forms.TextInput(attrs={'readonly': 'readonly', 'id': 'rua', 'class': 'form-control'}), 'bairro': forms.TextInput(attrs={'readonly': 'readonly', 'id': 'bairro', 'class': 'form-control'}), 'cidade': forms.TextInput(attrs={'readonly': 'readonly', 'id': 'cidade', 'class': 'form-control'}), 'estado': forms.TextInput(attrs={'readonly': 'readonly', 'id': 'uf', 'class': 'form-control'}), 'numero': forms.TextInput(attrs={'id': 'numero', 'class': 'form-control', 'placeholder': 'Nº'}), 'complemento': forms.TextInput(attrs={'id': 'complemento', 'class': 'form-control', 'placeholder': 'Complemento'}),} The checkout.html template: <form action="" method="post" id="payment-form"> <div class="box-element" id="form-wrapper"> <div id="user-info"> <p><strong>{{ user.username }}</strong>, confira abaixo o endereço de entrega:</p> <p><input type="radio" name="address" checked="checked"> Endereço de entrega:<br> {{ user.profile.rua }}, nº {{ user.profile.numero … -
Django skips a url pattern?
In my urls.py, I have the following: urlpatterns = [ path("", views.homepage, name="homepage"), path('completed/', views.completed, name='completed'), path("<single_slug>", views.link_slug, name="link_slug"), ] When I'm testing locally, if I visit IP:8000/completed, it calls the completed() function in my views.py, but when I run it on Heroku (connect to www.WEBSITE.com/completed), it ends up skipping it, passing 'completed' into my link_slug() function. Here is my views.py: def completed(request): return render(request=request, template_name='main/completed.html', context={'categories':ProjectCategory.objects.all}) def link_slug(request, single_slug): #do stuff -
Second page of Pagination not working in django after searching
Searching result is not appearing in second page what should I change to solve my problem ? and I'm using elasticsearch as search engine index.html <ul> {% for i in paginator.page_range %} {% if i <= page_number|add:5 and i >= page_number|add:-5 %} <li class=" {% if i == page_number %} active {% endif %} " > <a href="?page={{forloop.counter}}">{{forloop.counter}}</a> </li> {% endif %} {% endfor %} </ul> and this is in my views.py def index(request): q = request.GET.get('q') if q: articles = PostDocument.search().query("match", title=q, ) paginator = Paginator(articles, 5) page_number = request.GET.get('page', 1) page_obj = paginator.get_page(page_number) return render(request, 'index.html', { 'articles': page_obj.object_list, 'paginator': paginator, 'page_number': int(page_number), }) else: articles = '' return render(request, 'index.html', {'articles': articles}) -
How to filter records in complex DB by the fields in related tables?
For example the code /models.py class Tourney(models.Model): tourney = models.CharField() tourney_1 = models.CharField() tourney_2 = models.CharField() class Stage(models.Model): tourney = models.ForeignKey(Tourney, on_delete=models.CASCADE) stage = models.CharField() stage_1 = models.CharField() stage_2 = models.CharField() class Group(models.Model): stage = models.ForeignKey(Stage, on_delete=models.CASCADE) group = models.CharField() group_1 = models.CharField() group_2 = models.CharField() Group has relation on Stage which has relation on Tourney. So now we want to set API for them. Imagine we has serializers for them which include all their fields and called TourneySerializer, StageSerializer and GroupSerializer We want to let possibility to find in all tables the records by the fields in related tables. Actually we would like to search through all of them. /views.py class GroupViewSet(viewsets.ModelViewSet): queryset = Group.objects.all() serializer_class = serializers.GroupSerializer def list(self, request, *args, **kwargs): queryset = self.get_queryset() if 'tourney' in request.GET: queryset = queryset.filter(stage__tourney__tourney=request.GET['tourney']) if 'tourney_1' in request.GET: queryset = queryset.filter(stage_tourney_tourney_1=request.GET['tourney_1']) if 'tourney_2' in request.GET: queryset = queryset.filter(stage_tourney_tourney_1=request.GET['tourney_2']) if 'stage_1' in request.GET: queryset = queryset.filter(stage_stage_1=request.GET['stage_1']) if 'stage_2' in request.GET: queryset = queryset.filter(stage_stage_2=request.GET['stage_2']) if 'group' in request.GET: queryset = queryset.filter(group=request.GET['group']) if 'group_1' in request.GET: queryset = queryset.filter(group_1=request.GET['group_1']) if 'group_2' in request.GET: queryset = queryset.filter(group_2=request.GET['group_2']) serializer = self.get_serializer_class()( queryset, many=True) return Response(serializer.data) Here we have one ViewSet with a bunch of obvious … -
Issues with psycopg when installing local requirements.txt
I have tried installing psycopg-binary as some have suggested, but no success. System: Mac 10.15.6 Django3.0.8 Python3.8 ld: library not found for -lssl clang: error: linker command failed with exit code 1 (use -v to see invocation) error: command 'gcc' failed with exit status 1 -
Static Files Pythonanywhere
When I run python manage.py collectstatic in the bash console I keep getting "python: can't open file 'manage.py': [Errno 2] No such file or directory". But I can clearly see my manage.py file in my code editor, I am a beginner in django and its pretty frustrating. If anyone has any ideas what this can possibly be, I would love your help. Thanks settings.py -
Graphene: "Expected a value of type XXX but received: ..."
I'm using graphene-django to build my API. I have a DjangoObjectType named StoreType which represents the model Store. This model has a MultiSelectField named opening_days that indicates what days in the week the store is open. To create new stores, I use this mutation: class Weekdays(graphene.Enum): MO = "Mo" TU = "Tu" WE = "We" TH = "Th" FR = "Fr" SA = "Sa" SU = "Su" class CreateStore(graphene.Mutation): store = graphene.Field(StoreType) class Arguments: opening_days = graphene.Argument(graphene.List(Weekdays)) def mutate(self, info, opening_days): store = Store(opening_days=opening_days) store.save() return CreateStore(store=store) The mutation works perfectly. But then, when I try to query a store, I get the error "Expected a value of type \"StoreOpeningDays\" but received: Monday, Tuesday", which makes sense really, because this field saves the data as a single string with the values separated by commas. The issue is that graphene is expecting the list specified in graphene.List(Weekdays) which is impossible to retrieve. Any ideas on how to fix this? Thanks in advance! -
Previous form data being applied to Form for editing in django
I have a way for users to edit comments they posted in Django but now Im trying to implement a feature where when users go to edit their comments the previous comment is displayed in the form. This way when a user goes to edit their comment it will show what they said previously in the form field. views.py def update_comment(request, year, month, day, post, comment_id = None ): post = get_object_or_404(Post , slug=post, status='cleared',publish__year=year,publish__month=month,publish__day=day) comments = post.comments.filter(active=True) comment = Comment.objects.get(id=comment_id) user = request.user comment_form = CommentForm(request.POST, instance=Comment.objects.get(id=comment_id)) if (comment.name != user): raise PermissionDenied if request.method == 'POST': comment_form = CommentForm(request.POST, instance=Comment.objects.get(id=comment_id)) if comment_form.is_valid(): comment_form.instance.post = post comment_form.instance.name = request.user comment_form.save() return HttpResponseRedirect( post.get_absolute_url() ) else: comment_form = CommentForm() return render(request,'posts/update_comment.html', {'post':post , 'comments': comments,'comment_form': comment_form, 'comment_id':comment_id }) urls.py from . import views from django.urls import path, include, re_path from django.contrib.auth import views as auth_views from .views import PostListView, PostCreateView,PostUpdateView app_name = 'posts' urlpatterns = [ path('', views.PostListView.as_view(), name='post_list'), #path('<int:year>/<int:month>/<int:day>/<slug:post>/',views.PostDetailView.as_view(),name='post_detail'), path('<int:year>/<int:month>/<int:day>/<slug:post>/',views.post_detail,name='post_detail'), path('post/new/',PostCreateView.as_view(), name='post-create'), path('<int:year>/<int:month>/<int:day>/<slug:post>/update/',PostUpdateView.as_view(), name='post-update'), path('<int:year>/<int:month>/<int:day>/<slug:post>/<comment_id>/',views.update_comment, name='update_comment'), ] update_comment.html {% extends "Main/Base.html" %} {% block content %} <form method="POST" action="{% url 'posts:update_comment' post.publish.year post.publish.month post.publish.day post.slug comment_id %}"> {{ comment_form.as_p }} {% csrf_token %} <p><input type="submit" value="Update comment"></p> </form> {% … -
django.db.utils.OperationalError: (1366, "Incorrect string value: '\\xD9\\x88\\xDB\\x95\\xD8\\xB3...' for column 'name' at row 1")
hi i created a django project and tried to deploy it on ubuntu apache server with mysql database but when i run python3 manage.py migrate i get this error : django.db.utils.OperationalError: (1366, "Incorrect string value: '\xD9\x88\xDB\x95\xD8\xB3...' for column 'name' at row 1") when i run show variables like 'char%'; the output is : +--------------------------+----------------------------+ | Variable_name | Value | +--------------------------+----------------------------+ | character_set_client | utf8 | | character_set_connection | utf8 | | character_set_database | latin1 | | character_set_filesystem | binary | | character_set_results | utf8 | | character_set_server | latin1 | | character_set_system | utf8 | | character_sets_dir | /usr/share/mysql/charsets/ | +--------------------------+----------------------------+ and in my /etc/mysql/my.cnf i set [client] default-character-set = utf8 is there something i've missed ?! -
keys must be str, int, float, bool or None, not builtin_function_or_method
This is my cart views, im trying link my products/plans page to this view. Im trying to create an add to cart view so when i click add to cart it will go onto the cart page from django.shortcuts import render, redirect, reverse # Create your views here. def view_cart(request): """ A view that renders the cart page """ return render(request, 'cart/cart.html') def add_to_cart(request, item_id): """ Add plan to shopping cart """ cart = request.session.get('cart', {}) cart[id] = cart.get(id, 1) request.session['cart'] = cart return redirect(reverse('plans')) -
django endpoint not returning all fields specified in serializer
This is Source Def: class SourceDefinition(models.Model): source = models.ForeignKey(Source, on_delete=models.DO_NOTHING) special_id = models.IntegerField(default=0) ad_group = models.CharField(max_length=50) creator = models.CharField(max_length=100) config = JSONField(default=dict, blank=True) class SourceDefinitionSerializer(serializers.ModelSerializer): source = SourceSerializer(read_only=True, many=False) source_id = serializers.PrimaryKeyRelatedField(source="source", queryset=Source.objects.all(), write_only=True) class Meta: model = SourceDefinition fields = '__all__' Engine: class EngineDefinition(models.Model): engine = models.ForeignKey(Engine, on_delete=models.DO_NOTHING) source_def = models.ForeignKey(SourceDefinition, on_delete=models.DO_NOTHING) schedule_def = models.ForeignKey(ScheduleDefinition, on_delete=models.DO_NOTHING, null=True, blank=True) ad_group = models.CharField(max_length=50) creator = models.CharField(max_length=100) where_clause = models.CharField(max_length=1000, null=True, blank=True) config = JSONField(default=dict, blank=True) class EngineDefinitionSerializer(serializers.ModelSerializer): engine = EngineSerializer(read_only=True, many=False) source_def = ScheduleDefinitionSerializer(read_only=True, many=False) schedule_def = SourceDefinitionSerializer(read_only=True, many=False) engine_id = serializers.PrimaryKeyRelatedField(source="engine", queryset=Engine.objects.all(), write_only=True) source_def_id = serializers.PrimaryKeyRelatedField(source="source_def", queryset=SourceDefinition.objects.all(), write_only=True) schedule_def_id = serializers.PrimaryKeyRelatedField(source="schedule_def", queryset=ScheduleDefinition.objects.all(), write_only=True) class Meta: model = EngineDefinition fields = '__all__' Returned value from endpoint using EngineDefinitionSerializer : { "id": 1, "engine": { "id": 1, "name": "en" }, "source_def": { "id": 1, "ad_group": "YYY", "creator": "EEE", "config": {} }, "schedule_def": null, "ad_group": "YYY", "creator": "EEE", "where_clause": null, "config": {} } Why is special_id not being returned in the EngineDefinitionSerializer endpoint response? I also attempted to specify all field names instead of using __all__ and same result occurred. ........... (need more words words worcs words words words wrods) -
How to handle simultaneous requests in Django?
I have a standard function-based view in Django which receives some parameters via POST after the user has clicked a button, computes something and then returns a template with context. @csrf_exempt def myview(request, param1, param2): if request.method == 'POST': return HttpResponseRedirect(reverse("app1:view_name", args=[param1, param2])) '''Calculate and database r/w''' template = loader.get_template('showData.html') return HttpResponse(template.render(context, request)) It works with no problem as long as one request is processed at the time (tested both with runserver and in an Apache server). However, when I use two devices and click on the button simultaneously in each, both requests are mixed up, run simultaneously, and the website ends up trowing a 500 error, or 404 or sometimes success but cannot GET static files.. (again, tested both with runserver and Apache). How can I force Django to finish the execution of the current request before starting the next? Or is there a better way to tackle this? Any light on this will be appreciated. Thanks! -
Async Django view
I am curious about if I can use Async views for returning dynamic objects for my list view which has filtering. So view will update the list of objects shown in HTML without page refresh when user filters the list. Can I do it without ajax? Any explanation will help me. -
Problem in creating delete button in django
I am trying to build delete button and currently stuck. I am new to django and need help. Thank You This is my models.py:- from django.db import models from django.contrib.auth import get_user_model from django.db import models from django.urls import reverse # Create your models here. class simpleList(models.Model): title = models.CharField(max_length=250) def __str__(self): return self.title This is my views.py:- from django.shortcuts import render, get_object_or_404 from .models import simpleList from django.views.generic import ListView, DeleteView from django.urls import reverse_lazy from django.contrib.messages.views import SuccessMessageMixin # Create your views here. class ListListView(ListView): model = simpleList template_name = 'list_list.html' class DeleteList(SuccessMessageMixin, DeleteView): model = simpleList success_url = '/' success_message = "deleted..." def delete(self, request, *args, **kwargs): self.object = self.get_object() name = self.object.title # name will be change according to your need request.session['title'] = title message = request.session['title'] + ' deleted successfully' messages.success(self.request, message) return super(DeleteView, self).delete(request, *args, **kwargs) This is my urls.py:- from django.urls import path from .views import ListListView, DeleteList from django.conf.urls import url from . import views urlpatterns = [ path('', ListListView.as_view(), name='list_list'), path('<int:pk>/', DeleteList.as_view(), name='delete_view'), ] This is my home.html:- {% extends 'base.html' %} {% block title %}Home{% endblock title %} {% block content %} <div> {% if user.is_authenticated %} <button type="button" class="btn … -
How compare field of two different models in Django
One of the main goals of project is control users done visits to customers. Available Customers, Employees and Appointment models. Make appointment to Customer and assign it to Employee on any future date. Employee can see appointment assigned to him and make visits. Need somehow see are appointments to customers done or not. See customers on custom date with made visits and not visited. Need to see it in Django Admin. model.py class Customer(models.Model): name = models.CharField(max_length=255,blank=True, null=True) ...... class Emplyee(models.Model): name = models.CharField(max_length=255,blank=True, null=True) ...... class Visit(models.Model): employee_name = models.ForeignKey(Employee, on_delete=models.CASCADE) customer_name = models.ForeignKey(Customer, on_delete=models.CASCADE) visit_time = models.TimeField() visit_date = models.DateTimeField(auto_now_add=True) note = models.TextField(blank=True, null=True) ...... class Appointment(models.Model): employee = models.ForeignKey(Employee, on_delete=models.CASCADE) customer = models.ForeignKey(Customer, on_delete=models.CASCADE) appointment_date = models.DateTimeField(auto_now_add=True) note = models.TextField(blank=True, null=True) admin.py class VisitAdmin(admin.ModelAdmin): list_display = ('employee_name', 'customer_name','visit_time','visit_date') admin.site.register(Visit, VisitAdmin) ...... class AppointmentAdmin(admin.ModelAdmin): list_display = ('employee_name', 'customer_name','appointment_date','visit_done') admin.site.register(Appointment, AppointmentAdmin) // Need to write some def visit_done as a Boolean for example True/False that the visit to exact this Customer and Date and Employee was done or Not. -
Django-templated-email not connecting to my template file
I am sure that i have set up everything correctly and my template file welcome.email is in right folder but somehow when sending email, it is not showing as my template has been connected. Here is my view for django-template-email: def send(request, pk): if request.method == "POST": data = json.loads(request.body) trainingtitle = data['trainingtitle'] name = data['name'] email = data['email'] send_templated_mail( template_name='welcome', from_email='austin.roose1@gmail.com', recipient_list=['austin.roose1@gmail.com'], context={ 'email': email, 'name': name, 'trainingtitle': trainingtitle, }, ) return redirect('/api/') And i have also in my settings.py file: TEMPLATES = [ { 'DIRS': [os.path.join(BASE_DIR, 'templates')], My welcome.email file looks like: {% block html %} <p>Hi {{name}},</p> <p>You just signed up for my website, using: <dl> <dt>username</dt><dd>{{name}}</dd> <dt>join date</dt><dd>{{email}}</dd> </dl> </p> <p>Thanks, you rock!</p> {% endblock %} But my sent email looks like: screenshot of email As you can see it shows 'username' and 'full name' in there although i don't have them in my template. What should i change? -
Passing image file from React to Django backend
I am trying to upload a file on the frontend in React and pass that image file to the backend in django to run some code on the image. Right now, the data from React is being passed as a bytes array but when I reconstruct the image in the Django backend the image data is completely corrupt. I dont know what I am doing wrong here. The image is in the form of a InMemoryUploadedFile object in Django. HTML: <label onChange = {handleFileUpload} className = "custom-file-upload"> <input type = "file" name = "image" /> Upload Image </label> AJAX call to Django: I can confirm the correct data is being passed from the frontend to the backend const data = new FormData(); data.append('image', files[0]) fetch('/api/itot/', { method: 'POST', body:data }) .then(response => response.json()) .then(data => console.log(data["text"])) Django View: img = request.FILES["image"] # img is InMemoryUploadedFile object # I have tried .open() and .read() but that does not seem to work I dont know why the file is being corrupted.