Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Making external http calls using requests package within Daphne
I have a Django project that runs by Daphne, one of my views needs to submit a http request externally using the requests package, unfortunately that package is not async compatible, so if the http call is blocked, the whole Daphne app hangs. def view(request): # this call will get timed out data = requests.get('https://blocked') ... return Response(...) I did some quick search and couldn't find any quick answers. One possibility is to serve these views via Uwsgi, apart from this approach, are there any other quick wins? Maybe use aiohttp? -
How to render code based on checkbox value in Django?
I want to conditionally render part of form that's responsible for billing address. If user has checkbox checked, don't render it, if unchecked - render. I tried following: <div class="big-padding"> <input type="checkbox" id="billing-same-as-shipping" name="billing-same-as-shipping" checked> <label for="billing-same-as-shipping">Billing address same as shipping address</label> </div> {% if checked in 'billing-same-as-shipping' %} <h3>Billing Address</h3> <div class="big-padding"> <div class="row "> {% include "views/parts/billing-address.html" %} </div> </div> {% endif %} No matter what I try, I can't seem to make conditional rendering work. -
Getting error: 'No 'Access-Control-Allow-Origin' header is present on the requested resource.' for logout route in Django/React app
I have an app using React/Django, with Auth0 for authentication. I've followed this tutorial to fix any CORS errors, and all my routes are not running into any issues, except for my logout route. I'm creating a logout button, which will flush the user's session on Django and redirect to the Auth0 logout page as well. urls.py urlpatterns = [ ... path('logout/, views.logout, name = 'logout') ] views.py from django.contrib.auth import logout as django_logout def logout(request): django_logout(request) domain = settings.AUTH0_DOMAIN client_id = settings.AUTH0_CLIENT_ID return_to = '127.0.0.1:8000' return redirect(f'https://{domain}/v2/logout?client_id={client_id}&returnTo={returnTo}') App.jsx const App = () => { ... const logout = async () => { await fetch('http://127.0.0.1:8000/logout/') } return ( <div> ... <button onClick={logout}>Logout</button> <div> ) } When the user logs out, I'm getting a CORS error despite importing and configuring django-cors-headers and not getting this error for any other route. Specifically, the error is No 'Access-Control-Allow-Origin' header is present on the requested resource. -
How to map Django TextChoices text to a choice?
Suppose I have this code, inspired from the Django docs about enumeration types: class YearInSchool(models.TextChoices): FRESHMAN = 'FR', 'Freshman' SOPHOMORE = 'SO', 'Sophomore' JUNIOR = 'JR', 'Junior' SENIOR = 'SR', 'Senior' GRADUATE = 'GR', 'Graduate' Now suppose I have the string "Sophomore". How do I get from that to YearInSchool.SOPHOMORE? The only thing I can think of is a loop: the_str = "Sophomore" val = None for val1, label in YearInSchool.choices: if label == the_str: val = YearInSchool(val1) break assert YearInSchool.SOPHOMORE == val That seems awkward. Is there a better way? -
Django form scrubs blank spaces spaces
I have a model with a text field: models.py class Techtip(models.Model): title = models.CharField(max_length=150) year = models.PositiveIntegerField() year2 = models.PositiveIntegerField() make = models.CharField(max_length=30) model = models.CharField(max_length=30) description = models.TextField(max_length=10000) user = models.ForeignKey(User, null=True, on_delete=models.SET_NULL) date_created = models.DateTimeField(auto_now_add=True) date_revised = models.DateTimeField(null=True) additional_field = models.TextField(max_length=5000, null=True, blank=True) additional_field2 = models.TextField(max_length=5000, null=True, blank=True) image1 = models.ImageField(upload_to=user_directory_path, null=True, blank=True) image2 = models.ImageField(upload_to=user_directory_path, null=True, blank=True) image3 = models.ImageField(upload_to=user_directory_path, null=True, blank=True) def __str__(self): return self.title If a create a Techtip and give it a description of: "Hello, This is line one of the disctription. This is line two. and this is line 3." When using {{techtip.deescription}} in the template I receive this: "Hello, This is line one of the disctription. This is line two. and this is line 3." However, if you bring up a form to edit the description, the spaces are there. It is also displayed correctly in the admin panel. Here is the form: forms.py class TechtipFormModel(forms.ModelForm): """This form creates and edits techtips.""" class Meta: model = Techtip fields = '__all__' exclude = ('user', 'date_revised', 'additional_field', 'additional_field2', 'image1', 'image2', 'image3') def __init__(self, *args, **kwargs): super(TechtipFormModel, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_id = 'id-TechtipForm' self.helper.form_method = 'post' self.helper.add_input(Submit('submit', 'Submit')) self.fields['description'].strip = False Here are … -
DataTables with Django Rest Framework New/Edit/Delete Buttons not working
I am trying to incorporate DataTables Editor into a Django REST API I made. While I am able to get the datatable to display, the create/edit/delete buttons to do not work. I want to focus on just the edit function for now and hopefully the answer can be applied to the create/delete functions as well. Every time I select the edit button and chose an entry to edit I am returned PUT http://127.0.0.1:8000/dashboard/api/investigator/1 403 (Forbidden) I am able to edit the entry but the request is not processed which makes me believe it is either my datatables being setup wrong or the REST API not connecting with datatables. Can anyone provide input if I setup the datatable wrong? urls.py from django.urls import path, include from . import views from rest_framework import routers from .views import StudyList, StudyDetail, InvestigatorView app_name = 'dashboard' router = routers.DefaultRouter() router.register('study', views.StudyView) router.register('investigator', views.InvestigatorView) router.register('lead', views.LeadView) router.register('institution', views.InstitutionView) router.register('site', views.SiteView) investigator_list = InvestigatorView.as_view({ 'get': 'list', 'post': 'create' }) investigator_detail = InvestigatorView.as_view({ 'get': 'retrieve', 'PUT': 'update', 'patch': 'partial_update', 'delete': 'destroy' }) urlpatterns = [ path('', views.datatables, name='datatable'), path('investigator/', views.datatables_investigator, name='datatables_investigator'), path('api/', include(router.urls)), path('api/investigator/', investigator_list, name='InvestigatorList'), path('api/investigator/<int:pk>', investigator_detail, name='InvestigatorDetail'), path('api/study/', StudyList.as_view(), name='StudyList'), path('api/study/<int:pk>/', StudyDetail.as_view(), name='StudyDetail') ] datatables_investigator.html {% … -
get and show cookies for backend user model -- django
I want cookies to be displayed in the Admin User Model, the customer's data is located in the cookie section and when the customer login, Django requests a cookie from the user authentication account. My Cookie name is 'device', I can use it for guest user but i don't know how to send it to backend and django ask me for it. Error : Field 'id' expected a number but got ''. My Custom User Model: class Account(AbstractBaseUser): phone_number = models.CharField(unique=True, max_length=11, validators=[MinLengthValidator(11)]) device = models.CharField(max_length=200, blank=True) USERNAME_FIELD = 'phone_number' models.py: class Customer(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=True, null=True) # Get COOKIE For guest user -- I set a cookie as device device = models.CharField(max_length=200, blank=True) views.py: Error comes from here def Add_To_Cart(request, pk): if request.user.is_authenticated: """" Error comes from here, i have no idea how to call cookie to user authentication backend.""" customer = request.user.device <<-- item = get_object_or_404(Post, pk=pk) order_item, created = OrderPost.objects.get_or_create( item=item, user=customer, ordered = False ) order_qs = Order.objects.filter(user=customer, ordered=False) if order_qs.exists(): order = order_qs[0] # check if the order post is in the order if order.items.filter(item__pk=item.pk).exists(): order_item.qunatity += 1 order_item.save() messages.info(request, "this item just added to your cart") return redirect('article-detail', pk=pk) else: order.items.add(order_item) messages.info(request, … -
Graphen-Django possible to filter a set?
newly working with GraphQl and wondering is it possible to filter a set in a query? I'm still new to database design as well so could be an issue there. So I run the below query, managerGwPicks has a field player with is a player object containig their name etc. This player object contains a set of all the weeks they have played which is a separate table in my database. So as can be seen in the above image when I display the set it shows all the game week data whereas ideally I would like it filtered by the gameweek:21 parameter passed to the managerGwPicks query. I'm not sure it should be possible as there is no direct link between the managerGwPicks and playergwstats tables but I'd like to be sure that my thinking is correct. My solution for my front end would be to have two queries, one similar to what I have getting the player informartion and a second query using the player id and gameweek to query playergwstats to get the player stats for the individual week. Does this sound like a reasonable approach? Thanks -
Django conditional post save signal not working
I have a model for user profiles that has a post save signal that auto creates a user profile whenever a new user is created. I don't want the post save signal to create a user profile when a new superuser is created. So far I have not been able to get this to work. Any ideas about how to fix this? the model: from django.db import models from tinymce import models as tinymce_models from accounts.models import CustomUser from phone_field import PhoneField from constrainedfilefield.fields import ConstrainedFileField import os from io import BytesIO from django.core.files.uploadedfile import InMemoryUploadedFile import sys from PIL import Image from django.db.models.signals import post_save import PIL class UserProfile(models.Model): user = models.OneToOneField(CustomUser, null=True, on_delete=models.CASCADE) preferred_name = models.CharField(null=True, blank=True, max_length= 75) pronouns = models.CharField(null=True, blank=True, max_length= 40) phone = PhoneField(blank=True, help_text='Contact phone number') job_title = models.CharField(null=True, blank=True, max_length= 75) birthdate = models.DateField(null=True, blank=True) bio = tinymce_models.HTMLField(null=True, blank=True) profile_image = ConstrainedFileField( null=True, blank=True, upload_to='projects/employee_profiles', content_types=['image/png', 'image/jpg', 'image/jpeg', 'image/gif'], max_upload_size=2097152, ) def save(self, *args, **kwargs): super(UserProfile, self).save(*args, **kwargs) if self.profile_image: if os.path.exists(self.profile_image.path): image = Image.open(self.profile_image) outputIoStream = BytesIO() basewidth = 100 wpercent = basewidth / image.size[0] hsize = int(image.size[1] * wpercent) imageTemproaryResized = image.resize((basewidth, hsize)) imageTemproaryResized.save(outputIoStream, format='PNG') outputIoStream.seek(0) self.profile_image = InMemoryUploadedFile(outputIoStream, 'ConstrainedFileField', … -
Django: how to move the "page not found" exception and context from function to class-based view?
I'm converting a simple function to a class-based view. I had found a good resource with examples that helped me in the past to better understand the whole topic (can be found here), but I couldn't find a good example of how to handle exceptions related to a page in a class-based view when the page is not found (for example, someone makes a typo in URL). I'm also not sure how to handle additional context that I want also transfer to class-based view. I would appreciate some help, and suggestions based on this simple example below. My goal is to import the main View with `from django.views import View' and place all logic in this class instead of this function. def meetup_details(request, meetup_slug): try: selected_meetup = Meetup.objects.get(slug=meetup_slug) return render(request, 'meetups/meetup-details.html', { 'meetup_found': True, 'meetup_title': selected_meetup.title, 'meetup_description': selected_meetup.description }) except Exception as exc: return render(request, 'meetups/meetup-details.html', { 'meetup_found': False }) -
In Django, how to annotate inside a M2M field?
I have these models: class Convocacao(models.Model): cursos = models.ManyToManyField(Curso) class RegistroConvocacao(models.Model): aluno = models.ForeignKey(Aluno) convocacao = models.ForeignKey(Convocacao) tipo = models.IntegerField(choices=TiposConvocacao) class Aluno(models.Model): curso = models.ForeignKey(Curso) Then I get a Convocacao object: obj = get_object_or_404(Convocacao, pk=pk) Now, I want to use annotate inside obj.cursos, to sum the tipo of RegistroConvocacao. Something like: cursos = obj.cursos.all() cursos = cursos.annotate( total_ingressantes=obj.registroconvocacao_set.filter( aluno__curso__in=obj.cursos, tipo_convocacao=RegistroConvocacao.TIPO_CONVOCACAO_INGRESSANTE ).count() ) But it gives error: TypeError: 'ManyRelatedManager' object is not iterable I want to do something like: for curso in obj.cursos.all(): total = curso.total_ingressantes ... -
'Manager' object has no attribute 'remove'
I am trying to allow a logged in user to delete their comment under a comment section, but I keep getting the error thrown in the title, and I'm not sure why. I've read up on Managers in the docs but don't quite understand what the issue is, as all my other models work just fine. Here is the code views.py def delete_comment(request, comment_id): comment_details = Comment.objects.get(id=comment_id) # Throws error at this line Comment.objects.remove(comment_details) return HttpResponseRedirect('view') models.py class Comment(models.Model): comment = models.CharField(max_length=64) item = models.ForeignKey('Listing', on_delete=models.CASCADE, null=True) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) date_created = models.DateTimeField(auto_now=True) def __str__(self): return f"{self.comment}" -
Error: Cannot import 'account'. Check that 'accounts.apps.AccountConfig.name' is correct
When I run python manage.py runserver in Django, I get the following error. Error django.core.exceptions.ImproperlyConfigured: Cannot import 'account'. Check that 'accounts.apps.AccountConfig.name' is correct. I tried everything but could not figure it out. What should I do? acconuts/apps.py from django.apps import AppConfig class AccountConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'account' mysite/settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'widget_tweaks', 'app', 'accounts', 'django.contrib.sites', 'allauth', 'allauth.account', 'allauth.socialaccount', ] -
i have a problem with docker. service "todo" is not running container
i trying to make a docker-compose for my django project but when im using "docker-compsoe exec" i geting this error. service "todo" is not running container im expecting when write "docker-compose exec todo sh -c "python startapp todolist" its make an app but its not happend and i getting this error. "service "todo" is not running container" enter image description here enter image description here -
Debug of django {{form.as_p}} in html
I am a beginner in django with python, I confront a problem about the TemplateDoesNotExist in django/forms/errors/list/default.html, Is anyone know the solution? Error capture I already tried remove the {{form.as_p}} in my html, the page is work without the form. Therefore, I guess the problem may come from the modalform I made, but I still not find the wrong. -
Remove port from URL - Django Apache2 Gunicorn
I would like to know how to omit the port number from my URL. I currently host a website on an Apache Ubuntu server on port 443 and redirect any http traffic to the https version of the site. (www.mycompany.com) However, I also run a Django server on the same Apache VPS using Gunicorn, currently on port 8000 and would like to achieve the URL of www.mycompany.com/blog My current situation for the URL is www.mycompany.com:8000/blog I have tried altering the ports that the Django server runs on to 443 and 80, but quickly realised the firewall won't allow that. I am not sure what to do. Do I have to do a reverse proxy? This is my first time doing this so any help is greatly appreciated. -
How can a model be cleared (Django ) when moving to another page or reloading the current one?
Good day! I ask for help please, this is very important for me, can someone tell me something. I have a page template. And a view made for it. I also have code with various operations on models in this view. When there is a transition on this page - representation, I have a form in which I place the processed data. When I reload the page or go to another page - view, the data in the form remains unchanged because I use a model specially made for this as the data source for the model. I need to clear the model or do some other operation when I leave this page to another one or reload it. -
DRF: Dynamic literal type hint for models.TextChoices
Given this model from django.db import models class Olympian(models.Model): MedalType = models.TextChoices('MedalType', 'GOLD SILVER BRONZE') medal = models.CharField(max_length=6, choices=MedalType.choices, default=MedalType.GOLD) and this function which takes in the CharField as a param fn_with_type_hint(olympian.medal) How can I type hint the param more strictly without hard-coding like this? def fn_with_type_hint(medal: Literal['Gold', 'Silver', 'Bronze']): pass What I tried I tried Olympian.medal but it's just a string medal: Olympian.medal I also tried variations of this to no avail medal: Literal[*Olympian.MedalType.values] I also can't use this solution because I don't start with a list of strings https://stackoverflow.com/a/64522240/8479344 -
Unable to host Tensorflow model on Heroku
I am trying to host a Django application that holds a tensorflow model on heroku. When pushing to the heroku application I receive this error: "Could not find a version that satisfies the requirement tensorflow-intel==2.11.0." From what I understand heroku runs pip install requirements.txt, so I am not sure why it would not be able to find that version. Screenshot of output from trying to push to heroku Any explanations or solutions would be appreciated. Also if there is a better way to host a tensorflow model, please let me know. -
Django 403 forbidden only happens at login in prod environment
I have a Login using the Django Login/authentication, once I Post the request to login I get the 403 Forbidden error with the following message: CSRF verification failed. Request aborted. You are seeing this message because this site requires a CSRF cookie when submitting forms. This cookie is required for security reasons, to ensure that your browser is not being hijacked by third parties. If you have configured your browser to disable cookies, please re-enable them, at least for this site, or for “same-origin” requests. This only happens with the login and not with the other forms that I have in my application. this is my login form: {% extends "main/base.html" %} {% load static %} {% load widget_tweaks %} {% block content%} <div class='container'> <div class='row pt-4'> <div class="col"> </div> <div class="col-md-4 col-md-offset-4"> <div class="card text-center"> <!-- Login Form --> <div class="card-header bg-dark"> <h2 class="text-secondary">Login</h2> </div> <div class="card-body card text-left"> <form method="POST"> {% csrf_token %} {% for hidden in form.hidden_fields %} {{ hidden }} {% endfor %} {% for field in form.visible_fields %} <div class="form-group"> <label>{{ field.label_tag }}</label> {% render_field field class="form-control" %} {% for error in field.errors %} <span class="help-block">{{ error }}</span> {% endfor %} </div> {% endfor … -
How to connect django to MS-SQL server in pycharm?
error as - No matching distribution found for ms-sql I am unable to connect to the ms-sql server with the command "pip install ms-sql django". In previous projects, I was able to connect using the same command. it's not working now. This command uninstalls Django 4.1.1 version and installs the 4.0.7 version. But, now, its giving an error. Is there any update? please advise how to connect django to MS-SQL server using pycharm. -
Filtering one model with the id column of a different model in Django
I want to display a table in HTML which contains columns from two different tables/models. The models look something like this: class Vor(models.Model): id_vv = models.BigIntegerField(db_column='ID_VV', blank=True, null=False, primary_key=True) vdat = models.DateField(db_column='VDat', blank=True, null=True) v_li = models.TextField(db_column='V_Li', blank=True, null=True) ... # more columns/objects exist and class VorDet(models.Model): id_det = models.BigIntegerField(db_column='ID_Det', blank=True, null=False, primary_key=True) v_li = models.TextField(db_column='V_Li', blank=True, null=True) v_twg = models.TextField(db_column='v_twg', blank=True, null=True) ... # more columns/objects exist vor = models.ForeignKey(Vor, on_delete=models.CASCADE, blank=True, null=True) #empty as it was not part of the legacy data table The data in the DB was imported from csv files (legacy data base from access) using ./ manage.py migrate --fake -initial. So models.ForeignKey() is empty - I'm not quite sure if that matters or not. I need to display vdat, v_li and v_twg in the same list. id_vv has a one-to-many connection to id_det and only becomes unique if the v_li-columns also match. Right now I can solve the problem by: filtering the first model Vor by vdat Using the the output of 1. I input id_vv values into VorDet.objects.filter(id_det__in=...) then merge both outputs via pd.merge() vor_list = Vor.objects.filter(vdat__startswith="2022").values() det_list = VorDet.objects.filter(id_det__in=[x['id_vv'] for x in vor_list]).values() comb_list = pd.merge(pd.DataFrame(vor_list), pd.DataFrame(det_list), left_on = ['id_vv', 'v_li'], right_on … -
FATAL: role 'postgres' does not exist
I've been dockerizing an app with postgresql and making it ready for production. However, when going back to work to a different app (that also is using PostgreSQL), I'm not able to run the django server, neither to access to PostgreSQL 14 server inside of Pgadmin. When trying to initializate the server in the Pgadmin, there is this message error when entering the password: connection to server at "localhost" (::1), port 5432 failed: could not initiate GSSAPI security context: The operation or option i s not available. Credential for asked mech-type mech not found in the credential handle connection to server at "localhost" (::1), port 5432 failed: FATAL: role "postgres" does not exist I was using this database normally and without problems, both from Django local development server as well as from Pgadmin. Django project database's user is a different user, but also says role 'username' does not exist. I tried to follow other answers but can't make it work. How could I have messed it up? -
Max retries exceeded with url: Failed to establish a new connection: [Errno 111] Connection refused'
I keep getting this error: HTTPConnectionPool(host='127.0.0.1', port=8001): Max retries exceeded with url: /api/v1/auth/sign_in (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7f0f8cbdd430>: Failed to establish a new connection: [Errno 111] Connection refused')) I searched through the stackoverflow and couldn't find the solution that would help me. Here's my code example: host = 'http://127.0.0.1:8001' response = requests.request(method=request_data['method'], url=f'{host}/{settings.ACCOUNTS_API_PREFIX}{request_data["url"]}', json=json_data, params=params, headers=headers, ) Basically I'm trying to send a POST request to authenticate myself on the service, however I keep getting the above error. I have 2 containers - one is a web application (Django), another one is accounts that stores all details of the users to authenticate them. Both containers are up and running, I can open the website, I can open the API swagger for accounts, however I can't send the POST request and get any response. Can someone assist me to figure it out? -
how to give the client argument in django management commands?
I have a function in django management commands that should take a url as an argument class Command(BaseCommand): help = u'Enter the url' def add_arguments(self, parser): parser.add_argument('url',type=str,help=u'Enter the url') def handle(self,*args,**kwargs): url = kwargs['url'] main(url) it doesn't matter what the function is, everything in it works when a command is called through the terminal but I have a question, how can I implement this into the client part? I want the user to enter a url and it is passed to the function. What are the ways to pass user arguments to django management commands?