Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Python Django Template language unpack List
I am trying to pass values from the views.py to the html to be displayed but a list is being passed instead of a single value. I have a random link that should randomly pick an item from the list, this is the html where the item should link to <a href="{{entries}}">Random{{entries}}</a> this is the views.py def rando(request, title): items = util.list_entries() randomitem = Random.choice(items) return render(request, "encyclopedia/view.html", { "entries": md.convert(util.get_entry(randomitem)) }) this is the error i receive TypeError at /wiki/['CSS', 'Django', 'Git', 'HTML', 'Python'] the random link in the html should pass only one of the items in the list. can anyone help me with a solution -
How to run migrations on specific database using call_command() in Django?
I'm just wondering what the correct syntax is for calling $ python manage.py migrate app_name --database db_name with the management.call_command() function at runtime. So far, I have the following: from django.core import management from django.core.management.commands import migrate # Migrate the core.contrib.dynamics if needed to the pre-specified database: management.call_command(migrate.Command(), 'dynamics', '--database {}'.format(DB_NAME)) However, I get the following error at runtime when calling the above: Cannot find a migration matching '--database default_node' from app 'dynamics'. I'm 99% sure I'm probably calling the -- args incorrectly? Can anyone point me in the right direction with this? -
Nginx : why 400 bad request happend?
I'm doing build my own django server with nginx and uwsgi. i almost done but 400 Bad Request always appear... what am i wrong? [info] 61794#0: *35 client sent invalid method while reading client request line, client: 127.0.0.1, server: localhost, request: " QUERY_STRINGREQUEST_METHODGET CONTENT_TYPECONTENT_LENGTH REQUEST_URI/ PATH_INFO/" this is error.log(info) and this is .conf file upstream django { #server localhost:9001; server unix://~/Desktop/fido_virtual/fido.sock; } server { listen 8999; server_name localhost; charset utf-8; client_max_body_size 75M; location /media { alias ~/Desktop/fido_virtual/media/; } location /static { alias ~/Desktop/fido_virtual/fidoproject/staticfiles/; } location / { uwsgi_pass django; include /usr/local/etc/nginx/uwsgi_params; } } this .conf in project folder upstream django { #server localhost:9001; server unix:///Users/junbeomkwak/Desktop/fido_virtual/fido.sock; } server { listen 8999; server_name localhost; charset utf-8; client_max_body_size 75M; location /media { alias /Users/junbeomkwak/Desktop/fido_virtual/media/; } location /static { alias /Users/junbeomkwak/Desktop/fido_virtual/fidoproject/staticfiles; } location / { uwsgi_pass django; #include /Users/junbeomkwak/Desktop/fido_virtual/fidoproject/uwsgi_params; include /usr/local/etc/nginx/uwsgi_params; } } this file is in /usr/local/etc/nginx/site-enabled/.conf #user nobody; worker_processes 1; error_log /var/log/error.log; #error_log logs/error.log notice; error_log /var/log/errorngnix.log info; events { worker_connections 1024; } http { large_client_header_buffers 4 16k; include mime.types; include /usr/local/etc/nginx/sites-enabled/*; default_type application/octet-stream; #log_format main '$remote_addr - $remote_user [$time_local] "$request" ' # '$status $body_bytes_sent "$http_referer" ' # '"$http_user_agent" "$http_x_forwarded_for"'; #access_log logs/access.log main; sendfile on; #tcp_nopush on; #keepalive_timeout 0; keepalive_timeout 65; #gzip … -
Why doesn't Django template show data correctly?
I'm a new Django programmer and I'm writing a learning app. This app have a foreign key relations and I use prefetch_related method. This system runs well ;-) My problem is at the template, when I show the data from the table, the browser shows this menssages: ID Bill number Warehouse Article Quantity Price (<<-- columns) 1 CabeceraDeFacturas object (1) Primer almacén Bolsa plástico .05 mm. KK. 10 1 ... The questions are: ¿Why does show the message "CabeceraDeFacturas object (1)" instead of a bill number? ¿Can I fix this? ¿How? The information about is: Part of models.py class CabeceraDeFacturas(models.Model): ID_cliente = models.ForeignKey('Clientes',on_delete=models.CASCADE) fecha_factura = models.DateField('Fecha de factura: ') ID_formaDePago = models.ForeignKey('FormasDePago',on_delete=models.CASCADE) Porcentaje_IVA = models.PositiveSmallIntegerField(default=21) Total_factura = models.IntegerField() class Meta: ordering = ('id',) #def __str__(self): # return self.id class LineasDeFacturacion(models.Model): ID_factura = models.ForeignKey('CabeceraDeFacturas',on_delete=models.CASCADE) ID_almacen = models.ForeignKey('Almacen',on_delete=models.CASCADE) ID_articulo = models.ForeignKey('Articulos',on_delete=models.CASCADE) cantidad = models.IntegerField(default=1) Precio = models.IntegerField() class Meta: default_related_name = 'lineas' # def __str__(self): # return str(self.ID_factura) Part of views.py class VerFacturaCompleta(ListView): #model = CabeceraDeFacturas model = LineasDeFacturacion template_name = "ListarTodasLasFacturasConLineas.html" # recuperar las facturas completas y líneas --> comprobar # queryset = CabeceraDeFacturas.objects.all().select_related('lineas') queryset = LineasDeFacturacion.objects.all().prefetch_related('ID_factura') paginate_by = 10 And finally, the template: <h1>Listar facturas</h1> <table class="table"> <thead> <tr> <th … -
Django R F, How to perform object creation using incoming data with CreateAPIView
The code is to grab data from request and save in database. I am sending data through url variables but it seems not the best practice. How can I rewrite the VIEWS.PY so that it take data from request and saves ? MODELS.PY class Cart(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE) product=models.ForeignKey(Product,on_delete=models.CASCADE) quantity = models.PositiveIntegerField(default=1) payment = models.BooleanField(default=False) VIEWS.PY class CartCreate(generics.CreateAPIView): serializer_class = CartSerializer queryset = Cart.objects.all() permission_classes = [IsAuthenticated] def perform_create(self, serializer): request_user = self.request.user pk = self.kwargs.get("pk") product = get_object_or_404(Product,pk) quantity = self.kwargs.get("quantity") serializer.save(user=request_user, product=product,quantity=quantity) URLS.PY path('CartCreate/<int:pk>/<int:quantity>/',views.CartCreate.as_view(),name='CartCreate'), As you may see I am sending hardcoded pk and quantity through urls. -
The script from “http://localhost:8000/static/js/cart.js” was loaded even though its MIME type (“text/plain”) is not a valid JavaScript MIME type.?
i'm getting this error can somebody tell me whats going wrong The script from “http://localhost:8000/static/js/cart.js” was loaded even though its MIME type (“text/plain”) is not a valid JavaScript MIME type. -
Is there a tool available where I can check my django dependency compatability for an upgrade?
I am gearing up to do a Django upgrade, and I was just wondering if anyone knows of some kind of tool where I can check what whether each dependency is compatible with the desired version of Django, and if not what version the dependency needs to be upgraded too? -
Log into Django using login form on different site
I have a client that has a customer-facing site, and an internal site to track things within their business. I am developing the internal site using Django. They have asked for an "Employee Login" button on the front-facing site that, when clicked, will display a login form right there in order to log into my Django application. I have been using Django for a while but I haven't encountered this before, and I can't find any resources to help me get there. I know right off the bat that the CSRF token will need to be on the public site, because I don't want to disable CSRF on the login page just for this purpose. I tried an iframe but by default that doesn't work, and I also don't want to override that. Has anyone done this or know of packages that might make this easier? -
how can we use more than one class object attributes of one model in another model in Django
class Webpage(models.Model): topic=models.CharField() name=models.CharField(max_length=264,unique=True) url=models.URLField(unique=True) def __str__(self): return self.url,self.name class AccessRecord(models.Model): name=models.ForeignKey(Webpage) date=models.DateField() urls=models.ForeignKey(Webpage) def __str__(self): return str(self.date) how can i use "name and url" attribute of "Webpage" class in "AccessRecord" class -
How to open TCP socket with Django webserver and update HTML page without new HTTP request
so I started to learn Django for full-stack solution for web application and I'm getting stuck in the sockets area.. I want the server to have background threads that can open TCP and UDP sockets and with the info I receive on the sockets to update the web application without refreshing the whole page? (is it possible?) How can I update the page without getting a new HTTP request, in the HTML itself I tried to open socket but it dident work (using js). I read about Websockets but could not understand how to implement it with Django. Any help would be amazing! -
Sharethis Twitter share image not loading
When using Sharethis to share a post from my website, the Twitter share button is unable to grab a dynamically generated image for the post. I have also included the link to the image in the head with "twitter:image" but the problem seems to persist. Any idea how to go around this? -
How to show the data entered in textarea using django?
I want to create a debate website. I am unable to show the data typed in my text-area on the screen. I create a model named NoteModel and in forms.py file I created a NoteForm. I am using views.py to save the data entered in the textarea. App name:debate html_file name:content.html. this is my views.py file: from django.http import HttpResponseRedirect from .models import * from .forms import * def index(request): return render(request,'debate/content.html') def NoteView(request): if request.method == 'POST': m = NoteForm(data=request.POST) if m.is_valid(): method = m.save() return HttpResponseRedirect('method/') else: return render(request,'debate/content.html', {'NoteForm': method}) this is models.py file: from django.db import models class NoteModel(models.Model): title = models.CharField(max_length=200) complete = models.BooleanField(default=False) def __str__(self): return self.title this is content.html file: <button onclick="myFunction()">for</button> <button onclick="myFunction()">against</button> <form method="post" action="NoteView/"> {%csrf_token%} {{form.title}} <script> function myFunction() { var x = document.createElement("TEXTAREA"); var t = document.createTextNode("enter your for point"); var y = document.createElement("INPUT"); y.setAttribute("type", "submit"); document.body.appendChild(y); x.appendChild(t); document.body.appendChild(x); } </script> </form> -
CrispyError at /task/ |as_crispy_field got passed an invalid or inexistent field
This might seem really trivial, but I've cross-checked my code multiple times, I've read a number of S.O answers, but still can't find the root. I'll really appreciate it if someone corrected and pin-pointed my mistake. My html file: {% extends "base.html" %} {% load static %} {% load crispy_forms_tags %} {% load bootstrap4 %} {% block content %} <div class="row1"> <h1 class="display-3">Tasks</h1> </div> <div class="row2" style="height:auto; padding-bottom: 200px"> <div class="container" > <h2 class="mt-5">Add New Task:</h2> <form action="/addTask/" method="POST"> {% csrf_token %} {{ form.task|as_crispy_field }} {{ form.description|as_crispy_field }} <label for="datetimepicker1">Due Date:</label> <div class="input-group date mb-2" id="datetimepicker1" data-target-input="nearest"> {{ form.due_date }} <div class="input-group-append" data-target="#datetimepicker1" data-toggle="datetimepicker"> <div class="input-group-text"><i class="fa fa-calendar"></i></div> </div> </div> {{ form.user|as_crispy_field }} <div class="block mx-5 p-5 mt-5" style="background-color: #e1f4f3; color: black; border-radius: 5px;"> <!-- <div class="container" > {% include "task_manager/comment.html" %} </div> --> </div> <input type="Submit" value="Add" class="btn btn-warning px-3 py-2 mt-5 float-right"> </form> </div> </div> {% endblock %} My Models from django.db import models import datetime from django.contrib.auth import get_user_model User = get_user_model() # Create your models here. class task(models.Model): user = models.ForeignKey(User,verbose_name='Assigned to',on_delete = models.CASCADE,default='') task = models.CharField("Task", max_length = 250, null = False, blank = False) description = models.TextField() time = models.DateTimeField("Assigned on", default = datetime.datetime.now) … -
Django: Annotate a filtered reverse relationship
I have 4 models: class Platform(models.Model): name = models.CharField(max_length=10) class Streamer(models.Model): name = models.CharField(max_length=50) class Account(models.Model): name = models.CharField(max_length=50) platform = models.ForeignKey(Platform, on_delete=models.CASCADE) class Stream(models.Model): host = models.ForeignKey(Account, on_delete=models.CASCADE) score = models.PositiveIntegerField(default=0) There are 3 Platforms: Instagram, Twitch, and YouTube Each Streamer has multiple accounts connected to it. Each account can have multiple streams. and each stream has one score. Now lets say that for each Streamer I want to add a total score for every stream connected to every account connected to that Streamer. I would do: from django.db.models import Sum Streamer.objects.annotate(total_score=Sum('account__stream__score')) If I wanted to order each streamer by the total score I would do: streamers = Streamer.objects.annotate(total_score=Sum('account_stream__score')).order_by('total_score') What I'd like to do is now filter a list of Streamers by the same score but only from Accounts that have the Instagram Platform connected to it. I'm not sure how to do this, but I would think it'd be something like this (not actual working code): instagram_top_streamers_list = Streamer.objects.annotate(total_score_instagram=Sum( # Somehow filter the account 'account__platform__name="Instagram" # Then calculate the score for that one 'account__stream__score')).order_by('-total_instagram_score') I've been looking for something related to this for hours but couldn't find an answer. It needs to be filtered by streamers. Again, the … -
Human-readable value of choice field on serialize
I'm sending serialized data of a queryset into my templates, like so: from django.core import serializers def View(request): invoices = serializers.serialize('json', Invoice.objects.all()) context = {'invoices':invoices} return render(request, r'template_folder\template.html', context) However my choice fields are being parsed as the actual value and not the human-readable value class Invoice(models.Model): (...) office = models.IntegerField(choices = [(1, 'ABC'), (2, 'DEF')]) What can i do to send the human-readable value to the template ('ABC', 'DEF'..) instead of the ('1', '2'..)? -
Get set of objects within top x% their rating via Django orm
Question is regarding annotation and aggregation in Django. For example I have following model. class Example(models.Model) rating = models.PositiveSmallIntegerField(min=1, max=10, null=True, blank=True) Where rating is a positive integer from 1 to 10 Goal is to fetch queryset from db that would contain top X % entries according their rating(for example top 20%) and do it in one single queryset without raw sql usage (only by Django ORM). Database -Postgres. Dataset might not contain all values from 1 to 10 necessarily. It might be 6,7,3,3,3,4,5 for example easily. What I do : from django.db.models import FloatField, Max, Min from django.db.models.functions import Ceil, Floor def top_x_percent(self, percent: int) -> models.QuerySet: """ Returns top x % of according their rating. """ result = self.aggregate( Min('rating', output_field=FloatField()), Max('rating', output_field=FloatField()), ) one_percent_value = (result['rating__max'] - result['rating__min']) / 100 top_range = ( Ceil(result['rating__max'] - (percent * one_percent_value)), Floor(result['rating__max']) ) return self.filter(rating__range=top_range) But it makes 2 querysets Any ideas how to make it all in one singular neat queryset? Thank you -
How to render view generated from dynamic url in Django?
I have a page with a table consisting of each client in a database. I am trying to make it so that when clicking on a client in the table it will pass only that client's data to the next page. I attempted to accomplish this by making a dynamic url in my urls.py that looks like: path("/client/<int:id>", client_view) In views.py the client view uses that parameter to search the database for the client with that id and generates a json response consisting of that client's name, client's photo location etc like so: def client_view(request, ID, *args, **kwargs): obj = Client.objects.get(id=ID) data = { "response": [obj.id, obj.first_name, obj.last_name, obj.id, obj.getImgUrl()] } return JsonResponse(data) However this url is generated within a script on the initial client table page so I'm confused as how to pass this parameter to the page that will open the dynamic url to render it? The script on the client table page: <script> const clientElement = document.getElementById("client") /*table body*/ const xhr = new XMLHttpRequest() const method = 'GET' //http get method const url = "/rosterlist/" /*trailing slash important!!*/ const responseType = "json" xhr.responseType = responseType xhr.open(method, url) /* open request with specified method at url */ xhr.onload … -
Error while running '$ python CommonModules/manage.py collectstatic --noinput'
i am new to django. I am deploying my simple web application on heroku server via github. But when i deploy it, my build going to fail and it show this error on heroku logs: -----> Python app detected -----> Installing python-3.8.3 -----> Installing pip -----> Installing SQLite3 -----> Installing requirements with pip Collecting appdirs==1.4.4 Downloading appdirs-1.4.4-py2.py3-none-any.whl (9.6 kB) Collecting asgiref==3.2.10 Downloading asgiref-3.2.10-py3-none-any.whl (19 kB) Collecting distlib==0.3.1 Downloading distlib-0.3.1-py2.py3-none-any.whl (335 kB) Collecting Django==3.0.8 Downloading Django-3.0.8-py3-none-any.whl (7.5 MB) Collecting django-filter==2.3.0 Downloading django_filter-2.3.0-py3-none-any.whl (73 kB) Collecting filelock==3.0.12 Downloading filelock-3.0.12-py3-none-any.whl (7.6 kB) Collecting gunicorn==20.0.4 Downloading gunicorn-20.0.4-py2.py3-none-any.whl (77 kB) Collecting Pillow==7.2.0 Downloading Pillow-7.2.0-cp38-cp38-manylinux1_x86_64.whl (2.2 MB) Collecting pytz==2020.1 Downloading pytz-2020.1-py2.py3-none-any.whl (510 kB) Collecting six==1.15.0 Downloading six-1.15.0-py2.py3-none-any.whl (10 kB) Collecting sqlparse==0.3.1 Downloading sqlparse-0.3.1-py2.py3-none-any.whl (40 kB) Collecting virtualenv==20.0.26 Downloading virtualenv-20.0.26-py2.py3-none-any.whl (4.9 MB) Collecting virtualenvwrapper-win==1.2.6 Downloading virtualenvwrapper-win-1.2.6.tar.gz (21 kB) Collecting whitenoise==5.1.0 Downloading whitenoise-5.1.0-py2.py3-none-any.whl (19 kB) Building wheels for collected packages: virtualenvwrapper-win Building wheel for virtualenvwrapper-win (setup.py): started Building wheel for virtualenvwrapper-win (setup.py): finished with status 'done' Created wheel for virtualenvwrapper-win: filename=virtualenvwrapper_win-1.2.6-py3-none-any.whl size=18609 sha256=2894b9f0d8294f17c34d3498acb2ec9baba93dd1039a36a8e44c1252d8d2bb41 Stored in directory: /tmp/pip-ephem-wheel-cache-lqj2a4ec/wheels/66/25/f7/f4b3539b1cc86289c4e24e637c09a39f8f2ab6de61928f0be1 Successfully built virtualenvwrapper-win Installing collected packages: appdirs, asgiref, distlib, pytz, sqlparse, Django, django-filter, filelock, gunicorn, Pillow, six, virtualenv, virtualenvwrapper-win, whitenoise Successfully installed Django-3.0.8 Pillow-7.2.0 appdirs-1.4.4 asgiref-3.2.10 distlib-0.3.1 django-filter-2.3.0 filelock-3.0.12 gunicorn-20.0.4 pytz-2020.1 … -
display 4 forms but the last form aint working
thanks for your time. i've been trying to display 4 forms on the same template and based on the submit button do the POST request to the right form. the first 3 are working fine just the last one (Estoque) that dont save the object. When i check the request.post sims to be fine. views.py: @login_required @allowed_users(allowed_ones=['Admin']) def test_view(request, id): prod = Produto.objects.get(id=id) prod_form = ProdutoForm() img_form = ImagemForm() model_form = ProdutoForm() storage_form = ProdutoForm() prod_query = Produto.objects.all() img_query = Imagem.objects.all() model_query = Modelo.objects.all() storage_query = Estoque.objects.all() t1 = 'no' t2 = request.POST if request.method == 'POST' and 'producting' in request.POST: print('PROD') prod_form = ProdutoForm(request.POST, instance=prod) t1 = 'product' t2 = request.POST if prod_form.is_valid(): prod_form.save() elif request.method == 'POST' and 'img' in request.POST: print('IMG') img_form = ImagemForm(request.POST, request.FILES) t1 = 'img' t2 = request.POST if img_form.is_valid(): img = img_form.save(commit=False) img.product = prod img.save() elif request.method == 'POST' and 'model' in request.POST: print('MODEL') model_form = ModeloForm(request.POST) t1 = 'model' t2 = request.POST if model_form.is_valid(): model_form.save() elif request.method == 'POST' and 'storge' in request.POST: print('STORAGE') storage_form = EstoqueForm(request.POST, product=prod) t1 = 'storage' t2 = request.POST if storage_form.is_valid(): storage_form.save() else: prod_form = ProdutoForm(instance=prod) img_form = ImagemForm() model_form = ModeloForm() storage_form = EstoqueForm() context … -
Django DRF ModelSerializer to handle a custom form
I have a custom model field that is stored as text (inherits from TextField) The field also has a choices attribute. class CustomField(models.TextField): def __init__(self, *args, **kwargs): self._choices = kwargs.pop("choices") ...lots of validation class FooModel: bar = CustomField(choices=[...]) I have written an extended ModelSerializer that should be able to serialize this field type: class SerializerCustomField(serializers.ChoiceField): pass class CustmModelSerializer(serializers.ModelSerializer): serializer_field_mapping = serializers.ModelSerializer.serializer_field_mapping.copy() serializer_field_mapping[CustomField] = SerializerCustomField The last line makes it aware that a CustomField on a model should be mapped to a SerializerCustomField. This works - the serializer maps them correctly. I have tried setting debug traces in the __init__ method of the serializer and the serializer field, but the choices kwarg from the model never comes through. This results in the __init__ for serializers.ChoiceField erroring, because it requires a choices kwarg, and anyway, I need access to the choices field to write the serializer field's to_internal_value and to_representation methods. I assume this must be possible, because for models.ChoiceField, the default ModelSerializer pulls the choices from the model field. -
Django subtract function
I'm trying to create a function in which when I click to buy in my order_list.html it should subtract 1 from its quantity and redirect to purchase_success.html. Right now my function is redirecting me to purchase_success.html but it's not subtracting 1 from its quantity when I click buy. models.py class Order(models.Model): date = models.ForeignKey('date', null=True, on_delete=models.CASCADE) user = models.ForeignKey(User, null=True, on_delete=models.CASCADE) name = models.CharField(max_length=30) quantity = models.IntegerField(default='0', blank=True, null=True) quantity = models.IntegerField(default='0', blank=True, null=True) views.py def purchase_success(request, pk): if request.method == 'POST': Order.objects.get(id=pk).update(quantity=F('quantity') - 1) Order.save() return redirect('/success') context = {} return render(request, "purchase_success.html", context) purchase_success.html <!DOCTYPE html> <html> <head> <title> </title> </head> <body> Congrats ! Order Completed !! </body> </html> order_list.html <td><a href="{% url 'accounts:purchase-success' Order.id %}">buy</a></td> -
Django ORM: Get all records and the respective last log for each record
I have two models, the simple version would be this: class Users: name = models.CharField() birthdate = models.CharField() # other fields that play no role in calculations or filters, but I simply need to display class UserLogs: user_id = models.ForeignKey(to='Users', related_name='user_daily_logs', on_delete=models.CASCADE) reference_date = models.DateField() hours_spent_in_chats = models.DecimalField() hours_spent_in_p_channels = models.DecimalField() hours_spent_in_challenges = models.DecimalField() # other fields that play no role in calculations or filters, but I simply need to display What I need to write is a query that will return all the fields of all users, with the latest log (reference_date) for each user. So for n users and m logs, the query should return n records. It is guaranteed that each user has at least one log record. Restrictions: the query needs to be written in django orm the query needs to start from the user model. So Anything that goes like Users.objects... is ok. Anything that goes like UserLogs.objects... is not. That's because of filters and logic in the viewset, which is beyond my control It has to be a single query, and no iterations in python, pandas or itertools are allowed. The Queryset will be directly processed by a serializer. I shouldn't have to specify … -
Container Command Fails in Django on Elastic Beanstalk Python 3.7
I am using Django Python 3.7 on Elastic Beanstalk (Amazon Linux 2) and the following command fails: container_commands: 01_migrate: command: "pipenv run python ./manage.py migrate" leader_only: true 2020-07-17 09:31:57,017 [ERROR] Command 01_migrate (pipenv run python ./manage.py migrate) failed 2020-07-17 09:31:57,017 [ERROR] Error encountered during build of postbuild_0_sarahandanatol: Command 01_migrate failed Traceback (most recent call last): File "/usr/lib/python2.7/site-packages/cfnbootstrap/construction.py", line 542, in run_config CloudFormationCarpenter(config, self._auth_config).build(worklog) File "/usr/lib/python2.7/site-packages/cfnbootstrap/construction.py", line 260, in build changes['commands'] = CommandTool().apply(self._config.commands) File "/usr/lib/python2.7/site-packages/cfnbootstrap/command_tool.py", line 117, in apply raise ToolError(u"Command %s failed" % name) ToolError: Command 01_migrate failed -
Django on_delete = models.SET()
Below is my table : class Project(models.Model): name = models.CharField(max_length=100, null=False) desc = models.CharField(max_length=100, null=False) def __str__(self): return self.name class Activity(models.Model): title = models.CharField(max_length=100, null=False) project = models.ForeignKey(Project, on_delete=models.SET(some_func), null=False, related_name='project_model') So above is my table and when one of the datas of "project" table gets deleted then i want to assign "id or name" of the deleted "project" data to foreign key of the "activity" table. How can i achieve this? pls help. -
How to join two tables in django and serialize the same using one serializer?
I have been learning django and django rest framework since couple of weeks and I want to figure out how can I join two tables and serialize the data of same to return the json response using django rest framework. I want to return result as json response: { 'user_id_id': 1, 'request_msg': 'Hi', 'response_msg': "Hi, Welcome" } where result is from django.db import connection cursor = connection.cursor() con = cursor.execute("SELECT backend_request_messages.user_id_id, backend_request_messages.request_msg as request_msg,backend_response_messages.response_msg as response_msg FROM backend_request_messages,backend_response_messages Where backend_request_messages.user_id_id=backend_response_messages.user_id_id=1 ") Here is what I have tried : #backend/Models.py class User(models.Model): username = models.CharField(max_length=50) name = models.CharField(max_length=50, blank=True, null=True) uid = models.CharField(max_length=12, blank=True, null=True) age = models.CharField(max_length=3, blank=True, null=True) active = models.BooleanField(default=True) class Meta: default_related_name = 'users' def __str__(self): return self.name class Request_Messages(models.Model): request_msg = models.CharField(max_length=100) request_msg_created_at = models.DateTimeField(auto_now_add=True) user_id = models.ForeignKey( User, on_delete=models.CASCADE, null=True) class Meta: default_related_name = 'request_messages' def __str__(self): return self.request_msg class Response_Messages(models.Model): response_msg = response_msg = models.CharField(max_length=400) response_msg_created_at = models.DateTimeField(auto_now_add=True) user_id = models.ForeignKey( User, on_delete=models.CASCADE, null=True) class Meta: default_related_name = 'response_messages' def __str__(self): return self.response_msg #backend/serializers.py class ListSerializer (serializers.Serializer): user_id_id = serializers.IntegerField() request_msg = serializers.CharField(max_length=100) # request_msg_created_at = serializers.DateTimeField(read_only=True) response_msg = serializers.CharField() # response_msg_created_at = serializers.DateTimeField(read_only=True)