Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to use poetry in Supervisor
I am trying to run huey, precisely django_huey, but each time I try to connect to DB. in the background task, 'root' is used as the user for the DB. Other parts of the application work well with the database config in django settings, like migration, etc. [program:application] directory=/home/.../django_project command=/home/.../.cache/pypoetry/virtualenvs/..../bin/python /home/.../.../manage.py djangohuey --queue application user='...' autostart=true autorestart=true redirect_stderr = true stdout_logfile = /etc/supervisor/realtime.log environment=PATH="/home/.../.../lib/python3.12/site-packages" stopwaitsecs=30 # task @db_periodic_task(crontab(minute='*/1'), queue='application') def app_task(): # current date and time current_timestamp = timezone.localtime(timezone.now()) # get all event get_events = Mymodel.objects.order_by('-creation_time').filter( time_ends__lt=current_timestamp ) if get_events.exists(): ... Error: connection failed: connection to the server at "127.0.0.1", port 5432 failed: FATAL: password authentication failed for user "root" -
Django View Causing ConnectionError in Production When Fetching TMDB API Data
Problem I am encountering a ConnectionError when trying to fetch data from the TMDB API and add it to my database in a production environment. The error message indicates that the connection was reset by the peer: This issue does not occur in the local development environment. Below are the relevant parts of my views.py and nginx settings. Code Snippets views.py: def SeriesAddView(request): org = Org.objects.first() if request.method == 'POST': tmdb_id = request.POST.get('tmdb_id') reqUrl = f"https://api.themoviedb.org/3/tv/{tmdb_id}?language=en-US" headersList = { "accept": "application/json", "Authorization": f"Bearer {org.tmdb_token}" } payload = "" series_details = requests.request("GET", reqUrl, data=payload, headers=headersList) update_series = Series.objects.filter(tmdb_id=tmdb_id).first() if series_details.status_code == 200: data = series_details.json() genre_data = data["genres"] genre_list = [] for genre_data in genre_data: genre_id = genre_data.get("id") genre_name = genre_data.get("name") if genre_id and genre_name: genre = Genre.objects.filter(genre_id=genre_id).exists() try: genre = Genre.objects.get(genre_id=genre_id) except Genre.DoesNotExist: genre = Genre.objects.create(genre_id=genre_id, name=genre_name) genre_list.append(genre) # Check if the poster image already exists img_path = data["poster_path"] poster_path = f"media/posters/tv{img_path}" if not os.path.exists(poster_path): # Save the poster image locally poster_url = "https://image.tmdb.org/t/p/original" + img_path poster_response = requests.get(poster_url) if poster_response.status_code == 200: with open(f"media/posters/tv/series{img_path}", 'wb') as f: f.write(poster_response.content) if update_series: # Update the existing movie update_series.adult = data["adult"] update_series.title = data["name"] update_series.original_title = data["original_name"] update_series.overview = data["overview"] update_series.release_date = … -
error in django application packaged with pyinstaller version > 5.1
Greetings to the community. I have an issue that is driving me nuts for a long time now. I have a Django application and I am trying to package it with pyinstaller (Windows). Everything works when I use Pyinstaller 5.1, which is quite old. With any pyinstaller version above 5.1, I am getting the following error To make it even weirder, in the more recent versions of pyinstaller it works when using the --console=True option. But i don't want the console to appear in my packaged application. With --console=False, I am still getting the error. Tried to use both python 3.11 and 3.12, i doubt it has anything to do with the python version. From what I could gather from my limited Django knowledge, the NoneType is one of the Django basic models like the User, which are not supposed to be None hence the weird bug. I am sorry, I cannot provide any code from the Django app. Anyone has any idea (so I can start looking somewhere) would be highly appreciated, because now I really don't know what to look for. Thanks -
GeoDjango_Installation_don't_work
in my GeoDjango installation process (https://docs.djangoproject.com/fr/5.0/ref/contrib/gis/install/#windows), GDAL is an important component. I followed the recommendations from the Python website by using OSGeo4W. When I run gdalinfo --version (as you can see in the image), Django recommends installing Python 3.12, which I have already done! I have also installed PostgreSQL and PostGIS. However, when I install OSGeo4W, it directly installs GDAL 0.9. I’m not sure why it’s asking for GDAL 0.8 when I run gdalinfo --version. I also tried another method by following this video https://youtu.be/ZpD-pkmquTo?si=hMsSalfOoGOEg8Eq. When I run pipwin install gdal, I get this error. Traceback (most recent call last): File "<frozen runpy>", line 198, in _run_module_as_main File "<frozen runpy>", line 88, in _run_code File "C:\Users\Administrator\Desktop\ARRDELBEE\Projetarrdelultime\Backend_ArrdelBee_Territorial_Digital\venv\Scripts\pipwin.exe\__main__.py", line 4, in <module> File "C:\Users\Administrator\Desktop\ARRDELBEE\Projetarrdelultime\Backend_ArrdelBee_Territorial_Digital\venv\Lib\site-packages\pipwin\command.py", line 28, in <module> from . import pipwin, __version__ File "C:\Users\Administrator\Desktop\ARRDELBEE\Projetarrdelultime\Backend_ArrdelBee_Territorial_Digital\venv\Lib\site-packages\js2py\base.py", line 1377, in __init__ cand = fix_js_args(func) ^^^^^^^^^^^^^^^^^ File "C:\Users\Administrator\Desktop\ARRDELBEE\Projetarrdelultime\Backend_ArrdelBee_Territorial_Digital\venv\Lib\site-packages\js2py\utils\injector.py", line 27, in fix_js_args code = append_arguments(six.get_function_code(func), ('this', 'arguments')) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Administrator\Desktop\ARRDELBEE\Projetarrdelultime\Backend_ArrdelBee_Territorial_Digital\venv\Lib\site-packages\js2py\utils\injector.py", line 121, in append_arguments arg = name_translations[inst.arg] ~~~~~~~~~~~~~~~~~^^^^^^^^^^ KeyError: 3 ``` Thank you for helping me and not ignoring this. -
If you continue to make changes such as debugging with pythonAnywere 3.10, an error like the one shown in the image will appear
I want to deploy a Django app with pythonAnywhere. If I'm using Python3.12, is it okay to use the latest 3.10? If you continue to make changes such as debugging in 3.10, an error like the one shown in the image will appear. -
list of object evrey object contine image whene i send it from vue.js axios to django viewset the data come messy data
pice of data that come in django <QueryDict: {'user[username]': ['اسم المستخدم'], 'user[password]': ['123'], 'user[first_name]': ['الاسم الاول بيانات الشهادة'], 'user[last_name]': ['بيانات الشهادة الاسم الاخير'], 'user[email]': ['samer@gmail.com'], 'user[date_of_birth]': ['2024-05-21'], 'user[mobile_no]': ['7478888888'], 'user[phone_no]': ['7878787897898'], 'user[gender]': ['1'], 'user_fk_ssn_archive[document_no]': ['22222222222222222222222222222'], 'user_fk_ssn_archive[document_type]': ['1'], 'user_fk_ssn_archive[issue_date]': ['2024-05-21'], 'user_fk_ssn_archive[expiration_date]': ['2024-05-21'], 'user_fk_ssn_archive[issue_place]': ['مكان الاصدار بيانات البطاقة'], 'user_fk_ssn_archive[code]': ['4444444444'], 'user_fk_place_of_brith[street]': ['الشارع بيانات البطاقة '], 'user_fk_place_of_brith[fk_region]': ['1'], 'user_fk_address[street]': ['الشارع بيانات الاقامة'], 'user_fk_address[fk_region]': ['1'], 'academic_qualification[0][fk_qualification][fk_documnet_type]': ['1'], 'academic_qualification[0][fk_qualification][qualification_type]': ['1'], 'academic_qualification[0][fk_qualification][name_ar]': ['الاسم العربي الموؤهل'], 'academic_qualification[0][fk_qualification][educational_level]': ['1'], 'academic_qualification[0][fk_document][document_no]': ['121231231'], 'academic_qualification[0][fk_document][document_type]': ['1'], 'academic_qualification[0][fk_document][issue_date]': ['2024-05-21'], 'academic_qualification[0][fk_document][expiration_date]': ['2024-05-21'], 'academic_qualification[0][fk_document][issue_place]': ['مكان الاصدار المؤهلات'], i used serializer to save data -
Django RESTFRAMEWORK Serializer with nested Serializer
I've got a problem with adding a serializer to another serializer and call it correctly. My models.py with just the WorkshopMaterials Model class WorkshopMaterials(models.Model): id = models.BigAutoField(primary_key=True) workshop = models.ForeignKey(Workshop, on_delete=models.CASCADE, related_name="workshop") material = models.ForeignKey(Material, on_delete=models.CASCADE, related_name="material") amount = models.IntegerField(blank=False, default=1) amountType = models.CharField( max_length=3, choices=AmountType.choices, default=AmountType.PCT, blank=False ) My serializer.py class MaterialSerializer(ModelSerializer): class Meta: model = Material fields = ('id', 'name', 'amount', 'amountType', 'link', 'status') extra_kwargs = {'id': {'read_only': True}} class WorkshopMaterialsSerializer(ModelSerializer): class Meta: model = WorkshopMaterials fields = ('amount', 'amountType', 'material', 'workshop') def to_representation(self, instance): rep = super().to_representation(instance) rep["material"] = MaterialSerializer(instance.material).data["name"] rep["workshop"] = WorkshopSerializer(instance.workshop).data["id"] return rep class WorkshopSerializer(ModelSerializer): class Meta: model = Workshop exclude = ['created_at', 'updated_at'] def __init__(self, *args, **kwargs): fields = kwargs.pop('fields', None) super().__init__(*args, **kwargs) if fields is not None: allowed = set(fields) existing = set(self.fields) for field_name in existing - allowed: self.fields.pop(field_name) def to_representation(self, instance): rep = super().to_representation(instance) workshopLeaderData = WorkshopLeaderSerializer(instance.leader).data workshopLeaderName = workshopLeaderData["name"] if workshopLeaderData["displayname"] == "AN": workshopLeaderName = workshopLeaderData["artistname"] rep["leader"] = workshopLeaderName return rep My views.py class WorkshopListView(APIView): #permission_classes = (IsAuthenticated,) def get(self, request): ### TESTED MATERIALS FOR DIFFERENT WORKSHOPS #workshop = WorkshopMaterials.objects.prefetch_related(Prefetch('workshop', queryset=Workshop.objects.filter(id=3))) #serializer = WorkshopMaterialsSerializer(workshop, many=True) ### WORKING FOR LIST VIEW (NO DETAILS) #workshops = Workshop.objects.prefetch_related('workshop').all() #serializer = WorkshopSerializer(workshops, many=True, fields=('id', … -
Filtering queryset depending on incoming parameters?
I have the filter parameters that I get through GET request. These parameters are used for filtering QuerySet: class FilterData(TypedDict): title: str min_price: int max_price: int freeDelivery: bool available: bool tags: list[int | None] As you can see, the list of tags can be empty and this field shouldn't be in the filter query. So what's the best way to change my filter query depending on incoming parameters? if might help, but I'm not sure it's a good solution: if not tags: result = Product.objects.filter( Q( price__gte=filter_data["min_price"], price__lte=filter_data["max_price"], ) & Q(freeDelivery=filter_data["freeDelivery"]) & Q(available=filter_data["available"]) & Q(title__icontains=filter_data["title"])) ).order_by(order_field) else: result = Product.objects.filter( Q( price__gte=filter_data["min_price"], price__lte=filter_data["max_price"], ) & Q(freeDelivery=filter_data["freeDelivery"]) & Q(available=filter_data["available"]) & Q(title__icontains=filter_data["title"]) & Q(tags__contains=[1, 2, 3]) ).order_by(order_field) Thx. -
testing django oauth2_provider authentication endpoint
I need to test o/token endpoint of the oauth2_provider. I wrote the test in pytest. I think I considered every thing but I get invalid_client error. The code: factory: class UserApplicationFactory(factory.django.DjangoModelFactory): name = factory.Faker('pystr', min_chars=5, max_chars=255) client_id = factory.LazyAttribute(lambda _: generate_client_id()) client_secret = factory.LazyAttribute(lambda _: generate_client_secret()) client_type = factory.Iterator(['confidential', 'public']) authorization_grant_type = factory.Iterator(['client-credentials', 'password', 'openid-hybrid', 'authorization-code']) class Meta: model = UserApplication The test: @pytest.mark.django_db def test_token_generation(api_client, user): # secret is 12345 hashed_secret = "pbkdf2_sha256$600000$fB3GLAgzjFjcBAzaHTMyrP$/0qtnsOKi3KRqQgbZ7B0/PcudGTSIgItHXxg9R9Zkf4=" application=UserApplicationFactory( name='test app', client_type='confidential', client_secret=hashed_secret, authorization_grant_type='client_credentials', user=user ) token_url = reverse('oauth2_provider:token') authorization = base64.b64encode( bytes(application.client_id + ":12345" , "ISO-8859-1") ).decode("ascii") bearer = f"Basic {authorization}" data = { "grant_type": "client_credentials", } headers = { "Authorization": bearer, "Cache-Control": "no-cache", "Content-Type": "application/x-www-form-urlencoded", } response = api_client.post(token_url, data=data, headers=headers) response_data = json.loads(response.content) access_token = response_data['access_token'] AccessToken = get_access_token_model() token = AccessToken.objects.get(token=access_token) assert response.status_code == 200 I printed the application.client_secret the result was different from hashed_secret: print(application.client_secret) #result : md5$20JXardwR2tDHMzpZAGkVy$45cdd904b795af35d7a9f64d15086a59 -
JavaScript Fetch API is reluctant to include cookies in its requests
My program includes a Django backend and a React frontend that communicate with each other. If I log in via the corresponding endpoint of the django backend, the "sessionid" cookie is set correctly in the browser. (In the application tab of Chrome I can see the "sessionid" cookie). So far so good. However, when I send a request containing this cookie from the frontend to my backend, I can see in the networks tab that the cookie is not sent with the request. I have the 'credentials' option of my fetch requests set to 'include'. Additionally, React is running on 'localhost:3000' and Django on 'localhost:8000' (therefore there should not be any issues concerning cross-origin requests). My fetch request: fetch("http://127.0.0.1:8000/user", { method: "GET", credentials: "include", }); The cookie in the browser: No cookie included in the request to the Django backend by the browser: Another peculiar thing is that the 'sessionid' cookie is included in the requests made by React automatically, as can be seen here: Moreover, I have implemented the CORS-middleware in Django. I am quite sure that the issue is not related to CORS. I tried doing the request with axios and setting 'withCredentials: true'. But this does not … -
allauth twitch oauth 2.0 and Login
Is it possible to get the twitch access_token using the allauth library, and, at the same time, log in? If so, how do you do it? And, if so there was the access_token, it will be automatically saved in the socialaccount_socialtoken table SOCIALACCOUNT_PROVIDERS = { 'twitch': { 'APP': { 'client_id': '', 'secret': '', 'key': '' }, 'SCOPE': { 'user:read:chat', 'user:read:follows', 'bits:read', 'user:read:subscriptions', 'moderation:read', 'moderator:read:chatters', 'moderator:read:followers', 'moderator:read:blocked_terms', 'channel:read:redemptions', 'channel:read:vips', 'channel:read:subscriptions', 'moderator:manage:banned_users', 'moderator:manage:blocked_terms', 'moderator:manage:chat_messages', 'channel:manage:broadcast', 'channel:manage:polls', 'channel:manage:vips', 'channel:manage:redemptions', 'clips:edit', 'channel:edit:commercial', }, 'LOGIN_CALLBACK_URL': 'http://127.0.0.1:8000/accounts/twitch/login/callback/', 'AUTH_PARAMS': { 'response_type': 'code' }, # 'AUTH_PARAMS': { 'response_type': 'token' }, }, } -
Django Error 405 - Method Not Allowed (POST), can't figure out the cause
I'm using Python 3.10.6, Django 4.2.10, Django REST Framework 3.15.1 I have a login page in JavaScript sending POST request to Django with user credentials (and CSRF token in header), but the login view doesn't even open, I immediately get said error: Method Not Allowed (POST): api/users/login Method Not Allowed: api/users/login "POST api/users/login HTTP/1.1" 405 0 views.py @csrf_protect def login_view(request): if request.method == "POST": .... urls.py from .views import login_view, ... urlpatterns = [ ... path('api/users/login', login_view, name='login_view'), ... ] I can't figure out what's causing the 405 I tried deleting the @csrf_protect but didn't change anything error405 -
loading the provider_login_url tag on my login page
I'm trying to configure all-auth in my django project and after clicking on my login button i configured everything in the backend I'm getting the following error on line 95 TypeError at /accounts/login/ string indices must be integers 95 <a class="google-btn" href="{% provider_login_url 'google' %}> I've loaded the {% load socialaccount %} and this is the button: <a class="google-btn" href="{% provider_login_url 'google' %}> Log in with Google </a> in settings.py: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'Fashion', 'django.contrib.sites', 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.google' ] tried loading the tag on a different page, same error -
How to customize style of django-autocomplete-light Forms
I need your help on customizing the style of TextInput Box while using django-autocomplete-light. Specifically, I have a data model TextHeader, UserInputDataSearch then I'm creating a view object as # views.py class DataSearchAutocomplete(autocomplete.Select2QuerySetView): model = UserInputDataSearch form_class = SearchDataForm success_url = 'data_access' def get_queryset(self): qs = TextHeader.objects.all() if self.q: qs = qs.filter(keywordFinder__istartswith=self.q) return qs The forms.py is as below class SearchDataForm(forms.ModelForm): userSearch = forms.ModelChoiceField( queryset=TextHeader.objects.all(), widget = autocomplete.ModelSelect2( url='dataSearch-autocomplete', attrs={ 'data-html': True, "type":"search", "class":"form-control", "id":"autoCompleteData", "autocomplete":"off", }, ) ) dateRange = fields.DateRangeField( input_formats=['%d/%m/%Y'], widget=widgets.DateRangeWidget( format='%d/%m/%Y', ) ) class Meta: model = UserInputDataSearch fields = ["userSearch"] Then, on html template, I write down these lines #htmlTemplate <form method="POST"> {% csrf_token %} <div class="row g-3"> <div class="col-lg-6"> <div> {{ form.userSearch|as_crispy_field }} </div> </div><!--end col--> <div class="col-lg-6"> <div> {{ form.dateRange|as_crispy_field }} </div> </div><!--end col--> <div class="col-lg-12"> <div class="text-left"> <button type="submit" class="btn btn-primary">Find</button> </div> </div><!--end col--> </div><!--end row--> </form> However, it renders my page with difference style of two boxes as a screenshot below, I wonder how to make them in the same style -
"This field is required" when all fields are filled in Django(5.0.6)
So, I ran into an error during developement of a django project and someone asked the same question 5 years ago so stackoverflow won't let me ask it again. Here's the question. "This field is required" when all fields are filled in Django But the answer did not fix the error for me. The current answer is out-of-date and require revision given recent changes. view.py from django.shortcuts import render,redirect from .forms import ProductForm # Create your views here def Upload(request): if request.method == 'POST': form = ProductForm(request.POST) if form.is_valid(): form.save() return redirect('home') else: form = ProductForm() if request.user.is_superuser: return render(request, r'../templates/upload.html', {'form': form}) else: return redirect('home') forms.py from django import forms from .models import Product CategoryChoices = { ('Overwhelming', "Overwhelming"), ('Outrageous', "Outrageous"), ('Mnmlsm', "Mnmlsm"), ('Gothic', "Gothic") } class ProductForm(forms.ModelForm): title = forms.CharField(widget=forms.Textarea) image1 = forms.FileField(label='select an image') image2 = forms.FileField(label='select an image',required=False) image3 = forms.FileField(label='select an image',required=False) image4 = forms.FileField(label='select an image',required=False) image5 = forms.FileField(label='select an image',required=False) category = forms.ChoiceField(choices=CategoryChoices) price = forms.IntegerField() price.widget.attrs.update({'placeholder': 'Enter Price'}) title.widget.attrs.update({'placeholder': 'Enter product title'}) class Meta: model = Product fields = ['title', 'image1', 'image2', 'image3','image4','image5','category','price'] upload.html {% extends 'base.html' %} {% block content3 %} <title>Henkan - Login</title> {% endblock %} {% block content1 %} … -
Django route cannot be accessed during fetch POST method but can be accessed during manual GET method
When I attempt to delete a faction from my application using the route saga/delete/2 after clicking the deleteSubmit button, the program returns the following error: "POST /saga/delete/2/ HTTP/1.1" 404 3048 Not Found: /saga/delete/2/ My application uses the following relevant url patterns saga/ edit/<int:factionId> [name='edit'] saga/ delete/<int:factionId> [name='delete'] This JavaScript handles the form submission factionForm.addEventListener('submit', function(event) { //prevent the default form submission event.preventDefault(); //If the Save Changes button is clicked if (event.submitter === saveSubmit){ console.log("Save Changes Pressed"); // Code to handle form submission and save changes to the database } //Otherwise if the Delete changes button is clicked else if(event.submitter === deleteSubmit){ console.log("Delete Faction Pressed"); //Attempt to send data to server fetch(`/saga/delete/${factionId.value}/`, { method: 'POST', headers: { 'X-CSRFToken': getCSRF(), }, }) //Get response from server .then(response => { if (response.ok) { console.log('Faction deleted successfully'); } else { //If a problem occurred display the response console.error('Error deleting faction',response); } }) //If There is an error output it .catch(error => { console.error('Error:', error); }); } //Otherwise if neither approved button submitted the form something went wrong else { console.log(event.submitter, "somehow submitted the form, check and correct the code near that element"); } }) The code I am using for the getCSRF() function is … -
Typed-ast ailed building wheel required to install pyproject.toml-based projects
I tried to install the requirements in Django project using pip install -r requirements.txt but it always generates the same error. I am not able to find the solutions and I tried everything suggested on the internet. The versions I used are: Python - 3.11.1 typed-ast==1.4.2 I downgraded both python and typed-ast version to see if it worsk...but it didnt work. h(457): error C2143: syntax error: missing '{' before '*' C:\Users\Aliza Paudel\AppData\Local\Temp\pip-install-13jms7r1\typed-ast_5878f64c514840fdb0c3d18010aba49b\ast27\Custom\../Include/Python-ast.h(457): error C2059: syntax error: ')' C:\Users\Aliza Paudel\AppData\Local\Temp\pip-install-13jms7r1\typed-ast_5878f64c514840fdb0c3d18010aba49b\ast27\Custom\../Include/Python-ast.h(459): error C2143: syntax error: missing ')' before '*' C:\Users\Aliza Paudel\AppData\Local\Temp\pip-install-13jms7r1\typed-ast_5878f64c514840fdb0c3d18010aba49b\ast27\Custom\../Include/Python-ast.h(459): fatal error C1003: error count exceeds 100; stopping compilation error: command 'C:\\Program Files\\Microsoft Visual Studio\\2022\\Community\\VC\\Tools\\MSVC\\14.39.33519\\bin\\HostX86\\x64\\cl.exe' failed with exit code 2 [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. ERROR: Failed building wheel for typed-ast Failed to build typed-ast ERROR: Could not build wheels for typed-ast, which is required to install pyproject.toml- based projects (venv) PS C:\ALL_FILES\Projected\kvwsmb> My requirements.txt looks like this. pytz==2021.1 # https://github.com/stub42/pytz python-slugify==4.0.1 # https://github.com/un33k/python-slugify argon2-cffi==20.1.0 # https://github.com/hynek/argon2_cffi redis==3.5.3 # https://github.com/andymccurdy/redis-py hiredis==1.1.0 # https://github.com/redis/hiredis-py typed-ast==1.4.2 tablib # Django # ------------------------------------------------------------------------------ django==3.1.7 # pyup: < 3.2 # https://www.djangoproject.com/ django-environ==0.4.5 # https://github.com/joke2k/django-environ django-model-utils==4.1.1 # https://github.com/jazzband/django-model-utils django-allauth==0.44.0 # https://github.com/pennersr/django-allauth django-crispy-forms==1.11.1 # https://github.com/django-crispy-forms/django-crispy-forms … -
Django request is slow but sql seem to be fast, need advice on how to debug
Django admin pages take very long time to load, debugged using django-debug-toolbar. It shows the request is taking very long time However, the sql queries seem to fast What exactly does this mean? Is the time spent on processing and returning the request but not on the sql execution? Appreciate any advice on how to debug this further. -
Django render() and redirect() produce unintended url
I'm sure I'm not understanding render() and redirect() correctly, but why does this: return render(request, 'catalog/add.html', {'form': form}) (where the app name is 'catalog') Produce this url: http://127.0.0.1:8000/catalog/add/catalog_add This happens with this function: def catalog_add(request): if request.method == 'POST': form = ArtworkForm(request.POST) if form.is_valid(): form.save() return redirect('catalog') else: form = ArtworkForm() return render(request, 'catalog/add.html', {'form': form}) The GET finds the html page (catalog/add.html) and correctly populates it with an empty form, but the POST results in 'Page not found… The current path, catalog/add/catalog_add, didn’t match any of these.' Both render() and redirect() have the same behavior. -
Problems with custom model user in Django 5.0
I'm pretty new in this world of django apps so I'm still learning how the things works. I'm trying to do a CRUD for my work, so we can register some things like clients info, ours tasks, assistance... etc. In an entuthiastic and young learning spirit I decided to make a custom user model in order to be able to add a profile picture of the users of this app. I was part succeded while I was able to add users and edit its info in the app but some problems came to me later: I can create users from Django admin pannell but then this users can't logging neither the app nor the admin pannell even when I created this with the superuser and staff marks on. I can make a relation between my users and groups of the model auth.Group. To solve 1) or at least to live with it, I found I can create users with the terminal and the command 'createsuperuser' and remove permissions later altought I suspect this 'removing permission' don't work at all. But for the purpose of this project I tought it wold be fine anyway at least for now. I include this … -
Django-how to set the schema of mySql database in settings.py?
I have a database connection in settings.py to mySql database: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'OPTIONS': { 'options': '-c search_path=xxx', }, 'NAME': 'xxx', 'USER': 'xxx', 'PASSWORD': 'xxx', #fixed 'HOST':'localhost', 'PORT':'3306', } I want to set the schema of this DB. But settings the options like that trigger the following error: connection = Database.connect(**conn_params) TypeError: Connection.__init__() got an unexpected keyword argument 'options' What is triggering the error ? -
Django: Allowing a User being able to see, then update, form of their information
Im trying to create a game tracking app and I wanted the user to be able to see, then update if they wanted, a form that turns on and off features to track. I know this should be quite simple but I cannot for the life of me get the form to populate with the user's data, then be able to update it. Thanks in advance. views.py @login_required(login_url='my-login') def track_pref(request): user = User.objects.get(username=request.user) print(user) if request.method == "POST": print('first if') form = UpdateTrackPrefForm(request.user, request.POST) if form.is_valid(): print('Form Valid') obj = form.save(commit=False) obj.user = user obj.save() return HttpResponseRedirect('/view-games') else: print("else statement") form = UpdateTrackPrefForm() context = {'form': form, 'user': user, } return render(request, 'gametracker_app/track-preference.html', context=context) forms.py class UpdateTrackPrefForm(forms.ModelForm): track_cedh = forms.BooleanField(required=False) track_wincon = forms.BooleanField(required=False) track_tournament = forms.BooleanField(required=False) track_medium = forms.BooleanField(required=False) class Meta: model = TrackPref fields = {'track_cedh', 'track_wincon', 'track_tournament', 'track_medium', } models.py class TrackPref(models.Model): track_cedh = models.BooleanField(default=True) track_wincon = models.BooleanField(default=True) track_tournament = models.BooleanField(default=True) track_medium = models.BooleanField(default=True) track_note = models.BooleanField(default=True) user = models.ForeignKey(User, max_length=100, on_delete=models.CASCADE, null=True) def __str__(self): return str(self.user) html <div class="container shadow-md p-5 form-layout"> <h1 class="">Update Tracking</h1> <form action="" method="POST" autocomplete="off"> {% csrf_token %} {{ user }} <br> {{ form.track_cedh|as_crispy_field }} {{ form.track_wincon|as_crispy_field }} {{ form.track_tournament|as_crispy_field }} {{ form.track_medium|as_crispy_field … -
How do I deploy Wagtail CMS to Ionos Standard Web Hosting
I have tried to deploy Wagtail CMS to Ionos Standard hosting using the instructions at How can I deploy Django App to 1and1 (ionos) but I am just getting an internal server error. Any ideas how I can go about doing this? I have the following in wavecruiseclub/cgi-bin/application.fcgi: # -*- coding: UTF-8 -*- import os import sys import traceback home = '(htdocs location)/htdocs/wavecruiseclub' try: project = os.path.join(home, 'wavecruiseclub') # Add a custom Python path. sys.path.insert(0, project) # Switch to the directory of your project. os.chdir(project) # Set the DJANGO_SETTINGS_MODULE environment variable. os.environ['DJANGO_SETTINGS_MODULE'] = "wavecruiseclub.settings" from django_fastcgi.servers.fastcgi import runfastcgi from django.core.servers.basehttp import get_internal_wsgi_application wsgi_application = get_internal_wsgi_application() runfastcgi(wsgi_application, method="prefork", daemonize="false", minspare=1, maxspare=1, maxchildren=1) except: traceback.print_exc(stdout) with open(os.path.join(home, 'tmp/error.log'), 'w') as fp: traceback.print_exc(file = fp) I also have set up the .bashrc, .bash_profile and .htaccess files as detailed in the instructions. -
Specifying large polygons in Django GEOS
I am getting results I don't understand when creating or combining polygons to cover most of the globe. If I use one polygon, GEOS assumes the shortest boundary between coordinates. So the following specifies a 0.2° wide shape, not a 359.8° wide shape: from django.contrib.gis.geos import MultiPolygon, Polygon Polygon([(-179.99, -85), (-179.99, 85), (179.99, 85), (179.99, -85), (-179.99, -85)], srid=4326) So I create two polygons, so that each boundary is less than 180°, and combine in a multi-polygon: west = Polygon(((0, 85), (-179, 85), (-179, -85), (0, -85), (0, 85)), srid=4326) east = Polygon(((0, 85), (179, 85), (179, -85), (0, -85), (0, 85)), srid=4326) big = MultiPolygon(east, west) feature.geography = big feature.save() But I don't get any matches in the east: from django.contrib.gis.geos import Point queryset.filter(feature__geography__intersects=Point(-2.5, 2.5, srid=4326)) # match queryset.filter(feature__geography__intersects=Point(-2.5, -2.5, srid=4326)) # match queryset.filter(feature__geography__intersects=Point(2.5, -2.5, srid=4326)) # no match queryset.filter(feature__geography__intersects=Point(2.5, 2.5, srid=4326)) # no match If I just search on east, ie, feature.geography = east, all four of the above queries match. If I split the globe into four zones along the equator like so: northwest = Polygon(((0, 0), (0, 85), (-179, 85), (-179, 0), (0, 0)), srid=4326) northeast = Polygon(((0, 0), (0, 85), (179, 85), (179, 0), (0, … -
Django modification of UserCreationForm
My problem is that I am trying to modify the Django default UserCreationForm and its default messages, but it does not work. I also heard that some of the checks and initial messages are defined separately and should be customized separately, but I did not find a lot on that. I tried to search around, but most of what I found was either old and not working for current django version or did just modify the fields and not the error messages. I am importing the UserCreationForm in forms.py like this: from django.contrib.auth.forms import UserCreationForm And then I tried to modify it like this: The fields and everything is completely functional just the messages are still the default and not the custom I was trying to set. class UserSignUpForm(UserCreationForm): username = forms.CharField(label="custom", error_messages={'required': 'custom.', 'unique': 'custom.'}) password1 = forms.CharField(label="custom", widget=forms.PasswordInput, error_messages={'required': 'custom.'}) password2 = forms.CharField(label="Potvrďte custom", widget=forms.PasswordInput, error_messages={'required': 'custom.', 'password_mismatch': 'custom.'}) class Meta(UserCreationForm.Meta): model = User fields = UserCreationForm.Meta.fields error_messages = { 'password_mismatch': {"password_mismatch": "custom"}, 'password_too_short': {"password_too_short": "custom"}, 'password_common': {"password_common": "custom"}, 'password_entirely_numeric': {"password_entirely_numeric": "custom"}, } If someone knows how to solve this, please let me know. I would appreciate any feedback.