Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
DateTime filter in django rest
I am creating an api which returns weather data of particular city for n number of days given.(api definition: weatherdata/city_name/ndays/).I have problem sorting out data for ndays. I sorted out the city name using simple icontains. similarly I want to sort out for ndays. previous ndays data needs to be shown. example: suppose today is 2019-08-29, on providing ndays to be 6, weather data of particular city has to be provided from 2019-08-24 to 2019-08-26. views.py class weatherDetail(APIView): def get_object(self, city_name, ndays): try: x = weatherdata.objects.filter(city_name__icontains=city_name) now = datetime.datetime.now() fromdate = now - timedelta(days=ndays) y = return x except Snippet.DoesNotExist: raise Http404 def get(self,*args,**kwargs): city_name = kwargs['city_name'] snippet = self.get_object(city_name,ndays) serializer = weatherdataserializer(snippet,many =True) return Response(serializer.data) models.py class weatherdata(models.Model): city_name = models.CharField(max_length = 80) city_id = models.IntegerField(default=0) latitude = models.FloatField(null=True , blank=True) longitude = models.FloatField(null=True , blank=True) dt_txt = models.DateTimeField() temp = models.FloatField(null = False) temp_min = models.FloatField(null = False) temp_max = models.FloatField(null = False) pressure = models.FloatField(null = False) sea_level = models.FloatField(null = False) grnd_level = models.FloatField(null = False) humidity = models.FloatField(null = False) main = models.CharField(max_length=200) description = models.CharField(max_length=30) clouds = models.IntegerField(null=False) wind_speed = models.FloatField(null = False) wind_degree = models.FloatField(null = False) urls.py urlpatterns = [ path('admin/', admin.site.urls), … -
Django: unique_together for foreign field
For next two models: class Foo(models.Model): parent = models.ForeignKey(Parent) name = models.CharField() class Bar(models.Model): foreign = models.ForeignKey(Foo) value = models.CharField(max_length=20) I need to have unique_together constraint for Bar model: class Meta: unique_together = ('value', 'foreign__parent') Which is impossible in Django. But is it possible to achieve this on database level (Postgresql) with some contraint or model level validation to omit possible case (lock table?) when simultaneously same value may be saved to different Bar instances? Django 2.2.4 No ModelForm or default validate_unique() -
What's the best way to handle service accounts in django?
I have a Django / REST framework application that needs to recieve logs from remote workers and store them as objects in the database so that they can be provided to users through the web interface. I am using the standard DRF token authentication and I was thinking the best way to do this would be to create a service account with permissions restricted to PUT on the log view, so that the workers could use this to send logs back to the django app. Is there a way I can have an account with token authentication but without password login? Is there any best practices / reading material around service accounts, or is there a better way of achieving this goal? I can't seem to find anything relevant. Is there an easy way of generating such an account on initial setup without having to use the admin interface so that it is ready to go on install? Thanks in advance -
django group by on annotated data
I have a result queryset which contains annotated data. I want to further group by on column hour and want to sum of another column number for hour. For example , i have a queryset:- <QuerySet [{'hour': 10, 'num_time': 101}, {'hour': 10, 'num_time': 1}, {'hour': 10, 'num_time': 2}, {'hour': 10, 'num_time': 4}, {'hour': 10, 'num_time': 1}, {'hour': 10, 'num_time': 13}, {'hour': 10, 'num_time': 6}, {'hour': 10, 'num_time': 2}, {'hour': 10, 'num_time': 3}, {'hour': 10, 'num_time': 8}, {'hour': 10, 'num_time': 4}, {'hour': 10, 'num_time': 6}, {'hour': 10, 'num_time': 1}, {'hour': 10, 'num_time': 3}, {'hour': 10, 'num_time': 18}, {'hour': 10, 'num_time': 3}, {'hour': 10, 'num_time': 19}, {'hour': 10, 'num_time': 3}, {'hour': 10, 'num_time': 14}, {'hour': 10, 'num_time': 4}, '...(remaining elements truncated)...']> I want below result:- [{'hour': 10, 'num_time' : 210},{'hour': 18, 'num_time': 30}] How can i achieve with django queryset? Here is my query for first queryset resullt:- table_name.objects.filter(id=id,created_time__isnull=False,day__range=[(date.today()-timedelta(days=30)),date.today()]).annotate(hour=ExtractHour('created_time'),num_time = Sum('A') + Sum('B') + Sum('C') + Sum('D')).values('hour', 'num_time').order_by('hour') Any help will be much appreciated!! -
Difference between two model fields
I have a model named 'CarAdd', and two other models are connected with a foreign key to this CarAdd model that are ShippingDetails, MaintenanceDetails. and each foreign key model has an item and price field." foreign key have more than 2 items under one id" I need to find the profit amount of each car profit = sold_amount - (purchased amount + total shipping cost + total maintenance cost) class CarAdd(models.Model): # Car Details name = models.CharField(max_length=60) purchased_amount = models.DecimalField() # there 3 choices in STATUS shipped, maintenance, sold status = models.CharField(max_length=12, choices=STATUS) sold_amount = models.DecimalField(max_digits=15, decimal_places=1) profit_amount = models.DecimalField(max_digits=15, decimal_places=1) class ShippingDetails(models.Model): car = models.ForeignKey(CarAdd, related_name='shipping_details', on_delete=models.CASCADE) item = models.CharField(max_length=60) price = models.DecimalField(max_digits=15, decimal_places=1,) class MaintenanceDetails(models.Model): car = models.ForeignKey(CarAdd, related_name='maintenance_details', on_delete=models.CASCADE) item = models.CharField(max_length=60) price = models.DecimalField(max_digits=15, decimal_places=1) class CarAdd(models.Model): def save(self, *args, **kwargs): if self.status == 'sold': sum_invested = self.purchased_amount + ShippingDetails.price + MaintenanceDetails.price profit = self.sold_amount - sum_invested self.profit_amount = profit super().save(*args, **kwargs) how do I calculate the profit amount and save to profit_amount field -
505 Error could not connect to server: Connection refused Is the server running on host "127.0.0.1" and accepting TCP/IP connections on port 5432?
0 This is my first project to publish with django on Google Cloud Console but it gives the error : could not connect to server: Connection refused Is the server running on host "127.0.0.1" and accepting TCP/IP connections on port 5432? Other pages load but when I want to connect to the psql db this is the error message I get after i set debug to True -
Does ajax run on PythonAnywhere?
My page worked fine on localhost. I deployed my page on PythonAnywhere and it pop up a "500 Internal Server Error" when I tried to submit a form using POST method. The error point to jquery.min.js and my ajax code. $(document).on('submit', '#CustomerRequest', function(e){ e.preventDefault(); $.ajax({ <!--This line is where the error is--> type:'POST', url:'/create_request', data:{ ... Do I need to add anything for PythonAnywhere to run ajax? I read somewhere that a page need SSL for ajax to run, is it true? -
Model inheritance with a dynamic form
i am pretty new to django and i am having issues atm with model inheritance combined with a dynamic form class ConstructionVehicle (models.Model): name = models.CharField(max_length=100, null=False, blank=False) class Meta: db_table="constructionvehicle " class Crane(ConstructionVehicle): consturcion_year = models.PositiveIntegerField(validators=[MaxValueValidator(9999), MinValueValidator(1900)]) class Meta: db_table="crane" class Excavator(ConstructionVehicle): weight = models.PositiveIntegerField() class Meta: db_table="excavator" So, for example, i have the datastructure above. Now i want to create a dynamic form, where i can select the typ of construction vehicle and it displays me the fields of the model. After that i should be able to save the model to the database. Is that possible? -
How to can I work with multiple select options and make these options selected to stay selected?
Form widget value not selected after saving data options using CheckboxSelectMultiple() widget forms.py class Client_ProcessForm(forms.Form): process = forms.ModelChoiceField(queryset= Process.objects.all(), widget=forms.CheckboxSelectMultiple) Views.py def Edit_Client(request, id): form = Client_ProcessForm(request.POST) edit_record = Client.objects.get(pk=id) obj = Client.objects.all() cp = Client_Process.objects.filter(client_id=edit_record) cp1 = cp.values_list('process') obj1 = {} for i in range(len(cp1)): ps = Process.objects.filter(id__in=cp1[i]) print(ps) obj1[cp1[i][0]] = list(ps) return redirect('/client_list/') return render(request, 'edit_client.html',{'edit_record': edit_record, 'form' : form, 'obj' : obj, 'cp' : obj1}) html <select name="process"> {% for entry in form %} <option value="{{ entry }}">{{ entry.process }}</option> {% endfor %} </select> -
Error 'Reverse for 'password_reset_confirm' not found.' In Django
So, I was trying to build a blog website in which the user can reset his password by sending an email to his email address, I was mostly using Django Build In functionality for that. I was trying to make the confirm URL path in which the user can reset his password but was getting an error even when I included the path for password reset confirm. Error: Reverse for 'password_reset_confirm' not found. 'password_reset_confirm' is not a valid view function or pattern name. My urls.py for password-reset from django.conf.urls import url from django.contrib.auth import views as auth_view from django.urls import path app_name = "blog" urlpatterns = [ # for /blog/password-reset/ path('password-reset/', auth_view.PasswordResetView.as_view(template_name='blog/password_reset.html'), name="password_reset"), # for /blog/password-reset/done/ path('password-reset/done/', auth_view.PasswordResetDoneView.as_view(template_name='blog/password_reset_done.html'), name="password_reset_done"), # for /blog/password-reset/confirm/<uidb64>/token> path('password-reset-confirm/<uidb64>/<token>', auth_view.PasswordResetConfirmView.as_view(template_name='blog/password_reset_confirm.html'), name="password_reset_confirm"), ] Note: I'm not including all the urls cause it's kinda big My blog/password_reset_confirm.html {% extends "blog/base.html" %} {% load crispy_forms_tags %} {% block body %} <div class="content-section"> <form method="POST"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">Reset Password</legend> {{ form|crispy }} </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit">Reset Password</button> </div> </form> </div> {% endblock body %} I expect the output to be a connection error which by the way is what I want to … -
“Is there an R function for finding the index of an element in a vector?”
“I’m setting up a new server, and want to support UTF-8 fully in my web application. Where do I need to set the encoding/charsets?” “This is for a new Linux server, running MySQL 5, PHP 5 and Apache 2. In the past, I’ve tried on existing servers and always seem to end up having to fall back to ISO-8859-1.” Use code fences and syntax highlighting to format your code properly and provide context def function(foo): print(foo) “I expect the output of 5/2 to be 2.5, but the actual output is 2.” -
Can I Perform All Django Queries in a dicitionay?
Firstly I Have More than 1 Million Data In my database , while i want to perform aggregation or annotation or filter it took huge time , i have to show all data at a time,,, i use select_related() for foreign key but i want to optimize database hitting , like i want to fetch all data from database in first database hit and convert them into dictionary or list and perform another queries into dictionary or list without hitting database i hope it can optimize database hit Example : In Laravel I Fetch All data from database and convert it into Array while i have to perform queries into it i convert them into collect() and perform queries , and it dont hit the database . [a link ]:(https://laravel.com/docs/5.8/collections) ! I Can perform this in Django ??? -
How to update css/scss files with NGINX
I am running a Digital Ocean droplet with Gunicorn and NGINX. I am able to view my web pages but I am not able to update html/css/scss. I have added include /etc/nginx/mime.types; in /etc/nginx/nginx.conf as suggested in another post. Also tried python manage.py collectstatic and received the following: 0 static files copied to '/home/ubuntuadmin/pyapps/nomad/static', 177 unmodified sudo nano /etc/nginx/sites-available/nomad >>> server { listen 80; server_name 157.245.0.153; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/ubuntuadmin/pyapps/nomad; } location /media/ { root /home/ubuntuadmin/pyapps/nomad/; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; include /etc/nginx/mime.types; } }``` -
The current path, home/, didn't match any of these
I have two apps on my project- one is accounts and home home app url - http://localhost:8000/home/ is rising an error that the current path, home/, didn't match any of these. I'm using django version 2.2.4 and i'm using regular expression on my home url pattern My home url from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.home, name='home') ] My home view from django.shortcuts import render from django.http import HttpResponse # Create your views here. def home(request): return HttpResponse('It worked !..') **My project url** urlpatterns = [ path(r'^admin/', admin.site.urls), url(r'^$', views.login_redirect, name='login_redirect'), # automatically takes to login page path(r'^account/', include(('accounts.urls','accounts'), namespace='accounts')), path(r'^home/', include(('home.urls','home'), namespace='home')), path('', include('django.contrib.auth.urls')), ] i'm expecting simple message on the browser that is 'It worked!..' -
Django form submission & CSRF (403 Forbidden)
Upon providing valid data and submitting a form, I get the following: Forbidden (CSRF cookie not set.): /membership/success/. I have a {% csrf_token %} in my template and my settings.py middleware is configured for CSRF. #urls.py from django.contrib import admin from django.urls import path, include from membership import views as ms_views membership_patterns = ([ path("", ms_views.RegistrationPage.as_view(), name="register"), path("success/", ms_views.SuccessPage.as_view(), name="success") ], 'membership') urlpatterns = [ path('admin/', admin.site.urls), path('membership/', include(membership_patterns, namespace="new_members")) ] # membership/views.py from django.shortcuts import render from django.template.loader import get_template from django.views import View from django.http import HttpResponse, HttpResponseRedirect from membership.forms import RegisterForm from django.urls import reverse # Create your views here. class RegistrationPage(View): def get(self, request): register_page = get_template('membership/signup.html') register_form = RegisterForm() return HttpResponse(register_page.render({'form' : register_form})) def post(self, request): submitted_form = RegisterForm(request.POST) if submitted_form.is_valid(): return HttpResponseRedirect(reverse('membership:success')) return HttpResponse(reverse('membership:register')) class SuccessPage(View): def get(self, request): return HttpResponse("Success") # signup.html {% extends 'index.html' %} {% block content %} <form action="{% url 'membership:success' %}" method='post'> {% csrf_token %} {{ form.as_p }} <button type="submit">Submit</button> </form> {% endblock %} Once the form is submitted and valid, I'm expecting a 302 to occur. Like I said though I get 403 forbidden. -
How to implement 'follow' functionality on a blog author
I have a blog app that works pretty well. However I want to expand its functionality to include an option for users to follow authors. I created a class FeedListView has a get_queryset function but i dont know how to use this to return the authors the logined in user follows. my FeedListView looks like this: class FeedListView(ListView): model = Post template_name = 'blog/feed_posts.html' # <app>/<model>_<viewtype>.html context_object_name = 'posts' paginate_by = 6 def get_queryset(self): queryset = Post.objects.filter(author__followers=user) return queryset # self.user = self.get_object() # return Post.objects.filter(author__followers=user) The model (User) like this: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='profile_pics') follows = models.ManyToManyField('self', related_name='followed_by', symmetrical=False) def __str__(self): return f'{self.user.username} Profile' the url.py is: path('feed/', FeedListView.as_view(), name='feed_posts'), If i can get it to the state where when i navigate to the url the posts only by the followed users are displayed I would be overjoyed. But I need some guidance on how this query set works as im a bit lot here. -
Linode/Django Can't see site when I runserver at ip:8000
I had started a fresh linode running ubuntu 19.04 and the first time I used the directions at: https://www.rosehosting.com/blog/how-to-install-mezzanine-cms-on-ubuntu-18-04/ To install Mezzanine CMS it worked just fine, I could run the runserver command and see the django website. Eventually it started giving me a problem after trying 50 ways to deploy the site using apache and mod_wsgi. I gave up and rebuilt the server and then still couldn't see the new install at the IP when I ran run server. I figured maybe it was because I accidentally installed some things using "python" and others with "python3" so I rebuilt the server. This third time I followed the direction perfectly, the only difference is I didn't install a mysql server just kept the default SQLlite server and created a DB and Django Superuser. I have added my ip as a host in settings.py and local_settings.py I have already ran makemigrations and migrate I did check to see if maybe the IP had changed when I rebuilt, it hadn't My local environment on my laptop works fine, just not the linode Any suggestions on anything I'm missing? -
some advices on deploying Django app to product locally
I want to deploy (production not testing) Django app with PostgreSQL database for my company, however, for security reason I want the app to be on local network and not accessible through the internet. I need some recommendations and advices to achieve that on setup and tools. Suppose I know python3 manage.py runserver myip:8000 EDIT: I wanted to be accessible by different machine on the same network. -
Is it possible to set the enctype="multipart/form-data" for a form in the backend?
I'm working on Ticketing System using Django framework. I want to implement a functionality where tickets can be created via email so far the recipient email is tied to a user. I used mailgun to create a route which redirect the mail data to a URL. I've been able to handle the mail content successfully except the attachment and i think this because i'm not setting the enctype attribute which is mandatory when uploading a file. The form isn't validating. Is it possible to set the enctype="multipart/form-data" in the bankend? model.py from django.db import models from .utils import * from django.db.models.signals import pre_save class Ticket(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) subject = models.CharField(max_length=50, blank=False, null=False) message = models.TextField() task = models.ForeignKey(Task, on_delete=models.CASCADE, null=True, blank=True) status = models.CharField(max_length=50, choices=STATUS_CHOICES, default='open') request_time = models.DateTimeField(auto_now_add=True) response_time = models.DateTimeField(auto_now=True) priority = models.CharField(max_length=50, choices=PRIORITY_CHOICES, default='mid') is_active = models.BooleanField(_('active'), default=True) objects = GeneralManager() def __str__(self): return self.subject def get_absolute_url(self): return reverse('ticket_detail', kwargs={'pk': self.pk}) def req_ticket_create_update_receiver(sender, instance, *args, **kwargs): # reciever function for ticket model from_email = config('from_email') if Ticket.objects.filter(id=instance.id).exists(): if instance.status == 'close': subject = f'Ticket With ID {instance.id} Has Been Closed' message = f'Hello {instance.user.get_short_name()}, \nYour ticket with ID {instance.id} has been closed. We hope the … -
Django-taggit, tag slug is not linking to the correct ListView
I installed django-taggit and django-taggit-templatetags2 and included in all the models that I needed. On the app name blog with model Post the tags work perfect as the code bellow. '''blog/views.py''' def tutorialpage(request): tutorial_list = Post.objects.all() context = { 'tutorial_list': queryset, } return render(request, "tutorialpage.html", context) class TagMixin(object): def get_context_data(self, **kwargs): context = super(TagMixin, self).get_context_data(**kwargs) context['tags'] = Tag.objects.all() return context class TagIndexView(TagMixin, ListView): template_name = 'tutorialpage.html' model = Post context_object_name = 'tutorial_list' def get_queryset(self): return Post.objects.filter(tags__slug=self.kwargs.get('slug')) '''blog/urls.py''' path('tag/<slug:slug>/', views.TagIndexView.as_view(), name='tagged'), '''tutorialpage.html''' {% load taggit_templatetags2_tags %} {% for tutorial in tutorial_list %} <a href="/tutorialdetail/{{tutorial.slug}}">{{ tutorial.title }}</a> {% endfor %} {% get_taglist as tags for 'blog.Post' %} {% for tag in tags %} <a href="{% url 'tagged' tag.slug %}">{{ tag.name }}</a> {% endfor %} Now on a different app name articles with model ArticlePost. I applied the same idea and the tags display correct from the ArticlePost, but when I click on one of them it links to the blog Post ListView template and blank, and it has the correct slug, here is the code. '''articles/view.py''' def articlepost(request): article_list = ArticlePost.objects.all() context = { 'article_list': article_list, } return render(request, "articlepost.html", context) class TagMixin(object): def get_context_data(self, **kwargs): context = super(TagMixin, self).get_context_data(**kwargs) context['tags'] = … -
Django Listing Users with specific object in template
I want to display the list of users with some objects in 2 apps created. these are the models. first model: class UserProfile(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE) indirizzo = models.CharField(max_length=50) citta = models.CharField(max_length=50) paese = models.CharField(max_length=50) ecap = models.CharField(max_length=4) descrizione = models.CharField(max_length=100, default='') image = models.ImageField(upload_to='profile_image', blank=True,null=True) second model: class Ore(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="ore",null=True,) data = models.DateField(default=timezone.now) oret = models.CharField(max_length=3,) contrattiok = models.PositiveSmallIntegerField() contrattiko = models.PositiveSmallIntegerField(default=0,) nomecognome = models.CharField(max_length=100,blank=True) my view: def inizio(request): users = User.objects.all() return render (request, "base.html", {"users":users}) my template: {% for users in users %} <tbody> <tr> <td> <img src="{{ users.userprofile.image.url }}"class="thumbnail"> <h4 class="small font-weight-bold">{{users}}</h4> </td> <td><h4 class="small font-weight-bold">{{users.last_name}}</h4></td> <td class="text-center"> <h4 class="small font-weight-bold" class="btn btn-primary btn-circle">{{ users.ore.contrattiok }}</h4> <<<<<(does not work) </td> </tr> {% endfor %} -
How to fix double result date range in django queryset
I have a three model, that looks something like this: class BuildingCell(models.Model): building_name = models.CharField(max_length=100, blank=True, null=True) publish = models.DateField(auto_now=False) cell_name = models.CharField(max_length=100, blank=True, null=True) ... class InputCutSew(models.Model): user = models.ForeignKey(Profile, blank=True, null=True, on_delete=models.SET_NULL) cell = models.ForeignKey(BuildingCell, blank=True, null=True, on_delete=models.SET_NULL) publish = models.DateField(auto_now=False) ... class Absent(models.Model): cell = models.ForeignKey(BuildingCell, blank=True, null=True, on_delete=models.SET_NULL) building_name = models.CharField(max_length=12, blank=True, null=True) publish = models.DateField(auto_now=False) ... #my queryset q1 = BuildingCell.objects.filter(inputcutsew__publish__range=[get_publish_start, get_publish_end], absent__publish__range=[get_publish_start, get_publish_end], absent__building_name='f1', absent__bagian='CUT', inputtcutsew__user='1').exclude(inputcutsew__cell_name__isnull=True)/ .exclude(inputcutsew__cell_name__exact='')/ .order_by('inputcutsew__cell')/ .values('inputcutsew__cell', 'inputcutsew__model', 'absent__cell', 'inputcutsew__output') #my error result: 'inputcutsew__cell', 'inputcutsew__model', 'absent__cell', 'inputcutsew__output 1a aa 1a 122 1b as 1b 100 1a aa 1a 122 1b as 1b 100 I want to query to get some field from three model, but the result is still double. Could you please have your suggestions on this??, any help will be appreciated. -
How to pass payment gateway parmament to an api in json in django
How do i get Collect data with the parameters below and send as a json payload to an api in djnago . https://test.theteller.net/checkout/initiate merchant_id transaction_id desc amount redirect_url email API_Key apiuser -
Editing dynamic choice fields in Django
I have a standard Django blog with a Post model, only on the model I have added a ManyToManyField for approvers, the idea being that the backend passes the post to 2 or more approvers to confirm the content before it is published. class Post(models.Model): author = models.ForeignKey( get_user_model(), null=True, on_delete=models.SET_NULL) title = models.CharField(max_length=30) content = models.CharField(max_length=30) approvers = models.ManyToManyField(Approvers) I will probably learn towards something like django-fsm to create a finite state machine for the Post model to govern whether it is draft/in approval/published, but I would like to be able to change the approvers field so that the number and order of approvers (users) can be changed dynamically by the user. What is the best way to do this? I thought I could try and change the approvers field to a JSONField so that users can add / delete / change the order of approvers and then handle the interpretation in the frontend and write some function to interface with django-fsm, but this feels like it conflates things too much. Am I missing a simpler route? -
Using Value From One View in Another View Django
In View 1's form their is a field called 'reference'. I need to access whatever value is submitted in that field in View 2 and set a variable equal to it. Right now I am just getting an error "orders matching query does not exist". This is what I'm trying (I've commented the code in view2 to indicate where im getting the error). views.py def view1(request, pk): item = get_object_or_404(Manifests, pk=pk) if request.method == "POST": form = CreateManifestForm(request.POST, instance=item) if form.is_valid(): form.save() return redirect('view2') else: form = CreateManifestForm(instance=item) return render(request, 'edit_manifest_frombrowse.html', {'form': form}) def view2(request): form = CreateManifestForm(request.POST) if request.method == "POST": if form.is_valid(): form.save() ... reference_id = request.POST.get('reference') #this is how Im trying to get reference from the previos view data = Manifests.objects.all().filter(reference__reference=reference_id) form = CreateManifestForm(initial={ 'reference': Orders.objects.get(reference=reference_id), #this is where im getting "does not exist" }) total_cases = Manifests.objects.filter(reference__reference=reference_id).aggregate(Sum('cases')) context = { 'reference_id': reference_id, 'form': form, 'data': data, 'total_cases': total_cases['cases__sum'], } return render(request, 'manifest_readonly.html', context) forms.py class CreateManifestForm(forms.ModelForm): class Meta: model = Manifests fields = ('reference', 'cases', 'product_name', 'count', 'CNF', 'FOB') I just want to be able to use whatever value is submitted in the 'reference' field in view1 in view2 and assign it equal to reference_id