Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Parameter "form" should contain a valid Django Form. error happen
now I use Django and try to make some Board included upload file function actually, I do not have any experience in making a web HTML code so just try to use Django for making a web Board and I success just make a board but wanna which have a file upload function so I mix my code and other code and I think almost success but did not work it and got an error like a title I guess almost clear but a few problems just remain like below [about Bootstrap] so need help. 1 is my git address 2 is refer code address <div class="form-group"> <label for="content">command</label> <textarea class="form-control" name="content" id="content" rows="10">{{ form.content.value|default_if_none:'' }}</textarea> <button type="submit" class="btn btn-primary">save</button> </div> <!-- add code --> <div class="container"> <form method="POST" action="{% url 'pybo:fileUpload' %}" enctype="multipart/form-data"> {% csrf_token %} {% bootstrap_form fileuploadForm %} <input type="submit" class="btn btn-primary col-12" value="submit"> </form> </div> -
Accessing values stored in a Field and comparing it with other parameter in serializer
This is what i have in Django Author model as a primary key id = models.URLField(primary_key=True) One example can be {id:"http://localhost:3000/authors/1d698d25ff008f7538453c120f581471"}. In My serializer, i want to compare 1d698d25ff008f7538453c120f581471 portion of the path to an author_id i passed in. Right now, I am using, from urllib.parse import urlparse ... def create(self, validated_data, author_id): author, created = Author.objects.update_or_create( urlparse(id).path.split('/')[2]=author_id, defaults=validated_data) return author Is there an alternative of doing this? -
Django Oscar - Multi Vendor Setup where partners can only manage their own products
I am using django-oscar to set up a multi vendor marketplace I have linked a user as a partner and given them "limited access dashboard" But they still have management access to all products on the site. (Menu item: Catalogue\Products) I only want my vendors to add/edit/sell/delete their own products only! What do I need to do? -
Making Login Api with custom django user model with my defined username and emp_password fields
Custom User model authentication not work for me i need to override default password field with my define emp_password field because in database i have already created users with their passwords field name as emp_password. I try to map my username and password with employee table emp_password field.I try this last 2 days so still stuck in this issue. Please help me thank you in advance. Let share with you code models.py Hello everyone, Custom User model authentication not work for me i need to override default password field with my define emp_password field because in database i have already created users with their passwords field name as emp_password. I try to map my username and password with employee table emp_password field and then if everything work then make login api for employee login Let share with you code models.py from django.db import models from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager from django.contrib.auth.models import PermissionsMixin from django.contrib.auth.hashers import make_password class CustomUserManager(BaseUserManager): """ Custom user model manager where email is the unique identifiers for authentication instead of usernames. """ def create_user(self, emp_email, password, **extra_fields): """ Create and save a User with the given email and password. """ if not emp_email: raise ValueError('The Email … -
django settings does not affect after changes(CELERY_BROKER_URL)
CELERY_BROKER_URL = 'redis://127.0.0.1:6379/0' CELERY_ACCEPT_CONTENT = ['json'] TASK_SERIALIZER = 'json' [2022-02-14 12:02:26,910: ERROR/MainProcess] consumer: Cannot connect to amqp://guest:**@192.168.3.100%3A6379:5672//: failed to resolve broker hostname. Trying again in 2.00 seconds... (1/100) -
Need to fetch two specific field values from one model to another seperately in django API rest framework
model 1 class Users(models.Model): employee_name = models.CharField(max_length=50) dob=models.DateField(max_length=8) email=models.EmailField(max_length=254,default=None) pancard=models.CharField(max_length=25,default=None) aadhar=models.CharField(max_length=20,default=None) personal_email_id=models.EmailField(max_length=254,default=None) phone = PhoneField(blank=True) emergency_contact_no=models.IntegerField(default=None) emergency_contact_name=models.CharField(max_length=100,null=True) relation=models.CharField(max_length=25,default=None) blood_group=models.CharField(max_length=25,choices=BLOOD_GROUP_CHOICES,null=True) desingnation=models.ForeignKey(Designation,on_delete=CASCADE,related_name="desingnation") billable_and_non_billable=models.CharField(max_length=25,choices=BILLABLE_and_NON_BILLABLE_CHOICES,default='Billable') joining_date=models.DateField(max_length=15,null=True) relieving_date=models.DateField(max_length=15,null=True) def __str__(self): return self.employee_name model 2 class Consolidated(models.Model): emp_name=models.ForeignKey(Users,on_delete=CASCADE) proj_name=models.ForeignKey(Project,on_delete=CASCADE) custom_name=models.ForeignKey(Client,on_delete=CASCADE) Cons_date=models.ForeignKey(Add_Timelog,on_delete=CASCADE) bill_no_bill=models.ForeignKey(Users,on_delete=CASCADE,related_name="billable_and_non_billable+") def __str__(self): return str(self.emp_name) Serializers class UserSerializers(serializers.ModelSerializer): class Meta: model= Users fields = '__all__' class Consolidated_serializers(serializers.ModelSerializer): class Meta: model=Consolidated fields= '__all__' Viewsets class UserViewset(viewsets.ModelViewSet): permission_classes=(permissions.IsAdminUser,) queryset=models.Users.objects.all() serializer_class=serializers.UserSerializers class Consolidated_ViewSet(viewsets.ModelViewSet): permission_classes=(permissions.IsAdminUser,) queryset=models.Consolidated.objects.all() serializer_class=serializers.Consolidated_serializers Actually I was stucked in the middle, as I need to take the values from 'billable_and_non_billable' field from the Users model and display those values under Consolidated model bill_no_bill field. With the above code I can only take the employee_name values from the Users model to the emp_name of Consolidated model and the same value is getting displayed in the bill_no_bill field. Please help me find any ways for this problem as I am new to this Django. Basically its needs to be a API which operates GET method. -
Django Rest Framework Multiple Model Serializtion
I am using Django Rest Framework to make and API. I have and endpoint that i want to use to generate a JSON object that contains data from different models. The viewset for the model is: class InvoiceView(viewsets.ModelViewSet): def list(self, request): cart_id = request.data["cart_id"] shop = Shop.objects.get(id=request.user.id) cart = ShoppingSession.objects.get(id=cart_id) cart_items = CartItem.objects.filter(session=cart_id) paymentmethod = PaymentMethod.objects.get(id=cart.payment_method.id) Invoice = namedtuple('Receipt',('shopname','cart', 'cartitems', 'paymentmethod')) invoice = Invoice( shopname = shop, cart = cart, cartitems = cart_items, paymentmethod = paymentmethod ) serializer = ReceiptSerializer(Invoice) return Response(serializer.data,) The serializers used are: class ShopSerializer(serializers.ModelSerializer): class Meta: model = Shop exclude = ['is_staff', 'is_active', 'start_date'] class ReceiptSerializer(serializers.Serializer): shopname = ShopSerializer() cart = ShoppingSessionSerializer() cartitems = CartItemSerializer(many=True) paymentmethod = PaymentMethodSerializer() When the url is run and a GET request is executed. An error is generated that looks like this. AttributeError: Got AttributeError when attempting to get a value for field `first_name` on serializer `ShopSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `_tuplegetter` instance. Original exception text was: '_collections._tuplegetter' object has no attribute 'first_name'. How are you supposed to user multiple serializers in one serializer class for this kind of custom use-case? -
Django url path matching not working as expected
I have problem with Django model get_absolute_url reverse methods. I have a url pattern that works perfectly but the problem for example when I visit example.com/blog/python/first-post the path works perfectly, but when I try a random path like, example.com/blog/python-randomr9353/first-post it still works correctly even though it shouldn't because, python-randomr9353 is not a valid path and it should return a page not found error. Here is my code. Models class ArticleSeries(models.Model): title = models.CharField(max_length=200) series_slug = AutoSlugField(populate_from='title') def __str__(self): return self.title def get_absolute_url(self): return reverse('blog:article_list', kwargs={'series_slug': self.series_slug}) class Tag(models.Model): title = models.CharField(max_length=50) def __str__(self): return self.title class Article(models.Model): title = models.CharField(max_length=200) article_slug = AutoSlugField(populate_from='title') tag = models.ManyToManyField(Tag, default=1, verbose_name='Tag') series = models.ForeignKey(ArticleSeries, default=1, verbose_name='Series', on_delete=models.SET_DEFAULT) def __str__(self): return self.title def get_absolute_url(self): return reverse('blog:article_detail', args=(self.series.series_slug, self.article_slug)) url patterns app_name = 'blog' urlpatterns = [ path('', views.IndexView.as_view(), name='index_view'), path('blog', views.BlogView.as_view(), name='blog_view'), path('blog/<slug:series_slug>', views.ArticleListView.as_view(), name='article_list'), path('blog/<slug:series_slug>/<slug:article_slug>', views.ArticleDetailView.as_view(), name='article_detail'), ] Views class IndexView(TemplateView): template_name = 'blog/index.html' extra_context = {} class BlogView(ListView): model = ArticleSeries template_name = 'blog/blog_view.html' context_object_name = 'series_list' def get_queryset(self): series = ArticleSeries.objects.all() return get_list_or_404(series) class ArticleListView(ListView): model = Article template_name = 'blog/article_list.html' context_object_name = 'article_list' def get_queryset(self): slug = self.kwargs['series_slug'] articles = Article.objects.filter(series__series_slug=slug) return get_list_or_404(articles) class ArticleDetailView(DetailView): model = Article template_name = … -
ordering = ['-created'] what it means in Django? why we use - sign in ordering?
Below is my code. class Basecalss(models.Model): title = models.CharField(max_length=255) created = models.DateTimeField(auto_now_add=True) update = models.DateTimeField(auto_now=True) class Meta: abstract = True ordering = ['-created'] Here why we use - sing before created, what it means?? -
Grab forms for specific model objects
I have a product model, each product objecg created has a vendeur field which returns the logged in user. I have an other order model in m2m relationship with the product model. To make an order, the order form should grab only the products where vendeur field is the current user Class Product(models.Model): name = model.CharField(max_lenth = 29) vendeur = model.ForeignKey(User, on_delete= models.CASCADE) Class Order(models.Model): products = model.ManyToMany(Product) forms.py Class NewOrderForm(forms.ModelForm): Class Meta: model = Order fields = ('products') I can't find the logic for this -
Why doesn't this Nested Serializer(ForeignKey) work?
class RFIDReaderSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = RFIDReader bind_state_choice = ProductEntityStateChoiceSerializer() # depth = 2 fields = ( "url", "pk", "reader_name", "reader_host", "reader_address", "reader_ip", "reader_port", "bind_state_choice", "bind_state_location" ) Serializer Nested Serializer Model Graph RestFul -
Password authentication failed for user "postgres" with Django, whereas it works with psql
I've read through the SO posts with the similar error message, but I'm thinking my case is a bit different. I have a kubernetes cluster with a few django pods. If I ssh into one of these pods and type python manage.py runserver, I get following error: django.db.utils.OperationalError: connection to server at "resource-monitor-db-postgresql.resource-monitor-system.svc.cluster.local" (10.152.183.205), port 5432 failed: FATAL: password authentication failed for user "postgres" In settings.py: DATABASES = { "default": { "ENGINE": "django.db.backends.postgresql", "NAME": "postgres", "USER": "postgres", "PASSWORD": "mypassword123", "HOST": "resource-monitor-db-postgresql.resource-monitor-system.svc.cluster.local", "PORT": "5432", } } The strangest part is that I'm able to log in with psql with the same HOST and PASSWORD. That is, the following command successfully logs in as user postgres. PGPASSWORD="mypassword123" psql --host resource-monitor-db-postgresql.resource-monitor-system.svc.cluster.local -U postgres -d postgres -p 5432 I assume this command is equivalent to the DATABASES property in settings.py. Am I missing something here? Any help would be appreciated. -
How can I solve the problem of repeating the values in the datatable inputs?
How can I solve the problem of repeating the values in the datatable input, I need that each row has a different data, that I bring from a modal. I leave you the code of the input of the datatable and the function I am using django and javascript Javascript function buscar_toma: function (valor1, valor2) { console.log(valor1); console.log(valor2); $('input[name="final_inventory"]').val(valor1) $('input[name="physical_take"]').val(valor2) }, HTML <tbody> {% for dt in tank_measurements %} <tr> <td>{{ dt.code }}</td> <td>{{ dt.tank }}</td> <td>{{ dt.centimeter_measure }}</td> <td>{{ dt.measure_liters }}</td> <td>{{ dt.tank_percentage }}</td> <td class="text-center"> <button class="btn btn-outline-warning mb-2" id="btnSelectFinalInventory" data-dismiss="modal" onclick="tankcontrol.buscar_toma('{{ dt.measure_liters }}', '{{ dt.centimeter_measure }}')"> <i class="fas fa-hand-pointer"></i></button> </td> </tr> {% endfor %} </tbody> Datatable image -
Cannot import Django in docker container installed with miniconda
I followed essentially the same setup that is working flawlessly in a different project, but here, it is not working as expected. I have this docker file: FROM continuumio/miniconda3 ENV PYTHONUNBUFFERED=1 RUN mkdir /static RUN apt update && apt install -y build-essential time libgraphviz-dev graphviz RUN conda create -n env -c conda-forge python==3.10 django==4 pip SHELL ["conda", "run", "-n", "env", "/bin/bash", "-c"] COPY backend/requirements.txt requirements.txt RUN pip install -r requirements.txt COPY ./backend /backend WORKDIR /backend/ And this docker-compose file: version: "3.3" services: backend: container_name: backend restart: always user: ${UID} build: context: . dockerfile: dockerfiles/Dockerfile-backend env_file: - ./.env command: ./manage.py runserver --database docker volumes: - ./backend/:/backend/ - ${STATIC}:/static/ ports: - "8000:8000" depends_on: - db db: container_name: db restart: always image: postgres:13.4 volumes: - ${DB}:/var/lib/postgresql/data environment: - POSTGRES_DB=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres So, this looks all pretty simple. I can see django is installed and also pip is used to install the other requirements, however, when I run the container with docker-compose, it returns that django cannot be imported. I tried to add the SHELL command to specify the conda environment (I tried the base environment as well as env), but it does not work. Can anybody spot an error here, and … -
Hello . Need a little help for a beginner . Creating Local.py and Prod.py under new folder Settings
So I am trying to before start my first project to separate data by creating a new Folder "Settings" and putting there 2 files Local. py and Prod. py. I wrote in each this enter image description here then I change Debug to False in prod. py then I deleted those settings in original Settings.py then in WSGI. py and ASGI. py I show the path by putting Prod at the end enter image description here and in manage.py I change to local enter image description here and when I go to terminal and trying to run python manage.py runserver it gives me those errors.enter image description here Thank you! -
Access users values in python, django
I'm a bit stuck in figuring out how to access the body, title, author ... values, so that I can show them in the user profile. Is there another way of making sure that the logged-in user can see their data? Models.py """ X """ title = models.CharField(max_length=150, unique=True) slug = models.CharField(max_length=150, unique=True) body = models.TextField() author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='user_questions') created_on = models.DateTimeField(auto_now_add=True) updated_on = models.DateTimeField(auto_now=True) answered = models.BooleanField(null=False, blank=False, default=False) status = models.IntegerField(choices=STATUS, default=0) class Meta: """ X """ ordering = ['-created_on'] def __str__(self): return str(self.title) if self.title else '' views.py class UserProfile(View): """ X """ def get(self, request, *args, **kwargs): """ X """ mquestions = Question.objects.filter(author=self.request.user).filter(status=1).order_by('-created_on') return render( request, 'user_profile.html', { 'mquestions': mquestions } ) -
I want to use the .py file in Django but faced some issues I'm totally new and need some solution
I have made a python script to find the subnet mask for the given number of host. But I want it to take HTML input on button click and pass it as user input in python script and give the output on same HTML page. I have tried to give you guys max details of this program I'm not able to understand the problem. it shows taking input in url like here the terminal output is for input 500 urls.py path('findSM_H', views.findSM_H, name='findSM_H'), path('findSM_Houtput', views.findSM_Hexecution, name='findSM_Houtput') findSM_H.html <form method="GET" action="/findSM_H"> {% csrf_token %} <table> <tbody> <tr> <td width="450"> <table width="450"> <tbody> <tr> \\TAKING INPUT FROM THE USER <td width="250" height="50"> <label for="noofhostinput"> Number of host </label> </td> <td width="250" height="50"> //ON CLICKING THE BUTTON IT TAKES TO 'findSM_Houtput' FUNCTION <input id="noofhostinput" type="text" name="noofhostinput" /> <input type="submit" onclick="location.href ='{%url 'findSM_Houtput'%}'" > </td> </tr> </tbody> </table> </td> <td width="30"></td> <td width="450"> <table width="450"> <tbody> <tr> <td width="250" height="50"> //OUTPUT OF THE USER INPUT <label for="subnetmask"> Subnet mask </label> </td> <td width="200" height="50"> <div id="subnetmask" style="background-color: ddb(39, 6, 39)" type="text"> 00{{noofhost_op}} </div> <h3>0.{{noofhost_op}}</h3> </td> </tr> </td> </tr> </tbody> </table> </td> </tr> </tbody> </table> </form> views.py def findSM_H(request): return render(request, 'findSM_H.html') def findSM_Hexecution(request): noofhost_input … -
How to insert a QR code and some text in a pdf template in Python (preferably) to generate tickets
Hi I am currently making a web application for a congress at my university. The project is not too complicated, but the main functionality is that a user should register himself for the congress and get sent a pass/ticket in PDF through email, with a QR code identifying him/her. This is so that the user can then assist to any event in the congress where a volunteer will read said QR code at the entrance so we can keep track of assistance and reward it at an individual level, as well as keep track of room capacity for COVID reasons. The website is being built using Django and DjangoRest, hence I want to keep using Python wherever I can. I have looked at tools such as ReportLabs python package. It is quite dense and I can't find what I am looking for, which is: Open a pdf template Fill the template with the information regarding the user: name and email for example. Paste/Insert the QR code generated for the user (this is already done). It seems pretty simple but I just can't find how to do it, so any input would be very much appreciated. Maybe I am getting at … -
AttributeError at /Test/ 'tuple' object has no attribute 'get'
I am currently seeing the following error when I try to open a django crispy-reports form. All the info Í can find online about this is, that i persumably added a comma where ther shouldn't be one. But I really can't find any. My PlaylistForm class from django import forms from crispy_forms.helper import FormHelper from crispy_forms.layout import Submit class PlaylistForm(forms.Form): name = forms.CharField( label='Name', max_length= 64, required = True) comment = forms.CharField( label='Kommentar', max_length= 256, required = False) def __init__(self, *args, **kwargs): super().__init__(args, kwargs) self.helper = FormHelper() self.helper.form_id = 'id_playlist_form' self.helper.form_class = 'forms' self.helper.form_method = 'post' self.helper.form_action = 'test' self.helper.add_input(Submit('submit', 'Absenden')) the edit.html template {% load crispy_forms_tags %} {% crispy playlist_form playlist_form.helper %} the urlpatterns entry path('Test/', views.test, name='test') excerpt from the views.py from django.http import HttpRequest, HttpResponse from django.shortcuts import render from trackmanager.Forms.PlaylistForm import PlaylistForm def test(request: HttpRequest)->HttpResponse: context = {'playlist_form': PlaylistForm()} return render(request, 'trackmanager/edit.html', context) -
For loop for nav-tabs
I have 2 objects in corporate_goal and I am trying to execute blocks with this objects in for loop like: {% load static %} {% for goal in corporate_goal %} {% block content %} <!-- Corporate goal section--> <div class="row"> <div class="section-title"> Corporate Goal: {{goal.corp_goal_title}} </div> <div style="margin-inline-start:auto"> {{todo}}0 % of total score TODO </div> </div> <div class="row"> <p>HR Rating</p> <p>&nbsp</p> {% if goal.corp_factor_rate %} <p style="color:mediumspringgreen">rated</p> {% else %} <p style="color:indianred">unrated</p> {% endif %} <p>&nbsp</p> </div> <!-- Tabs for details--> <ul class="nav nav-tabs"> <li class="nav-item"> <a class="nav-link active" data-toggle="tab" href="#det1{{goal.corp_goal_title}}">Goal Details</a></li> <li class="nav-item"> <a class="nav-link" data-toggle="tab" href="#det2{{goal.corp_goal_title}}">Other Details</a></li> </ul> <!-- Tabs content for details--> <div class="tab-content" > <!--First tab--> <div id="det1{{goal.corp_goal_title}}" class="tab-pane fade show active"> <div class="row"> <!--Column 1--> <div class="col"> <table class="table-bordless" style="margin-top:20px;"> <tbody> <tr> <th>Start Date</th> <td width="50"></td> <td>{{goal.start_date}}</td> </tr> <tr> <th>Weight</th> <td width="20"></td> <td>{{goal.corp_factor_weight}} %</td> </tr> </tbody> </table> </div> <!--Column 2--> <div class="col"> <table class="table-bordless" style="margin-top:20px;"> <tbody> <tr> <th>Due Date</th> <td width="50"></td> <td>{{goal.end_date}}</td> </tr> </tbody> </table> </div> </div> </div> <!--Second tab--> <div id="det2{{goal.corp_goal_title}}" class="tab-pane fade" style="margin-top:20px;"> <p>Factor for Goal Achievement:</p> <table class="table"> <tbody> <tr> <th>Factor</th> <td>0</td> <th>Description</th> <td>{{goal.corp_factor_0}}</td> </tr> <tr> <th>Factor</th> <td>1</td> <th>Description</th> <td>{{goal.corp_factor_1}}</td> </tr> <tr> <th>Factor</th> <td>2</td> <th>Description</th> <td>{{goal.corp_factor_2}}</td> </tr> <tr> <th>Factor</th> <td>3</td> <th>Description</th> <td>{{goal.corp_factor_3}}</td> … -
Django - Transferring data to a new database
I am using Django as my web framework with Django REST API. Time and time again, when I try to migrate the table on production, I get a litany of errors. I believe my migrations on development are out of sync with production, and as a result, chaos. Thus each time I attempt major migrations on production I end up needing to use the nuclear option - delete all migrations, and if that fails, nuke the database. (Are migrations even supposed to be committed?) This time however, I have too much data to lose. I would like to preserve the data. I would like to construct a new database with the new schema, and then manually transfer the old database to the new one. I am not exactly sure how to go about this. Does anyone have any suggestions? Additionally, how can I prevent this from occurring in the future? -
Model not saving refresh token
Just trying to save the refresh token from Google OAuth 2.0 into the abstractuser profile which signed in. It displays the refresh token and the user correctly. However when logged in the user doesn't have the refresh token stored in the model. pipeline.py: from .models import Profile def save_token(user,*args,**kwargs): extra_data = user.social_auth.get(provider="google-oauth2").extra_data print(extra_data["refresh_token"],user) Profile.objects.get_or_create( username=user, defaults={"refresh_token": extra_data["refresh_token"]} ) models.py from django.db import models from django.contrib.auth.models import AbstractUser from phonenumber_field.modelfields import PhoneNumberField from django.templatetags.static import static class Profile(AbstractUser): refresh_token = models.CharField(max_length=255, default="") Now when displaying it, it comes up empty. calendar.html: {% block content %} {{user.refresh_token}} <h1>Calendar</h1> <button>+</button> <ul> {% for result in results %} <li>{{result.start.date}}{% if result.end.date %}-{% endif%}{{result.end.date}}: {{result.summary}}</li> {% endfor %} </ul> {% endblock %} -
M2M relation ship : Can't save to the through model
i have a an order model which is in m2m relationship with a product model, when i create an order, and after checking my DB, i can see the order saved but not in the through model models.py from inventory.models import Product from user.models import User class Order(models.Model): product = models.ManyToManyField(Product, through='OrderItems' ) vendeur = models.ForeignKey(User, on_delete=models.CASCADE) quantity = models.PositiveIntegerField() class Customer(models.Model): full_name = models.CharField(max_length=60, verbose_name='full name') address = models.CharField(max_length=255) phone = models.CharField(max_length=20) city = models.CharField(max_length=30) class OrderItems(models.Model): product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True) order = models.ForeignKey(Order,on_delete=models.CASCADE) customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, null=True) views.py @login_required def add_order(request): if request.method == 'POST': form = NewOrderForm(request.POST) if form.is_valid(): order = form.save(commit=False) order.vendeur = request.user order.save() return redirect('dashboard-index', ) else : form = NewOrderForm() return render(request, 'dashboard/add_order.html', {'form': form}) forms.py class NewOrderForm(forms.ModelForm): class Meta: model = Order fields = ('product','quantity') -
Why Is My Django Post Request Sending Incorrectly Parsed My List of Dictionaries?
Here is my Django view: def sendMail(request): url = 'https://example.com/example' dictwithlist = request.FILES['dictwithlist'] parsed = json.load(dictwithlist) // the log file shows that the lists are intact after json.loads logip(request, json.loads(parsed)) x = requests.post(url, json.loads(clockoutJSON)) return HttpResponse(status=204) If I just send parsed data my express server receives an empty dict, {}. When I log the json.loads(parsed) I find good data, with the lists intact. When the data gets to the other side though, the dictionaries inside the nested list are all removed, replaced by only strings of their keys. I tried using headers as described here: Sending list of dicts as value of dict with requests.post going wrong but I just get 500 errors. I don't know if I'm formatting the headers wrong or not. (because the code has line spacing and I'm copying it) Can anyone help me understand why this is failing? I need that list to get through with its dictionaries intact. -
How to convert svg string to svg file using Python?
Using AJAX I send a svg image to Django using the following function: function uploadSVG(){ var svgImage = document.getElementById("SVG"); var serializer = new XMLSerializer(); var svgStr = serializer.serializeToString(svgImage); $(document).ready(function(){ $.post("ajax_upload_svg/", { csrfmiddlewaretoken: csrftoken, svgImage: svgStr }, function(){ console.log('Done') }); }); } In Django I end up with the svg image as a string using the following function: def uploadSVG(request): svgImg = request.POST.get('svgImage') return HttpResponse('') The string I get looks like this: <svg xmlns="http://www.w3.org/2000/svg" id="SVG" width="460" height="300" style="border:2px solid #000000"><rect x="150" y="70" width="160" height="130" fill="#292b2c"/></svg> How can I convert this svg string into a svg file?