Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to identify and authenticate the right "user" when we use Django (Existing proj) for authentication and FastAPI (new feature) for API's?
Hello guys I have an existing Django project which has certain features and also has user data. For certain features, users use the API served through Django, but since there is a need for new feature which needs to be implemented through FastAPI, I need to have the same users authenticate or to be recognized by FastAPI (as this is the same user in Django) to save an action corresponding to user in the db. How to achieve that? How do I store the user data, like user_id and username for each user safely? How to properly design the database table? Please do let me know, how to start. Thank you. -
No module named 'ecommerce.store' in django
I run command python3 manage.py runserver It throws an error showing that no module named ecommerce.store but it is. This is my ecommerce.store.views file from ecommerce.store.models import Product from django.shortcuts import render from .models import * def store(request): products = Product.objects.all() context = {'products':products} return render(request, 'store/store.html', context) def cart(request): context = {} return render(request, 'store/cart.html', context) def checkout(request): context = {} return render(request, 'store/checkout.html', context) This is my ecommerce.store.admin file from django.contrib import admin from .models import * admin.site.register(Customer) admin.site.register(Product) admin.site.register(Order) admin.site.register(OrderItem) admin.site.register(ShippingAddress) This is my ecommerce.store.models file from django.db import models from django.contrib.auth.models import User from django.db.models.fields.related import ForeignKey class Customer(models.Model) : user = models.OneToOneField(User, on_delete=models.CASCADE, null=True, blank=True) name = models.CharField(max_length=200, null=True) email = models.CharField(max_length=200, null=True) def __str__(self) : return self.name class Product(models.Model) : name = models.CharField(max_length=200, null=True) price = models.FloatField() digital = models.BooleanField(default=False, null=True, blank=True) def __str__(self) : return self.name class Order(models.Model) : customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, blank=True, null=True) date_ordered = models.DateTimeField(auto_now_add=True) complete = models.BooleanField(default=False, null=True, blank=True) transaction_id = models.CharField(max_length=200, null=True) def __str__(self) : return str(self.id) class OrderItem(models.Model) : product = models.ForeignKey(Product, on_delete=models.SET_NULL, blank=True, null=True) order = models.ForeignKey(Order, on_delete=models.SET_NULL, blank=True, null=True) quantity = models.IntegerField(default=0, blank=True, null=True) date_added = models.DateTimeField(auto_now_add=True) class ShippingAddress(models.Model) : customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, blank=True, … -
Creating multiple test databases in Django TestCases
I wanted to create multiple test databases, so I could check if my synchronizing script is working properly. I have added them to Django settings like this: DATABASES = { "default": { "ENGINE": env.str("DB_ENGINE"), "NAME": env.str("name[1]"), "USER": env.str("DB_USER"), "PASSWORD": env.str("DB_PASSWORD"), "HOST": env.str("DB_HOST"), "PORT": env.str("DB_PORT"), "TEST": { "NAME": 'name[1]', } }, "name[2]": { "ENGINE": env.str("DB_ENGINE"), "NAME": "[name1]", "USER": env.str("DB_USER"), "PASSWORD": env.str("DB_PASSWORD"), "HOST": env.str("DB_HOST"), "PORT": env.str("DB_PORT"), "TEST": { "NAME": "name[2]", } }, "name[3]": { "ENGINE": env.str("DB_ENGINE"), "NAME": "name[3]", "USER": env.str("DB_USER"), "PASSWORD": env.str("DB_PASSWORD"), "HOST": env.str("DB_HOST"), "PORT": env.str("DB_PORT"), "TEST": { "NAME": "name[3]", } }, } This is how my test for sake of testing looks like: class SyncTestCase(TestCase): def setUp(self) -> None: self.client = Client() def test_func_tester_client(self): bitbucket_db_setup.main() response = self.client.get("/v1/devices/?name=a", SERVER_PORT=8000) print(response.content) self.assertEqual(200, 200) But when I run it, it only creates DB for 'default' alias: Creating test database for alias 'default'... *DB_SMTH are imported names from environment and name[x] are just names -
unable to use db.sqlite3 db when I am pushing it to Heroku server
what I am doing...! I have made a django project and I am trying to to host the website on heroku what is not a problem. the website is being deployed successfully when I push it to Heroku using heroku CLI . while I am trying to run the website on localhost it's working fine - I am able to upload data on sqlite3 db, I found that UI is appearing properly. my problem I am getting following error when I login as admin Environment: Request Method: POST Request URL: https://obscure-lake-92881.herokuapp.com/admin/login/?next=/admin/ Django Version: 3.2.5 Python Version: 3.9.6 Installed Applications: ['blogs.apps.BlogsConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'hello'] Installed Middleware: ('whitenoise.middleware.WhiteNoiseMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware') Traceback (most recent call last): File "/app/.heroku/python/lib/python3.9/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) The above exception (relation "auth_user" does not exist LINE 1: ...user"."is_active", "auth_user"."date_joined" FROM "auth_user... ^ ) was the direct cause of the following exception: File "/app/.heroku/python/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/app/.heroku/python/lib/python3.9/site-packages/django/views/decorators/cache.py", line 44, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "/app/.heroku/python/lib/python3.9/site-packages/django/contrib/admin/sites.py", line 414, in login return LoginView.as_view(**defaults)(request) File "/app/.heroku/python/lib/python3.9/site-packages/django/views/generic/base.py", line 70, in view … -
How CSRF token works in Django and how to use it in Postman
I am a newbie in Django, I understand that Django has inbuild csrf middleware for protection. Could someone explain how including {% csrf_token %} in the template generates the csrf token behind scenes. I would also like to test my APIs from Postman, but I would need to pass the csrf token also in the request, any suggestions on how to generate the csrf token so that I can use in my API testing? Any help is much appreciated. -
how to assigned user preferred size with it item id in django
I want to fetch user selected size with the quantity and product but I don't understand how to do that any how idea to achieve that i try to look documentation but didn't find one any idea how to do that right now I am only able to fetch its item id and quantity any idea how to assign size with is id using dictionary to achieve that my views.py for add to cart class Product_detail(View): def get(self, request, item_id,): item = Item.objects.filter(id=item_id) category_list = Categories.objects.all() items = Item.objects.all() print(item) return render (request, 'product_detail.html',{"items" : item, 'category_list': category_list, 'item': items }) def post(self, request, item_id): item = request.POST.get('item') size = request.POST.get('size') cart = request.session.get('cart') if cart: quantity = cart.get(item) if quantity: cart[item] = quantity+1 else: cart[item] = 1 else: cart = {} cart[item] = 1 request.session['cart'] = cart print(request.session['cart']) return redirect('products:detail', item_id=item_id) my html code for that <form method="POST" action="#{{ item.id }}"> {% csrf_token %} <input type="text" hidden value="{{item.id}}" name="item"> <label class="size" for="size">Size:</label> <p class="input"><input type="radio" name="size" value="S"> <span>S</span> <input type="radio" name="size" value="M"> <span>M</span> <input type="radio" name="size" value="L"> <span>L</span> <input type="radio" name="size" value="XL"> <span>XL</span> <input type="radio" name="size" value="2XL"> <span>2XL</span></p> <button type="submit" class="cart btn btn-outline-primary">Add to cart</button> </form> any suggestion will … -
How to remove the name "Queryset" from queryset data that has been retrieved in Django Database?
we all know that if we need to retrieve data from the database the data will back as a queryset but the question is How can I retrieve the data from database which is the name of it is queryset but remove that name from it. maybe I can't be clarified enough in explanation so you can look at the next example to understand what I mean: AnyObjects.objects.all().values() this line will back the data like so: <QuerySet [{'key': 'value'}] now you can see the first name that is on the left side of retrieving data which is: "QuerySet" so, I need to remove that name to make the data as follows: [{'key': 'value'}] if you wonder about why so, the abbreviation of answer is I want to use Dataframe by pandas so, to put the data in Dataframe method I should use that layout. any help please!! -
applying filter to other pages
i've got sort on main page of shop, it works , but in other pages it doesn't works. How could i apply this sort to other pages? at the url address it updates but no result, it just shows items in default order.i tried to find any answer but couldn't view class Shop(ListView): template_name = 'essense/shop.html' context_object_name = 'items' paginate_by = 9 allow_empty = True model = Item def get_context_data(self, *, object_list=None, **kwargs): context = super().get_context_data(**kwargs) categories = Category.objects.all() collections = Collection.objects.all() brands = Brand.objects.all() context['brands'] = brands context['categories'] = categories context['collections'] = collections return context def get_ordering(self): return self.request.GET.get('orderby', ) class ShopCategory(Shop, ListView): def get_queryset(self): return Item.objects.filter(category__slug=self.kwargs['slug']) def get_ordering(self): return self.request.GET.get('orderby', ) template <div class="product-sorting d-flex"> <p>Sort by:</p> <form name="selectForm" action="{{request.get_full_path}}" method="get"> <label for="orderby"></label> <select name="orderby" id="orderby" onchange="selectForm.submit();"> <option value="">default</option> <option value="price">price: $ - $$</option> <option value="-price">price: $$ - $</option> </select> <input type="submit" class="d-none" value="submit"> </form> </div> urls urlpatterns = [ path('shop/', Shop.as_view(), name='shop'), path('shop/subcategory/<slug:slug>', ShopBySubCategory.as_view(), name='shop_subcategory'), path('shop/category/<slug:slug>/', ShopCategory.as_view(), name='shop_category'), path('shop/on-sale', ItemsOnSale.as_view(), name='on_sale'), path('shop/brand/<slug:slug>', ShopByBrand.as_view(), name='shop_brand'), path('shop/<slug:slug>/', ItemDetail.as_view(), name='single_product') ] -
Why can I access Django Development Server from localhost (vscode)?
Okay so I've just started to learn Django and I've been using vscode to SSH connect to my remote development machine and I save my changes on the remote machine. But when I run the development server, I access it on my localhost network, not from the remote IP. How is this possible given I ran the command manage.py runserver 9000 from the remote machine? Is this something to do with VSCode? Cheers -
Django charfield choices compatibility
I've a model which has field choices. In the saving case i wanna make sure that value is in that choices list. class Foo(models.Model): GENDER_CHOICES = ( ('M', 'Male'),('F', 'Female'), ) gender = models.CharField(max_length=1, choices=GENDER_CHOICES) But when i try to save with value out of choices , it saves that value. foo = Foo(gender = "A") foo.save() Yes i can control it in code like if value in genderlist: but in my project that will take so time to add this control in every usage of choices saves. Is there any chance to control it in MODEL ( overriding save method or some option for field or etc ) ? -
Django how to test whether password validators are being used
My Django settings file contains the following 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', }, ] I am using django allauth and django restauth to set up authentication endpoints. If I post to the registration endpoint with a password that is too short, too common, or only numeric, I receive and appropriate error message. Here's an example with all three: { "email": "toasterffs@gmail.com", "password1": "1223", "password2": "1223" } { "password1": [ "This password is too short. It must contain at least 8 characters.", "This password is too common.", "This password is entirely numeric." ], } When I post to the registration endpoint with a password that is the same as the email address, I receive no error. I need to debug this but where to even start? I there somewhere I can inspect which validators are actually called? Can I monkey patch the validator and put some logging in to see where things are going wrong? Is there a signal? some other hook? Thanks -
How to deploy django crm on cpanel (shared hosting fastcomet)
KINDLY REFER TO IMAGE AND LINKS.. I did once, basically application startup file would be manage.py and entrypoint would be entrypoint.sh right? log file error: App 660 output: /opt/cpanel/ea-ruby27/root/usr/share/passenger/helper-scripts/wsgi-loader.py:26: DeprecationWarning: the imp module is deprecated in favour of importlib; see the module's documentation for alternative uses App 660 output: import sys, os, re, imp, threading, signal, traceback, socket, select, struct, logging, errno App 660 output: Traceback (most recent call last): App 660 output: File "/opt/cpanel/ea-ruby27/root/usr/share/passenger/helper-scripts/wsgi-loader.py", line 369, in App 660 output: app_module = load_app() App 660 output: File "/opt/cpanel/ea-ruby27/root/usr/share/passenger/helper-scripts/wsgi-loader.py", line 76, in load_app App 660 output: return imp.load_source('passenger_wsgi', startup_file) App 660 output: File "/home/vendscon/virtualenv/crm.vendscon.com/3.7/lib64/python3.7/imp.py", line 171, in load_source App 660 output: module = _load(spec) App 660 output: File "", line 696, in _load App 660 output: File "", line 677, in _load_unlocked App 660 output: File "", line 728, in exec_module App 660 output: File "", line 219, in _call_with_frames_removed App 660 output: File "/home/vendscon/crm.vendscon.com/passenger_wsgi.py", line 8, in App 660 output: wsgi = imp.load_source('wsgi', 'manage.py') App 660 output: File "/home/vendscon/virtualenv/crm.vendscon.com/3.7/lib64/python3.7/imp.py", line 171, in load_source App 660 output: module = _load(spec) App 660 output: File "", line 696, in _load App 660 output: File "", line 677, in _load_unlocked App 660 … -
How and in which module do I reference a Django user uploaded file in python backend business logic?
The aim of this application it to receive a user uploaded file and do some transformations on it using python. It is very, very basic. After reading many similar questions, I still have not found the solution. The relevant modules are: models.py from django.db import models import pandas as pd import numpy as np # Create your models here. class M_input(models.Model): m_input_description = models.CharField(max_length=255, blank=True) m_input_file = models.FileField(upload_to='m_input') m_sold_to = models.CharField(max_length=20) m_ship_to = models.CharField(max_length=20) def delete(self, *args, **kwargs): self.m_input_file.delete() super().delete(*args, **kwargs) views.py from django.shortcuts import render, redirect from django.views import generic from django.urls import reverse_lazy import pandas as pd import numpy as np import os from django.conf import settings # Create your views here. from .models import M_input def index(request): """View function for home page of site.""" context = { # 'file_path': Document.file_path, } # Render the HTML template index.html with the data in the context variable return render(request, 'index.html', context=context) class M_inputListView(generic.ListView): model = M_input class M_inputCreate(generic.CreateView): model = M_input fields = ('m_input_description', 'm_input_file', 'm_sold_to', 'm_ship_to') success_url = reverse_lazy('m-list-input') #f = M_input.objects.filter(id=1).first() f = M_input.objects.get(id=1) forecast_dict = pd.read_excel(f.m_input_file.name, sheet_name=['F'], skiprows=1) def delete_m_input(request, pk): if request.method == 'POST': m_input = M_input.objects.get(pk=pk) m_input.delete() return redirect ('m-list-input') urls.py from django.urls import path … -
How to read headers from request
I have an API, those who would access this API would have to pass an authorization token, so my question is how can I get that auth token from headers? class RealTimeAPI(APIView): def post(request): pass -
django-admin runserver error (DJANGO_SETTINGS_MODULE not set )
I'm getting the following error when trying to run django-admin runserver PS C:\Users\gasgu\PycharmProjects\djangodennisproj\devsearch> django-admin runserver Traceback (most recent call last): File "C:\Users\gasgu\AppData\Local\Programs\Python\Python39\lib\runpy.py", line 197, in _run_module_as_main return _run_code(code, main_globals, None, File "C:\Users\gasgu\AppData\Local\Programs\Python\Python39\lib\runpy.py", line 87, in _run_code exec(code, run_globals) File "C:\Users\gasgu\PycharmProjects\djangodennisproj\venv\Scripts\django-admin.exe\__main__.py", line 7, in <module> File "c:\users\gasgu\pycharmprojects\djangodennisproj\venv\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line utility.execute() File "c:\users\gasgu\pycharmprojects\djangodennisproj\venv\lib\site-packages\django\core\management\__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "c:\users\gasgu\pycharmprojects\djangodennisproj\venv\lib\site-packages\django\core\management\base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "c:\users\gasgu\pycharmprojects\djangodennisproj\venv\lib\site-packages\django\core\management\commands\runserver.py", line 61, in execute super().execute(*args, **options) File "c:\users\gasgu\pycharmprojects\djangodennisproj\venv\lib\site-packages\django\core\management\base.py", line 398, in execute output = self.handle(*args, **options) File "c:\users\gasgu\pycharmprojects\djangodennisproj\venv\lib\site-packages\django\core\management\commands\runserver.py", line 68, in handle if not settings.DEBUG and not settings.ALLOWED_HOSTS: File "c:\users\gasgu\pycharmprojects\djangodennisproj\venv\lib\site-packages\django\conf\__init__.py", line 82, in __getattr__ self._setup(name) File "c:\users\gasgu\pycharmprojects\djangodennisproj\venv\lib\site-packages\django\conf\__init__.py", line 63, in _setup raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: Requested setting DEBUG, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. I have done a clean installation with a virtualenv, then I didi pip install django, created the project and do the runserver. I'm running this from pycharm community and I read that I should also set an enviroment variable called DJANGO_SETTINGS_MODULE and I should put my project.settings as value. I did that and I still get the error. I've also tried the same process from outside … -
Poll's choices are not showing while accessing from view in template
I am building a Poll App and I am stuck on an Problem. What i am trying to do :- I am trying to access all three choices of poll from view in template BUT only one choices is showing. BUT when i access Poll object in view and access choice model from template then all three choices are successfully showing. models.py class Poll(models.Model): user = models.ForeignKey(User, null=True, on_delete=models.CASCADE) title = models.TextField() def get_absolute_url(self): return reverse('detail_poll', kwargs={'pk': self.pk}) class Choice(models.Model): poll = models.ForeignKey(Poll, on_delete=models.CASCADE) choice_text = models.CharField(max_length=30) forms.py class PollAddForm(forms.ModelForm): choice1 = forms.CharField(label='Choice 1',max_length=100,min_length=2) choice2 = forms.CharField(label='Choice 2',max_length=100,min_length=2) choice3 = forms.CharField(label='Choice 3',max_length=100,min_length=2) class Meta: model = Poll fields = ['title','choice1', 'choice2', 'choice3'] I am increasing choices from forms. views.py def detail_poll(request,poll_id): poll = get_object_or_404(Poll, id=poll_id) for choice in poll.choice_set.all(): printChoice = choice.choice_text context = { 'printChoice ':printChoice , } return render(request, 'detail_poll.html',context) In view i am accessing all the choice from choice_text of the poll. I am accessing three choices for vote with the same (choice_set) method in template. AND When i create poll then poll is successfully saving with all three choices. When i vote then poll is successfully voting with choices. BUT when i accessing the choices to … -
Show all the items in admin site (something interferes with the queryset)
Django 3.5.2 models, managers and mixins class ActiveManager(models.Manager): """ Select objects that are not archived. Ref.: omnibus.model_mixins.general.ArchivedMixin """ def get_queryset(self): result = super().get_queryset().filter(archived=False) return result class ArchivedMixin(models.Model): archived = models.BooleanField(verbose_name=gettext_lazy("Archived"), null=False, default=False, db_index=True, ) objects = models.Manager() active = ActiveManager() class Meta: abstract = True class ToSendManager(models.Manager): """ Select contacts to whom emails can be sent. """ def get_queryset(self): result = super().get_queryset().filter(archived=False).\ filter(bad_email=False).\ filter(being_actively_contacted=False).\ filter(paused=False) return result class Contact(CreatedMixin, FlagMixin, ModifiedMixin, CommentMixin, ArchivedMixin, models.Model): category = models.ForeignKey(Category, on_delete=models.PROTECT, ) region = models.ForeignKey(Region, on_delete=models.PROTECT, ) email = models.CharField(max_length=255, blank=True, default="", null=False, db_index=True, unique=True, ) bad_email = models.BooleanField(default=False) # Sent but Mailer Daemon announced an error, # or MX record is unproven or something else. being_actively_contacted = models.BooleanField(default=False) # If we are contacting actively by phone or somehow, # there is no need to send them mass emails. paused = models.BooleanField(default=False) # In this case a comment is neccessary. to_send = ToSendManager() def __str__(self): return self.email admin.py @admin.register(Contact) class AddressListAdmin(admin.ModelAdmin): exclude = [] list_display = ["email", "created", "modified", "archived", "bad_email", ] list_filter = ['email', "archived", "bad_email", ] Problem In the Admin site I have 528 objects. But in reality there are 576 of them. >>> len(Contact.objects.all()) 576 I believe that managers are … -
How to Django ORM update() multiple values nested inside a JSONField?
I have a Django JSONField on PostgreSQL which contains a dictionary, and I would like to use the queryset.update() to bulk update several keys with values. I know how to do it for one value: from django.db.models import Func, Value, CharField, FloatField, F, IntegerField class JSONBSet(Func): """ Update the value of a JSONField for a specific key. """ function = 'JSONB_SET' arity = 4 output_field = CharField() def __init__(self, field, path, value, create: bool = True): path = Value('{{{0}}}'.format(','.join(path))) create = Value(create) super().__init__(field, path, value, create) This seems to work - with some gaps as per my other question - like this: # This example sets the 'nestedkey' to numeric 199. queryset.update(inputs=JSONBSet('inputs', ['nestedkey_1'], Value("199"), False)) But if I now wanted to update a second nestedkey_2 inside the same inputs, I obviously cannot use the inputs argument twice like this: queryset.update(inputs=JSONBSet(...'nestedkey_1'...), inputs=JSONBSet(...'nestedkey_2'...) Is there a way to do this? -
django.core.exceptions.ImproperlyConfigured: WSGI application 'newsletterAPI.wsgi.application' could not be loaded; Error importing module
project name: newsletterAPI app name: newsletterApp after running python3 manage.py runserver getting the above error -
How to Django ORM update() a value nested inside a JSONField with a numeric value?
I have a Django JSONField on PostgreSQL which contains a dictionary, and I would like to use the queryset.update() to bulk update one (eventually, several) keys with a numeric (eventually, computed) values. I see there is discussion about adding better support for this and an old extension, but for now it seems I need a DIY approach. Relying on those references, this is what I came up with: from django.db.models import Func, Value, CharField, FloatField, F, IntegerField class JSONBSet(Func): """ Update the value of a JSONField for a specific key. """ function = 'JSONB_SET' arity = 4 output_field = CharField() def __init__(self, field, path, value, create: bool = True): path = Value('{{{0}}}'.format(','.join(path))) create = Value(create) super().__init__(field, path, value, create) This seems to work fine for non-computed "numeric string" values like this: # This example sets the 'nestedkey' to numeric 199. queryset.update(inputs=JSONBSet('inputs', ['nestedkey'], Value("199"), False)) and for carefully quoted strings: # This example sets the 'nestedkey' to 'some string'. queryset.update(inputs=JSONBSet('inputs', ['nestedkey'], Value('"some string"'), False)) But it does not work for a number: queryset.update(inputs=JSONBSet('inputs', ['nestedkey'], Value(1), False)) {ProgrammingError}function jsonb_set(jsonb, unknown, integer, boolean) does not exist LINE 1: UPDATE "paiyroll_payitem" SET "inputs" = JSONB_SET("paiyroll... ^ HINT: No function matches the given name and … -
Django - how do i save a generated pdf file into a FileField table automatically
I have the following code snippet: c.drawString(140, 160, 'Hello') c.setFont('Arial', 38) c.drawString(110, 260, 'Goodbye') c.showPage() c.save() buffer.seek(0) return FileResponse(buffer, as_attachment=True, filename='Hello.pdf') This seems to work fine and my browser downloads the pdf to my PC What i want to do is to automatically create the above pdf file and then save it into this model: class test_pdf(models.Model): date = models.DateField() file = models.FileField(upload_to='test/') I tried: c.drawString(140, 160, 'Hello') c.setFont('Arial', 38) c.drawString(110, 260, 'Goodbye') c.showPage() c.save() buffer.seek(0) tt = FileResponse(buffer, as_attachment=True, filename='Hello.pdf') aa = test_pdf(date=dat, file=tt) aa.save() But this didn't work. Also tried c.drawString(140, 160, 'Hello') c.setFont('Arial', 38) c.drawString(110, 260, 'Goodbye') c.showPage() c.save() buffer.seek(0) aa = test_pdf(date=dat, file=c) aa.save() Again didn't work, btw 'dat' was generated earlier in my code and works fine Any help much appreciated -
Application labels aren't unique, duplicates: rest_framework
on running, python3 manage.py runserver, getting folowing error app name is 'newsletterApp' raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: Application labels aren't unique, duplicates: rest_framework what is the reason -
After React + Django integration href is not working i used href instead of react router
I am integrating react js with django react framework i used href for navigating inside react but if integrate it with django the href are not working properly it is showing like this Page not found (404) Request URL: http://localhost:8000/costumercollection Using the URLconf defined in fin.urls, Django tried these URL patterns, in this order In react is used href like this <a href='/page2'> Get Records </a> -
Django MemcacheUnexpectedCloseError and [WinError 10061] No connection could be made because the target machine actively refused it
Hi I am new at django and trying to use django-cache to speed up page load that will list out 100 companies and their details per page but I am constantly running into errors. When I use the IP and Port from the django doc 127.0.0.1:11211 I get this error: Environment: Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 3.2.4 Python Version: 3.9.1 Installed Applications: ('django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'debug_toolbar', 'mailer') Installed Middleware: ('django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'debug_toolbar.middleware.DebugToolbarMiddleware') Traceback (most recent call last): File "C:\Users\Rafin\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\Rafin\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Rafin\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\decorators.py", line 122, in _wrapped_view result = middleware.process_request(request) File "C:\Users\Rafin\AppData\Local\Programs\Python\Python39\lib\site-packages\django\middleware\cache.py", line 145, in process_request cache_key = get_cache_key(request, self.key_prefix, 'GET', cache=self.cache) File "C:\Users\Rafin\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\cache.py", line 362, in get_cache_key headerlist = cache.get(cache_key) File "C:\Users\Rafin\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\cache\backends\memcached.py", line 77, in get return self._cache.get(key, default) File "C:\Users\Rafin\AppData\Local\Programs\Python\Python39\lib\site-packages\pymemcache\client\hash.py", line 361, in get return self._run_cmd('get', key, None, *args, **kwargs) File "C:\Users\Rafin\AppData\Local\Programs\Python\Python39\lib\site-packages\pymemcache\client\hash.py", line 334, in _run_cmd return self._safely_run_func( File "C:\Users\Rafin\AppData\Local\Programs\Python\Python39\lib\site-packages\pymemcache\client\hash.py", line 214, in _safely_run_func result = func(*args, **kwargs) File "C:\Users\Rafin\AppData\Local\Programs\Python\Python39\lib\site-packages\pymemcache\client\base.py", line 619, in get return self._fetch_cmd(b'get', [key], False).get(key, default) File "C:\Users\Rafin\AppData\Local\Programs\Python\Python39\lib\site-packages\pymemcache\client\base.py", line 1018, in _fetch_cmd self._connect() File "C:\Users\Rafin\AppData\Local\Programs\Python\Python39\lib\site-packages\pymemcache\client\base.py", line 420, in _connect … -
Can ngx_http_auth_basic_module be used for backends on different ports?
I can't add authentication system for the new backend for some reasons, so I want to check user authentication status from the old backend and give access for the new backend new endpoints if this user logged. So, can ngx_http_auth_basic_module be used for backends on different ports? Or is there a better practice?