Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to maintain the get query param for all template page Django
I have written some adminview for request the data from user and based on that data i put query and populating the data on template. My question is how I have to request data from user once and render template. and till the next data asked. views.py class ReadView(AbstractAdminView): def get(self, request, *args, **kwargs): roll_no = request.GET['roll_no'] roll_obj1 = Roll.objects.get(student__profile=roll_no) return self.admin_render(request, template1, { 'roll_details':roll_obj1 }) class PlayView(AbstractAdminView): def get(self, request, *args, **kwargs): roll_no = request.GET['roll_no'] roll_obj2 = Sub.objects.get(sec__student=roll_no) return self.admin_render(request, template2, { 'roll_details':roll_obj2 }) urls.py {% if request.path == roll_detail %}{% endif %}<a href="{% url 'roll_detail'%}?roll_no={{roll_no}}">ROll Detail</a> {% if request.path == sub_detail %}{% endif %}<a href="{% url 'sub_detail'%}?roll_no={{roll_no}}">Sub Detail</a> SO, what I want, That I have request roll_no once and that should work for both urls template, and when moving from one url/tab to another then it should maintain the data of current roll_no till next roll_no to be entered. -
Django Fixtures: Importing Nested Models
New to Python and Django and trying to import a .json file. The JSON file is structured in such a way that each root-level object has a nested object within it. For example, the JSON is structured as: [ { "model": "testapp.Person", "pk": 1, "fields": { "firstName":"Jane", "lastname":"Doe", "haircolor":"black", "mailingaddress": { "streetaddress": "1214 Example St.", "city": "Silver Spring", "state": "MD", "zipcode": "20910" } } } ] And the python model definition is as follows: from django.db import models # Create your models here. class address(models.Model): streetaddress = models.CharField(max_length=200) city = models.CharField(max_length=200) state = models.CharField(max_length=5) zipcode = models.CharField(max_length=10) def __init__(self, streetaddress, city, state, zipcode): self.streetaddress = streetaddress self.city = city self.state = state self.zipcode = zipcode class Person(models.Model): firstName = models.CharField(max_length=200) lastname = models.CharField(max_length=200) haircolor = models.CharField(max_length=200) mailingaddress = address(streetaddress, city, state, zipcode) Getting an error when running python manage.py loaddata because, obviously, the init parameters streetaddress, city, state, zipcode don't exist in that context. How do I construct my model to dynamically generate those other objects? -
How to upload file to django 2.0 server via django-restframwork using Volley library in android?
my goal is create an app like whasapp or telegram(image only - no chats) i want to send a picture to my django server this is my model: class exchange(models.Model): sender=models.CharField(verbose_name="sender",max_length=11) reciever=models.CharField(verbose_name="reciever",max_length=11) img=models.CharField(verbose_name="imageAddress",max_length=150) createTime=models.TimeField( auto_now_add=True,auto_now=False) class users(models.Model): number=models.CharField(verbose_name="userNumber",max_length=11) name=models.CharField(verbose_name="name",max_length=40) createTime=models.TimeField( auto_now_add=True,auto_now=False) status=models.BooleanField(default=False) class SMS(models.Model): users_id=models.ForeignKey(users,on_delete=models.CASCADE,default=0) code=models.PositiveSmallIntegerField(verbose_name="randomCode") createTime=models.TimeField( auto_now_add=True,auto_now=False) status=models.BooleanField(default=False) exchange class ==> to store sender and reciever (phone number) img store image path on django server .image store in directory on server users class ==> for register users SMS class ==> for sms verificaion users like whatsup my serializer api : class exchangeSerializer(ModelSerializer): class Meta: model=exchange fields="__all__" class SMSSerializer(ModelSerializer): class Meta: models=SMS fields="__all__" class usersSerializer(ModelSerializer): class Meta: model=users fields="__all__" my views api : class exchangeShow(generics.ListAPIView): queryset=exchange.objects.all() serializer_class=exchangeSerializer class SMSShow(generics.ListAPIView): queryset=SMS.objects.all() serializer_class=SMSSerializer class usersShow(generics.ListAPIView): queryset=users.objects.all() serializer_class=usersSerializer class exchangeDetailShow(generics.RetrieveAPIView): queryset=exchange.objects.all() serializer_class=exchangeSerializer lookup_field='id' class exchangeDelete(generics.DestroyAPIView): queryset=exchange.objects.all() serializer_class=exchangeSerializer lookup_field='id' class exchangeCreate(generics.CreateAPIView): queryset=exchange.objects.all() serializer_class=exchangeSerializer class SMSCreate(generics.CreateAPIView): queryset=SMS.objects.all(); serializer_class=SMSSerializer; class usersCreate(generics.CreateAPIView): queryset=users.objects.all() serializer_class=usersSerializer and urls api: urlpatterns=[ path('exchange/',views.exchangeShow.as_view()), path('sms/',views.SMSShow.as_view()), path('users/',views.usersShow.as_view()), path('exchange/<int:id>/delete',views.exchangeDelete.as_view()), path('exchange/create',views.exchangeCreate.as_view()), path('sms/create',views.SMSCreate.as_view()), path('users/create',views.usersCreate.as_view()), ] in volley library how can i implement sms vertificaion in django-restframework how can i send image from android device to django and save it in a directory in server and store path it in exchange table (img) and show it in … -
Django ajax redirecting on form submission
I'm trying to return data with an ajax request on a form submission. My goal was too use two views, one too handle the template loading and the other to handle the POST request from the form. In the current state, the form is redirecting to the JSON that is in the callback. That makes sense as it's for the form action url is pointing, however, i want to just pass the data to the current page and not reload the page or be redirected to another page. Here is the code: user.html <form action="{% url 'ajax-user-post' %}" method="post"> {% csrf_token %} {% for user in users %} <input type="submit" name="name" value="{{ user }}"> {% endfor %} views.py def ajax_user(request): # get some data.. if request.METHOD == 'POST': user = request.POST['user'] user_data = User.objects.get(user=user) data = {'user_data': 'user_data'} return JsonResponse(data) def user(request): return render(request, 'user.html', context) urls.py url(r'^success/', user, name="user"), url(r'^ajax/user/', ajax_user, name="ajax-user-post") .js $('form').on('submit', function(){ var name = // the name of the user selected $.ajax({ type: "POST", dataType: "json", url: 'ajax/user/', data: { 'csrfmiddlewaretoken': csrftoken, 'name': name, 'form': $form.serialize() }, success:function(data) { // hide the current data console.log(data); displayUserData(data) } }) }); Thanks for the help in advance! -
Django model field verbose name in template
How would you approach getting a Field verbose name to show up in a template when you are iterating over the fields via a custom array? Suppose you have #models.py class Letter (models.Model): a = models.CharField(max_length=1, verbose_name=u'The Letter and Vowel A') b = models.CharField(verbose_name=u'The Letter and Consonant B') ... y = models.CharField(verbose_name=u'The Letter, Consonant, and sometimes Vowel Y') def vowel_array(self): return [self.a,self.e,self.i,self.o,self.u,self.y,] nothing special in the view: ... return render(request, 'app/view.html', { 'language' : language, 'letters' : letters, }) and in the template {% for letter in letters.vowel_array %} <div>{{letter.verbose_name}}</div> <!-- for 'a' => The Letter and Vowel A --> {% endfor %} My current implementation seems problematic? def vowel_array(self): return [ [self.a, self._meta.get_field('a').verbose_name.title()], [self.e, self._meta.get_field('e').verbose_name.title()], [self.i, self._meta.get_field('i').verbose_name.title()], [self.o, self._meta.get_field('o').verbose_name.title()], [self.u, self._meta.get_field('u').verbose_name.title()], [self.y, self._meta.get_field('y').verbose_name.title()] ] and {% for letter in letters.vowel_array %} <div>{{letter.1}}</div> <!-- for 'a' => The Letter and Vowel A --> {% endfor %} -
Anonymous User - Displaying User Information
I am trying to display my users information but I am getting anonymous user as my output; Anonymous User My code in my views.py is as follows; def register(request): if request.method == 'POST': form = RegistrationForm(request.POST) if form.is_valid(): form.save() return redirect('/account') else: form = RegistrationForm() args = {'form' : form} return render(request, 'accounts/register.html', args) def view_profile(request): args = {'user': request.user} return render (request, 'accounts/profile.html',args) I am over-riding the UserCreationForm, my code in forms.py is; class RegistrationForm(UserCreationForm): email = forms.EmailField(required=True) class Meta: model = User fields = { 'username', 'first_name', 'last_name', 'email', 'password1', 'password2' } def save(self,commit=True): user = super(RegistrationForm,self).save(commit=False) user.first_name = self.cleaned_data['first_name'] user.last_name = self.cleaned_data['last_name'] user.email = self.cleaned_data['email'] if commit: user.save() return user My profile.html where I want my profile information to be displayed is; {% block head %} <title> User Profile </title> {% endblock %} {% block body %} <div class="container"> <p> <h1> {{user}}</h1> <h3>First Name: {{user.first_name}}</h3> <h3>Last Name: {{user.last_name}}</h3> <h3>Email: {{user.email}}</h3> </p> </div> {% endblock %} Really not sure where I am going wrong any help is greatly appreciated. -
Not autocomplete django-autocomplete-light (Django)
I have my model called DetalleVenta: class DetalleVenta(models.Model): producto = models.ForeignKey(Producto,on_delete=models.CASCADE,verbose_name='Producto') cantidad = models.IntegerField(verbose_name='Cantidad') preciounit = models.DecimalField(decimal_places=2, max_digits=7, verbose_name='Precio unitario') subtotal = models.DecimalField(decimal_places=2, max_digits=7, verbose_name='Subtotal') venta = models.ForeignKey(Venta,on_delete=models.CASCADE, related_name='detalleventa', verbose_name='Venta') def __str__(self): return '{} - {}'.format(self.venta,self.producto) It has as a foreign key to the Producto model class Producto(models.Model): nombre = models.CharField(max_length=30,unique=True,verbose_name='Nombre de Producto:') precio = models.DecimalField(decimal_places=2, max_digits=7, verbose_name='Precio de Producto:') categoria = models.ForeignKey(Categoria,on_delete=models.CASCADE,verbose_name='Categoría:') def __str__(self): return self.nombre My view class ProductoAutocomplete(autocomplete.Select2QuerySetView): def get_queryset(self): qs = Producto.objects.all() if self.q: qs = qs.filter(name__istartswith=self.q) return qs My Url url(r'^producto-autocomplete/$',ProductoAutocomplete.as_view(),name='producto-autocomplete'), My form class DetalleForm(forms.ModelForm): class Meta: model = DetalleVenta fields = [ 'producto', 'cantidad', 'preciounit', 'subtotal', ] labels = { 'producto':'Producto', 'cantidad':'Cantidad', 'preciounit':'Prec.Unit.', 'subtotal':'Subtotal', } widgets = { 'producto':autocomplete.ModelSelect2(url='producto-autocomplete/', attrs={'class': 'form-control'}), 'cantidad':forms.NumberInput(attrs={'class':'form-control cantidad'}), 'preciounit':forms.NumberInput(attrs={'class':'form-control'}), 'subtotal':forms.NumberInput(attrs={'class':'form-control subtotal', 'readonly':True}), } DetalleFormSet = inlineformset_factory(Venta, DetalleVenta, form=DetalleForm, extra=1) These are the steps that the official documentation says, but I can not see the autocomplete field. Something missing? Excuse the ignorance. But it's the first time I use this library. My template {% extends 'base/base.html' %} {% load static %} {% block titulo%} Registrar venta {%endblock%} {% block contenido %} <div class="col-md-12"> <form method="post">{% csrf_token %} <div class="col-md-4 form-group"> <label class="font-weight-bold" for="{{form.cliente.name}}">{{form.cliente.label}}</label> {{form.cliente}} </div> <h4 class="text-left">Detalle de venta: </h4> … -
add data to my Json in django
This is how my JSON data looks like {"id": 50, "first_digit": "2", "second_digit": "1", "calculate": "Addition"} I want to add extra data "result":"3" to my JSON this is my view def calc(request): if request.method == 'POST': first_number = request.POST['first number'] second_number = request.POST['second number'] operation = request.POST['operation'] result = do_calc(operation, first_number, second_number) # how to pass the result to my tempelate value = Calculation.objects.create( first_digit=first_number, second_digit=second_number, calculate=operation ) data = model_to_dict(value) return JsonResponse(data) Can anyone help me with it -
Docker + Gunicorn + Nginx + Django: redirect non-www to www on AWS Route 53
I have a Docker + Gunicorn + Nginx + Django setup on AWS EC2 and Route 53. Right now I want to redirect mydomain.com to www.mydomain.com. Is it appropriate to do a redirect in a Nginx configuration? Or are there are better solutions. Here is docker-compose-yml, using gunicorn to start the Django server. version: '2' services: nginx: image: nginx:latest container_name: dj_nginx ports: - "80:8000" - "443:443" volumes: - ./src/my_project/static:/static - ./src:/src - ./config/nginx:/etc/nginx/conf.d depends_on: - web web: build: . container_name: dj_web command: bash -c "python manage.py makemigrations && python manage.py migrate && gunicorn my_project.wsgi -b 0.0.0.0:8000" depends_on: - db volumes: - ./src:/src - ./apps/django_rapid:/src/my_project/django_rapid expose: - "8000" db: image: postgres:latest container_name: dj_db Here is my Nginx Conf upstream web { ip_hash; server web:8000; } # portal server { listen 8000; location / { proxy_pass http://web/; } location /media { alias /media; # your Django project media files - amend as required } location /static { alias /static; # your Django project static files - amend as required } server_name localhost; } # portal (https) server { listen 443; server_name localhost; ssl on; ssl_certificate /etc/nginx/conf.d/mynginx.crt; ssl_certificate_key /etc/nginx/conf.d/mynginx.key; location /media { alias /media; # your Django project media files - amend as … -
How to make field unique with other models
I have 3 different models, and they all have index field (small positive integer number). How to make them unique with each other? I was trying to override save model in models.py, and this is work pretty good, except ValidationError exception. It redirect me to the error page, and if i turn Debug=False, it will nothing show me at all, just "error 500" or something like that. It would be great if this validation show message in admin's page, without refreshing. Maybe someone know how to validate this properly, or how to make this in other way? -
Python + Django: Trouble with setting up mkvirtualenv on macOS
I’m trying to dabble around with Python and Django and am getting stuck on what is probably a dumb issue. I’m using macOS and have installed Python v 3.6.4 I'm trying to follow the instructions per this Mozilla article: [https://developer.mozilla.org/en-US/docs/Learn/Server-side/Django/development_environment][1] I only know enough terminal commands to be dangerous (which is why I'm learning) and I'm very much a Python n00b, so please be nice. :) My process: 1 which python » /usr/local/bin/python note, somewhere along the way I did a Symlink ln -s /usr/local/bin/python3 /usr/local/bin/python 2 python3 -V » Python 3.6.4 3 sudo -H pip3 install virtualenvwrapper » Requirement already satisfied: virtualenvwrapper in /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages Requirement already satisfied: stevedore in /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages (from virtualenvwrapper) Requirement already satisfied: virtualenv in /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages (from virtualenvwrapper) Requirement already satisfied: virtualenv-clone in /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages (from virtualenvwrapper) Requirement already satisfied: pbr!=2.1.0,>=2.0.0 in /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages (from stevedore->virtualenvwrapper) Requirement already satisfied: six>=1.10.0 in /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages (from stevedore->virtualenvwrapper) 4 nano .bash_profile » Add following: » export WORKON_HOME=$HOME/.virtualenvs export VIRTUALENVWRAPPER_PYTHON=/usr/local/bin/python3 ## is this the issue? export PROJECT_HOME=$HOME/Devel source /usr/local/bin/virtualenvwrapper.sh 5 mkvirtualenv my_django_environment » Running virtualenv with interpreter /usr/local/bin/python Using base prefix '/usr/local/bin/../../../Library/Frameworks/Python.framework/Versions/3.6' New python executable in /Users/myuser/.virtualenvs/my_django_environment/bin/python ERROR: The executable /Users/myuser/.virtualenvs/my_django_environment/bin/python is not functioning ERROR: It thinks sys.prefix is '/Library/Frameworks/Python.framework/Versions/3.6' (should be '/Users/myuser/.virtualenvs/my_django_environment') ERROR: … -
python virtual environment change
I am a beginner for django framework. I am working on multiple tutorial projects. According to best practices , I use different virtual environments for different projects. I have a problem. When I want to switch to another project , even through I deactivate virtual environment of closed project , my browser still looks to the virtual environment that I deactivated. So , I can not display my new project at http://127.0.0.1:8000/ . It still display the older one. Can you please show me the way? Thanks. -
How to make related dropdown search filter with Django
So for a while I had trouble with this... I have more models like: Faculty, Department, Study Programme and Courses. Now, based on these models I want to show specific courses. Like for faculty of biology, department of sciences, study programme of science, I want to list all courses in that study programme, specific to the department, specific to faculty. I want to make each of this in a dropdown and then to display results on page. I did some research and found something about using Ajax, but I don't know how to use that thing. Considering the attached models, how should I do this ? class Course(models.Model): study_programme = models.ForeignKey('StudyProgramme', on_delete=models.CASCADE, default='') name = models.CharField(max_length=50) ects = models.PositiveSmallIntegerField(validators=[MaxValueValidator(99)]) description = models.TextField() year = models.PositiveSmallIntegerField(validators=[MaxValueValidator(99)]) semester = models.IntegerField(choices=((1, "1"), (2, "2"), ), default=None) slug = models.SlugField(max_length=140, unique=True) class StudyProgramme(models.Model): department = models.ForeignKey('Department', on_delete=models.CASCADE) name = models.CharField(max_length=50) studies_type = models.IntegerField(choices=((0, "Bachelor Studies"), (1, "Master Studies"), (2, "PhD Studies"), (3, "Integrated Studies")), default=0) duration = models.PositiveSmallIntegerField(validators=[MaxValueValidator(99)]) class Department(models.Model): faculty = models.ForeignKey('Faculty', on_delete=models.CASCADE) name = models.CharField(max_length=50) class Faculty(models.Model): name = models.CharField(max_length=50) -
Data intensive application with Django?
I am trying to build a data intensive web application in Django. When I start this django application, I want it load a large amount of data (a few Gigabytes) into memory, and then whenever I receive a request, I will use the preloaded data to do some computation and generate a response based on the complicated calculations. I am wondering what might be the best way to organize this application. What will be the best way to build another layer that running purely on Python and Django can interact with the isolated running Python program for the calculation results. -
Django forms not sh
For some reason, my forms.py doesn't view any of the fields, instead, it only shows the 'Add' button and I don't know what to do anymore. I'd really appreciate if someone who knows what they're doing could tell me what I did, or didn't do. Please note that I'm new to Django, thank you. Here's my views.py: from django.shortcuts import render from django.utils import timezone from .models import Measurement from .forms import MeasurementForm from django.views import generic class IndexView(generic.ListView): model = Measurement context_object_name = 'measurement_list' template_name = 'index.html' queryset = Measurement.objects.all() def new_measurement(request): if request.method == "POST": form = MeasurementForm(request.POST) if form.is_valid(): measurement = form.save(commit=False) measurement.measurement_date = timezone.now() measurement.save() else: form = MeasurementForm() return render(request, 'index.html', {'form': form}) urls.py: from django.urls import path from . import views urlpatterns = [ path('', views.IndexView.as_view(), name='index'), ] forms.py: from django import forms from .models import Measurement class MeasurementForm(forms.ModelForm): class Meta: model = Measurement fields = ('measurement_value', 'measurement_unit') index.html: {% extends "base.html" %} {% block content %} <h1>Climate Measurement Tool</h1> <h2>Add a new measurement</h2> <form method="POST" class="post-form"> {% csrf_token %} {{ form.as_p }} <button type="submit" class="save">Add</button> </form> <h2>Measurements</h2> {% if measurement_list %} <ul> {% for measurement in measurement_list %} <li> <p>{{ measurement }}</p> </li> … -
How do I insert or create data with Django ORM programmatically? Or how do I specific Model field name with a string?
If I have: class Tag(models.Model): number = models.IntegerField() config = { "data": 1, "field": "number" } How do I do the following? record = Tag(config["field"], config["data"]) record.save() -
Django REST Framework- how can I create or update a foreign key object when POSTing parent
I am currently working on an API view, for a Job Planning system. Each Job, has a single JobPlan (which has a start and end date) and each JobPlan, may have several JobPlanManagers, users assigned to manage said Job. User one might be in charge of one month, and User two might overlap User 1, but extend the job by a couple of weeks. Thus, when User 2 POSTS their new JobPlanManager instance, they need to either create a new JobPlan (if no plan yet exists) or update the existing JobPlan, to extend the start and end appropriately. The user's POST data would include their user ID, the Job ID, and a start and end date, something like: { "manager": (User ID), "job_plan": { "id": null, "job": { "id": (existing Job ID) }, "start": "2018-02-01", "end": "2018-02-28" } } Additionally, I would like the return of this POST call to include all fields for JobPlan and Job, nested: e.g.: { "id": (created JobPlanManager instance ID) "manager": (User ID), "job_plan": { "id": (New or existing JobPlan ID) "job": { "id": (Existing Job ID), "name": "Existing Job Name" } "start": "2018-01-02", "end": "2018-02-28" } } My models look like: class Job(models.Model) name … -
How to use bootstrap styling in django project
I have downloaded bootstrap files (css, js) and put in the static folder of my project and made changes in header section of index.html as shown in the below code. But still django can't locate bootstrap.min.css as shown in the error "GET /static/css/bootstrap.min.css HTTP/1.1" 404 1687 Project Structure Project |---Project |---static |---css |---js |---templates |---index.html |---manage.py index.html <head> {% load staticfiles %} <link rel='stylesheet' href="{% static 'css/bootstrap.min.css' %}" type='text/css' /> </head> I followed tutorials and read documentation But could not locate the problem can anybody help, thanks in advance. -
Django: running a python shell in a sandbox environment, similar to rails console --sandbox
Inside my Django project, I want to fire up a python shell wherein I can make simple changes to my database (saving new records, updating old ones, etc.) which are then automatically reverted back when I exit the shell. Essentially the same functionality as running "rails console --sandbox" in a Ruby on Rails project. I'm not looking for all the features of a traditional sandbox such as blocking web-service calls, just the basic database rollback. Is this--or something similar--possible in Django? I want to use this for testing purposes. I know I can use Django's testing infrastructure to do this, but there are some basic instances where this would be very useful (e.g. quickly confirming that a specific model functions the way I expect it to). -
How do I use a CSS attribute's value of an html element as input when submiting a form with Django?
Please first click the link to the image below to understand my question/situation. If the text below a particular species icon (circle with animal image inside it) is bold, I would like that to be used as input criteria for getting information from a database. In other words, I want to use the font-weight CSS property of a element as an input. Only one "species text" can be bold at a time. For example, if I have "D. rerio" selected (its font is bold) and I click the "search" button, I would like for the back-end to know that it needs to pull information from the "D. rerio" database specifically. Click here to see the picture of the situation I described above -
How could I extend my user model with field profile_image = models.FileField()?
I have created a form and have all criterias of name, email, password but not the image. In order to create "upload image" option, I am in need to extend my user model with field profile_image = models.FileField() Do help. -
Pre-populating dropdown menus with ViewFlow Material Forms
I am using Django and am trying to get a dropdown menu to prepopulate. This is how I am currently trying to do it in the form: {% if asset.id|stringformat:"s" == pageID|stringformat:"s" %} {% attr form.assetID "option" selected %}"selected"{% endattr %} {% endif %} As you can see, I am trying to select the asset from the dropdown menu if it's ID matches the ID that was passed into the page and change it's selected attribute to "selected" if it matches. I know this isn't the right way to do it but I haven't been able to figure it out otherwise. I have tried overriding {% part form.assetID control %} and putting this code in there but that just removes the dropdown field entirely. Is there a way to do this without just writing the whole field myself? -
Django REST: Automatically update connected model (After POST)
I would like to create an ability for users to exchange 1-to-1 messages. To do this, I would like to update fields in my Django models, depending on actions taken by the Message model. For example, I would like to update the last_message in Conversation model, each time a new message is posted. I have 2 main models: Conversation and Message, where each conversation can have many messages. Models.py class Conversation(models.Model): last_message = models.CharField(max_length=50, blank=True) class Message(models.Model): body = models.TextField(max_length=500, blank=False) conversation = models.ForeignKey(Conversation, on_delete=models.CASCADE) I figured that I need to use the override the save() method in the Message class. def save(self, *args, **kwargs): super(Message, self).save(*args, **kwargs) # something that I need self.conversation.last_message = self.body In the end, I would like to send a POST request to my API endpoint e.g. /api/conversation/<id>/messages/ and it will update the Conversation object with every new latest message. -
How Could I Add Image Upload Option To The Registration Form?
My forms.py is this. from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm,UserChangeForm class RegistrationForm(UserCreationForm): email= forms.EmailField(required = True) class Meta: model = User fields = { 'username', 'first_name', 'last_name', 'email', 'password1', 'password2' } def save(self, commit=True): user = super(RegistrationForm, self).save(commit=False) user.first_name = self.cleaned_data['first_name'] user.last_name = self.cleaned_data['last_name'] user.email = self.cleaned_data['email'] if commit: user.save() And, i have to add "upload image" option for the user so that user could upload their image from any file and load it on the profile. -
Linking two django fields in two different models
I am going slightly crazy as I am sure this is a super simple question. I have two models in django: class Play(models.Model): gid = models.IntegerField() pid = models.IntegerField(primary_key=True) off = models.CharField(max_length=5) deff = models.CharField(max_length=5) type = models.CharField(max_length=10) class FGXP(models.Model): pid = models.IntegerField() fgxp = models.CharField(max_length=5) fkicker = models.CharField(max_length=10) This is a football database and when there is a Play that scores there is another table where additional data about the extra point is held: FGXP. So in Play pid is the primary_key. In FGXP there is a link between pid and the pid in play. In my Django model should I link them? I will end up needing to join the data when I do a query. Thanks - an apologies if a duplicate.