Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
POST request authentication from django to link another apps
Login on my django "localhost" want to authenticate user login at http://mylink.com/api/login token is "123123123123". how to make authentication and session after login? -
Integrate Django as a consumer with AWS Api Gateway Websockets
I'm not sure how to do it. I've looked for in almost all the network and information is not clear and confuse. I have a websocket done in AWS ApiGateway Websocket. I'm trying to connect to my websocket path from Django, the idea is to pass the information retrieved by Django to HTML to do a dynamic website. I know I can do this directly from the HTML template using javascript but, the websocket is would be open for whatever person and couldn't protect it. For that reason I'm trying to do it by Django. I've found information about channels library but the examples found are not clear due to the Websocket server used on these examples are localhost while my websocket server has a AWS path. I really appreciate your help -
How to get the product title name in the product image model
class Product(models.Model): TYPE_CHOICES = ( ('T-Shirt', 'T Shirt'), ) title = models.CharField(max_length=120) description = models.TextField() price = models.CharField(max_length=10) type = models.CharField(max_length=12, choices=TYPE_CHOICES) bestselling = models.BooleanField() def __str__(self): return self.title class ProductImage(models.Model): product = models.ForeignKey(Product, related_name='images', on_delete=models.CASCADE) image = models.ImageField(upload_to='images/' + str(product.)) def __str__(self): return self.image.url -
Issue with Django rendering raw queryset to template
i'm pretty new to Django so still trying to understand some concepts. I'm trying to render the text from a simple CharField in a template. I would like this to be used throughout the project so i've made a context_processors.py file to handle this Models.py class HeaderCustomisation(models.Model): small_banner_text = models.CharField(blank=False, null=False, max_length=200, default="Welcome") class Meta: verbose_name_plural = 'Header Customisation' def __str__(self): return self.small_banner_text Views.py def header_customisation(request): header_customisation = HeaderCustomisation.objects.all() context = { 'header_customisation' : header_customisation, } return render(request, 'includes/header.html', context) Context_processors.py from home.views import HeaderCustomisation def header_customisation_processor(request): header_customisation = HeaderCustomisation.objects.all() return {'header_customisation': header_customisation} header.html <div id="delivery-banner" class="row text-center bg-black"> <div class="col free-delivery-wrap"> <h5 class="free-delivery-text my-1">{{ header_customisation }}!</h5> </div> </div> This renders the text from the Model but renders the raw query, like so: If anyone can help or point me in the right direction to only returning the CharField value, that would be much appreciated. Also, if any additional info is needed i'll be happy to provide. Thanks! -
ERROR: Could not find a version that satisfies the requirement Django==1.10.5 from versions: none ERROR: No matching distribution found Django==1.10.5
[enter image description here] [1]WARNING: Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ReadTimeoutError("HTTPSConnectionPool(host='pypi.org', port=443): Read timed out. (read timeout=15)",)': /simple/django/ C:\dev\django\entornos\srh\lib\site-packages\pip\_vendor\urllib3\util\ssl_.py:164: InsecurePlatformWarning: A true SSLContext object is not available. This prevents urllib3 from configuring SSL appropriately and may cause certain SSL connections to fail. You can upgrade to a newer version of Python to solve this. For more information, see https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings InsecurePlatformWarning, enter image description here -
Django virtual env locate
I've bought a new pc, and I downloaded my django project, which was saved in one drive, but when I open it in vs code, I can manipulate the .py files but not any other. I suppose this is because of not having the pipenv enabled. I had saved the pipenv on a pendrive, but how can I activate it now? Here goes a picture of the pipenv folder I saved: 1 2 -
The filter function on my model return me <QuerySet []>
I have this models in my models.py I'm trying to send my Purchase details and return that as a json, but the myModel.objects.filter function return me a void QuerySet objects class Purchase(models.Model): total = models.IntegerField() date = models.DateTimeField(auto_now=True) user_phone = models.CharField(max_length=50) id_user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, ) class Purchase_detail(models.Model): id_product = models.ForeignKey(Product, on_delete=models.CASCADE) id_purchase = models.ForeignKey(Purchase, on_delete=models.CASCADE) quantity= models.IntegerField() price = models.IntegerField() But when a trying to do Purchase_detail.objets.filter don't work def see_purchase_detail(request, id): if request.headers.get('X-Requested-With') == 'XMLHttpRequest': purchase_detail = json.loads(serializers.serialize( 'json', Purchase_detail.objects.filter(id_purchase=id) )) print(purchase_detail, Purchase_detail.objects.filter(id_purchase=id)) return JsonResponse({'details': purchase_detail}, safe=False) else: return JsonResponse({None}, safe=False) -
One Project Two Apps Two Static Folder - django
I have a problem about static files, I have two apps and I want to use different static file in each. Like {% load static1 %} <html><h1>App1</h1></html> {% load static2 %} <html><h1>App2</h1></html> STATICFILES_DIRS = [ BASE_DIR / "app1/static1", BASE_DIR / "app2/static2", ] How can I do that ? -
Django how to save object status in signals?
I am using signals in my model. The status of blog post will be pending for admin approval when any user try to edit existing blog post. But when I trying to change status from pending to published from my admin panel, it's keeping the old status "pending". here is my code: models.py def post_update(sender,instance,*args,**kwargs): if instance: instance = Blog.objects.filter(is_published="published").update(is_published="pending") post_save.connect(Blog.post_update,sender=Blog) -
Copy a directory recursively from Google Cloud Storage Bucket to another Google Cloud Storage Bucket using Django
I intend to copy a whole directory with all files and directories recursively from one Google Cloud Storage Bucket to another Google Cloud Storage Bucket. The following code works fine from local to a Google Cloud Storage Bucket : import glob from google.cloud import storage def upload_local_directory_to_gcs(local_path, bucket, gcs_path): assert os.path.isdir(local_path) for local_file in glob.glob(local_path + '/**'): if not os.path.isfile(local_file): upload_local_directory_to_gcs(local_file, bucket, gcs_path + "/" + os.path.basename(local_file)) else: remote_path = os.path.join(gcs_path, local_file[1 + len(local_path):]) blob = bucket.blob(remote_path) blob.upload_from_filename(local_file) upload_local_directory_to_gcs(local_path, bucket, BUCKET_FOLDER_DIR) How can I copy a directory recursively from one bucket to another in the same project ? -
Different django rest approach for urls.py, INSTALLED_APPS, apps.py
reading few similar topics in stackoverflow and https://docs.djangoproject.com/en/3.2/ref/applications/#configuring-applications Im still facing issue understanding proper way of handling urls. I'm following two REST API tutorials in which they differ from each other about urls.py's, settings.py, apps.py files. Having structure like this: ├───my_project │ └───api │ ├───apps.py | └───urls.py │ └───my_project | ├───urls.py | └───settings.py | └───manage.py Tutorial #1 my_project\api\apps.py from django.apps import AppConfig class ApiConfig(AppConfig): default_auto_field = "django.db.models.BigAutoField" name = "api" ########### DIFF my_project\api\urls.py from django.urls import include, path from rest_framework import routers from . import views router = routers.DefaultRouter() router.register(prefix="symbols", viewset=views.SymbolsViewSet) urlpatterns = [ ########### DIFF path("", include(router.urls)), ########### DIFF ] ########### DIFF my_project\my_project\urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path("admin/", admin.site.urls), path("api/", include("api.urls")), ########### DIFF ] my_project\my_project\settings.py INSTALLED_APPS = [ "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", "rest_framework", "api", ########### DIFF ] Tutorial #2 my_project\api\apps.py from django.apps import AppConfig class ApiConfig(AppConfig): default_auto_field = "django.db.models.BigAutoField" name = "my_project.my_project.api" ########### DIFF my_project\api\urls.py from rest_framework import routers from . import views router = routers.DefaultRouter() router.register(prefix="symbols", viewset=views.SymbolsViewSet) ########### DIFF Lack of 3 lines my_project\my_project\urls.py from django.contrib import admin from django.urls import path, include from my_project.my_project.api.urls import router urlpatterns = [ path("admin/", admin.site.urls), path("api/", include(router.urls)), ########### DIFF ] my_project\my_project\settings.py … -
Doesn't django implement Content Security Policy by default?
In a RoR project I had <%= csp_meta_tag %> in the main html file. I was trying to build a conceptual app in Django with the knowledge I had at RoR, but when searching for Django Content Security Policy, only a extension appears (https://django-csp.readthedocs.io/en/latest/). There is no documentation regarding the topic so, is it possible that Django does not solve this common security issue by default? Also, I only found this SO question about this. -
How can I use Wagtail Forms for a Headless CMS? ( without Template )
According to the documentation, Wagtail API is read-only ( POST Method not allowed ). Hence, the only way to use Forms from the Sidebar Menu is using Templates, so the client is capable of making post requests against the API internaly. But that´s not headless. To be headless the API must be capable of receiving form data by providing a URL. Wagtail Docs - API "The Wagtail API module exposes a public, read only, JSON-formatted API which can be used by external clients (such as a mobile app) or the site’s frontend." ... At this point I´m not having the slightest clue, that means at a last resort I have to rethink my stack, although so far I have been very satisfied with Wagtail as headless CMS together with Nuxt as Client. Any ideas to avoid this measure would be much apprechiated. -
POST 400 Bad Request in React/Axios/Django
I'm building a website with React, with a Django backend. I have a button that when clicked runs the following function (I want to be able to send post requests from an AuthContext to be able to share the context with all my components): async function handleLogIn(e) { e.preventDefault(); const data = { email: "nultero", password: "password123", }; const headers = { "Content-Type": "application/json" }; const api = axios.create({ baseURL: "http://localhost:8000", }); try { const { resp } = await api.post("users/token/", data, { headers: headers, }); localStorage.setItem("@ezbps:JWToken", resp); console.log(resp.data); } catch (err) { console.error(err); } } Here are the console errors I get: POST http://localhost:8000/users/token/ 400 (Bad Request) dispatchXhrRequest @ xhr.js:177 xhrAdapter @ xhr.js:13 dispatchRequest @ dispatchRequest.js:52 Promise.then (async) request @ Axios.js:61 Axios.<computed> @ Axios.js:87 wrap @ bind.js:9 handleLogIn @ index.js:43 callCallback @ react-dom.development.js:188 invokeGuardedCallbackDev @ react-dom.development.js:237 invokeGuardedCallback @ react-dom.development.js:292 invokeGuardedCallbackAndCatchFirstError @ react-dom.development.js:306 executeDispatch @ react-dom.development.js:389 executeDispatchesInOrder @ react-dom.development.js:414 executeDispatchesAndRelease @ react-dom.development.js:3278 executeDispatchesAndReleaseTopLevel @ react-dom.development.js:3287 forEachAccumulated @ react-dom.development.js:3259 runEventsInBatch @ react-dom.development.js:3304 runExtractedPluginEventsInBatch @ react-dom.development.js:3514 handleTopLevel @ react-dom.development.js:3558 batchedEventUpdates$1 @ react-dom.development.js:21871 batchedEventUpdates @ react-dom.development.js:795 dispatchEventForLegacyPluginEventSystem @ react-dom.development.js:3568 attemptToDispatchEvent @ react-dom.development.js:4267 dispatchEvent @ react-dom.development.js:4189 unstable_runWithPriority @ scheduler.development.js:653 runWithPriority$1 @ react-dom.development.js:11039 discreteUpdates$1 @ react-dom.development.js:21887 discreteUpdates @ react-dom.development.js:806 dispatchDiscreteEvent @ react-dom.development.js:4168 Error: Request failed … -
generate barcodes with crud information in python
This is a control access for builders with double check to enter the work area, first with the official ID then the barcode to verify the information. I already built a crud using Python, Django and Postgresql without the barcode because still don't know how to connect the data with the EAN code. How can I connect this information with the codebar to show on modal window? -
Getting ValuError: Field 'id' expected a number but got a html
I am a newcomer, about 10 days into a self-taught Django, and I am building a Django (v3.2) app. The main view in the app is a list of countries (view: CountryListView, template: countries_view.html). When I click on a country in that list, a detail view is brought up to see detailed country data (CountryDetailView and country_detail.html). In CountryDetailView, there are navigation buttons: either back to CountryListView, or 'Edit', which shall bring the user to CountryEditView, where the country parameters can be changed & saved. However, when I click on 'Edit', I get the following error: Request Method: GET Request URL: http://127.0.0.1:8000/manage_countries/countries/country_edit.html/ Django Version: 3.2.4 Exception Type: ValueError Exception Value: Field 'id' expected a number but got 'country_edit.html' I am guessing this might to do something with values returned (or rather expected but not returned) from CountryDetailView, but what they are? And how to make CountryDetailView to return the object id? (I am using plain integer id's in my model) views.py class CountryListView(LoginRequiredMixin, ListView): model = Countries context_object_name = 'countries_list' template_name = 'manage_countries/countries_view.html' class CountryDetailView(LoginRequiredMixin, DetailView): model = Countries template_name = 'manage_countries/country_detail.html' class CountryEditView(LoginRequiredMixin, UpdateView): model = Countries template_name = 'manage_countries/country_edit.html' success_url = reverse_lazy('manage_countries:countries_view') urls.py path('', CountryListView.as_view(),name='countries_view'), path('countries/<pk>/', CountryDetailView.as_view(), name='country-detail'), … -
Django Migrations not updating Heroku PostgreSQL database
I've been stuck on an issue for a while where I have a model that I've created locally (class User(AbstractUser)), ran "python manage.py makemigrations" and "python manage.py migrate", which also works and interacts correctly with the django server when run locally. When I push this to heroku however, I receive an error response to certain api requests which essentially say "relation "app_user" does not exist". I assumed this was because somehow the postgreSQL db didn't receive the migrations when the app was deployed to heroku. After logging into the db I noticed that it had a few other tables, including "auth_user" (I assume this is a default django table), but not "app_user". I have done "heroku run bash" and "python manage.py migrate" in an attempt to migrate the changes to the postgreSQL db, but this doesn't have any effect. I'm not sure if this will be useful but the postgreSQL server I'm using is the standard Heroku Postgres Hobby Dev add-on. My questions are: Should running "python manage.py migrate" on heroku update the postgreSQL database? If so, how does this work? Given that the migrations are all on heroku, how can I manually update the postgreSQL with the migrations? -
Django Add default value to model field having the value of another field
I want to add a field to my django model and I want its default value to be equal to the primarykey value (id), but I want it to apply to all already existing records in my database. class ModelB(models.Model): id= models.IntegerField() index = models.IntegerField(default=" i want something here to get id value") I found previous questions covering this but the answers only give a solution where you have to add a method that adds the value on save. In my case I want this value to be applied to previously saved records also. Please if you have an idea I'd appreciate your help, thanks. -
Django not saving ModelForm data
I've looked at other questions but I can't find the root of my problem. I'm making a checkout view which should save an address with a customer. It creates an Address object, with a customer referenced but isn't saving any of the form data. It just has an Address object with empty fields other than the customer field. models: class Address(models.Model): customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, blank=True, null=True) name = models.CharField(max_length=200) line_1 = models.CharField(max_length=200) line_2 = models.CharField(max_length=200, null=True, blank=True) state = models.CharField(max_length=100, null=True, blank=True) country = CountryField(null=True, blank=True) postal_code = models.CharField(max_length=15, null=True, blank=True) class Meta: verbose_name_plural = "addresses" class Order(models.Model): customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, blank=True, null=True) address = models.ForeignKey(Address, 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=False) transaction_id = models.CharField(max_length=100, null=True) def __str__(self): return str(self.id) @property def get_total(self): orderitems = self.orderitem_set.all() total = sum([item.get_total for item in orderitems]) return total def get_items(self): orderitems = self.orderitem_set.all() total = sum([item.quantity for item in orderitems]) return total class Meta: verbose_name_plural = "orders" forms.py class AddressForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(AddressForm, self).__init__(*args, **kwargs) class Meta: model = Address fields = ['name','line_1', 'line_2', 'state', 'postal_code', 'country' ] payment.py (view) import stripe from django.shortcuts import get_object_or_404, render from django.http import HttpResponseRedirect, JsonResponse from django.urls … -
How to configure the Index.fcgi path?
I'm finishing with setting up my Django project on my hosting using ssh. i am following an article to be able to install it correctly. Some of the steps I had to follow are as follows: Create the . htaccess file with the settings of the FCGI Handler and redirection to the index.fcgi file that will be created: AddHandler fcgid-script .fcgi RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^(.*)$ index.fcgi/$1 [QSA,L] and Create the index.fcgi file in the root of your application with the following content: #!/home/CONTA/.virtualenv/bin/python import os, sys from flup.server.fcgi import WSGIServer from django.core.wsgi import get_wsgi_application sys.path.insert(0, "/home/CUENTA/mydjango") os.environ['DJANGO_SETTINGS_MODULE'] = "mydjango.settings" WSGIServer(get_wsgi_application()).run() Already having those two files in the public html and opting the permissions to the index.fcgi using chmod 0755 At the time of me see if it is running using the following command ./index.fcgi, tells me that there is no file or directory. Which leads me to assume that I need to set a path within the index.fcgi or . htaccess but I do not know what I need to change since in the article only comes that. Thank you -
How to update fields of currently logged in user with data from stripe webhook ex) subscription, customer in django?
import stripe from django.http import HttpResponse from django.conf import settings from django.contrib.auth.decorators import login_required from django.http.response import JsonResponse from django.http import HttpResponse from django.shortcuts import render from django.views.decorators.csrf import csrf_exempt from django.contrib.auth import get_user_model I need help with getting the currently logged in user to update their subscription and customer fields, to what gets returned from stripe. Any help would be very appreciated. @csrf_exempt def payment_confirmation_webhook(request): endpoint_secret = 'wh***********************' payload = request.body sig_header = request.META['HTTP_STRIPE_SIGNATURE'] event = None try: event = stripe.Webhook.construct_event( payload, sig_header, endpoint_secret ) except ValueError as e: # Invalid payload return HttpResponse(status=400) except stripe.error.SignatureVerificationError as e: # Invalid signature return HttpResponse(status=400) if event['type'] == 'checkout.session.completed': session = event['data']['object'] subscription = session.get('subscription') customer = session.get('customer') else: print('failed') return HttpResponse(status=200) I tried this but I don't have an id to look for since its stripe who is hitting the endpoint so obviously I can't use request.user.id user = get_user_model().objects.get() -
Why When i try to open a link using object id then it's not working in django 3.2?
I am using django 3.2 and i am trying to learn how i can print models.py data on my html page. During this i wanted to add a href tag on home page that will redirect to about page with object id and display the other details. But it's not working. App Name is greeting_app greeting_app/urls.py from . import views urlpatterns = [ path('', views.home, name="home"), path('/about/<int:pk>/', views.about, name="about"), ] greeting_app/models.py from django.db import models from django.db.models.enums import Choices # Create your models here. gender_choice = ( ("0", "Nothing"), ("1", "Male"), ("2", "Female"), ) class basicinformation(models.Model): name = models.CharField(max_length=50) age = models.IntegerField() gender = models.CharField(choices=gender_choice, max_length=10) description = models.TextField() def __str__(self): return self.name greeting_app/views.py from django.shortcuts import render, HttpResponse from .models import basicinformation # Create your views here. def home(request): information = basicinformation.objects.all() return render(request, 'index.html', {"info":information}) def about(request, id): data = basicinformation.objects.get(id=id) return render(request, 'about.html', {"data":data}) -
Django: How to clean a model with inlines?
I created an app that implements a quiz. I got a glitch, however, when I tried to clean a model. models.py class Question(models.Model): def clean(self): options = Option.objects.filter(question=self) correct = 0 for option in options: option.save() print(option) if option.correct == True: correct += 1 print(correct) if correct > 1: raise ValidationError(_('Please only input 1 correct answer.')) if correct <= 0: raise ValidationError(_('Please input 1 correct answer.')) #limit questions if options.count() > 4: raise ValidationError(_('Only 4 maximum amount of options!')) class Option(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE, related_name="question") correct = models.BooleanField(default=False, verbose_name="Correct?") The problem I figured is that when the site tries to save each question, it saves each model Question before saving each Option. -
Different ways to add an app to settings.py
There are two ways to add an app to Django's settings.py: 'appname.apps.AppnameConfig', and 'appname', I know for third-party apps installed through pip, it is not possible to use the first method. But what's the pros and cons of each method? -
Django Extended page is not rendering image as expected
Basically, I am trying to build a website similar to one from W3Schools. However, the image does not get rendered unless I add like 500px top padding. Here is the link to the sample page: https://www.w3schools.com/w3css/tryit.asp?filename=tryw3css_templates_startup base.html {% load static %} <!DOCTYPE html> <html lang="en"> <link rel="icon" href="{% static 'images/favicon.ico' %}" type="image/x-icon"> <head> <title>{% block title %}{% endblock %}</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css"> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Raleway"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> </head> <style> body, h1, h2, h3, h4, h5, h6 { font-family: "Raleway", sans-serif } body, html { height: 100%; line-height: 1.8; } .w3-bar .w3-button { padding: 16px; } </style> <body> <!-- Navbar (sit on top) --> <div class="w3-top"> <div class="w3-bar w3-white w3-card" id="myNavbar"> <a href="/"><img src="{% static 'images/logo.png' %}" style=" position: absolute; height: 60px; padding: 5px; left: 100px"></a> <!-- Right-sided navbar links --> <div class="w3-right w3-hide-small"> {% if request.user.is_authenticated %} <a href="{% url " home " %}" class="w3-bar-item w3-button">Feed</a> <a href="/" class="w3-bar-item w3-button">Messages</a> <a href="{% url " dashboard " %}" class="w3-bar-item w3-button">Account</a> <a href="{% url " logout " %}?next=/" class="w3-bar-item w3-button">Logout</a> {% else %} <a href="{% url " login " %}" class="w3-bar-item w3-button">Log In</a> <a href="{% url " register " %}" class="w3-bar-item w3-button">Register</a> {% endif %} …