Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django NoReverseMatch When Using URL Argument With CreateView / ModelForm
The problem: /signup/1/ throws a NoReverseMatch despite matching the pattern exactly. Specific error: NoReverseMatch at /signup/1/ Reverse for 'signup' with no arguments not found. 1 pattern(s) tried: ['signup/(?P<event>[0-9]+)/$'] config/url.py: from users.views import SignupCreateView urlpatterns = [ ... path("signup/<int:event>/", view=SignupCreateView.as_view(), name="signup"), ... ] users/view.py class SignupCreateView(LoginRequiredMixin, CreateView): form_class = SignupCreateForm template_name = 'users/user_signup_form.pug' users/form.py class SignupCreateForm(ModelForm): class Meta: model = Signup fields = [ <field list> ] I note that if I simply remove the URL argument from the path() definition and call /signup/ the form loads fine. My ultimate intent is to pass this argument down into the form via overriding get_form_kwargs, but of course I haven't added that yet. I've searched fruitlessly for any documentation that might explain this behavior for two hours now. I can't believe this incredibly simple example is giving me so much trouble. Any suggestions are greatly appreciated. -
Django: Autosave different default dates for different occurrences of the same form?
Building a Django app where for each day of the week, weight and calorie data needs to be inputted and saved to the respective date. I currently have it designed so that the template renders Mon, Tues, Wed, etc. with a form for each day connected to the same mode via a modelform. My problem is that with auto_now, auto_now_add and default=today.date() the date is fixed. I.e - if Monday is the 1st of the month, I'd like it so that when a user inputs his Tuesday weight and calories, it autosaves to the 2nd of the month. Here is my code: Template: <form method='POST'> {% csrf_token %} {{ mainform.as_p }} <input type="submit" value="save" /> </form> Tuesday <form method='POST'> {% csrf_token %} {{ mainform.as_p }} <input type="submit" value="save" /> Form: class Meta: model = Daily_Inputs fields = [ "Daily_Weight", "Daily_Cals", "Daily_Date", ] View: initinputz = Initial_Inputs.objects.filter(user=request.user) mainform = Daily_Inputs_Form() if request.method == 'POST': mainform = Daily_Inputs_Form(request.POST) if mainform.is_valid(): maininstance = mainform.save(commit=False) maininstance.user = request.user maininstance.save() context = { 'initz': initinputz, 'mainform': mainform, } return render(request, "pages/home.html", context) Model: Daily_Weight = models.DecimalField(max_digits=4, decimal_places=2, verbose_name=None, null=True) Daily_Cals = models.IntegerField(verbose_name=None, null=True) Daily_Date = models.DateField(default=date.today()) user = models.ForeignKey(User,on_delete=models.CASCADE,default=None, null=True) Thank you in advance for … -
Which is better choice Cloud Storage or Compute Instances for using Django Static File [closed]
That's My Question. Which is Better Theoretically and Which is Better with DJango. -
How to access Django local server data with React-native?
I build a Django API using django rest framework. And a want to access the json response data of the api in my react-native app. But a get an error (Network request failed) DJANGO RESPONSE REACT-NATIVE ERROR Network request failed node_modules/whatwg-fetch/dist/fetch.umd.js:505:17 in setTimeout$argument_0 node_modules/react-native/Libraries/Core/Timers/JSTimers.js:135:14 in _callTimer node_modules/react-native/Libraries/Core/Timers/JSTimers.js:387:16 in callTimers node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:425:19 in __callFunction node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:112:6 in __guard$argument_0 node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:373:10 in __guard node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:111:4 in callFunctionReturnFlushedQueue [native code]:null in callFunctionReturnFlushedQueue -
Django is not adding class Question with forms
I have created an app called /f/ask/ and on that page, I am adding class Question in the form, but I don't know why it's not adding that class to my database. Here are my files. ask.html <!DOCTYPE html> {% load static %} <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="{% static 'f/ask/ask.css' %}"> <title>BareTalk</title> </head> <body> <div id="wrapper"> <form method="post"> {% csrf_token %} {{ form }} <!-- TODO: input submit Reg() function javascript --> <input name="final" id="final" type="submit" value="Ask"> </form> </div> </body> <script src="{% static 'f/ask/ask.js' %}"></script> </html> views.py from django.views.generic.edit import CreateView from django.shortcuts import render from .forms import QuestionForm from .models import * def QuestionView(request): ''' List of Questions ''' questions = Question.objects.all() return render(request, 'f/index.html', {'question_list': questions}) def QuestionCurrent(request, pk): ''' Current Question ''' question = Question.objects.get(id=pk) return render(request, 'f/current.html', {'question': question}) def ask(request): form = QuestionForm() if request.method == 'POST': form = QuestionForm(request.POST) if form.is_valid(): form.save(commit=False) content = {'form': form} return render(request, 'f/ask.html', content) urls.py from django.urls import path, register_converter from . import views, converter register_converter(converter.HexConverter, 'hex') urlpatterns = [ path('', views.QuestionView, 'f'), path('ask/', views.ask, name='ask'), path('<hex:pk>/', views.QuestionCurrent, name='question_current'), ] forms.py from django.forms import ModelForm from .models import * class QuestionForm(ModelForm): … -
Is there a python based alternative/replacement for Javascript?
I don't think there is a client-side script/language based on python. I know python and suppose I don't want to learn javascript, is there something that I can use? For instance, I use Jinja syntax in HTML pages in Flask. It can perform things on the browser side, but it's not a replacement for Javascript. So, if there's something I'm not aware of, please let me know. Thanks in advance. -
How to edit query vaules before sending to template in django
course_obj = Courses.objects.all() .. logic .. logic return render(request,'dummy.html',{'course_obj':dummy1}) I want to encrypt the id coming from above queryset and pass to template with other values as it is so that in template, i can get it by loop like {% for c_obj in course_obj %} c_obj.id [ should populate encrypted id value and not as 1 or 2 or 3] c_obj.name [ should be same as in database] {% end for %} Any help is highly appreciated. -
How to get related Product in Django?
I have product by category in my Django application, I am getting products in particular category, and when i am going to product single view page, then i want product related to single product category, I want related products there, which is available in above single product view page. Here is my models.py file for subcategory and product class Product(models.Model): name=models.CharField(max_length=225) slug=models.SlugField(max_length=225, unique=True) subcategory=models.ForeignKey('SubCategory', related_name='prosubcat', on_delete=models.CASCADE, blank=True, null=True) brand=models.ForeignKey('Brand', related_name='product_brand', on_delete=models.CASCADE, blank=True, null=True) supplement= models.ForeignKey('Supplement', related_name='product_supplement', on_delete=models.CASCADE, blank=True, null=True) totalprice=models.IntegerField() price = models.IntegerField() created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.name class SubCategory(models.Model): subcat_name=models.CharField(max_length=225) subcat_slug=models.SlugField(max_length=225, unique=True) category = models.ForeignKey('Category', related_name='subcategoryies', on_delete=models.CASCADE, blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True) update_at = models.DateTimeField(auto_now=True) def __str__(self): return self.subcat_name here is my views.py file...for display single product view def productview(request, slug): category = Category.objects.all() subcategories = SubCategory.objects.all() product = Product.objects.select_related('subcategory').get(slug=slug) #test=product.subcategory_id.all() related = Product.objects.select_related('subcategory')[0:6] template_name='mainpage/product-view.html' context={'product':product,'related':related, 'category':category, 'subcategories':subcategories} return render(request, template_name, context) I am getting products from all subcategory product using related, and i want to filter from product here is my product-view.html file... {% for relatedpro in related %} <div class="col-xl-2 col-md-4 col-sm-6"> <div class="product-box"> <div class="img-wrapper"> <div class="front"> <a href="/product/{{relatedpro.slug}}" class="bg-size blur-up lazyloaded"><img src="{{relatedpro.first_image.image.url}}" class="img-fluid blur-up lazyload bg-img" alt="" style="display: none;"></a> </div> … -
Django how to make select form
I want to make select phone service agency when user sign up. but my select form doesn't appear in the html. is there any way to make select form? models.py class User(AbstractUser): ... phone_service_provider = models.CharField( max_length=11, choices=AGENCY_CHOICES, blank=False ) ... forms.py: class SignUpGeneralForm(forms.Form): ... address_postcode_general = forms.CharField( widget=forms.TextInput( attrs={ "id": "postcode", "placeholder": "우편번호", "class": "appearance-none bg-transparent border-none w-full text-gray-700 mr-3 py-1 px-2 leading-tight focus:outline-none", "style": "width:100%; height:100%;", "readonly": "true", } ) ) phone_service_provider = forms.ChoiceField( widget=forms.Select(choices=AGENCY_CHOICES) ) phone_number = forms.CharField( widget=forms.TextInput( attrs={ "placeholder": "핸드폰 번호", "class": "appearance-none bg-transparent border-none w-full text-gray-700 mr-3 py-1 px-2 leading-tight focus:outline-none", "style": "width:100%; height:100%;", } ) ) ... -
Django REST API. How serialized ArrayField with user ids, and retrieve as JSON object of User model?
I have ArrayField in model Company models.py class Company(models.Model): members = ArrayField(models.IntegerField(blank=True), blank=True) ... serializers.py class CompanySerializer(serializers.ModelSerializer): class Meta: model = Company fields = ('name', 'description', 'date_created', 'user', 'status', 'theme', 'members') ... It return this JSON { "name": "Jeep", "description": "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.", "date_created": "2020-07-20T21:27:28.586149Z", "user": 2, "status": 2, "theme": 3, "members": [ 1, 2, 3 ] } ... where field members contains user ids from User model. I want change this ids to User data objects by him id ... "members": [ {"id" : 1, ...}, {"id" : 2, ...}, {"id" : 3, ...}, ] ... -
Field 'id' expected a number but got '<user-slug-string>'
right now I am working on a blog application which is made without using django admin site and I have added blog post feature to that.I have used two foreign keys to a single User model which is customized with Custom User Model. Now, the problem is that I can not assign two slugs in a url in a row.I have attached code of views and urls for better understanding. I had tried to delete all migrations and re migrate all the stuff, but it didn't worked for me.Is there any solution for this problem. Here is my code, views.py from django.shortcuts import render,redirect from .models import languages,BlogData from django.conf import settings from login.models import BaseUserManager,AbstractUser,User from login.views import register_user from django.shortcuts import get_object_or_404 from django.utils.text import slugify # Create your views here. def index(request): blogs = BlogData.objects.order_by('-publish_date') return render(request,"index.html",{'languages':languages, 'blogs':blogs}) def login(request): return render(request,"login.html") def about(request,user_slug): return render(request,"about.html") def sample(request): return render(request, "sample.html") def register(request): return render(request,"register.html") """-------------The main function below from which I am getting error---------""" def blog_details(request,user_slug,blog_slug): blog = get_object_or_404(BlogData,user_slug = user_slug,blog_slug = blog_slug) return render(request,"sample.html",{'blog':blog}) def post(request): return render(request,"contact.html") def submit_post(request): if request.method == 'POST': blg_tt = request.POST['blog_title'] blg_stt = request.POST['blog_subtitle'] blg_cnt = request.POST['blog_content'] blg_img = … -
Django is not saving data to database
I am trying to create an event blog for my django app. But the data is not being saved to the database. I have checked tons of solutions to similar questions on stack overflow but none of those solved my problem. Please have a look at my codes. Heres my models.py from django.db import models from django.db.models.signals import pre_save, post_delete from django.utils.text import slugify from django.conf import settings from django.dispatch import receiver def upload_location(instance, filename, **kwargs): file_path = "event/{author_id}/{title}-{filename}".format( author_id=str(instance.author.id), title=str(instance.title), filename=filename ) return file_path class EventPost(models.Model): CATEGORY_CHOICE = [ ("COMP/IT", "Computer"), ("EXTC/ETRX", "Electrical"), ("MECH/AUTO", "Mechanical"), ("ALL", "All"), ("NON-TECH", "Non-Technical"), ] title = models.CharField(max_length=50, null=False, blank=False) body = models.TextField(max_length=5000, null=False, blank=False) image = models.ImageField(upload_to=upload_location, default="default.png") category = models.CharField(max_length=10, choices=CATEGORY_CHOICE, default="All") event_date = models.DateField(null=False, blank=False, verbose_name="event date") reg_to = models.DateField( null=False, blank=False, verbose_name="registration to") fee = models.PositiveIntegerField(default=0) reg_link = models.URLField(null=False, blank=False) date_published = models.DateTimeField(auto_now_add=True, verbose_name="date published") date_updated = models.DateTimeField(auto_now=True, verbose_name="date updated") author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) slug = models.SlugField(blank=True, unique=True) def __str__(self): return self.title @receiver(post_delete, sender=EventPost) def submission_delete(sender, instance, **kwargs): instance.image.delete(False) def pre_save_event_post_receiver(sender, instance, *args, **kwargs): if not instance.slug: instance.slug = slugify(instance.author.username + "-" + instance.title) pre_save.connect(pre_save_event_post_receiver, sender=EventPost) Here's my forms.py from django import forms from event.models import EventPost class CreateEventPostForm(forms.ModelForm): class … -
Django loop model field for bootstrap collapse
Can you help with better way to process many similar bootstrap collapse for page ? I have 12 similar collapse, where collapse title it is a verbose name of model field, and collapse text it is a model field value. How can i make loop for this model and substitute name and value from model field instead creat 12 similar block of code ? <div class="col-md-12 col-lg-10 mx-auto mb-3"> <div class="accordion md-accordion" id="accordionEx" role="tablist" aria-multiselectable="true"> <div class="card border-top border-bottom-0 border-left border-right border-light"> <div class="card-header border-bottom border-light" role="tab" id="heading" style="background-color:#DDDFDF;"> <a data-toggle="collapse" data-parent="#accordionEx" href="#collapse" aria-expanded="true" aria-controls="collapse"> <h5 class="black-text font-weight-normal mb-0"> Title of collapse where i want get verbose_name of model </h5> </a> </div> <div id="collapse" class="collapse" role="tabpanel" aria-labelledby="heading" data-parent="#accordionEx"> <div class="card-body"> Some text where i want get value of model field </div> </div> </div> </div> </div> -
When i tried to install django through the pycharm terminal, it says that the name of my file is "unexpected at this time." How may i fix this please
When i had tried to install Django by entering some code into the terminal, it said that the name of my file was unexpected at this time. I'm not sure what that means at all and it would be very appreciated if someone could help me. -
associate product variation and attributes on django
I am trying to designing a database schema for e-commerce product(especially clothing line). I am struggling to understand attributes and variants relationship. Here is how I have designed class Product(models.Model): product_type = models.ForeignKey( ProductType, related_name="products", on_delete=models.CASCADE ) name = models.CharField(max_length=128) slug = models.SlugField() description = models.TextField(blank=True) class Attribute(models.Model): name = models.CharField(max_length=30, unique=True) slug = models.SlugField(max_length=250, unique=True) class Meta: verbose_name = "Attribute" verbose_name_plural = "Attributes" def __str__(self): return self.name class ProductAttribute(models.Model): product = models.ForeignKey(Product, related_name="productattribute", null=True, on_delete=models.CASCADE) attribute = models.ForeignKey(Attribute, null=True, on_delete=models.CASCADE) class ProductAttributeValue(models.Model): product_attribute = models.ForeignKey(ProductAttribute, null=True, on_delete=models.CASCADE) name = models.CharField(max_length=250) value = models.CharField(max_length=100, blank=True, default="") slug = models.SlugField(max_length=255) class ProductVariant(models.Model): sku = models.CharField(max_length=255, unique=True) name = models.CharField(max_length=255, blank=True) price = models.DecimalField(default=0, decimal_places=2, max_digits=6) product = models.ForeignKey( Product, related_name="variants", on_delete=models.CASCADE ) images = models.ManyToManyField("ProductImage", through="VariantImage") class ProductVariantValue(models.Model): variant = models.ForeignKey(ProductVariant, on_delete=models.CASCADE) value = models.ForeignKey(ProductAttribute, on_delete=models.CASCADE) stock = models.PositiveIntegerField(default=0) price = models.DecimalField(default=0, decimal_places=2, max_digits=6) Based on various attributes, a product can have multiple variants. For example, a t-shirt with color white with L size is one variant and a t-shirt with same color with XL size is another variant. Here color, size are attributes. There can be many attributes so I have created a table for them but I am struggling … -
Cannot get all fields in admin?
I am new on django and creating project to rate movies this is my models.py and programs donot show "stars" in the admin from django.db import models from django.contrib.auth.models import User from django.core.validators import MaxValueValidator, MinValueValidator # Create your models here. class Movie(models.Model): title = models.CharField(max_length=32) description = models.TextField(max_length=360) class Rating(models.Model): movie = models.ForeignKey(Movie, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) stars = models.IntegerField(validators=[MinValueValidator(1), MaxValueValidator(5)]), class Meta: unique_together = (('user','movie'),) index_together = (('user','movie',),) -
Margin changes in every page in HTML Django Template
I have created a django template from the following code: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> * { box-sizing: border-box; } .grid-container { width: 21cm; display: flex; flex-direction: column; justify-content: space-between; } .page { width: 21cm; height: 29.7cm; padding-top: 1.5362cm; padding-bottom: 1.5362cm; padding-left: 0.5122cm; padding-right: 0.5122cm; } .grid-row { display: flex; } .grid-col { margin-left: 0.0854cm; margin-right: 0.0854cm; width: 9.9024cm; height: 3.7552cm; display: flex; align-items: center; justify-content: center; background-color: #eee; } img { max-width: 100%; height: auto; } </style> </head> <body> <div class="grid-container"> {% for page in imglist %} <div class="page"> {% for row in page %} <div class="grid-row"> <div class="grid-col"> <span style="text-align: center"> Yantraksh Logistics Pvt Ltd <img src="data:image/png;base64,{{ row.image }}" alt="" srcset=""> <br> {{ row.label }} <br> {% if row.lname %} {{ row.lname }} {% else %} _____ {% endif %} </span> </div> <div class="grid-col"> <span style="text-align: center"> Yantraksh Logistics Pvt Ltd <img src="data:image/png;base64,{{ row.image }}" alt="" srcset=""> <br> {{ row.label }}<br> {% if row.lname %} {{ row.lname }} {% else %} _____ {% endif %} </span> </div> </div> {% endfor %} </div> {% endfor %} </div> </body> </html> Th first page is rendered correctly but as soon as the pages … -
Virtual Environment is not being created in my User Account
I recently created a new user on my family Laptop, so that I can have a seperate place for my django project. I was trying to create a virtual environment, with the code : C:\Users\Me\Desktop>python.exe -m venv themanor it is not being created. But when I try the same code in the original Family User Account in my Windows, then it is being properly executed and I can see a new venv called 'themanor'. I tried changing my user from Standard to Administrator, but it didn't help. Please help, what settings do I need to change?. -
Python save data in different way
IN my code i have a variable where i am getting the count like 4,6,8.what i actually want is i want is : This is when count = 6 New A New B New C If count is 4 then : New A New B and so on for multiple count i want to save value in this order how can i mange this can anyone please help me related this . because i want data in this way to save . -
create and update method of django dsl drf Document Serializers
I am using django elastic search dsl-drf in my web application. I tried to serialized data and show them in my API successfully. But When it came to creating and updating instances, I found create and update method of DocumentSerializers code empty. should it be implemented by myself for every document? Is there any options like django rest framework modelSerializers to have default create and update logic? -
Getting error with html to pdf converter(pdfkit) in local windows 10 machine
"cmd=['Xvfb', '-help']\nOSError=[WinError 2] The system cannot find the file specified\nProgram install error! " I'm getting this error while converting from HTML to pdf in windows10 I have installed wkhtmltopdf0.9.9 in my windows10 configured the wkhtmltopdf path in my project and also in environment variable. -
Serving React and Django with SSL and a domain
Currently, I'm deploying a react app and using django as the backend API on an ubuntu nginx server. The react app is already online have a SSL certificate, but the backend API does not. By default, browsers can't show a http content on a https connection. Do I need to get another SSL certificate afor the backend API? Or is there another way to do it? Thanks Found this link, but wasn't able to post a comment because my reputation is not enough. And I don't really understand. Can anyone help me? How to deploy react and django in aws with a ssl and a domain -
Django - Appending dictionary values return empty dictionary
I have a list of words, called lyrics_sorted, that looks like this: lyrics_sorted = ['word1', 'word2', 'word3', ] Now I want to make a dictionary with this as one of the keys, and another key the normalized form of the word. So first I declare the key values, like this: word_original = lyrics_sorted word_normalized = [] And then the dictionary: grammar_dict = {'word_original': word_original, 'word_normalized': word_normalized} And now for every word in word_original (or lyrics_sorted), I want to add the normalized form, so I do as follows: for word in lyrics_sorted: w = morph.parse(word)[0] word_normalized.append(w.normal_form) context['grammar_dict'] = list(zip(grammar_dict['word_original'], grammar_dict['word_normalized'],)) return context But I get just an empty dictionary. I can't figure out what I'm doing wrong; when I test it in the shell it works. -
Test with Django and Celery
I want to write unit tests for the below django views and am facing some errors. I don't know much about Celery task and how to unit test a Celery task. Can someone help me? How can I test file upload and celery task in this case? Here is the views.py class HomeView(TemplateView): template_name = "pages/home.html" form_class = EmptyForm def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) return context def post(self, request, *args, **kwargs): if "file_url" in request.POST: # start a worker task for processing file located at file_url res = start_watching.apply_async( (request.POST["file_url"],), time_limit=60 * 20, soft_time_limit=60 * 15 ) return JsonResponse({"task_id": res.id}) def post(self, request, *args, **kwargs): if "task_id" in request.POST: task_identifier = request.POST["task_id"] async_res = start_watching.AsyncResult(task_identifier) # save Score if the results are ready if async_res.ready(): # construct JSON we log on the console val_score = float(async_res.get("score")["score"]) # get the user post_user = request.user # set user object # make a new model instance score = Score.objects.create( user=post_user if post_user.is_authenticated else None, task_id=task_identifier, emotion_score=val_score, ) score.save() return JsonResponse({"ready": True, **async_res.get()}) return JsonResponse({"ready": False}) Here is the model class Score(models.Model): user = models.ForeignKey( User, on_delete=models.PROTECT, help_text="User who posted the video being scored.", null=True, ) task_id = models.CharField( max_length=200, null=True, blank=True, help_text=("Link … -
Python API with Django
I'm writing an API for a Django application that gets inventory from another website. The code was working at first but recently I get the error "NoneType object is not Subscriptable". I'm new to this but I understand why NoneType is not Subscriptable. I just can't figure out how to resolve it in my code. headers = { 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3)' ' AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.47 Safari/537.36'} login_url = 'http://www.website.com/login/validate_login' inventory_url = 'http://www.website.com:1002/orders/t_lookup' t_search_url = 'http://www.website.com:1002/orders/do_t_lookup?update=t_list' t_fitment_url = 'http://www.website.com:1002/fit/update_fit' login_params = { "commit": "Login", "login[account]": os.getenv("tsearch_number"), "login[password]": os.getenv("tsearch_number"), "login[sales]": "1400" } t_search_params = { "authenticity_token": None, "commit": "Find", "search_options[exact]": 1, "search_options[max]": 300, "search_options[scol]": 1, "search_options[show_cost]": {0: 0, 1: 1}, "search_options[show_retail]": 0, "search_options[size]": None, "search_options[zero]": 0, "utf8": True } cookie_dir = "extras/" cookie_file = cookie_dir + "session.cookie" logged_in = False session = requests.Session() session.headers = headers if os.path.exists(cookie_file): print("Found existing cookies. Loading into session.") with open(cookie_file, "rb") as f: cookies = requests.utils.cookiejar_from_dict(pickle.load(f)) session.cookies.update(cookies) logged_in = True if not os.path.exists(cookie_dir): print("Extras folder not found. Creating.") os.mkdir(cookie_dir) if not logged_in: print("Not signed into website. Signing in.") session.post(login_url, data=login_params, headers=headers) with open(cookie_file, "wb") as f: pickle.dump(session.cookies.get_dict(), f) s = session.get(inventory_url) b = bs4(s.text, "html5lib") auth = b.find(attrs={"name": "authenticity_token"})["Value"] …