Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I CSS-style different returns from the same Python function?
I have a Python function which returns different messages in different scenarios. I want to style different messages differently, but I don't know how to do it. This is my function: def checkans(request, spanish_id): random_spanish_question = get_object_or_404(Spanish, pk=spanish_id) query = request.GET.get('ans') coreng = random_spanish_question.english_set.get() if query == str(coreng): message = { 'message' : "Correct!" } return JsonResponse(message) else: message = { 'message' : "Incorrect. The correct answer is " + str(coreng) } return JsonResponse(message) This is the HTML page: <div class="flexcontainer" style="justify-content: center;"> <div class="sectiontitle">Quiz time </div> <div class="question_card"> <div class="question_word">{{ random_spanish_question }}</div> <div id="msg"></div> <form action="/checkans/{{random_spanish_question.id}}/" method="get">{% csrf_token %} <label for="ans">Answer:</label> <input type="text" name="ans"autofocus autocomplete="off" id="ansfield"/> <input type="submit" value="Submit"/ id="submitbtn"> </form> <input type="submit" value="Skip"/> <button onclick="location.reload();">Next</button> </div> </div> And this is the JS and AJAX code: $('form').on('submit', function(e){ e.preventDefault(); var form = $(this); var url = form.attr('action'); $.ajax({ type: 'GET', url: url, data: form.serialize(), success: function(data){ $("#msg").html(data.message); } }); disable(); }) function disable(e){ $('#submitbtn').prop('disabled', true); $('#ansfield').prop('disabled', true) } For example, I want to make the "Correct!" message green, while if it returns "Incorrect...", I want it to be red, and underline the answer, "str(coreng)". Please tell me how I can do it. Thanks in advance! -
Save Image from url Django Rest Framework
I'm trying to save an image from a url in the post request. Here is what I have so far, the error is while passing the file to the serializer. #models.py class Picture(models.Model): picture = models.ImageField( upload_to=upload_location_picture, max_length=255 ) owner = models.ForeignKey( User, on_delete=models.CASCADE, related_name='owned_pictures') #views.py class PlanPostPictureByUrl(APIView): ''' Class to post dislike to plan ''' permission_classes = (permissions.IsAuthenticated,) def post(self, request, format=None): img_url = request.data["picture"] name = urlparse(img_url).path.split('/')[-1] response = requests.get(img_url) if response.status_code == 200: serializer = PlanPicturesSerializer( data={"picture":ContentFile(response.content)}) if serializer.is_valid(): serializer.save(owner=self.request.user) return Response(status=status.HTTP_201_CREATED) return Response(status=status.HTTP_400_BAD_REQUEST) #serializers.py class PlanPicturesSerializer(serializers.ModelSerializer): class Meta: model = Picture fields = ['picture'] This is the error I am getting from the serializer: {'picture': [ErrorDetail(string='No filename could be determined.', code='no_name')]} -
The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*'
So I am building a Django REST API with a Vue.js frontend and am not able to do cross origin get requests using Axios. I have seen several other posts to enable CORS on Django and what not which I have done but continue to get the same error. My Django backend settings looks like: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'corsheaders', 'api', ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'corsheaders.middleware.CorsPostCsrfMiddleware', 'django.middleware.common.CommonMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/2.0/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] from corsheaders.defaults import default_headers CORS_ALLOW_HEADERS = True CORS_ALLOW_CREDENTIALS = True CORS_ORIGIN_ALLOW_ALL = False # CORS Origin Whitelist is the list of origins that are authorized # to make cross-site HTTP requests to our Django local server CORS_ORIGIN_WHITELIST = [ 'http://localhost:8080', ] CRSF_TRUSTED_ORIGINS = [ 'http://localhost:8080', ] And this is the Vue component I am trying to make the get request with: <script> import axios from 'axios' export default { mounted: function () { this.getStocks() console.log('Mounted Got Here') }, data: () => ({ … -
Django TypeError when accessing a link by get_absolute_url()
Good day. So i'm going through Django 2 by Example and i've encoutered a strange error when visiting a object from list of objects. TypeError at /1/black-tea/ product_detail() got an unexpected keyword argument 'id' The type it recieves is correct so small help would be appriciated. code from views.py def product_detail(request, product_id, slug): product = get_object_or_404(Product, slug=slug, id=product_id, available=True) return render(request, 'shop/product/detail.html', {'product': product}) models.py class Product(models.Model): category = models.ForeignKey(Category, related_name='products', on_delete=models.CASCADE) name = models.CharField(max_length=200, db_index=True) slug = models.SlugField(max_length=200, db_index=True) image = models.ImageField(upload_to='products/%Y/%m/%d', blank=True) description = models.TextField(blank=True) price = models.DecimalField(max_digits=10, decimal_places=2) available = models.BooleanField(default=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) class Meta: ordering = ('name',) index_together = (('id', 'slug')) def __str__(self): return self.name def get_absolute_url(self): return reverse('shop:product_detail', args=[self.id, self.slug]) urls.py path('<int:id>/<slug:slug>/', product_detail, name='product_detail'), Code from template <div id="main" class="product-list"> <h1>{% if category %} {{ category.name }}{% else %}Products{% endif %}</h1> {% for product in products %} <div class="item"> <a href="{{ product.get_absolute_url }}"> <img src="{% if product.image %}{{ product.image.url }} {% else %}{% static 'img/images.jpeg' %}{% endif %}"> </a> <a href="{{ product.get_absolute_url }}">{{ product.name }}</a> <br> ${{ product.price }} </div> {% endfor %} </div> -
fetch() URL won't get recognized
I keep getting error that the get-response in fetch("/get-response/" isn't found Can you help me figure out why? Here is some code fetch("/get-response/", { //<---- Not found body: JSON.stringify({'message': message['text']}), cache: 'no-cache', credentials: 'same-origin', headers: { 'user-agent': 'Mozilla/4.0 MDN Example', 'content-type': 'application/json' }, method: 'POST', mode: 'cors', redirect: 'follow', referrer: 'no-referrer', }) The get-response is coming from urls.py: from django.contrib import admin from django.conf.urls import include, url from django.urls import path from MyApp.views import Index, get_response from django.conf.urls.static import static from django.conf import settings urlpatterns = [ path('admin/', admin.site.urls), url('', Index), path('get-response/', get_response), ] And the get_response is coming from views.py @csrf_exempt def get_response(request): response = {'status': None} if request.method == 'POST': data = json.loads(request.body.decode('utf-8')) message = data['message'] chat_response = chatbot.get_response(message).text response['message'] = {'text': chat_response, 'user': False, 'chat_bot': True} response['status'] = 'ok' else: response['error'] = 'no post data found' -
Django password protected pages
I've made a Django based website that can authenticate users by logging in, but I'm wondering if there is a way I could lock pages to a password? for example, on the front page I would have a form asking for a code (such as "SecretPassword1") and once a correct passphrase has be entered you would be re-directed to a 'secret' page? is this possible or am I thinking about it in the wrong way? (this is my first post on StackOverflow so sorry if anything is posted incorrectly) -
How do I link the is_org_admin field in the User model to the org_admin field in the Organization model in Django?
I'm trying to create some models in Django. I currently have the following: User and Organization. One of the fields in the User model is "is_org_admin", which is a boolean. How should I link this field to the "org_admin" field in the Organization model? Here's the simplified code: class Organization(models.Model): id = ... org_admin = models.OneToOneField("users.User"... class User(AbstractUser): id = ... is_org_admin = models.BooleanField(default=False) organization = models.ForeignKey("organizations.Organization", on_delete=models.CASCADE, null=True) -
Getting actual name of file after upload Django
I got a problem with retrieving the current name of the file. At the moment when I'm uploading file to my model with suffix. class DataUpload(models.Model): file_uploaded_path = models.FileField(upload_to="csv/%Y/%m/%d/") The problem with that is that I can't retrive file name with suffix. When i use >> DataUpload.file_uploaded_path.path I get only only path to the media root folder project/media/file.txt I've tried also .name or .url, still it's not it. I think I checked everywhere and I'm really out of ideas. -
vscode didn't close all django processes when comment "--noreload"
VSCode Version: 1.42.1 OS Version: Ubuntu 18.04 Steps to Reproduce: Comment "--noreload" in launch.json Press Ctrl + F5 to run the django process. Click "stop(Shift + F5)" button to stop all django processes. But there is still a process (pid 23069) that has not been closed. And its parent process become 1 from 23064 -
Model design for One to many relationship
I have to design model for a customer and cars owned by customer. A customer can own one car or multiple cars. The template should have a car dropdown thru which user can select a car model, there should be a add button for user to add another car model. [template view][1] [1]: https://i.stack.imgur.com/N8Fo6.png how do i go forward designing the model currently the model looks like this: class Customer(models.Model): customer_name = model.Charfield(max_length=30) class Car(model.Model): model_name = model.Charfield(max_length=30) class Engine(model.Model): horse_power = model.Charfield(max_length=30) car = model.ForeignKey(Car) class Car_Owned(model.Model): driver = model.ForeignKey(Customer, related_name="members",on_delete=models.CASCADE) model_name = model.ForeignKey(Car, related_name="car",on_delete=models.CASCADE) engine = model.ManytoMany(Engine) -
django python google distance matrix api json question
so, I'm new to python and Django. I created a view and html page for a very basic form that uses the google distance matrix api. I'm able to display the output of the json back to my html page without any issues. the question is, how do I get the distance in miles to appear on my html page. Right now I'm just getting the raw json. but I can't seem to get just the distance in miles. Current output from the HTML page: origin ['660 Celebration Ave, Celebration, FL 34747, USA'] destination ['878 Columbus Ave, New York, NY 10023, USA'] distance in miles: [{'elements': [{'distance': {'text': '1,093 mi', 'value': 1759428}, 'duration': {'text': '16 hours 13 mins', 'value': 58364}, 'status': 'OK'}]}] ''' views.py def mapdistance_view(request): distance = {} if 'From' in request.GET: origin = request.GET['From'] destination = request.GET['To'] apikey = "mykey" url = 'https://maps.googleapis.com/maps/api/distancematrix/json?mode=driving&units=imperial&origins=' + origin + ',DC&destinations=' + destination + ',' + apikey response = requests.get(url) distance = response.json() print(url) print(distance) return render(request, 'mapdistance.html', {'distance': distance}) ''' Html page ''' {% block content %} <h2>map API</h2> <form method="GET"> {% csrf_token %} <label>Pickup Location:</label><input type="text" name="From"><br> <label>Delivery Location:</label><input type="text" name="To"><br> <button type="submit">post to google map</button> </form> {% if distance … -
django channels - delayed messaging does not work
I am trying to imitate a time consuming django response, by delaying group message in Django channels, but it does not work. The consumer is very simple: class ExportConsumer(JsonWebsocketConsumer): ... def delayed_message(self, event): print("In delayed") time.sleep(5) self.send(text_data=json.dumps({ 'message': 'delayed!' })) def immediate_message(self, event): print("In Immediate") self.send(text_data=json.dumps({ 'message': 'immediate_message!' })) and in views I just send to a group two messages - for delayed and immediate processing: class DecisionListView(PaginatedListView): ... def get(self, *args, **kwargs): async_to_sync(get_channel_layer().group_send)( '5e001793-18be-4a4b-8caf-c4a8144a11d2', { 'type': 'immediate_message', 'message': 'message' } ) async_to_sync(get_channel_layer().group_send)( '5e001793-18be-4a4b-8caf-c4a8144a11d2', { 'type': 'delayed_message', 'message': 'message' } ) return super().get(*args, **kwargs) The 'immediate message' is delivered. And I get In delayed on terminal (which means that it reaches the delayed_message but the message is never delivered (unless I comment out time.sleep. What am I doing wrong? -
Python Django Interaction between users. Asking for Directions
I am a Beginner so please be kind and forgive me for not being able to use the english language correctly. Anyway, I have a blog of posts. Every user can create posts. I want to make it so any user can send any of his/her posts to another user and get as a result a comment for that post. I do not have any code to show for this as i have not any idea how to even approach this. All i ask is some directions to any Documentation or tutorials where i can dig in and learn about this. I thank all in advance and Good Luck to Everyone. -
Django QuerySet Any
I want to get a queryset of all books that are currently in Library (the dateReturn of a currently rent is set to null). I'm new to python and i don't know how to do subqueries in django. In other words in want to filter every related object field on a condition, if only one related-object doesn't match to this condition the object must not be returned models.py class Book(models.Model): cod = models.CharField(max_length=255, unique=True) title = models.CharField(max_length=255) ..... class Rent(models.Model): dateRent = models.DateField(default=timezone.now) dateReturn = models.DateField(null=True, blank=True) book = models.ForeignKey(modelsBook.Book, on_delete=models.DO_NOTHING, related_name="rent") ..... P.S: I need this subquery for display book currently not render in a choiceField forms.py class RentForm(forms.ModelForm): __pk=None def __init__(self, *args, **kwargs): self.__pk = kwargs.pop('pk', None) super(RentForm, self).__init__(*args, **kwargs) class Meta(): model = models.Rent fields = ('book', 'student') labels = { 'book' : _('Libro'), 'student' : _('Studente'), } widgets = { 'book': queryset, ..... -
django database router not writing to database
I have configured the below database router but once I run it the output indicated success but the tables do not appear in the database. I have tried walking through the code in debug mode but cannot figure out why it won't write to my custom db router. I have changed the config so that my default db router uses the config of the new router and the default django tables are created. So this proves I can connect and write to my default and custom db router. my project structure: ├── django_app │ ├── manage.py │ ├── package.json │ ├── __pycache__ │ ├── requirements.txt │ └── zoho_integration │ ├── apps │ │ ├── __init__.py │ │ ├── __pycache__ │ │ └── quoting │ │ ├── admin.py │ │ ├── apps.py │ │ ├── forms.py │ │ ├── __init__.py │ │ ├── migrations │ │ │ ├── 0001_initial.py │ │ │ ├── __init__.py │ │ │ └── __pycache__ │ │ ├── models.py │ │ ├── __pycache__ │ │ ├── serializers.py │ │ ├── static │ │ │ └── quoting │ │ │ ├── css │ │ │ │ └── index_style.css │ │ │ └── js │ │ │ └── product_selection.js … -
adding input to form by button django
I want to add new input in page when user clicks button. I wasn't really sure how to do it. I found some tutorial on google and came up with that: forms.py class CreateChoiceForm(forms.ModelForm): class Meta: model = Question fields = ['question_text',] def __init__(self, *args, **kwargs): self.request = kwargs.pop('request') super(CreateChoiceForm, self).__init__(*args, **kwargs) choices = Choice.objects.filter( question=self.instance ) for i in range(len(choices) + 1): field_name = 'choice_%s' % (i,) self.fields[field_name] = forms.CharField(required=False) try: self.initial[field_name] = choices[i].choice except IndexError: self.initial[field_name] = "" field_name = 'choice_%s' % (i+1,) self.fields[field_name] = forms.CharField(required=False) def clean(self): choices = set() i = 0 field_name = 'choice_%s' % (i,) while self.cleaned_data.get(field_name): choice = self.cleaned_data[field_name] if choice in choices: self.add_error(field_name, 'Duplicate') else: choices.add(choice) i += 1 field_name = 'choice_%s' % (i,) self.cleaned_data['choices'] = choices def save(self): question = self.instance question.question_text = self.cleaned_data['question_text'] question.author = self.request.user question.save() question.choice_set.all().delete for choice in self.cleaned_data['choices']: Choice.objects.create(question=question, choice_text=choice) def get_choice_fields(self): for field_name in self.fields: if field_name.startswith('choice_'): yield self[field_name] The problem is that i don't know what to do from here. If i add new input in my page by simply copy the other input with js and changing id and name incrementation, only first two inputs will save and others won't. Here is the … -
Django - How to fix model with id field
I unintentionally created a model with a field "id" and did the migration. The model at first looked like this: class VsSession(models.Model): id = models.TextField(default="123"), state = models.CharField(choices=VSSESSION_CHOICES, default='dead', max_length=10) Afterwards I rename the field to vs_session: class VsSession(models.Model): vs_session = models.TextField(default="123"), state = models.CharField(choices=VSSESSION_CHOICES, default='dead', max_length=10) Now whenever I try to use the model e.g., like this: def get(self, request): try: sessionid = uuid.uuid4() new_session = VsSession(vs_session=sessionid, state="active") new_session.save() return Response({'success': 'true', 'vssession': sessionid}) except Exception as e: print(str(e)) return Response({'success': 'false'}) I get this error: VsSession() got an unexpected keyword argument 'vs_session' Can anybody please tell me what I did wrong and how to fix this. Thank you very much! -
Can I perform queries in Django where both the LHS and RHS are a function?
I'd like to perform queries in Django where both the left-hand-side and right-hand-side are a function. As simple example, something like: SELECT * FROM table WHERE LCASE(field1) = LOWER(field2) Is this possible using the QuerySet.filter(..) or Q(..) objects API? -
Add the second records into the model return ""Column 'created_at' cannot be null""
I have a problem with the following model class TagBuyer(CreatedatModelStaff): id = models.UUIDField( primary_key=True, default=DEF_UUID, editable=False) buyer = models.ForeignKey( Buyer, on_delete=models.SET(DEF_UUID), ) tag = models.OneToOneField( Tag, on_delete = models.SET(DEF_UUID), blank=True, to_field='unique_id', ) description = models.CharField( blank=True, null=True, max_length=256, help_text=_('Observatii:'), ) objects = models.Manager() # The default manager. active_objects = IsActiveManager() # Select only active records class Meta: verbose_name = _('Cumparator TAG') verbose_name_plural = _('Cumparatori TAG-uri') def __str__(self): return str(self.tag) class CreatedatModelUser(BaseCreateModel): created_by = models.ForeignKey( User, on_delete=models.SET_NULL, null=True, verbose_name=(_("Ultima modificare")), ) class Meta: abstract = True class BaseCreateModel(models.Model): """ Abstact class for common model atributes """ created_at = models.DateTimeField( verbose_name=(_("Creat la")), auto_now_add=True, ) last_change = models.DateTimeField( verbose_name=(_("Ultima modificare")), auto_now=True, ) is_active = models.BooleanField( default=True, help_text= _('Modelul de tiparire este disponibil pentru tiparire'), ) class Meta: abstract = True First insert works good from django admin and from my view. Problem popup with the second record. django admin return "Column 'created_at' cannot be null" my view actually perform an update of the first record ''' class BuyerAddTagPopupView(LoginRequiredMixin, CreateView): template_name = 'buyer/popup/buyer_add_tag.html' readonly_fields = ['buyer'] def get(self, request, slug=None): if request.user.is_authenticated: form = BuyerAddTagForm() try: buyer_obj = Buyer.active_objects.get(slug=slug) except Buyer.DoesNotExist: ## args = { 'msg': msg, 'form':form, 'page_title':self.title, 'gargs':self.gargs, } return render(request, self.template_name, … -
How to create a django model for JSONField that takes values from other fields from the same table?
I am writing a model in django which looks like this: name = models.CharField(max_length=50) address = models.CharField(max_length=100) info = JSONField() Question: For POST request, I will provide name and address as json. Now how should I store name and address in their respective fields and store json data i.e. "name:{...},address:{...}" and store it into info field? -
How to fetch date to output in a form in Django?
I have a flight model, which has a date field. I am creating an update form and, so far, it works. But, I also want it to show the already stored values. I can show every value but the date. This is my forms.py: class UpdateFlight(ModelForm): def __init__(self, *args, **kwargs): super(UpdateFlight, self).__init__(*args, **kwargs) self.fields['date'].widget = forms.DateTimeInput(attrs={'class': 'form-control', 'data-target': '#datetimepicker1'}) self.fields['flight_id'].widget = TextInput(attrs={'class': 'form-control'}) class Meta: model = Flight fields = ('date', 'flight_id', 'company', 'airport') This is my views.py: @login_required(login_url='../accounts/login/') def flight_upd(request, id): fs = Flight.objects.get(id=id) if request.method == 'POST': form = UpdateFlight(request.POST, instance=fs) if form.is_valid(): form.save() return redirect('flights') else: form = UpdateFlight(initial={'date': fs.date, 'flight_id': fs.flight_id, 'company': fs.company, 'airport': fs.airport}) return render(request, 'backend/flight_update.html', {'form': form, 'fs': fs}) And this is my html file: <div class="col-lg-3"> <label class="form-control-label" for="input-first-name">Data</label> <div class="input-group date" id="datetimepicker1"> {{form.date}} <span class="input-group-addon input-group-append"> <button class="btn btn-outline-primary" type="button" id="button-addon2"> <span class="fa fa-calendar"></span></button> </span> </div> </div> -
How to access to dictionary value via variables in another list in Django
I have this situation in my views.py d = {'05:45':3,'06:30':6 (...) } T = ['05:45','06:30' (...)] I would like to get d[T[i]] in my HTML site I tried to call this with dot, but it doesn't work. I will be thankful for help/hint. -
Invalid syntax urls.py
I'm doing a project with Django, when i start my site i see a error message that says: invalid syntax. here is the source codes: urls.py: from django.urls import path from my_app import views as post_views urlpatterns = [ path(r'^',posts_views.lista_post, name="lista") path(r'^',posts_views.post_singolo, name="singolo") #here is the error path(r'^',posts_views.contatti, name="contatti") #also here ] views.py: from django.shortcuts import render # Create your views here. def post_singolo(request): return render(request,"post_singolo.html") def lista_post(request): return render(request,"Lista_post.html") def contatti(request): return render(request,"Contatti.html") Please help me, i can't see the problem -
Populating a dropdown with a django variable after AJAX call
I have a dropdown that triggers an AJAX call when a new value is selected. The AJAX script calls my Django view, which returns a variable (a list of values). It seems to work until the step where I need to fill a second dropdown with the values from that list. I couldn't figure out how to do this. Here is my html code: <form class="wrapper" action="" method="post"> {% csrf_token %} <select name="myVal" class="toChange"> <option val="1">1</option> <option val="2">2</option> </select> <select id="dep" name="dep"> </select> <script type="text/javascript"> function dropdownChange () { var selectedValue = $(".toChange option:selected").val(); $.ajax({ url: '/myApp/templates/3/', type: 'POST', data: {'myVal': selectedValue}, success: function(result) { alert(result); } }); } $(".toChange").change(dropdownChange); </script> </form> And here is my views.py file: @csrf_exempt def MyView3(request): if request.method == 'POST' and request.is_ajax: myVariable = json.dumps(["1", "2", "3", "4", "a"]) return HttpResponse(myVariable , content_type='application/json') else: return render(request,'home3.html') When I select a new value in my dropdown, it triggers the AJAX call and the alert(result) line returns "1,2,3,4,a". So this part works, but I don't know how to populate with these values my "dep" dropdown. I've been trying to insert the following code in the script, but it didn't produce any results: var select = document.getElementById("dep"); var … -
Submit Button and Preview Button In Same View (Django)
Here's my situation. I have one view which displays a form for the user to fill out. The html contains two buttons, one for 'Submit' and one for 'Preview'. My intention is that the 'Submit' option would truly save and commit the form, whereas the 'Preview' option would launch a PDF preview of whatever data has currently been entered into the form. I am able to make each work one at a time (i.e. submit function works and preview doesn't or preview function works and submit doesn't). Also I want 'Submit' to work only if the form is valid, but preview could work even if it is not. How can I have two buttons in the same view execute different logic? Maybe I need to change one of my <button> to an <a> and launch another view? Here's my code: Views.py (not behaving the way I way would like) def PackingListView(request): if request.method == "POST": form = PackingListForm(request.POST) if form.is_valid(): request.session['data'] = form.cleaned_data #passing data to view which generates pdf form.save() return redirect('myview') else: form = PackingListForm() return render(request, 'packlist.html', {'form': form}) class myview(View): def get(self, request, *args, **kwargs): data = request.session.pop('data', {}) pdf = render_to_pdf('packlist_preview.html', data) return HttpResponse(pdf, content_type='application/pdf') …