Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
In django, admin.py file, while providing link to other page, the reverse function from django.urls module, is not working. showing models not found
enter image description here #this is my code enter image description here #this is my problem I'm facing. despite everything's ok in models.py file. -
Reverse Proxy for Django App 404 Not Found
I am following this guide to try show this url www.mycompany.com/testblog instead of www.mycompany.com:8000/testblog These are my current config files setup <VirtualHost *:80> ServerAdmin webmaster@localhost ServerName website.com ServerAlias www.website.com DocumentRoot /var/www/website.com Redirect permanent / https://website.com/ ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined </VirtualHost> ` <VirtualHost *:443> ServerAdmin webmaster@localhost ServerName website.com ServerAlias www.website.com DocumentRoot /var/www/website.com SSLEngine on SSLCertificateFile /etc/ssl/certs/website.com.cer SSLCertificateKeyFile /etc/ssl/private/website.com.key SSLCertificateChainFile /var/www/website.com/SSLCert/SSLIntermediateCertificate.cer ProxyPreserveHost On ProxyPass /testblog https://website.com:8000/testblog ProxyPassReverse /testblog https://website.com:8000/testblog </VirtualHost> However, when I run my server and try to access the URL www.mycompany.com/testblog I get a 404 Not Found error -
Download pdf file Django
views.py The download function using an API to convert a page to pdf using the URL. The pdf is saved in the project folder but i want it to be downloaded using HttpResponse and if possible not saved in the folder but a variable instance in code pdf=file.write(response.content). def downloadpdf(request, feedback_id): apiKey = '*****************' resume = Personal_Details.objects.get(feedback_id=feedback_id) response = requests.post( 'https://api.restpdf.io/v1/pdf', headers = { 'X-API-KEY' : apiKey, 'content-type': 'application/json' }, json = { "output": "data", "url": "https://github.com/chryzcode" } ) if response.status_code == 200: with open(f'{resume.resume_name}.pdf', 'wb') as file: file.write(response.content) return redirect('Resume', feedback_id=feedback_id) else: print("There was an error converting the PDF") -
Which is better Python vs PHP
As a newbie which is better for speed and back end development between PHP and Python As a newbie which is better for speed and back end development between PHP and Python -
Django-Oscar - Address Book not working on shipping-address
I'm having this problem that I mentioned in the title and I've been trying to fix it all morning, I've done some tests to find out where the error is coming from, I found out where it came from, but when I get to the file, I don't see any errors... As you can see, the user is logged in, but he cannot find an address for this user, since I have already registered one. See the code: {% extends "oscar/checkout/checkout.html" %} {% load i18n %} {% block title %} {% trans "Shipping address" %} | {{ block.super }} {% endblock %} {% block checkout_nav %} {% include 'oscar/checkout/nav.html' with step=1 %} {% endblock %} {% block checkout_title %}{% trans "Shipping address" %}{% endblock %} {% block order_contents %}{% endblock %} {% block shipping_address %} <div class="col-sm-12"> <div class="sub-header"> <h2>{% trans "Where should we ship to?" %}</h2> </div> {% if user.is_authenticated %} <p>User logged in</p> {% if addresses %} <p>Addresses: {{ addresses }}</p> <h3>{% trans "An address from your address book?" %}</h3> <div class="choose-block"> <div class="row"> {% for address in addresses %} {% block select_address_form %} <div class="col-sm-6 d-flex"> <div class="card card-body bg-light"> <address> {% block select_address_fields %} {% for … -
How to make the inventory decrease by 1 book when I borrow from the library, and increase by 1 when I return the book?
In the Book model, I made 2 methods to call them in the Borrowing field, but I haven't figured out how exactly to do it. And it is especially not clear how to connect the logic of returning the book. In the Borrowing model, there is only the actual_return_date field, when it is filled in, 1 should be added to the inventory, I think so. I tried to change the create method but it didn't work. model Book: from django.db import models class Book(models.Model): COVER_CHOICES = [("HARD", "Hard cover"), ("SOFT", "Soft cover")] title = models.CharField(max_length=255) authors = models.CharField(max_length=256) cover = models.CharField(max_length=15, choices=COVER_CHOICES) inventory = models.PositiveIntegerField() daily_fee = models.DecimalField(max_digits=7, decimal_places=2) class Meta: ordering = ["title"] def __str__(self): return ( f"'{self.title}' by {self.authors}, " f"cover: {self.cover}, " f"daily fee: {self.daily_fee}, " f"inventory: {self.inventory}" ) def reduce_inventory_book(self): self.inventory -= 1 self.save() def increase_inventory_book(self): self.inventory += 1 self.save() book/view.py from rest_framework import viewsets from book.models import Book from book.serializers import BookSerializer class BookViewSet(viewsets.ModelViewSet): queryset = Book.objects.all() serializer_class = BookSerializer book/serializers.py from rest_framework import serializers from book.models import Book class BookSerializer(serializers.ModelSerializer): class Meta: model = Book fields = ("id", "title", "authors", "cover", "inventory", "daily_fee") model Borrowing: from django.conf import settings from django.contrib.auth.models import AbstractUser from … -
Django: how to exclude certain results based on the values of other rows in the table?
I have a Django model called ProductPrice with a custom QuerySet as a manager: class ProductPriceQuerySet(models.QuerySet): def available(self, user): Group = apps.get_model("memberships", "Group") q = Q(title="Non-Member") if user.is_authenticated and user.member: q = q | Q(membership__members__user=user) return self.annotate( available=Case( When( membership_group__in=Group.objects.filter(q), then=True, ), default=False, ) ).order_by("stock", "-price") class ProductPrice(models.Model): stock = models.ForeignKey( StockManagement, on_delete=models.CASCADE, related_name="prices" ) membership_group = models.ForeignKey( "memberships.Group", null=False, blank=False, on_delete=models.PROTECT ) price = models.FloatField() objects = ProductPriceQuerySet.as_manager() This works for displaying available prices on the front end. But what I want to do is exclude the higher non-member price if the user is able to buy the item at a lower price point. What would be the best way to do this? I was thinking of another annotation like: display=Case( When( membership_group__in=Group.objects.filter(q) & ProductPrice.objects.filter( price__lt=F("price"), ), then=True, ), default=False, ) But this gives the error Cannot combine queries on two different base models. Is there an option to do this with SubQuery? Or would that be too expensive? -
Django complex filter through ManyToManyField and ForeignKey
I have a number of database tabels that are connected via manytomany and foreign key fields. from django.db import models class User(models.Model): name = models.CharField(max_length=20) class Bookings(models.Model): user = user = models.ForeignKey( User, blank=True, null=True, on_delete=models.SET_NULL) class Event(models.Model): bookings = models.ManyToManyField( Booking, related_name="event_bookings", blank=True) class ScheduleManager(models.Manager): def for_user(self, user): """ Returns a Schedule queryset for a given user object. Usage: user= User.objects.first() Schedule.objects.for_user(user) """ qs = self.get_queryset() #need to extend this to return Schedule qs return qs class Schedule(models.Model): event = models.ForeignKey( Event, on_delete=models.CASCADE ) objects = ScheduleManager() I would like to query the database to output a Schedule queryset for a given User object by calling Schedule.objects.for_user(User). I have been playing with a combination of prefetch_related and select_related to no prevail. I can get hold of the correct qs by using a bunch of chained queries and loops but its not the most elegant and I'm am hitting the db far too many times. Any help will be appreciated. -
OperationalError at /admin/store/product/
http://127.0.0.1:8000/admin/store/product/ it shows the error on that http://127.0.0.1:8000/admin/store/product/add/ links works perfect but whenever I try to add product it shows same error -
lookup was already seen with a different queryset. Django
I have a Quotes model referenced by the Comment model, which has a liked field (likes of the Comment model). I am trying to optimize the query so that there is no n+1 error, but this exception occurs. The problem is that I need to pull the user out of Comment and like, but it doesn't come out. How to do it? Table 'user' - it's ForeignKey Table 'liked' - it's ManyToManyField Views.py def get(self, request, *args, **kwargs): post = Quotes.objects.prefetch_related( Prefetch( 'quotes_comment', queryset=Comment.objects.select_related('user')) ).prefetch_related( Prefetch( 'quotes_comment', queryset=Comment.objects.select_related('liked') ) ) -
How to make filtering with SerializerMethodField()?
I'm creating table that show objects of a model and I have a SerializerMethodField that shows a value from a different table with same transaction ID. The problem is I'm using the serializers for the filtering table and chargeback is not working in there. How Can I make it filterable? Simplifying the code, a have this model: class PSerializer(serializers.ModelSerializer): ... chargeback = serializers.SerializerMethodField() def get_value(self, obj): ctransaction = CTransaction.objects.raw('SELECT * ' 'FROM ctransaction ' 'WHERE TRIM(mid)=TRIM(%s) ' 'AND TRIM(unique_id)=TRIM(%s) ' 'AND TRIM(num)=TRIM(%s) ' 'AND rc_code IN (%s, %s, %s)', [obj.mid, obj.unique_id, obj.num, '1', '1', '1']) if len(cs_transaction) > 0: return 'Yes' return 'No' -
Django Api-Key with unit test
I am trying to implement unit tests to an existing project, the existing project uses Api-Key's to access and authenticate against the Api endpoints. if I do the following via postman or command line: curl --location --request GET 'http://127.0.0.1:8000/api/user_db' \ --header 'Authorization: Api-Key REDACTED' \ --header 'Content-Type: application/json' \ --data-raw '{ "username" : "test@testing.local" }' This will call the following view function and return the user details with the corresponding oid (json response) without error. from django.shortcuts import render from rest_framework_api_key.permissions import HasAPIKey from rest_framework.permissions import IsAuthenticated from rest_framework.response import Response from rest_framework.views import APIView from user_api.classes.UserController import ( GetBusinessUser, CreateBusinessUser, UpdateBusinessUser, DeleteBusinesssUser ) from celery.utils.log import get_task_logger import environ logger = get_task_logger(__name__) env = environ.Env() class ProcessUserRequest(APIView): permission_classes = [HasAPIKey |IsAuthenticated ] def get(self, request): logger.info("Get Business User Request Received") result = GetBusinessUser(request) return Response(result["result"], content_type='application/json charset=utf-8', status=result["statuscode"] This additionally calls the following shortened function: def GetBusinessUser(request) -> Dict[str, Union[str, int]]: logger.info(f"Processing Get Username Request: {request.data}") valid_serializer = ValidateGetBusinessUserFormSerializer(data=request.data) valid_serializer.is_valid(raise_exception=True) username = valid_serializer.validated_data['username'] return BusinessUser.objects.filter(username=username).first() As I wish to make unit test cases to ensure I can validate prior to deployment, I have implemented the following in the modules tests.py file: from rest_framework.test import APITestCase, APIClient from rest_framework_api_key.models import … -
500 internal server error while accessing hx-requests in Django project
I am working on a Django project to create a dynamic form using HTMX using a YouTube video.. As I am clicking "Add" button to add a form, no form gets added.. and as I inspect the browser console, I get the following error: GET http://127.0.0.1:8000/businesscase/htmx/project-form/ 500 (Internal Server Error) lr @ htmx.org@1.8.5:1 (anonymous) @ htmx.org@1.8.5:1 i @ htmx.org@1.8.5:1 Response Status Error Code 500 from /businesscase/htmx/project-form/ St @ htmx.org@1.8.5:1 ee @ htmx.org@1.8.5:1 Q @ htmx.org@1.8.5:1 fr @ htmx.org@1.8.5:1 o.onload @ htmx.org@1.8.5:1 load (async) lr @ htmx.org@1.8.5:1 (anonymous) @ htmx.org@1.8.5:1 i @ htmx.org@1.8.5:1 I tried to search a lot in Google to get rid of this error, but unfortunately all I received was to refresh browser, clear cache etc which I did but the problem persists.. I'd really appreciate of any quick solution here.. many thanks.. -
We have created django app , I am making test script for my api but I have getting AssertionError: 401 != 201 , I am giving sample code
We have created django app , I am making test script for my api but I have getting AssertionError: 401 != 201 , I am giving sample code error :- Traceback (most recent call last): File "C:\Abhishek\Git\taskManagement\tests.py", line 108, in test_auth_user_can_create_project self.assertEqual(response.status_code, status.HTTP_201_CREATED) AssertionError: 401 != 201 views.py class Projects(APIView): authentication_classes = [authentication.TokenAuthentication] permission_classes = [permissions.IsAuthenticated] """ To create the project """ def post(self, request): request.data['created_by'] = request.user.id request.data['username'] = request.user.username serializer = ProjectSerializer(data=request.data) if not serializer.is_valid(): print(serializer.errors) return Response({ 'success': False, 'errors': serializer.errors, 'message': _("something is wrong") }) serializer.save() return Response({ 'success': True, 'Project': serializer.data, 'message': _("Project create successfully") }) tests.py def test_auth_user_can_create_project(self): client = APIClient() data = { "project_name": "Test project testscript", "project_description": "test project desc", } response = self.client.post('/api/project/', data, format='json') self.assertEqual(response.status_code, status.HTTP_201_CREATED) -
Retrieve the human readable value of a a charfield with choices via get_F00_display in Django views.py
What I want to do : Display the human readable value of a charfield with choices via get_F00_display or other in views.py and then in template. I have a Leave model for leaves management et want to display a template with all the leaves associated with the authenticated user. What I have done : Of course, I've read Django documentation (4.1) and find something interesting with get_F00_display but cannot make it works fine. model.py (simplified) class Leave(CommonFields): LEAVES_TYPES = [ ('10', _('Type 1')), ('20', _('Type 2')), ('30', _('Type 3')), ] owner = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True) type = models.CharField(max_length=3, choices=LEAVES_TYPES, null=True, default="10") def __str__(self): return self.owner.first_name + " " + self.owner.last_name + " : du " + self.begin_date.strftime("%d-%m-%Y") + " au " + self.end_date.strftime("%d-%m-%Y") views.py from django.shortcuts import render from django.utils.translation import gettext as _ from .models import Leave from django.views import generic class LeaveListView(generic.ListView): model = Leave context_object_name = 'leave_list' def get_queryset(self): return Leave.objects.filter(is_active=True).values('type', 'begin_date','end_date','range','comment','status') def get_context_data(self, **kwargs): # Call the base implementation first to get the context context = super(LeaveListView, self).get_context_data(**kwargs) # Create any data and add it to the context context['colHeaders'] = ['Type', 'From', 'To.', 'Range', 'Comment', 'Status',] return context leave_list.html {% extends "main/datatables.html" %} <!-- TABLE … -
Writable nested serializers for multiple items for same base class
I have been following the guide to write nested serializer. Previously, I had only one item in my json object which was CashCashEquivalentsRestrictedCashAndRestrictedCashEquivalents and I am able to save the data properly in the databae. I want to add NetIncomeLoss the same way but I am running into the issue below. Can someone please point me where my mistake is? I am unable to find documentation/example or an answer online TypeError: Basetable() got unexpected keyword arguments: 'NetIncomeLoss' Serializer: class PeriodSerializer(serializers.ModelSerializer): instant = serializers.CharField(required=False, max_length=255) startDate = serializers.CharField(required=False, max_length=255) endDate = serializers.CharField(required=False, max_length=255) class Meta: model = Period fields = "__all__" extra_kwargs = {'cashcashequivalentsrestrictedcashandrestrictedcashequivalents_id': { 'required': False}, 'netincomeloss_id': { 'required': False}} class CashCashEquivalentsRestrictedCashAndRestrictedCashEquivalentsSerializer(serializers.ModelSerializer): period = PeriodSerializer(many=False) class Meta: model = Cashcashequivalentsrestrictedcashandrestrictedcashequivalents fields = ['decimals', 'unitRef', 'value', 'period'] class NetIncomeLossSerializer(serializers.ModelSerializer): period = PeriodSerializer(many=False) class Meta: model = Netincomeloss fields = ['decimals', 'unitRef', 'value', 'period'] class CashFlowSerializer(serializers.ModelSerializer): CashCashEquivalentsRestrictedCashAndRestrictedCashEquivalents = CashCashEquivalentsRestrictedCashAndRestrictedCashEquivalentsSerializer( many=True) NetIncomeLoss = NetIncomeLossSerializer( many=True) class Meta: model = Basetable fields = "__all__" def create(self, validated_data): itemOneData = validated_data.pop( 'CashCashEquivalentsRestrictedCashAndRestrictedCashEquivalents') cashflow = Basetable.objects.create(**validated_data) for data in itemOneData: period_data = data.pop("period") my_long_named_obj = Cashcashequivalentsrestrictedcashandrestrictedcashequivalents.objects.create( basetable_id=cashflow, **data) period_object = Period.objects.create( cashcashequivalentsrestrictedcashandrestrictedcashequivalents_id=my_long_named_obj, **period_data ) itemTwoData = validated_data.pop( 'NetIncomeLoss') cashflow = Basetable.objects.create(**validated_data) for data in itemTwoData: period_data … -
Set same color as prev row if data matches otherwise different color when rows are dynamically created
I need to set same color as previous row if data matches otherwise use a different color when rows . The code works if the rows, cells and text within cells are hardcoded as here https://codereview.stackexchange.com/questions/121593/set-same-color-as-prev-row-if-data-matches-otherwise-different-color but produces alternating colouring when the rows, cells and text are dynamically generated. $(document).ready(function () { var c = 0; $("#tblExport tbody tr").each(function () { var $item = $("td:first", this); var $prev = $(this).prev().find('td:first'); if ($prev.length && $prev.text().trim() != $item.text().trim()) { c = 1 - c; } $(this).addClass(['zebra-even', 'zebra-odd'][c]); }); }); #tblExport>tbody { font: normal medium/1.4 sans-serif; } #tblExport { border-collapse: collapse; width: 100%; } #tblExport th,td { padding: 0.25rem; text-align: left; border: 1px solid #ccc; } #tblExport th { background: #bfbfbf; } <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> {% for product in products %} <tr> <td>{{product.name}}</td> <td>{{product.price}}</td> </tr> -
Django Forms - Declarative Fields Meta class is not iterable
Why django throws me an error TypeError at /primary argument of type DeclarativeFieldsMetaclass is not iterable. I'm trying to work with django-forms for the first time, after i added this into my forms.py file, it keeps showing me the error message saying: TypeError at /primary argument of type 'DeclarativeFieldsMetaclass' is not iterable, how can i solve this problem? Forms.py from django import forms from .models import Primary, PrimaryAlbum, Secondary, SecondaryAlbum from jsignature.forms import JSignatureField from jsignature.widgets import JSignatureWidget class PrimaryForms(forms.Form): signature_of_student = JSignatureField( widget=JSignatureWidget( jsignature_attrs={'color':'#e0b642', 'height':'200px'} ) ) class Meta: model = Primary fields = ['admission_number', 'profile_picture', 'first_name', 'last_name', 'gender', 'address_of_student', 'class_Of_student', 'signature_of_student'] Views.py from .forms import PrimaryForms class CreatePrimaryStudent(LoginRequiredMixin, CreateView): model = Primary fields = PrimaryForms template_name = 'create_primary_student_information.html' success_url = reverse_lazy('Home') def get_form(self, form_class=None): form = super().get_form(form_class) form.fields['year_of_graduation'].queryset = PrimaryAlbum.objects.filter(user=self.request.user) return form def form_valid(self, form): form.instance.user = self.request.user return super(CreatePrimaryStudent, self).form_valid(form) -
I need to insert data in table SQLite Django
I am new to Django. I think it's really easy one for Django expert, so I wish I could get help from you. I have two tables in SQLite DB-namely Process and ScrapedData. While migrating models I have several error so I just create these two tables manually by Navicat. Following shows models. class Process(models.Model): PLATFORM=( ('Instagram','Instagram'), ('Facebook','Facebook'), ('LinkedIn','LinkedIn'), ('TikTok','TikTok'), ('Youtube','Youtube'), ('Twitter','Twitter') ) hashtag=models.CharField(max_length=300) platform=models.CharField(choices=PLATFORM,max_length=9) date=models.DateField(auto_now_add=True) class ScrapedData(models.Model): homepage=models.CharField(max_length=500) email=models.CharField(max_length=100) process_id=models.ForeignKey( Process, on_delete=models.CASCADE, verbose_name="the related Process") Then I tried to insert data into these two tables then I got following error. File "C:\Users\Administrator\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql, params) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Administrator\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\db\backends\sqlite3\base.py", line 423, in execute return Database.Cursor.execute(self, query, params) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ sqlite3.OperationalError: table info_scrapeddata has no column named process_id_id The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\Administrator\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) ^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Administrator\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Administrator\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\contrib\auth\decorators.py", line 21, in _wrapped_view return view_func(request, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "E:\task\scrapping\scraping for google api\College-ERP\info\views.py", line 116, in attendance_search ScrapedData.objects.create(homepage=url.strip(),email=email, process_id=new_process) File "C:\Users\Administrator\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\db\models\manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Administrator\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\db\models\query.py", line 453, in create obj.save(force_insert=True, using=self.db) File … -
Celery basic scheduling with apply_async is extremely slow
Scheduling tasks from Django endpoints are very slow. .delay / .apply_async of any (even dummy) task takes about 150-200ms which is terrible. Redis is up and running in docker, task is being scheduled to worker without any retries, but it takes ~200 ms just to deliver task to queue. Maybe i am missing some configuration options? My setup: Python 3.10 Django 4 Celery 5.2.7 Eager execution is disabled, celery configs are pretty much default. Attached is a profiler output where simple task eats twice a time of a heavy DB-load operations (see marked (!)): Line # Hits Time Per Hit % Time Line Contents ============================================================== 339 @profile 340 def handle_single_transition( 341 self, 342 *, 343 cr: CR, 344 user: User, 345 taxonomy_data: dict, 346 cr_metadata: dict, 347 attachments: list[InMemoryUploadedFile] = None, 348 ) -> CR: 350 1 0.0 0.0 0.0 target_state_id = cr_metadata.get("target_state_id") 351 1 0.0 0.0 0.0 action_id = cr_metadata.get("action_id") 352 354 1 0.0 0.0 0.0 if target_state_id is None or (cr.state_id == target_state_id): 355 return cr 356 357 1 28.0 28.0 6.1 transition = cr.workflow.get_transition( 358 1 0.0 0.0 0.0 target_state_id=target_state_id, 359 1 0.0 0.0 0.0 action_id=action_id, 360 ) 361 363 1 0.1 0.1 0.0 if taxonomy_data and … -
CORS Issues with Nginx as Reverse Proxy for Django
I am running Nginx as my webserver to server the static frontend files and as a reverse proxy for my Django Server. The Problem is that i am having CORS Issues, when doing request from the frontend. My Design-Plan was to use the Apex Domain example.com for the frontend and all API Calls go to api.example.com. I already did a tone of research and tried to catch OPTIONS request etc. but i still have CORS Errors. Also Django has the django-cors package installed and Axios is using .withDefaultCredentials = true. My current nginx config looks like this: server { listen 80; listen [::]:80; server_name $DOMAIN_HOSTNAME; root /var/www/example.com/dist; location /media { alias /var/www/example.com/media/; } location / { try_files $uri $uri/ /index.html =404; } } upstream djangoserver { server django:8000; } server { listen 80; listen [::]:80; server_name $API_DOMAIN_HOSTNAME; location / { proxy_pass http://djangoserver; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_set_header 'Access-Control-Allow-Origin' $http_origin; proxy_set_header 'Access-Control-Allow-Credentials' 'true'; proxy_redirect off; add_header 'Access-Control-Allow-Origin' 'https://example.com'; add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, OPTIONS'; add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type'; add_header 'Access-Control-Allow-Credentials' 'true'; if ($request_method = 'OPTIONS') { add_header 'Access-Control-Allow-Origin' 'https://example.com'; add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, OPTIONS'; add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type'; add_header 'Access-Control-Allow-Credentials' 'true'; return 204; } } } Also so … -
Server refusing to run in Pycharm giving the following error: OSError: [WinError 127] The specified procedure could not be found
OSError: [WinError 127] The specified procedure could not be found The app was working fine until after I pip installed django-sms. I have since uninstalled django-sms but still getting the same error. Contro panel output -
Django Request input from User
I'm having a Django stack process issue and am wondering if there's a way to request user input. To start with, the user is loading Sample data (Oxygen, CHL, Nutrients, etc.) which typically comes from an excel file. The user clicks on a button indicating what type of sample is being loaded on the webpage and gets a dialog to choose the file to load. The webpage passes the file to python via VueJS/Django where python passes the file down to the appropriate parser to read that specific sample type. The file is processed and sample data is written to a database. Issues (I.E sample ID is outside an expected range of IDs because it was keyed in wrong when the sample was taken) get passed back to the webpage as well as written to the database to tell the user when something happened: (E.g "No Bottle exists for sample with ID 495619, expected range is 495169 - 495176" or "356 is an unreasonable salinity, check data for sample 495169"). Maybe there's fifty samples without bottle IDs because the required bottle file wasn't loaded before the sample data. Generally you have one big 10L bottle with water in it, the … -
How to migrate from StaticBlock to StructBlock?
I have to change an already existing StaticBlock to a StructBlock: class SomeBlock(blocks.StaticBlock): pass class Meta: ... to: class SomeBlock(blocks.StructBlock): ... class Meta: ... However if the wagtail page has already SomeBlock configured in it, I receive the error: NoneType is not iterable Since I don't have anything inside the StaticBlock. I need to write a custom data migration for this. Based on Schema Operations listed, I couldn't find a way to change the actual block type. How do I approach this? -
Using for loop to Html Form in Django Template
I am facing problems handling forms in Django template for loop. <form method="post" id="infoloop{{forloop.counter}}"> {% csrf_token %} <div class="form-group"> <button type="submit" name="infobutton" class="btn btn-warning float-right {% if subs%} {% else %}disabled{% endif %}">update</button> </div> </form> I want to create this form my all employees, but seems doesn't work. Only first loop can create form tag so i can't update second employee info's. Can anyone help me?