Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
What should be written to the Superfeedr callback file, in Django, Python?
I have a backend project developed in Django and I need to create an url endpoint in my urlpatterns variable, to receive push notifications from Superfeedr. How should I do it? -
How do I update my inventory Database in django?
I am creating a web application that will serve as a grocery store. The way I set it up is so the customer can come onto the website, click on the items that they would like to purchase, and then click a submit button to purchase those items. The problem I am running into is having a views.py function to take the information of which products were selected and subtracting 1 from the quantity of the database. """models.py""" class Post(models.Model): title = models.CharField(max_length=100) Price = models.DecimalField(max_digits=4, decimal_places=2,default=1) Sale = models.DecimalField(max_digits=4, decimal_places=2,default=1) quantity = models.IntegerField(default=1) author = models.ForeignKey(User, on_delete=models.CASCADE) category = TreeForeignKey('Category',null=True,blank=True, on_delete=models.CASCADE) def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail', kwargs={'pk': self.pk}) views.py class PostListView(ListView): model = Post template_name = 'blog/home.html' # <app>/<model>_<viewtype>.html context_object_name = 'posts' def inventory(request): request.POST.getlist('products') for x in range (len('products')): a = Post.objects.get('products[x]') count = a.quantity() count -=1 a.quantity = count a.save() return HttpResponseRedirect("{% url 'profile'%}") urls.py path('user/<str:username>', UserPostListView.as_view(), name='user-posts'), path('inventory', views.inventory, name='inventory'), home.html {% extends "blog/base.html" %} {% block content %} {% for post in posts %} {% if post.quantity > 0 %} <input type="checkbox" name="products" id="product_{{ post.id }}" value="{{ post.id }}"> <article class="media content-section"> <div class="media-body"> <div class="article-metadata"> <a class="mr-2" href="{% url 'user-posts' post.author.username … -
Displaying data from 2 tables and ordering them
I have got 2 tables with the same fields: class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) class Post2(models.Model): title = models.CharField(max_length=100) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) I am displaying them on the same page: def home(request): context = { 'posts': Post.objects.all(), 'post2': Post2.objects.all() } return render(request, 'home.html', context) I use that in the html: {% for post in posts %} <p>{{ post.title }}</p> {% endfor %} {% for post in post2 %} <p>{{ post2.title }}</p> {% endfor %} What I am trying to do is display them all based on the date posted. Currently its doing so, but the tables are not mixed. First are displayed the posts from table Post ordered by date, and then there are displayed posts from table Post2 based on date. Is there a way to order by date, but taking to consideration both tables, so the posts from both tables would be mixed and displaying in order by date? -
An email subscription form with Django and Mailchimp doesn't work after deployment (DigitalOcean)
I've built a simple email subscription form with Django and Mailchimp. It works perfectly fine locally, however, after deploying it to DigitalOcean it doesn't seem to work. I thought it might be related to the database, but I did migrate on the server and haven't received any errors (using Ubuntu 20.04 on the server). Hope someone has a clue and could assist me with this issue. Here is the form: https://www.winoutt.io views.py from django.contrib import messages from django.http import HttpResponseRedirect # from django.conf import settings from .models import Signup from decouple import config import json import requests # MAILCHIMP_API_KEY = settings.MAILCHIMP_API_KEY # MAILCHIMP_DATA_CENTER = settings.MAILCHIMP_DATA_CENTER # MAILCHIMP_EMAIL_LIST_ID = settings.MAILCHIMP_EMAIL_LIST_ID MAILCHIMP_API_KEY = config("MAILCHIMP_API_KEY") MAILCHIMP_DATA_CENTER = config("MAILCHIMP_DATA_CENTER") MAILCHIMP_EMAIL_LIST_ID = config("MAILCHIMP_EMAIL_LIST_ID") api_url = f"https://{MAILCHIMP_DATA_CENTER}.api.mailchimp.com/3.0" members_endpoint = f"{api_url}/lists/{MAILCHIMP_EMAIL_LIST_ID}/members" def subscribe_email(email): data = {"email_address": email, "status": "subscribed"} req = requests.post( members_endpoint, auth=("", MAILCHIMP_API_KEY), data=json.dumps(data) ) return req.status_code, req.json() def newsletter_email_list(request): if request.method == "POST": email = request.POST.get("email", None) email_query = Signup.objects.filter(email=email) if email: if email_query.exists(): messages.info(request, "You are already on the waitlist.") else: try: subscribe_email(email) subscribed = Signup.objects.create(email=email) subscribed.save() messages.success( request, "Thank you! We're putting you on the waitlist. Bear with us.", ) except: messages.warning(request, "Something went wrong. Please try again.") return HttpResponseRedirect(request.META.get("HTTP_REFERER")) else: messages.warning(request, … -
Custom Django Login
I'm struggling to pass through/access the password that should be passed through from the form I have created. Can someone tell me where I am going wrong? I need a custom login page since I want to alter the way the username is inputted. I've changed my username authentication just for the time being to try and get this standard version correct before I change my username verification back. html Login template I want the password input to be visible to the user Views.py The prints return 'None' on the console urls.py Can anyone spot where I am going wrong or advise if this is a terrible way to create a custom login page on Django -
Django orm help pleasee
class Test(models.model): date = models.DateTimeField(auto_now=False, auto_now_add=True) date_two = models.DateTimeField(auto_now=True) Test.objects.flter(date != date_two ) ---> ???? -
I keep getting an "Invalid Format" error when creating Python Models with timestamps
Hey guys I'm creating a basic app and it was running fine until I created a new table with my Models.py file that had a timestamp. My NewPost model already had the Timestamp and that was working fine. However, when I run migrate (makemigrations runs OK) I'm now getting a weird error in the console that the format is not correct and I'm unable to start my app. I delete the timestamp fields, and I'm still getting the error! Can someone help me figure out what to do? Below is the error and my Models.py code. If you need any more code let me know. Thanks! Models.py: from django.contrib.auth.models import AbstractUser from django.contrib.postgres.fields import ArrayField from django.db import models from datetime import datetime class User(AbstractUser): userRanking = models.IntegerField(default=0) class NewPost(models.Model): username = models.CharField(max_length=64) body = models.CharField(max_length=64) category = models.CharField(max_length=64, default="movies") title = models.CharField(max_length=64, default="Hi", null="True") rating = models.IntegerField(default=0) timestamp = models.DateTimeField(auto_now_add=True, null=True) class Vote(models.Model): postID = models.IntegerField(default=0) userID = models.IntegerField(default=0) upVotes = models.IntegerField(default=0) downVotes = models.IntegerField(default=0) class Reply(models.Model): postID = models.IntegerField(default=0) username = models.CharField(max_length=64) body = models.CharField(max_length=64, default="") rating = models.IntegerField(default=0) timestamp = models.DateTimeField(auto_now_add=True, null=True) Error Message in Console: C:\school\project4>python manage.py migrate network Operations to perform: Apply all migrations: network … -
How to make a ModelForm with many to many relationship in Django?
I'm making a form that needs to send multiple "estados", and I need it to be able to send one or even 5 items at once. I have 3 tables connected by "estados" with an intermediary "flora2estado" table: models.py: class Listaflor(models.Model): especie_id = models.AutoField(primary_key=True) estados = models.ManyToManyField(Estados, through='Flora2Estado') class Flora2Estado(models.Model): estado = models.ForeignKey(Estados, models.DO_NOTHING, primary_key=True) especie = models.ForeignKey('Listaflor', models.DO_NOTHING) Class Estados(models.Model): estado_id = models.AutoField(primary_key=True) estado_nome = models.CharField(max_length=100, blank=True, null=True) views.py def CreateFlo(request): form = FloForm() if request.method == 'POST': form = Flo(request.POST) if form.is_valid(): Listaflor = form.save(commit=False) Listaflor.aprovado_id = 2 Listaflor.save() context = {'form': form} return render(request,'accounts/flora_form.html', context) forms.py: class FloForm(forms.ModelForm): class Meta: model = Listaflor fields = ['Especie','familia','estados' ] exclude = ["aprovado"] -
Can't find a github package inside docker container
I've been trying to install a github repository inside a docker container through a requirements.txt file. Running "docker-compose build --no-cache" I can see it being installed, but when I get inside the container itself, I try a "pip freeze" and all the other packages explicited inside requirements.txt are there, except the one from github. Here is my requirements: psycopg2-binary>=2.8,<2.9 Pillow>=7 django-rosetta gunicorn pytest pytest-django pytest-bdd pytest-xdist djangorestframework -e git://github.com/tb-brics/dorothy-data-reader.git#egg=xrayreader and my dockerfile (not complete here but I guess this is enough for understanding the problem): #Setting working environment WORKDIR /service #Here is where we will mount the volume containing all the x-ray images RUN mkdir /imagesrep RUN chown -R www-data:www-data /imagesrep #Installing dependencies COPY requirements.txt ./ RUN pip install --upgrade pip RUN pip install --no-cache-dir -r requirements.txt #Copying necessary files for production execution. COPY django ./ #Creating folder to contain static files. RUN mkdir -p /var/www/dorothy/static RUN chown -R www-data:www-data /var/www/dorothy/static #Creating folder for dorothy logs RUN mkdir -p /var/log/dorothy RUN chown -R www-data:www-data /var/log/dorothy Really need this asap, accepting any suggestion, thanks. -
How i can update email in a stripe customer object?
i didn't able to update the email of o customer with stripe API. This is the way what i have do, but in dashboard, the new email of customer not updated. stripe.Customer.modify(customer.id, metadata={'email': newEmail}) what i have to do? thanks for your time. -
Emulating JS environment in Django
I am developing a Django webapp and I need to enable users to submit JavaScript programs as solutions to certain puzzles. Those programs need to be ran by my server against a number of inputs, and their output need to match the expected one (stored in a json file or db record), or ran through a verification function that can give a parametrized score to the program provided by the user. This is pretty different than anything I've ever done. I'd like to be pointed to the right direction. What's the best way to execute JS code in a sandbox inside of python? Is there any way to preferably accomplish this inside of django? Any libraries worth checking out? -
using MySql with Django
I am trying to connect MySql to the Django project on Windows 10, and I am getting this error when using this command : pip install mysqlclient even though I installed visual studio tools and c++, the error : ERROR: Command errored out with exit status 1: command: 'c:\users\tech one\appdata\local\programs\python\python39\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\Users\Tech One\AppData\Local\Temp\pip-install-7i9pm26h\mysqlclient\setup.py'"'"'; file='"'"'C:\Users\Tech One\AppData\Local\Temp\pip-install-7i9pm26h\mysqlclient\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(file);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, file, '"'"'exec'"'"'))' install --record 'C:\Users\Tech One\AppData\Local\Temp\pip-record-sgylccv3\install-record.txt' --single-version-externally-managed --compile --install-headers 'c:\users\tech one\appdata\local\programs\python\python39\Include\mysqlclient' cwd: C:\Users\Tech One\AppData\Local\Temp\pip-install-7i9pm26h\mysqlclient Complete output (23 lines): running install running build running build_py creating build creating build\lib.win-amd64-3.9 creating build\lib.win-amd64-3.9\MySQLdb copying MySQLdb_init_.py -> build\lib.win-amd64-3.9\MySQLdb copying MySQLdb_exceptions.py -> build\lib.win-amd64-3.9\MySQLdb copying MySQLdb\connections.py -> build\lib.win-amd64-3.9\MySQLdb copying MySQLdb\converters.py -> build\lib.win-amd64-3.9\MySQLdb copying MySQLdb\cursors.py -> build\lib.win-amd64-3.9\MySQLdb copying MySQLdb\release.py -> build\lib.win-amd64-3.9\MySQLdb copying MySQLdb\times.py -> build\lib.win-amd64-3.9\MySQLdb creating build\lib.win-amd64-3.9\MySQLdb\constants copying MySQLdb\constants_init_.py -> build\lib.win-amd64-3.9\MySQLdb\constants copying MySQLdb\constants\CLIENT.py -> build\lib.win-amd64-3.9\MySQLdb\constants copying MySQLdb\constants\CR.py -> build\lib.win-amd64-3.9\MySQLdb\constants copying MySQLdb\constants\ER.py -> build\lib.win-amd64-3.9\MySQLdb\constants copying MySQLdb\constants\FIELD_TYPE.py -> build\lib.win-amd64-3.9\MySQLdb\constants copying MySQLdb\constants\FLAG.py -> build\lib.win-amd64-3.9\MySQLdb\constants running build_ext building 'MySQLdb._mysql' extension error: Microsoft Visual C++ 14.0 is required. Get it with "Build Tools for Visual Studio": https://visualstudio.microsoft.com/downloads/ ---------------------------------------- ERROR: Command errored out with exit status 1: 'c:\users\tech one\appdata\local\programs\python\python39\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\Users\Tech One\AppData\Local\Temp\pip-install-enter code here7i9pm26h\mysqlclient\setup.py'"'"'; file='"'"'C:\Users\Tech One\AppData\Local\Temp\pip-install-7i9pm26h\mysqlclient\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(file);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, file, '"'"'exec'"'"'))' … -
Semantic UI accordion with a modal inside shows when visible
I am using Semantic UI accordion to show different tables. The problem is that I have a modal on each table's row to show the deatils of that row. Everything works fine when click on the row (the modal pops up). But when I click the dropdown to show the rows the modals are shown too. I see that $('.ui.accordion').accordion() adds transition and visible classes to all his childs. So, I don't know if there is a way in Javascript to remove/modify classes AFTER .accordion() ends. I mean AFTER because the changes should be triggered after .accordion() and not asynchronous. Any help? Regards This is my code: <div class="ui accordion"> {% for status in status_list %} <div class="title"> <i class="dropdown icon"></i> <h3>{{status.grouper}}s</h3> </div> <div class="content"> <table class="ui olive selectable table transition hidden tablesorter" id="{{status.grouper}}"> <thead> <tr> <th>Name <i class="sort icon"></i></th> <th>Industry <i class="sort icon"></th> <th>Country <i class="sort icon"></th> ..... </tr> </thead> <tbody> {% for account in status.list %} <tr> {% comment %} TODO: Agregar link para modal de edit {% endcomment %} <td class="modal-button" data-account="{{account.slug}}" data-tooltip="Click for details" data-position="top left" data-inverted=""><a href="#">{{account.name}}</a></td> <td>{{ account.industry}}</td> <td><i class="{{account.country|lower}} flag"></i>{{ account.country}}</td> .... </tr> {% include 'accounts/modals.html' %} {% endfor %} </tbody> </table> </div> … -
how to retrieve first instance of saved value as string
what I am looking is retrieve the saved value from models as string, I tried this way class ExternalKeys(models.Model): public = models.CharField(max_length=80, blank=True, null=True) secret = models.CharField(max_length=80, blank=True, null=True) webhook_secret = models.CharField(max_length=80, blank=True, null=True) and call it in views as this stripe.api_key = ExternalKeys.objects.first().public but this is not working, but if I do this way it prints the correct value to template def get_public_key(request): public = ExternalKeys.objects.first().public return render(request, 'templat.html', {'public': public}) so how I can get this value as sting in views -
Django Unix Socket not connecting to Cloud SQL
Hey so I'm trying to connect my Django server properly to Cloud SQL but no luck. After double checking the Environment Variables, I tried reading the logs and I see issues like: connections on Unix domain socket "/cloudsql/project_name:us-central1:db_instance_name/.s.PGSQL.5432"? Connect exception: could not connect to server: No such file or directory Here are my production settings currently connecting to the Cloud SQL instance. DB_NAME = os.environ.get("DB_NAME") DB_USER_NM = os.environ.get("DB_USER_NM") DB_USER_PW = os.environ.get("DB_USER_PW") INSTANCE_CONNECTION_NAME = os.environ.get('INSTANCE_CONNECTION_NAME') DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': DB_NAME, 'USER': DB_USER_NM, "PASSWORD": DB_USER_PW, "HOST": f'/cloudsql/{INSTANCE_CONNECTION_NAME}', } } I feel like its a settings issue in GCP and nothing to do with coding. Please help me out! Thanks -
Django DetailView getting access to users in M2M field to restrict access?
I am currently working with a DetailView, returning a JsonResponse of some business details. I am using the test_func and UserPassesTestMixin to make sure that only users who have is_admin=True are getting access to these admin only views. Now in my BusinessDetail model, I have a field called owner which is a M2M field linked to users who are owners of the business. I also need to restrict views of course to make sure that self.request.user is in the BusinessDetail model's owner field. I have tried a few things including this... class BusinessDetailView(LoginRequiredMixin, UserPassesTestMixin, DetailView): model = BusinessDetail def test_func(self): return self.request.user.is_admin def get_object(self, queryset=None): business = get_object_or_404(BusinessDetail, pk=self.kwargs.get('pk')) serialized_obj = serializers.serialize('json', [business]) return serialized_obj def get(self, request, *args, **kwargs): try: business = self.get_object() logger.debug(business obj: {business}') if self.request.user not in business.owner.all(): logger.debug('Error: Access not granted.') return JsonResponse({'Error': 'Access restricted.'}) return JsonResponse(json.loads(business), status=200, safe=False) except Exception as e: logger.error(f'Error getting business detail with error: {e}') return JsonResponse({'Error': 'DB error, return to previous page'}, status=500) My logger is looking like... ==> /var/log/app/logger/debug.log <== DEBUG 2020-12-08 21:35:19,935 /app_site/business_admin/views.py get 379 Business obj: [{"model": "authentication.business_detail", "pk": 3, "fields": {"name": "test name", "phone_no": "(111)-111-1111", "street": "111 5th st, "city": "Fort Lauderdale", "state": "Florida", "zip": … -
Should backend variables be updated to match frontend changes?
A project I am working on involves categorising data into four separate categories. These categories are pivotal to the project logic and appear everywhere in the code. The project is pretty much finished. Yesterday, the client asked us to rename the categories. This is a very simple change to appear in the frontend, only a few lines of code. However, the old names are used in many variable names spread throughout the backend, and it would take quite a while to comb through the code and update all variable names and comments. Is it better to keep the old variable names and save time and keep things consistent for existing developers, or spend the time changing the variable names and ensure the frontend and backend are consistent and make things clearer for future development? -
How to provide Django error codes that are not hardcoded
I'm currently implementing some System Checks of my own, and noticed that Django recommends using hardcoded error identifiers, like so: Error( 'an error', hint='A hint.', obj=checked_object, id='myapp.E001', ) I thought that maybe this is merely serving tutorial purposes, but turns out that's actually how they do it. From the same code above, I noticed that they use a prefix scheme for identifying the type of message that is being created (e.g. E for Error, W for Warning, C for Critical, etc). But I don't understand the numbering system. You just enter any three digit number and that's it? What happens if there's a collision? Has anyone come across a better paradigm to manage the error codes? -
Django tenant Access another tenant data from public
Need to pass tenant specific user data to template. I've done following things. class ClientDetailView(DetailView): model = Client template_name = 'customer/detail.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) with schema_context(self.object.schema_name): context['users'] = User.objects.all() return context django-tenants schema context decorator is like below class schema_context(ContextDecorator): def __init__(self, *args, **kwargs): self.schema_name = args[0] super().__init__() def __enter__(self): self.connection = connections[get_tenant_database_alias()] self.previous_tenant = connection.tenant self.connection.set_schema(self.schema_name) def __exit__(self, *exc): if self.previous_tenant is None: self.connection.set_schema_to_public() else: self.connection.set_tenant(self.previous_tenant) On exit it just reset schema and also reset my user data of previous tenant. Is there anyway to get required tenant data? -
Django - Class Table Inheritance with model forms
I am very confused about how will I achieve my goal of doing this in Django, I am a beginner. It is quite simple, all I want is to create a form from models, and eventually use it to get the data back from it via POST when the user submits it. The user should be able to select the category first. e.g He goes over to Electronics -> PC and eventually should be able to select any of the last subcategory like Deskstop or Laptop and it's form should then be generated for the user to fill. Confusing part for me is that I am using Class Table Inheritence here and I am new to Django so it is getting hard for me to do this simply. Now to sum it up, anyone's help is greatly appreciated if he can tell how it's done with Models Form. I will add many more categories with their subcategories so no cheating, Models Form should be dynamic else it will get really tedious writing each ModelForm for every category and subcategory I will create Optional is if you can also help with the POST request after the form is finally submitted considering … -
django restful api with nested objects in url
I am try to expose an endpoint which looks like /v1/organizaions/org1/members so that I would be able to post to it and create a new member. The member model has org_id field but I can't figure out how to hook up the ModelViewSet to populate the new member object's org_id with the id corresponding to org1. Looking for some example code. -
Apache permissions overriding Django function for authorization check
I built an app where users can upload their files and only the user who uploaded the file can view it. This was working while I was developing the application but now after I hosted in on a VPS with Apache, it doesn't work. I gave permissions to www-data to create and read files and folders inside of /file which is a folder where I save all of the files. A folder inside of file is created for each user when he uploads his first file and the name of that folder is the username of the user i.e. if TestUser uploads his first file, then a folder will be created at /file/TestUser. I wrote a function that checks if the URL which the user opens, has /file in it. If it does, it check if it has the user's username and then opens the file. I have no clue why is this not working now, and anyone can open any file. def auth_file_check(request): url = request.build_absolute_uri() if not '//' in url: url = 'http://' + url o = urlparse(url) user = o.path.split("/") if str(request.user) == user[2].split("_", 1)[1] or request.user.is_superuser: # Change link to path where files will be stored … -
display category and sub category in django
I am Working on the Web Application and it needs to show the categories and sub catgories to the side bar. Here is the screenshot of the database.please take a look and hep enter image description here def home(request): return render(request,"myApp/index.html") def info(request): ac = REFERENCE_DATA_LOOKUP.objects.all() L_C_U = L_C_S = L_W_U = L_W_S =L_S_U= L_P_S= L_N_I= L_C_O=0 for row in Kpi_Data.objects.all(): if (row.kpi_Group == 'LOGIN_STATS' and row.kpi_subgroup== 'CONSUMER_PORTAL' and row.kpi_key == 'CP_USER'): L_C_U = row.kpi_value if (int(row.kpi_delta_ind) >= 0): L_C_U_A = 0 elif (int(row.kpi_delta_ind) < 0): L_C_U_A = -1 elif (row.kpi_Group == 'LOGIN_STATS' and row.kpi_subgroup== 'CONSUMER_PORTAL' and row.kpi_key == 'CP_SCRNS'): L_C_S = row.kpi_value if (int(row.kpi_delta_ind) >= 0): L_C_U_S = 0 or 1 elif (int(row.kpi_delta_ind) < 0): L_C_U_S = -1 elif (row.kpi_Group == 'LOGIN_STATS' and row.kpi_subgroup== 'WORKER_PORTAL' and row.kpi_key == 'WP_USER'): L_W_U = row.kpi_value if (int(row.kpi_delta_ind) >= 0): L_W_U_A = 0 elif (int(row.kpi_delta_ind) < 0): L_W_U_A = -1 elif (row.kpi_Group == 'LOGIN_STATS' and row.kpi_subgroup== 'WORKER_PORTAL' and row.kpi_key == 'WP_SCRNS'): L_W_S = row.kpi_value if (int(row.kpi_delta_ind) >= 0): L_W_U_S = 0 elif (int(row.kpi_delta_ind) < 0): L_W_U_S = -1 elif (row.kpi_Group == 'APP_STATS' and row.kpi_subgroup== 'CONSUMER_PORTAL' and row.kpi_key == 'CP_SUB'): L_S_U = row.kpi_value if (int(row.kpi_delta_ind) >= 0): L_C_P_S = 0 elif (int(row.kpi_delta_ind) < 0): … -
Djagno Rest Framework, updating multiple objects in one
I am trying to update using PATCH to my Django backend. This is the request I am sending: [ { "pk":78, "weekday":1, "from_hour":"21:00", "to_hour":"12:00:00", "closed":false, "lunch":true, "lunch_start":null, "lunch_end":null, "lunch2":false, "lunch_start2":null, "lunch_end2":null, "appointment_interval":15, "num_appointments_interval":4, "office":79 }, { "pk":79, "weekday":2, "from_hour":"09:00:00", "to_hour":"12:00:00", "closed":false, "lunch":true, "lunch_start":null, "lunch_end":null, "lunch2":false, "lunch_start2":null, "lunch_end2":null, "appointment_interval":15, "num_appointments_interval":4, "office":79 }, { "pk":80, "weekday":3, "from_hour":"09:00:00", "to_hour":"12:00:00", "closed":false, "lunch":true, "lunch_start":null, "lunch_end":null, "lunch2":false, "lunch_start2":null, "lunch_end2":null, "appointment_interval":15, "num_appointments_interval":4, "office":79 }, { "pk":81, "weekday":4, "from_hour":"09:00:00", "to_hour":"12:00:00", "closed":false, "lunch":false, "lunch_start":"14:59:50", "lunch_end":"14:59:51", "lunch2":false, "lunch_start2":null, "lunch_end2":null, "appointment_interval":15, "num_appointments_interval":4, "office":79 }, ] I send this to a custom view where I am trying to serialize and update the data. @api_view(['PATCH']) @parser_classes((JSONParser,)) def updateOfficeHours(request): office_id = request.data[0]['office'] qs = OfficeHour.objects.filter(office__pk=office_id) office_hours = OfficeHoursSerializer(qs, data=request.data, many=True, partial=True) if not office_hours.is_valid(): print(":(") return Response(status=status.HTTP_500_INTERNAL_SERVER_ERROR) else: office_hours.save() return Response(status=status.HTTP_200_OK) I only end up getting this error: AttributeError: 'QuerySet' object has no attribute 'pk' It seems like this error comes up when you are looking for one object, but I have many=True. What am I doing wrong? -
Can't submit a csrf token using javascript in Django
I'm using the following code to submit a csrf token purely in js since I want to cache the pages with the form. axios.defaults.xsrfHeaderName = 'X-CSRFTOKEN' axios.defaults.xsrfCookieName = 'csrftoken' axios.defaults.withCredentials = true This works locally (localhost, 127.0.0.1) without a problem. This is to get rid of the 403 errors that happen when I login into the app and try to submit a form that no longer has a csrf token embedded in the dom. The issue is I can't get this run in our development environment. The development environment uses CloudFront but i don't think that's an issue. Here is my dev config for Wagtail + Django: #Important for CloudFront USE_X_FORWARDED_HOST = True # Security Headers SECURE_HSTS_SECONDS = 63072000 SECURE_HSTS_PRELOAD = True SECURE_HSTS_INCLUDE_SUBDOMAINS = False CSRF_COOKIE_SECURE = True SESSION_COOKIE_SECURE = True UPGRADE_INSECURE_REQUESTS = True SECURE_BROWSER_XSS_FILTER = True SECURE_CONTENT_TYPE_NOSNIFF = True PREPEND_WWW = False All my API views have csrf_exempt on them, but i still need the token when i try to submit after a login. My middleware is: MIDDLEWARE = [ "django.contrib.sessions.middleware.SessionMiddleware", "django.middleware.locale.LocaleMiddleware", "app.site_translation.middleware.TranslationMiddleware", "django.middleware.common.CommonMiddleware", "django.contrib.auth.middleware.AuthenticationMiddleware", "django.contrib.messages.middleware.MessageMiddleware", "django.middleware.clickjacking.XFrameOptionsMiddleware", "django.middleware.security.SecurityMiddleware", "django.middleware.csrf.CsrfViewMiddleware", "app.base.middleware.AdditionalSecurityHeadersMiddleware", "app.base.middleware.CookieMiddleware", "app.base.middleware.DomainRedirectMiddleware", "app.base.middleware.CustomRedirectMiddleware", "app.base.middleware.LegacyURLsMiddleware", "debug_toolbar.middleware.DebugToolbarMiddleware", ] I don't know what is going on I keep getting CSRF Failed: CSRF …