Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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?? -
Django - How to get attribute from queryset objects list
I have a list of queryset objects like this: [<QuerySet [<Stuff: Phone>]>, <QuerySet [<Stuff: Vodka>]>, <QuerySet [<Stuff: Dictionary>]>] Now i need to get attributes of each object from it. Here is my html template <html lang="en"> <head> <meta charset="UTF-8"> <title>Changes saved</title> </head> <body> <p>Изменены объекты:</p> {% for el in elements %} <p>{{el.name}} new price: {{el.price}}</p> {% endfor %} </body> </html> And in my browser i have just "new price:" 3 times -
Django How to do a correlated EXISTS or NOT EXISTS
How can I perform the following correlated EXISTS and NOT EXISTS in Django? I do not want to use IN and NOT IN. These are not the same as EXISTS and NOT EXISTS. Correlated EXISTS: SELECT * FROM foo WHERE EXISTS ( SELECT 1 FROM bar WHERE foo.baz = bar.baz ) Correlated NOT EXISTS: SELECT * FROM foo WHERE NOT EXISTS ( SELECT 1 FROM bar WHERE foo.baz = bar.baz ) -
Trying to link a form to a custom data table I set up in pgadmin
So I have a custom data table set up and I would like to set that table as a destination for info that goes through my form. How would I go about doing that? I currently have django and the database linked, but currently I have it set to use the default user_auth table, that django automatically sets up. Here is my views.py file for more context: def register(request): if request.method == 'POST': first_name = request.POST['first_name'] last_name = request.POST['last_name'] username = request.POST['username'] email = request.POST['email'] newuser= User.objects.create_user(first_name=first_name,last_name=last_name, email=email, username=username) newuser.save() print(request.POST) return redirect('/home') else: return render(request,'userinfo.html') -
How to get data from model fields in django?
I made a patient register form. I added two patient to database. And i wanna save each patient informations to text file. And i wanna make all txt file is uniqe name. So i am using this code for save txt file; file_name must be each patient name, and i am having problem in this line... I didnt filter or pull data from model def deneme(request): dir_path = Path('/Users/emr/Desktop/ngsaglik/homeo/patient/templates/kayitlar') file_name = str(Post.objects.get(???)) # i wanna pull each patient name as a txt file name f = open (dir_path.joinpath(file_name),'w') testfile = File(f) kayitlar = Post.objects.all() lines = [] for kayit in kayitlar: lines.append(f'{kayit.soru1}\n{kayit.soru2}\n') testfile.write(str(lines)) testfile.close f.close return HttpResponse() my models.py from django.db import models from django.contrib.auth.models import User from django.urls import reverse #from datetime import datetime, date class Post(models.Model): name = models.CharField(verbose_name='Ad Soyad',max_length=10000, default="") surname = models.CharField(verbose_name='Tarih', max_length=10000, default="") soru3 = models.CharField(verbose_name='Doğum Tarihi', max_length=10000, default="") soru4 = models.CharField(verbose_name='Doğum Yeri', max_length=10000, default="") soru5 = models.CharField(verbose_name='Medeni Hali', max_length=10000, default="") -
In Django, how to create a model that stores proposed changes to another model?
I'm using Python 3.9 and Django 3.2. I have the following model class Coop(models.Model): objects = CoopManager() name = models.CharField(max_length=250, null=False) types = models.ManyToManyField(CoopType, blank=False) addresses = models.ManyToManyField(Address, through='CoopAddressTags') enabled = models.BooleanField(default=True, null=False) phone = models.ForeignKey(ContactMethod, on_delete=models.CASCADE, null=True, related_name='contact_phone') email = models.ForeignKey(ContactMethod, on_delete=models.CASCADE, null=True, related_name='contact_email') web_site = models.TextField() description = models.TextField(null=True) approved = models.BooleanField(default=False, null=True) We would like to set up a situation where someone could propose a change to a row in the db that would be reviewed before being saved, so I've created this struture class CoopChange(Coop): """ """ created_at = models.DateTimeField(null=False, default=datetime.now) The problem is that when I create a migration, the table that is created simply points back to the original model, instead of storing all the fields Table "public.directory_coopchange" Column | Type | Modifiers -------------+--------------------------+----------- coop_ptr_id | integer | not null created_at | timestamp with time zone | not null This is non-ideal because the original table would contain both finalized entries and those suggested for changes. Is there a way to create an entity that stores proposed changes that mirrors the structure of the original entity? -
How to include ManyToMany Fields in DjangoRestFramework?
class EntityServiceSerializer(serializers.ModelSerializer): class Meta: model = Service fields = '__all__' class EntityCreateSerializer(serializers.ModelSerializer): entity_service = EntityServiceSerializerThrough(read_only=True, source='serviceschedule_set', many=True) class Meta: model = Entity fields = '__all__' Model looks like this class Entity(models.Model): entity_service = models.ManyToManyField(Service, through='ServiceSchedule') class ServiceSchedule(models.Model): service = models.ForeignKey(Service, on_delete=models.CASCADE) entity = models.ForeignKey(Entity, on_delete=models.CASCADE) class Service(models.Model): service_name = models.CharField(max_length=256, null=True) slug = models.SlugField(max_length=128, unique=True, null=False, editable=False) created_at = models.DateTimeField(editable=False, default=timezone.now) updated_at = models.DateTimeField(default=timezone.now) animal = models.ForeignKey(Animal, on_delete=models.CASCADE, default=None) I have these serializers (there are more fields in entity model, but they're irrelevant since the only problem i have is with the Many2Many) The thing is, when i put in body "entity_service": [1,2] in the response i still get = []. Even though i have in my database Services with pk 1,2,3,4. Do you know how can i make it work?