Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I have CORS whitelisted in Django and the Cross Origin Request is still blocked
I have a Vue front-end and a Django back-end and I have CORS enabled in settings.py, but I still get these errors: Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:8000/api/register. (Reason: expected ‘true’ in CORS header ‘Access-Control-Allow-Credentials’). Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:8000/api/register. (Reason: CORS request did not succeed). Status code: (null). This is at the bottom of my settings.py file: CORS_ORIGIN_ALLOW_ALL = False CORS_ORIGIN_WHITELIST = ( 'http://localhost:8080', 'http://localhost:8000', ) -
Django extend `UserManager` instead of `BaseUserManager`
Django docs says to define a custom manager you have to extend the BaseUserManager and provide two additional methods. But after doing so, I realized that my custom manager is vary similar to the default UserManager. So, is there a problem with inheriting from that instead? Like this: from django.contrib.auth.models import UserManager class CustomUserManager(UserManager): """Custom user model manager with email as the unique identifier.""" def _create_user(self, email, password, **extra_fields): if not email: raise ValueError("The given email must be set") email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user I just overrode the _create_user method, because others were identical. -
ArrayField consisting of composite field type
I have modeled composite field using https://pypi.org/project/django-composite-field/ in my django model (A URL field + a Boolean Field). What I want is to store a number of those (maybe in a list) in my base 'User' model. But ArrayField using django.contrib.postgres.fields only support a single data type. What I want is a list of the object (URL + boolean) for every user. Further I want to add validations for the number of objects eg.(min 2 objects, max 6 objects). What is a good way to model this? Thanks. -
django-tenants: access tenant media files in script
I am running an app built with djang-tenants. The app asks the user (tenant) to upload some data. I want the data to be segregated in sub directories for each tenant. Acccording to the doc (https://django-tenants.readthedocs.io/en/latest/files.html), here is how media root is configured: settings.py MEDIA_ROOT = "/Users/murcielago/desktop/simulation_application/data" MULTITENANT_RELATIVE_MEDIA_ROOT = "%s" On the upload everything is great. Now, I can't find a way to retrieve the file being uploaded within the app. Basically I need the app to serve the file corresponding to which tenant is requesting it. Here is how I thought this would work: from django.conf import settings media_file_dir = settings.MULTITENANT_RELATIVE_MEDIA_ROOT df = pd.read_csv(media_file_dir+'/uploads/sample_orders_data.csv') but this does not work. I have made it work so far grabbing the tenant name from the url and passing it to the app using pickle but this is not right in terms of security and won't scale. Would someone has a clue on the best way to handle the lecture of tenant specific files? -
Docker Django_crispy_forms raise InvalidTemplateLibrary
I was developing a bookstore app using Django on Docker, I created a signup and login page, then utilized the django_crispy_forms for the signup and login page. Here is the commands flow: docker-compose exec web pipenv install django_crispy_forms==2.0.0 docker-compose down -v docker-compose up -d --build Lastly update the settings.py: # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'crispy_forms', # new # local apps 'users.apps.UsersConfig', 'pages.apps.PagesConfig', ] # django-crispy-forms CRISPY_TEMPLATE_PACK = 'bootstrap4' # new But when I check the logs with: docker-compose logs The console raise a error: raise InvalidTemplateLibrary(django.template.library.InvalidTemplateLibrary: Invalid template library specified. ImportError raised when trying to load 'crispy_forms.templatetags.crispy_forms_field': cannot import name 'BoundField' from 'django.forms.forms' (/usr/local/lib/python3.10/site-packages/django/forms/forms.py) My Dockerfile code: FROM python:3 ENV PYTHONDONTWRITEBYTECODE=1 ENV PYTHONUNBUFFERED=1 WORKDIR /code COPY requirements.txt /code/ RUN pip install -r requirements.txt COPY . /code/ And the docker-compose.yml: version: "3.9" services: db: image: postgres volumes: - ./data/db:/var/lib/postgresql/data environment: - POSTGRES_NAME=bookpostgresv2 - POSTGRES_USER=bookpostgresv2 - POSTGRES_PASSWORD=bookpostgresv2 web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" environment: - POSTGRES_NAME=bookpostgresv2 - POSTGRES_USER=bookpostgresv2 - POSTGRES_PASSWORD=bookpostgresv2 depends_on: - db requirements.txt: Django>=3.0,<4.0 psycopg2>=2.8 django-crispy-forms-ng==2.0.0 pipenv==2022.3.24 -
how to pass url name in Django template using context variable
In my Django project, I am experiencing an issue in passing url name in Django template. Say I have this line in urls.py ... path('hd2900', hd2900.as_view(), name='hd2900') ... In template if I pass 'hd2900' ass a string in the {% url %} tag things work. <a class="navbar-brand navbar-left" href="{% url 'hd2900' %}" id="navbarLogoLink"> <img src="{{ navbarLogoPath }}" alt="{{ navbarLogoAlt }}" id="navbarLogo"> </a> But if I use a context variable from a view for example in views.py context['urlName'] = 'hd2900' Then in template if I change 'hd2900' to urlName, I will get an error NoReverseMatch at /hd2900. Somehow it no longer looks for name my url pattern. -
Why is the route correct but still giving 404 error on Django
I got a 404 error on my website when accessing the correct route, did I do something wrong urls.py handles the main route from django.contrib import admin from django.urls import path,include,re_path urlpatterns = [ path('admin/', admin.site.urls), re_path(r'api/facebook/(.+?)', include('apifacebooks.urls')), path('', include('app.urls')), path('getcookie', include('app.urls')), path('change-lang', include('app.urls')), re_path(r'auth/(.+?)', include('app.urls')), ] urls.py handles routes in the apifacebooks app from django.urls import path from . import views urlpatterns = [ path('api/facebook/like-post',views.like_post) ] And when I go to http://localhost:8000/api/facebook/like-post I get a 404 error -
Unable to create super user in django on my online server
Inside the cpanel -> python app i have tried several time to create super user. when I tried to execute this commad inside Execute python script manage.py createsuperuser then it will return this error Superuser creation skipped due to not running in a TTY. You can run `manage.py createsuperuser` in your project to create one manually. How to solve this problem, or any manuall solution, i found several solution but all the solution for local server. -
How to get Radio Radio Button Data from POST Request Data in an HTML form?
So I'm coding a test platform consisting of Multiple Choice Questions ( MCQs ) in Django. Everything is working fine but somehow I think that the radio button value from my question page is not getting fetch via POST request. Would appreciate some help! Here are my models : from django.db import models from django.contrib.auth.models import AbstractUser from .managers import UserManager from questions.models import Question class User( AbstractUser ) : email = models.EmailField( verbose_name = 'Email Address', unique = True, null = False ) username = None USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = UserManager() def __str__( self ) : return self.get_username() class Student( models.Model ) : user = models.OneToOneField( User, on_delete = models.PROTECT ) mobile = models.CharField( verbose_name = 'Mobile Number', max_length = 10, unique = True ) def __str__( self ) : return self.user.get_username() JAVA='J' PYTHON='P' DATABASE='D' OPERATING_SYSTEM='O' NETWORKING='N' SUBJECT_CODE = [ ( JAVA,'java' ), ( PYTHON,'python' ), ( DATABASE,'database management' ), ( OPERATING_SYSTEM,'operating systems' ), ( NETWORKING,'Computer Networks' ) ] class Performance( models.Model ) : global SUBJECT_CODE student = models.ForeignKey( Student, on_delete = models.PROTECT ) question = models.OneToOneField( Question, on_delete = models.PROTECT, null = True ) score = models.PositiveSmallIntegerField( verbose_name = 'Score', null = True ) … -
Render a template within def get_object instead of raise raise Http404("Does not exist") in class based view
In the get_object method of class views, can I direct the user to a template instead of returning the object if an if statement fails? Currently raise Http404("Some message.") works good but it doesn't look nice, I want to use my own template. I'm trying to do this but with templates: def get_object(self): product = Product.objects.get(slug=self.kwargs.get('slug')) if product.deleted == False: if product.out_of_stock == False: return product else: raise Http404("This product is sold out.") # return reverse("404-error", kwargs={"error": "sold-out"}) # return render(request, "custom_404.html", {"error": "sold_out"}) else: raise Http404("This product is no longer available.") # return reverse("404-error", kwargs={"error": "deleted"}) # return render(request, "custom_404.html", {"error": "deleted"}) My main goal is to just avoid getting the object. I know I can perform the if statement in the get_context_data method, however I wasn't sure for objects containing sensitive data if there would be any way for a user to access it once it's in the get_object, so I just wanted to avoid getting the object altogether if the condition fails and display a template to the user. -
Django extend base.html along with its context
I've passed a variable to base.html from my views.py file in a context. I've extended this base.html to another several templates. The variable is only visible in the base.html and not any other extended template. It does work if I pass the same context to each templates views.py file. As I extended the base, shouldn't it also extend the variable? Is there any other way to get this working, or am I missing something? -
Student registrations system using django
I am developing a student registrations system using django. Task: Teacher will pay x amount for x students. (Completed) So After payment the teacher will receive a unique url to register their students. (Completed) The URL will be valid for 7 days. (Completed) Apply restrictions for x students for that url. ( Pending ) Example: If a teacher paid for 2 leaders and got the unique url. But he can add 1000 students with that url within 7 days. So my question is how to restrict the registration to 2 students only. Any help?? Thanks -
How to make the FileField downloadable for users that has permission to download in Django?
I am making a simple e-commerce website that sells my own software in a zip file, how to make a download link for the file that can only be accessed with the user who purchased the product? Any advice on how should i manage my product files? This is my Products model class Product(models.Model): name = models.CharField(max_length=150) price = models.FloatField() description = models.CharField(max_length=255, blank=True) product_type = models.CharField(max_length=20, default='tool') date_created = models.DateField(auto_now_add=True) date_updated = models.DateField(auto_now=True) image = models.ImageField(null=True, blank=True) -
Certain models not showing up in django 4 admin despite being registered
Using django 4.0.3 and the restframework. I have serval models registered in django admin: @admin.register(models.Drug) class DrugAdmin(admin.ModelAdmin): list_display = ('apl_label', 'name', 'drug_class', 'atc_code', ) @admin.register(models.Organism) class OrganismAdmin(admin.ModelAdmin): list_display = ('apl_label', 'long_name', 'short_name', 'genus', 'flagged', 'notes') .... For some reason, some o fthe models are not showing up in the admin view. In this example, Organism shows up, but Drug is hidden. I can go to http://localhost:8000/admin/api/drug/ and access this admin page, but it is not listed under http://localhost:8000/admin/. There is no error message either. I did run makemigrations and migrate. Permissions are only set globally in settings.py: ... 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.SessionAuthentication', ], It is always the same models not showing up. I tried deleting the database and creating everything from scratch. No luck. Why does Django decide to not show certain models? -
How to take user input and let the user upload / submit a .json file to a Docker image
So I am pretty new to Docker but already really liking its functionalities and container / block mentality. Long story short, lately I've been selling some scripts but I kept running into the same problem. My clients were usually on Windows and I would have to spend a lot of time setting things up for them, broken packages in Windows, annoying TeamViewer sessions etc. Now here the beauty that is Docker comes in which allows me to ship ready-made images. Just fantastic! Given my newbie status in Docker I am having some trouble doing certain things. I am currently reading the book "Docker in Action" and loving it but something like my problem has not (yet) been covered there. Now I have the following code (this is not everything but the part I am struggling with): def broadcast_transaction(sender, private_key, amount, contract): # Get the nonce. Prevents one from sending the transaction twice nonce = web3.eth.getTransactionCount(sender) to_address = web3.toChecksumAddress(contract) # Build a transaction in a dictionary tx = { 'nonce': nonce, 'to': to_address, 'value': web3.toWei(amount, 'gwei'), 'gas': 300000, 'gasPrice': web3.toWei('5', 'gwei'), 'chainId': 0x38 } # sign the transaction signed_tx = web3.eth.account.sign_transaction(tx, private_key) # send transaction tx_hash = web3.eth.sendRawTransaction(signed_tx.rawTransaction) # get transaction … -
django pwa error = cannot import name 'url' from 'django.conf.urls
hello i am using django 4.0.3 and i try to use django-pwa in my project but when i runserver i ge this error i followed this tutorial geeksforgeeks:make-pwa-of-a-django-project for including progressive web application feature in my project i think url from django.conf.urls is deprecated. i am sure is exist some solutions... help me please Error File "C:\Users\Republic Of Computer\Desktop\Master cours et TD\python\tberra3lipy\venv\lib\site-packages\pwa\urls.py", line 1, in <module> from django.conf.urls import url ImportError: cannot import name 'url' from 'django.conf.urls' (C:\Users\Republic Of Computer\Desktop\Master cours et TD\python\tberra3lipy\venv\lib\site-packages\django\conf\urls\__init__.py) urls.py from django.contrib import admin from django.conf.urls.static import static from django.urls import path,include from django.conf import settings urlpatterns = [ path('admin/', admin.site.urls), path('donation/',include('donation.urls',namespace='donation')), path('',include('pwa.urls')), ]+static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) settings.py from pathlib import Path import os INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'pwa', 'accounts', 'donation', ] ROOT_URLCONF = 'src.urls' # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.2/howto/static-files/ STATIC_URL = '/static/' #pwa PWA_SERVICE_WORKER_PATH = os.path.join(BASE_DIR, 'static/js', 'serviceworker.js') PWA_APP_NAME = 'tberra3li' PWA_APP_DESCRIPTION = "app for blood donors" PWA_APP_THEME_COLOR = '#000000' PWA_APP_BACKGROUND_COLOR = '#ffffff' PWA_APP_DISPLAY = 'standalone' PWA_APP_SCOPE = '/' PWA_APP_ORIENTATION = 'any' PWA_APP_START_URL = '/' PWA_APP_STATUS_BAR_COLOR = 'default' PWA_APP_ICONS = [ { 'src': 'static/assets/img/icon-160x160.png', 'sizes': '160x160' } ] PWA_APP_ICONS_APPLE = [ { 'src': 'static/assets/img/icon-160x160.png', 'sizes': '160x160' } ] PWA_APP_SPLASH_SCREEN … -
Having Issue Veryfing Successful Transactions After API Call
i Just Integrated paystack to my website and am having issues verifying transaction status. this transaction is successful when the users enter card details but the documentation is not clear on how to verify this successful transactions. see the doc below to understand my point The verify payment docs verify transaction docs The docs talks about using the callback url to verify transactions and this seems not easy with python. kindly take a look at my code. def paystackdeposit(request, comment = None): user = request.user email = user.email if request.method == 'POST': form = DepositForm(request.POST) if form.is_valid(): amount = form.cleaned_data.get('amount') #the callback is expected to return the url and replace YOUR_REFERENCE with the reference code used in making get request to verify transaction status url = 'http://127.0.0.1:8000//postpayment_callback.php?reference=YOUR_REFERENCE' parsed_url = urlparse(url) captured_value = parse_qs(parsed_url.query)['reference'][0] url = "https://api.paystack.co/transaction/verify/:captured_value" headers = {'Authorization': 'Bearer sxk_lixzve_1xxreeeeeeeeeeeeeb8e794f74ffzzfdddd','Content-Type': 'application/json'} response = requests.request("GET", url, headers=headers) if response.data.status == success: account.balance += amount asof = account.modified account.save(update_fields=[ 'balance', 'modified', ]) return render (request, 'accounting/deposit_successful.html', { 'amount':amount, 'balance':balance, 'created': created, }) else: form = DepositForm(request.POST) return render(request, 'depositing/paystack_deposit_fund.html', {'form': form, 'refcode': refcode}) this is what the documentation says. If the transaction is successful, Paystack will redirect the user back to … -
Send confirmation email right after sign up with auth0 application
I am a django starter, and I'm doing a backend project. Now, I meet some troubles. The user will login when they are in my home page. After they click login button, they will be redirected to auth0 authentication application. A new user has to sign up and the backend will send a email for verification. The problem is that I cannot find a good solution to send an email after a user has signed up. My solution is send email when the new users sign up and login in automatically and they will be redirected to my home page of web application. Then, I check if the email is verified and is sent verification. But I want to send email right after the user click the submit button of sign up page. Does anyone has better ideas? -
Django cbv multiple items to delete as te same time
I'm new here the reason of this message it's because I'm learning django with class based views, and all is working fine, it’s a little bit confused because django with functions are totally different. What I'm trying to do it's something like the image above, but I really have no idea how to achieve this. Do you have any link where I can see how to do it? I do not know how to do it with a detailview and delete view. Any advice is welcome. Thank you What I wanto to achieve it's to select multiple data from model and delete as the image -
How do I pass field value as argument to next view django?
I cannot find the functions in the Django documentation that allow me to pass a value that one form creates in my db to another function. I would like to pull create an object in my create_player_view capture that created objects pk and pass it to scoring_view. Doing this through the form action field has been unsuccessful as no data is passing between the views. What is a better way to do this? I want simple behavior that takes the Match ID created in create_player_view and passes it for update/use in the scoring view. ###model class Players(models.Model): matchID = models.AutoField(primary_key=True) player1Name = models.CharField(max_length=10) player2Name = models.CharField(max_length=10) def __str__(self): return f'{self.matchID}: {self.player1Name} vs {self.player2Name}' class Scores(models.Model): matchID = models.OneToOneField(Players, on_delete=models.CASCADE, related_name='match') p1_set_1_score = models.IntegerField(default=0) p1_set_2_score = models.IntegerField(default=0) p1_set_3_score = models.IntegerField(default=0) p1_set_4_score = models.IntegerField(default=0) p2_set_1_score = models.IntegerField(default=0) p2_set_2_score = models.IntegerField(default=0) p2_set_3_score = models.IntegerField(default=0) p2_set_4_score = models.IntegerField(default=0) def __str__(self): return f'{self.matchID}: ' ###Views def create_player_view(request): """" allows users to name two players competing vs one another """ if request.method == "POST": form = PlayerForm(request.POST) if form.is_valid(): form.save(commit=True) return redirect('tennis:m_score') #is it possible to pass this view created instance? else: message = "Form could not be completed" return render(request, "create_player.html", {"message":message}) else: form = … -
Django react router dom don't render file
my page don't render the HomePage but if i only use h1 Test HomePage h1 in render it work. i wanna know where i should fix it or what im doing wrong thanks for help or you need to see the other file you can tell me im kinda new to the programming import React, { Component } from "react"; import { render } from "react-dom"; import HomePage from "./HomePage"; import RoomJoinPage from "./RoomJoinPage"; import CreateRoomPage from "./CreateRoomPage"; export default class App extends Component { constructor(props) { super(props); } render() { return ( <div> <HomePage/> </div> ); } } const appDiv = document.getElementById("app"); render(<App />, appDiv); this is my HomePage Code import React, { Component } from "react"; import RoomJoinPage from "./RoomJoinPage"; import CreateRoomPage from "./CreateRoomPage"; import { BrowserRouter as Router, Switch, Route, Link, Redirect, } from "react-router-dom"; export default class HomePage extends Component { constructor(props) { super(props); } render() { return ( <Router> <Switch> <Route exact path="/"> <p>This is the home page</p> </Route> <Route path="/join" component={RoomJoinPage} /> <Route path="/create" component={CreateRoomPage} /> </Switch> </Router> ); } } -
Why DRF giving me 404
I am keep getting 404 in DRF whenever I send request from postman even though the url is correct. urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('backend.urls')) ] backend/urls.py from django.urls import path, include from . import views from rest_framework.routers import DefaultRouter router = DefaultRouter() router.register('/post', views.PostView, basename='post') urlpatterns = [ path('', include(router.urls)), ] from postman I am sending post request on this endpoint http://127.0.0.1:8000/post but I am keep getting 404 not found error. What am I doing wrong? -
I want to show last 4 products in Django
There are many products in the database. but I only want to show the 4 most recently added products. in the variable similar views.py def product_detail(request, category_slug, id): category = Category.objects.all() product = get_object_or_404(Product, category__slug = category_slug, id=id) images = ProductImages.objects.filter(product_id=id) similar = Product.objects.all().filter(category__slug=category_slug) context = { 'category': category, 'product': product, 'images': images, 'similar': similar, } return render(request, 'detail.html', context) -
Django- link answer choice to question and survey
I am trying to create a number of surveys in Django and put them in a survey index page. I have run into an issue: Up until now, all of my surveys had questions which had the same set of answer choices, so in my Django models I linked the answers only to the survey because it was the easiest for me and it was working. Now I have to add a new survey where each question has a different set of answers choices (if you are curious, this is the survey: https://www.fresno.ucsf.edu/pediatrics/downloads/edinburghscale.pdf). My problem is that for this new survey I am now getting every possible answer choice in the whole survey for each question. How can I link the answer choices to the question so that I will only see the choices for the corresponding question? Yes, I have read the Django polls tutorial and have tried requesting the question_id, but then I got an error along the lines of "missing question_id" so I went back to my original code. I think the right approach would be to link the answer choices to both the question and the survey, but not sure. Here is my model: class Questionnaire(models.Model): … -
how do I make a math Django and react web application?
Hope all is well. I want to have an input field in my react frontend that takes in a math expression (e.g 1 + 1) and I want my backend to respond with the answer 2. How do you do this using reactjs and Django? So far I have some of the frontend finished: it will send the input data to the backend using the API url. import React, {useState, UseEffect } from 'react'; function Home() { const [query, setQuery] = useState(""); return ( <div className='Home'> <form action={APIL_URL} method="POST"> <input name="linear-algebra-expression" id="linear-algebra-expression" type="text" onChange={e => setQuery(e.target.value)} value={query}> </input> </form> </div> ) } export default Home; I am aware that in my Django backend I am going to have something like: class LinearAlgebraView(APIView): def post(self, request): expression = request.POST['linear-algebra-expression'] return (... ?) I want to be able to return the computed data from Django to react at the samne web page where the user entered the math expression in the form/input. How do I do this? Thanks