Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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? -
PayPal JavaScript SDK button opens about:blank#blocked window in Django template but not in local HTML file
I've been trying to integrate PayPal buttons on my Django website, but I keep having this problem where the PayPal popup window appears as about:blank#blocked. I can see this error in console: popup_open_error_iframe_fallback {err: 'n: Can not open popup window - blocked\n at Ie (…owser=false&allowBillingPayments=true:1342:297830', timestamp: '1644780862712', referer: 'www.sandbox.paypal.com', sdkCorrelationID: 'f12370135a997', sessionID: 'uid_d36969c1b2_mtk6mja6mzy', …} What I don't understand is that the problem isn't there if I just open the HTML file itself in a browser... The script looks like this: <!-- Set up a container element for the button --> <div id="paypal-button-container" class='text-center mt-2'></div> <!-- Include the PayPal JavaScript SDK --> <script src="https://www.paypal.com/sdk/js?client-id=blahblahmyid&currency=EUR"></script> <script> // Render the PayPal button into #paypal-button-container paypal.Buttons({ locale: 'it_IT', style: { color: 'gold', shape: 'rect', layout: 'vertical', label: 'pay' }, // Set up the transaction createOrder: function(data, actions) { return actions.order.create({ purchase_units: [{ amount: { value: '88.44' } }] }); }, // Finalize the transaction onApprove: function(data, actions) { return actions.order.capture().then(function(orderData) { // Successful capture! For demo purposes: console.log('Capture result', orderData, JSON.stringify(orderData, null, 2)); var transaction = orderData.purchase_units[0].payments.captures[0]; alert('Transaction '+ transaction.status + ': ' + transaction.id + '\n\nSee console for all available details'); // Replace the above to show a success message within this page, … -
Display Django time variable as full hours, minutes am/pm
I want to use a time variable instead of a CharField for a model, which displays multiple saved times. My issue is it displays as "9 am" instead of "9:00 am", and "noon" instead of "12:00 pm". Can anyone help? Thanks in advance. Relevant code below- models.py class Post(models.Model): time=models.TimeField() free=models.CharField(max_length=50, default="") player1=models.CharField(max_length=50, default="Player 1") player2=models.CharField(max_length=50, default="Player 2") player3=models.CharField(max_length=50, default="Player 3") player4=models.CharField(max_length=50, default="Player 4") def __str__(self): return self.time HTML <h7>{{post.time}} &nbsp; &nbsp; <a href="{% url 'update0' post.id %}" class="btn-sm btn-success" >Update</a></h7> -
Getting Module parse failed: Unexpected token (1:0) error when I try to import css file for a specific component in react
I am building a gym website using React and Django. I am getting this error when I try to import external css file in my Homepage component.Module parse failed: Unexpected token (1:0) You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders > #mainDiv{ | position: absolute; | top: 50%; @ ./src/components/HomePage.js 4:0-28 @ ./src/components/App.js 3:0-34 10:90-98 @ ./src/index.js 1:0-35 webpack 5.68.0 compiled with 1 error and 1 warning in 2286 ms This my component code: import ReactDom from "react-dom"; import Navbar from "./Navbar"; import React, { Component } from "react"; import "./css/Homepage.css"; export default class HomePage extends Component { constructor(props) { super(props); } render() { return ( <body> {/*<Navbar />*/} <div id="mainDiv" className="container"> <div id="Homepgbtn1" className="mainbtns"> <button type="button" class="btn btn-success"> Plans </button> </div> <div id="Homepgbtn2" className="mainbtns "> <button type="button" class="btn btn-success"> Get Started </button> </div> </div> <div id="rbdiv"> <button type="button" class="btn btn-light"> Instagram </button> <button type="button" class="btn btn-light"> Twitter </button> <button type="button" class="btn btn-light"> Youtube </button> </div> </body> ); } } This is my webpack.config.js code: const path = require("path"); const webpack = require("webpack"); module.exports = { entry: "./src/index.js", output: { path: path.resolve(__dirname, "./static/frontend"), filename: "[name].js", }, … -
Checking properties of an object based on separete view (Django|Django-Rest-Framework)
I am using django-rest-framework and React.js. I need a seperate function in the backend to check if CartItem.amount is lower then ProductStock.quantity, if CartItem.product equals ProductStock.id of course (this part does not work). For the same function I need to check if the pricing is the same as in Product model, but suprisingly this part of a function works. What can I do to make sure CartItem.amount will get lowered if it is higher than ProductStock.quantity? Code below: Product is a blueprint for the rest of the models. ProductStock tracks the amount of different sizes of all of products. CartItem is a model used for tracking how many products a user bought. models.py class Product(models.Model): name = models.CharField(max_length=150) price = models.IntegerField() slug = models.SlugField(blank=True, null=True) def __str__(self): return self.name def save(self, *args, **kwargs): self.slug = slugify(self.name) super(Product, self).save() class ProductStock(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) size = models.CharField(max_length=6) quantity = models.IntegerField(default=0) def __str__(self): return f'{self.quantity} x {self.product.name}: {self.size}' class CartItem(models.Model): user = models.ForeignKey(CustomUser, on_delete=models.CASCADE) product = models.ForeignKey(ProductStock, on_delete=models.CASCADE, blank=True, null=True) amount = models.IntegerField(default=0, blank=True, null=True) size = models.CharField(max_length=10, blank=True, null=True) price = models.IntegerField(blank=True, null=True) def __str__(self): return f'{self.user.email}, {self.product.product.name}, {self.product.size}: {self.amount}' def save(self, *args, **kwargs): if self.amount > self.product.quantity: self.amount = … -
Duplicate instance returned in QuerySet
I'm attempting to create a method that filters questions based on tags which are only found in a particular user's questions. There is an issue with the QuerySet where it returns Queryset([Question13, Question 14, Question13]). Yet when the .distinct() is added it returns the desired result of QuerySet([Question13, Question 14]). Why does the chained .filter() method add the duplicate instance in the QuerySet? class Post(Model): body = TextField() date = DateField(default=date.today) comment = ForeignKey('Comment', on_delete=CASCADE, null=True) profile = ForeignKey( 'authors.Profile', on_delete=SET_NULL, null=True, related_name='%(class)ss', related_query_name="%(class)s" ) score = GenericRelation( 'Vote', related_query_name="%(class)s" ) class Meta: abstract = True class Question(Post): title = CharField(max_length=75) tags = ManyToManyField( 'Tag', related_name="questions", related_query_name="question" ) objects = Manager() postings = QuestionSearchManager() class QuestionSearchManager(Manager): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) def by_week(self, profile): today = date.today() weekago = today - timedelta(days=7) queryset = self.get_queryset().filter( date__range=(weekago, today) ).filter(tags__name__in=profile.questions.values_list( "tags__name", flat=True )) return queryset postings.json { "model": "posts.question", "pk": 13, "fields": { "body": "Content of Question 005", "date": "2022-02-12", "comment": null, "profile": 2, "title": "Question__005", "tags": [ 1, 7 ] } }, { "model": "posts.question", "pk": 14, "fields": { "body": "Content of Question 006", "date": "2022-02-12", "comment": null, "profile": 3, "title": "Question__006", "tags": [ 1, 2 ] } } -
object data editting form
I'm making django app which allow me to study. It has multiple tests with multiple question each. Every question has one correct answer. I'm trying to make form which allow me to edit answer If I made mistake in passing correct answer during making question. That's what I have already made: models.py class Answer(models.Model): text = models.CharField(max_length=200) question = models.ForeignKey(Question, on_delete=models.CASCADE, related_name='parent') def __str__(self): return self.text forms.py class AnswerEditForm(ModelForm): class Meta: model = Answer exclude = ('question',) views.py def UpdateAnswerView(request, pk): form = AnswerEditForm() if request.method == 'POST': form = AnswerEditForm(request.POST) if form.is_valid(): obj = form.save(commit=False) obj.question = Question.objects.get(id=pk) obj.save() return redirect('home') context = {'form':form} return render(request, 'exam/update_answer.html', context) urls.py urlpatterns = [ ~some other urls~ path('answer/edit/<int:pk>/', views.UpdateAnswerView, name='update-answer'), ] while I'm trying to edit answer i'm getting Question matching query does not exist. error. Where did i make mistake ? -
AWS Elastic Beanstalk Degraded
I am deploying a Django application on Elastic Beanstalk and getting 'Degraded' Health message. The gateway also shows 502 error. When I check for causes, I get the following messages: 'Following services are not running: web' and 'Impaired services on all instances. How do I resolve this? -
React POST request to Django Rest ManyToMany field
What I want to do is post a ListLink object, which contains Link objects, to the database. The Link objects are added by input field by the user and stored in the state until a request is sent for them to be saved in the database. I am trying to make a post request to DRF, but I am getting the following response: "Invalid data. Expected a dictionary, but got list." I am using axios to make the request: Home.jsx handleSave = event => { event.preventDefault(); return axios({ method: 'post', url: 'http://localhost:8000/api/lists/', headers: { 'Authorization': 'Token ' + localStorage.getItem('token') }, data: { links: this.state.links, name: this.state.listName }}) .then(res => { console.log(res); }); } This is the state I am using to save the lists in: this.state = { listName: 'Link List', listDescription: 'Add description here', listURL: '', currentLink: 'https://www.example.com', links: [] }; Here are my models and serializers: LinkList class LinkList(models.Model): owner = models.ForeignKey( User, related_name='lists', on_delete=models.CASCADE) name = models.CharField(max_length=100) description = models.CharField(max_length=250) public = models.BooleanField(default=False) links = models.ManyToManyField( Link, related_name='linklists') def __str__(self): return "%s - %s" % (self.owner, self.name) def save(self, *args, **kwargs): super().save(*args, **kwargs) Serializer: class LinkListSerializer(serializers.ModelSerializer): url = serializers.HyperlinkedIdentityField(view_name="lists-detail") owner = serializers.ReadOnlyField(source='owner.username') links = LinkSerializer() class Meta: … -
'conda' is not recognized as the name of a cmdlet, function, script file, or operable program
So I am working on Atom IDE and making a venv. I used this line of code in my terminal conda create --name myDjangoEnv Django But this is giving following error: **conda : The term 'conda' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. At line:1 char:1 conda create --name myDjangoEnv Django + CategoryInfo : ObjectNotFound: (conda:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException** How should I proceed further??