Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
custom size of field in crispy form django not working
i want to display a form to create posts. i use crispy-form and it currently displays: with html template: {% extends 'blog_app/base.html' %} {% load crispy_forms_tags %} {% block content %} <div class="content-section"> <form method="POST"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">Create Post</legend> {{ form.media }} {{ form|crispy }} </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit">Post</button> </div> </form> </div> {% endblock %} i want to increase size of the title box and reduce size of the content box so that i fits the content section. what i tried: in template, display each field as crispy field with specified css class: {% block content %} <div class="content-section"> <form method="POST"> {% csrf_token %} <div class="form-group col-md-8"> {{ form.title|as_crispy_field }} </div> <div class="form-group col-md-8"> {{ form.content|as_crispy_field }} </div> <div class="form-group"> <button class="btn btn-outline-info" type="submit">Post</button> </div> </form> </div> {% endblock %} in form class, set helper and layout: class PostCreateForm(forms.ModelForm): class Meta: model = Post fields = ['title', 'content'] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper() self.layout = Layout( Field('title', id="form-title", css_class="col-md-8", name="title"), Field('content', id="form-content", css_class="col-md-8", name="title")) in both ways, nothing changes. can someone give me a pointer? -
Calling FileField objects in template renders incorrect path
I've implemented a FileField model in my project. I can successfully upload svg files and they save to the desired location. Within my project, I make heavy use of user uploaded images (JPGs) and they save to the correct location and I can display them in my templates with no issue. However, when I upload an svg to the FileField and then attempt to display it within the template, the link is broken. The problem is that the correct file path isn't being set within the html Template <img src="{{ account.image }}" /> It should point to the following path: localhost:8000/media/Users/jimmy/file.svg But it resolves as the following, which is incorrrect: localhost:8000/profile/settingspage1/Users/jimmy/file.svg Essentially, I've I manually append '/media' to the filepath within the template, it works, but I shouldn't have to do this. The filepath should resolve correct. <img src="/media/{{ account.image }}" /> Any thoughts on what setting could be preventing only filefields from resolving to the correct path within my media folder? Thanks! -
django removes "is_staff" permission if I try to login
I have a pretty strange situation within my django project. I have a LoginForm where a user can log into the website. I am using django 3.2.12 with some other libraries like django-crispy-forms and so on. I implemented django-crowd-auth so that users can access the page with crowd. I made the neccessary configurations in settings.py and the app is running without any issues. Afterwards I gave my existing user is_staff and is_superuser permissions to access the django administration. I did it like this: python manage.py shell >>> from django.contrib.auth.models import User >>> user = User.objects.get(username="<myuser>") >>> user.is_staff = True >>> user.is_superuser = True >>> print(user.is_staff) True >>> print(user.is_superuser) True >>> save() After that I restart my django app the following way: sudo <path_to_conda_env_python>/python manage.py runsslserver --certificate <crt-file> --key <pem-file> 0.0.0.0:88 If I try to log into the django administration panel with the user which I just gave the permissions I get the error "Please enter the correct username and password for a staff account. Note that both fields may be case-senitive" Returning to the django shell gives me this output python manage.py shell >>> from django.contrib.auth.models import User >>> user = User.objects.get(username="<myuser>") >>> print(user.is_staff) False >>> print(user.is_superuser) False It seems … -
Getting Bad Gateway and Connection reset by peer using asyncio + aiohttp
Is there some async expert with sharp eyes around? I am using asyncio (Python 3.9) with aiohttp (v3.8.1) to fetch multiple urls asynchronously through a proxy, but this implementation seems to fail pretty often throwing reset by peer and Bad Gateway errors. The same proxy works well using Scrapy spiders so there must be something wrong with my async implementation. My code: from asgiref.sync import async_to_sync import asyncio import aiohttp async def async_fetch_url(session, url: str, method: str = "get"): async with getattr(session, method)(url, proxy="https://someproxy.com/") as response: return await response.json(content_type=None) async def my_async_fetch(urls: list, method: str = "get"): async with aiohttp.ClientSession(connector=aiohttp.TCPConnector(force_close=True)) as session: return await asyncio.gather(*[async_fetch_url(session, url, method=method) for url in urls]) def my_sync_func(): urls = [ 'https://somesite.com/1', 'https://somesite.com/2' ] result = async_to_sync(my_async_fetch)(urls) Error logs: [2022-04-28 21:47:28,576: ERROR/MainProcess] ???[???]: [Errno 104] Connection reset by peer [2022-04-28 21:47:28,576: ERROR/MainProcess] ???[???]: Traceback (most recent call last): File "/app/cubist_backend/helpers.py", line 176, in async_fetch_url async with getattr(session, method)(url, **kwargs) as response: File "/usr/local/lib/python3.9/site-packages/aiohttp/client.py", line 1138, in __aenter__ self._resp = await self._coro File "/usr/local/lib/python3.9/site-packages/aiohttp/client.py", line 535, in _request conn = await self._connector.connect( File "/usr/local/lib/python3.9/site-packages/aiohttp/connector.py", line 542, in connect proto = await self._create_connection(req, traces, timeout) File "/usr/local/lib/python3.9/site-packages/aiohttp/connector.py", line 905, in _create_connection _, proto = await self._create_proxy_connection(req, traces, … -
Paginate Iteratively
How to do custom pagination. I need to read csv file by rows, and return only 10 rows in response with link on the next page. -
Install Django on Gandi instance
I try to install an Django app on Gandi, and... I suck at it. If someone can help me, thx :) ! For now, what I have is un file name wsgi.py : import sys import os import os.path sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), 'cms'))) os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'cms.settings') from django.core.wsgi import get_wsgi_application and an other name requirements.txt : django-cms When I do pip --version : pip 22.0.4 from /home/hosting-user/.local/lib/python3.9/site-packages/pip (python 3.9) When I do python3 --version : python 3.5.3 (I don't know why because I have a 3.9 write in my Gandi dashboard, maybe it's a part of the probleme) When I do django-admin startproject django_delights : bash: django-admin: command not found When I do python -m django startproject mysite : /usr/bin/python: No module named django (same with python3 When I do env : LC_ALL=C LD_LIBRARY_PATH=/opt/mysql-8.0/lib/x86_64-linux-gnu:/opt/mysql-8.0/lib/x86_64-linux-gnu LANG=C OLDPWD=/srv/data/web DB_VERSION=8.0 CUSTOMER_DIR=/srv/data container_ttys=/dev/pts/0 /dev/pts/1 /dev/pts/2 /dev/pts/3 SHELL_START=true MAX_MEM=256 DB_USER=hosting-db PREFIX=/ container=lxc LOCAL_DIR=/srv/run WWW_ENGINE=python PWD=/srv/data/web/vhosts/default HOME=/home/hosting-user SYS_USER=hosting-admin MYSQL_HOME=/srv/data/.config/mysql-8.0 TMPDIR=/srv/data/tmp PIP_LOG=/srv/data/var/log/www/pip.log DB_ENGINE=mysql PAAS=lamp0 PIP_BUILD_DIR=/srv/data/tmp/pip-build TERM=vt100 APP_USER=hosting-app0 PIP_SRC_DIR=/srv/data/tmp/pip-src PAAS_USER=hosting-user SHLVL=4 PYTHONPATH=/srv/data/web/vhosts/default/local/lib/python2.7 WWW_VERSION=3.9 NO_MOUNT=yes LOGROTATE_CONF=/srv/data/var/admin/logrotate.conf PHP_USER=hosting-user PATH=/usr/sbin:/usr/bin:/sbin/:/bin:/opt/python-3.9/bin:/opt/python-3.9/sbin:/opt/python-3.9/usr/bin:/opt/python-3.9/usr/sbin:/opt/mysql-8.0/bin:/opt/mysql-8.0/sbin:/opt/mysql-8.0/usr/bin:/opt/mysql-8.0/usr/sbin:/opt/sqlite-3/bin:/opt/python-3.9/bin:/opt/python-3.9/sbin:/opt/python-3.9/usr/bin:/opt/python-3.9/usr/sbin:/opt/mysql-8.0/bin:/opt/mysql-8.0/sbin:/opt/mysql-8.0/usr/bin:/opt/mysql-8.0/usr/sbin:/opt/sqlite-3/bin GITWEB_USER=hosting-user LD_PRELOAD= /usr/local/lib/gandi/gandi-preload.so DISTRIB=jessie _=/usr/bin/env Tell me if you need more infos :), thx again for your time. -
How to use multiple databases in Django with an empty 'default'?
I'm trying to make a multiple database project in Django. But I'm having problems to properly migrate my models to the appropriate database. I'm using the 'Writing your first Django app' tutorial as a starting point; so ... I've written the following database routers; this one for 'polls' app: class PollsRouter: route_app_labels = {'polls'} def db_for_read(self, model, **hint): if model._meta.app_label == 'polls': return 'Polls' return None def db_for_rite(self, model, **hint): if model._meta.app_label == 'polls': return 'Polls' return None def allow_relation(self, obj1, obj2, **hint): if ( obj1._meta.app_label == 'polls' or obj2._meta.app_label == 'polls' ): return True return None def allow_migrates(self, db, app_label, model_name=None, **hints): if app_label == 'polls': return db == 'Polls' return None Also the router class for 'devices' app: class DevicesRouter: route_app_labels = {'devices'} def db_for_read(self, model, **hint): if model._meta.app_label == 'devices': return 'CTS_ER_BD' return None def db_for_rite(self, model, **hint): if model._meta.app_label == 'devices': return 'CTS_ER_BD' return None def allow_relation(self, obj1, obj2, **hint): if ( obj1._meta.app_label == 'devices' or obj2._meta.app_label == 'devices' ): return True return None def allow_migrates(self, db, app_label, model_name=None, **hints): if app_label == 'devices': return db == 'CTS_ER_BD' return None And finally, the router class for 'auth_user' database (for native Django apps) class Auth_userRouter: route_app_labels = … -
Django - query Grand Children with Autofield as Primay Key
I have this model: class AnlieferungKopf(models.Model): kopfNr = models.AutoField(primary_key=True) firma = models.ForeignKey( Firma, default="-", on_delete=models.PROTECT, verbose_name = 'Firma', ) # more fields and methods class AnlieferungPosition(models.Model): posNr = models.AutoField(primary_key=True) kopfNr = models.ForeignKey( AnlieferungKopf, #to_field='kopfNr', on_delete=models.CASCADE, verbose_name = 'KopfNr', ) marke = models.ForeignKey( Marke, default="-", on_delete=models.PROTECT, verbose_name = 'Marke', ) # more fields and methods class AutoFoto(models.Model): fotoNr = models.AutoField(primary_key=True ) posNr = models.ForeignKey( AnlieferungPosition, on_delete=models.CASCADE, verbose_name = 'PositionNr',) autoImage = models.ImageField( verbose_name = 'Foto', upload_to = get_filename, default='autos/default.jpg' ) I want to query all the Autofoto objects from AnlieferungKopf. I tried this query AutoFoto.objects.filter(posNr__anlieferungkopf__id=224) I got this error 'django.core.exceptions.FieldError: Related Field got invalid lookup: anlieferungkopf' What is the correct syntax for the filter? Thank you -
How to resolve Key Error Exception when accessing dictionary key inside an if statement
I'm currently developing EV calculator using python and django. I get a key error exception when trying to access a dictionary key in an if statement inside a function. To break it down, my calculator function does the following, prompts the user for four input values, wager_amount, odd1, odd2 and odd_to_bet/back_odd, based on values user has entered, the function will output expected value or ev in jinja html. Something to note is, odd_to_bet/back_odd must either be equal to odd1 or odd2, if odd_to_bet/back_odd is either not equal to odd1 or odd2, the function has an else block with a message to tell the user to Please, check the odds again for any typo error!. An example: lets say the user inputs the following values from html form wager_amount = 10 odd1 = 1.54 odd2 = 2.47 odd_to_bet/back_odd = 1.54 This works fine, i'm able to display output without issues the key error exception arises when the user inputs and submits odd_to_bet/back_odd a value not either equal to odd1 or odd2. wager_amount = 10 odd1 = 1.54 odd2 = 2.47 odd_to_bet/back_odd = 1.52 My expected output should be "Please, check the odds again for any typo error!." displayed in the html. … -
User draw rectangle on leaflet map and post the coordinates on django form
I would like to create a djagno app, which will enable users to draw a rectangle on a leafet map and post the coordinates in order to create a vector. Firtsly I have created the form.py file: from django import forms class CoordinatesForm(forms.Form): lat_max = forms.FloatField() lat_min = forms.FloatField() lon_max = forms.FloatField() lon_min = forms.FloatField() I set the post method in the views,py file: if request.method == 'POST': form = CoordinatesForm(request.POST) and I have created a leaflet map: <form action="" method="post" enctype="multipart/form-data"> {% csrf_token %} <script type="text/javascript"> function map_init(map, options) { var drawnItems = new L.FeatureGroup(); map.addLayer(drawnItems); var drawControl = new L.Control.Draw({ edit: { featureGroup: drawnItems, }, draw: { circle: false, circlemarker: false, polygon: false, marker: false, polyline: false, } }); map.addControl(drawControl); } </script> {% leaflet_map "yourmap2" callback="window.map_init"%} <button type="submit">Submit</button> </form> Is there any way to submit the coordinates on click the button? -
URL and page refresh issue for Multilingual site on Django
plz help me to solve one issue. I have a Multilingual site on Django with standart internationalization framework. Settings.py MIDDLEWARE = [ ... 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware' ...] LANGUAGES = ( ('en', _('English')), ('ja', _('Japanese')), ) LANGUAGE_CODE = 'en' USE_I18N = True USE_L10N = True LOCALE_PATHS = ['../locale/'] All *.mo and *.po files for both languages are successfully created. main.html has a code snippet for language switching: {% get_current_language as CURRENT_LANGUAGE %} {% get_available_languages as AVAILABLE_LANGUAGES %} {% get_language_info_list for AVAILABLE_LANGUAGES as languages %} <div class="languages"> <p>{% trans "Language" %}:</p> <ul class="languages"> {% for language in languages %} <li> <a href="/{{ language.code }}/" {% if language.code == CURRENT_LANGUAGE %} class="active"{% endif %}> {{ language.name_local }} </a> </li> {% endfor %} </ul> </div> url.py urlpatterns = i18n_patterns( path('', include('mysite.urls')) ) simplified website structure main.html --page1.html --page2.html Now I can click and change the page translation, but I've faced with next issue. When I switch the language, e.g. from main/en/page1 I redirected back to the main/ja page, regardless my current location on a website structure. In other words, I'd like to stay at the same page1 when I switch the language and change only the language prefix main/en/page1 -> main/ja/page1. The best working example … -
How to change the database local to be in a cloud (Django)
I wrote a project in django framework and I use the local DataBase SQLite, and I now want to upload it to the cloud so other people who work with me can access DataBase i.e. when I create a user then that user will exist with my co-workers. Maybe someone has a guide on how to do this without modifying the DataBase so that I do not have to modify the rest of the code? -
HTML name/value button attribute not being sent via POST request to server
I am currently using HTMX and Django to process button clicks within a table that adds the selected item to a list. I have the following form code: <form action="" method="post"> {% csrf_token %} <button hx-post="{% url 'add-analysis' %}" hx-target="#analysis-list" type="submit" name="projectChoice" value="{{project.project_title}}">Add</button> </form> in my Views.py I am trying to parse the data with the following code: print(proj_name = request.POST.get("projectChoice")) This returns None however. To debug this I tried listing all of the POST requests to the server with the following: print(list(request.POST.items())) However this only returns the CSRF token, what am I doing wrong here? -
It shows, Field 'id' expected a number but got ''
When I submit then shows this error. views.py: class userINFOupdate(View): def get(self,request): userid = request.GET.get("user_up_id") username = request.GET.get('user_up_username') email = request.GET.get('user_up_email') phone = request.GET.get('user_up_phoneNumber') address = request.GET.get('user_up_address') obj = AJAXCRUD.objects.get(id=userid) print(userid) template: <input type="text" hidden name="user_up_id" id="user_hid_id" class="user_hidden_id"> -
Queryset filter to filter response that exactly contains the value as substring in django views
I have created filters that filter API responses, if the response contains at least one letter in the value as substring, I need to create a filter to filter responses that exactly contain the value as a substring in Django views. **Existing code in views.py** class UserSearchFilterAPIView(APIView): def get(self,request,*args,**kargs): queryset=Joineduserdatanew.objects.all() #Custom filter surname=self.request.query_params.get('surname',None) firstname=self.request.query_params.get('firstname',None) login=self.request.query_params.get('login',None) racfid=self.request.query_params.get('racfid',None) assignee=self.request.query_params.get('assignee',None) phonenumber=self.request.query_params.get('phonenumber',None) company_or_group=self.request.query_params.get('company_or_group',None) email=self.request.query_params.get('email',None) segment=self.request.query_params.get('segment',None) if surname: queryset=queryset.filter(surname__icontains=surname) if firstname: queryset=queryset.filter(firstname__icontains=firstname) if login: queryset=queryset.filter(login__icontains=login) if racfid: queryset=queryset.filter(racfid__icontains=racfid) if assignee: queryset=queryset.filter(assignee__icontains=assignee) if phonenumber: queryset=queryset.filter(phonenumber__icontains=phonenumber) if company_or_group: queryset=queryset.filter(company_or_group__icontains=company_or_group) if email: queryset=queryset.filter(email__icontains=email) if segment: queryset=queryset.filter(segment__icontains=segment) serializer=JoineduserdatanewSerialization(queryset,many=True) return Response(serializer.data) Example: if company_or_group is given as : "aaa" ,it returns results containing at least one 'a' but I need to filter that the company_or_group in the API response exactly containing "aaa" as a substring in that company_or_group field. -
Improperly configured error says I'll have to define env variable DJANGO_SETTINGS_Module .Please help me solving this problem
So I m just a newbie trying to learn django .. i was just trying to copy what Harry did(a youtuber who teaches code) but I got stuck right after creating the project file, the url.py file of my project keep showing me the error (django.core.exception. improperly configured request settings INSTALLED APP but settings are not config. You must either define the DJANGO_SETTINGS_MODULE or call setting config() before accessing settings.)I tried doing everything I could with the help of Google and YouTube but still not able to solve it . Can someone help me with this And it's on a mobile ide named pydroid 3. BELOW IS THE ERROR I M GETTING -
How to display extra context and form fields at the same time on django template using class based view?
I am trying to display some extra context on the page, but when I adding get_context_data method it is displayed context but not a forms fields. This is because when I click ulr that triggers view below there is get method by default or prior to forms fields? I don't understand why forms disappear when this method present in SolutionCreate view, indeed all context data displayed template {% extends "base.html" %} {% block content %} <div class="container"> <div class="row"> <div class="col-sm"> <form action="" method="POST"> <table> {% csrf_token %} {{ form.as_p }} </table> <input type="submit" class="btn btn-primary" value="Submit"> </form> </div> <div class="col-sm"> {{ context }} <h5>Problem:</h5> {% for pr in prb %} <h5>Problem: {{ pr.title }}</h5> <h6>Description</h6> <li class="list-group-item">{{ pr.description }}</li> <p> </p> <h6>Risks</h6> <li class="list-group-item">{{ pr.risks }}</li> <p> </p> <h6>Parts</h6> <li class="list-group-item">{{ pr.parts }}</li> <p> </p> <h6>Causes</h6> <li class="list-group-item">{{ pr.causes }}</li> <p> </p> <h6>Published</h6> <li class="list-group-item">{{ pr.published }}</li> <p> </p> <a href="{% url 'delete_problem' pr.pk %}" class="btn btn-warning" role="button" aria-pressed="true">Delete</a> <a href="{% url 'update_problem' pr.pk %}" class="btn btn-warning" role="button" aria-pressed="true">Update</a> <p> </p> {% endfor %} </div> </div> </div> {% endblock content %} view class SolutionCreate(CreateView): model = Solution template_name = 'analysis/create_solution.html' fields = [ 'problem', 'research', 'solutions', 'resources', 'plan', 'test' … -
Multiple Git push in one command
I've an application that requires to run git add/commit/push on each single file i'd like to push, in order to trigger a Gitlab Job on each. My problem is that git is actually taking many time to do the git push command. Here are the commands i'm using: git add myFile.json git commit myFile.json -m "commitMessage" variable1 = git rev-parse HEAD # Storing last commit hash into a variable # Pushing only one specific commit to (maybe) make it faster git push $variable1:master What i'd like to do is to make the whole process "faster". What i've thought about: Doing multiple pipeline triggers using only one git push (maybe by running the pipeline on each commit instead of each push), but it doesn't seem possible. Doing multiple pushes in one git push command, so it doesn't have to reload some of the git push init operations before each file pushed (i have no idea on what is happenning during the git push process, so that idea may be wrong) Does anyone has an idea on how to make this process faster, by using one of my ideas, or even a brand new one from you ! Thanks in advance ! -
How do i use Data from other model inside forms that is made with other model in django?
right now my template looks like this I wish to use those cards as the choices in the form that is on the right side. i am a newbie so i cant figure out how. is this possible so i could render the data from plans model in the forms that is built using my orders model. in the orders model i have used plans as a foreign key Forms.py class BuyPlanForm(forms.ModelForm): error_css_class = 'error-field' required_css_class = 'required-field' pack = forms.ModelChoiceField(Plans.objects.all(), widget=forms.RadioSelect()) class Meta(): model = Orders fields = ['pack'] my Views.py class UserBuyPlan(LoginRequiredMixin, View): template = 'plans/plan.html' success_url = reverse_lazy('home-home') def get(self, request): plans = Plans.objects.all() form = BuyPlanForm() ctx = { 'form': form, 'plans': plans, } return render(request, self.template, ctx) def post(self, request): form = BuyPlanForm(request.POST) form.instance.user = self.request.user if not form.is_valid(): ctx = {'form': form} return render(request, self.template, ctx) make = form.save() return redirect(self.success_url) my models.py class Plans(models.Model): plan_name = models.CharField(max_length=50) speed = models.IntegerField() price = models.FloatField() def __str__(self): return self.plan_name def get_deadline(): return dt.today() + timedelta(days=30) class Orders(models.Model): user = models.ForeignKey(CustomUser, primary_key=True, on_delete = models.CASCADE) pack = models.ForeignKey(Plans, on_delete = models.CASCADE) start_date = models.DateField(auto_now_add=True) end_date = models.DateField(default=get_deadline()) is_active = models.BooleanField(default=True) def __str__(self): name = str(self.user.username) return … -
Django static loaded but not used
Nginx web server serves static. Browser downloads static files but they don’t work. Why would that be? Loaded static files docker-compose volumes: django_static: services: nginx: build: context: . dockerfile: ./_nginx/Dockerfile container_name: webserver restart: unless-stopped volumes: - django_static:/app/staticfiles ports: - "80:80" - "443:443" depends_on: - backend backend: build: context: . depends_on: - postgres command: /gunicorn.sh entrypoint: /entrypoint.sh restart: always env_file: .env volumes: - django_static:/app/staticfiles ports: - "${CUSTOM_PORT}:8000" staticfiles config STATIC_URL = '/static/' MEDIA_URL = '/media/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') MEDIA_ROOT = os.path.join(BASE_DIR, 'media') STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static") ] -
How to allow .svg formated file in Wagtail images
I want to upload svg files in Wagtail images. Is it posible to do so. I used "wagtailsvg" but it generate extra table in database not the same image table. So simply I need to allow .svg formated file in images. Any siggestions? -
Problems with Django URL routing
I'm building a website, to be used in dental practices, however I'm having trouble with the URL routing. I'm wanting af URL pattern like: Denthelp/kartotek/#nameofclinic#/opretpatient. My suggestion looks like this: urls.py: path('kartotek/<str:kl_id>/', views.kartotek, name="kartotek"), path('kartotek/<str:kl_id>/opretpatient/', views.opretpatient, name="opret_patient"), Views. py: def kartotek(request, kl_id): kliniknavn = Klinik.objects.get(navn=kl_id) E_patient = kliniknavn.patient_set.all() context = { 'kliniknavn':kliniknavn, 'E_patient':E_patient} return render(request,'DentHelp/kartotek.html', context ) def opretpatient(request, kl_id): kliniknavn = Klinik.objects.get(navn=kl_id) form = PatientForm() if request.method == 'POST': form = PatientForm(request.POST) if form.is_valid(): form.save() return redirect('kartotek/<str:kl_id>/') context = {'form':form, 'kliniknavn':kliniknavn} return render(request,'DentHelp/kartotek/<str:kl_id>/opretpatient.html', context) When running code I get an OSError for the last line of code shown here. Have you guys have any advise for this to work? -
POST HTML FORM verificaton doesn't work with Django
I am currently learning Django,I connected my register FORM with my views.py, and wrote a little backend code, the problem, is that it links successfully with my .html file, and the POST elements are registering, but as I try to make a verification, (if POST_element < 10), it does nothing. Here is a part of my HTML Register FORM: <div class="limiter"> <div class="container-login100" style="background:black;"> <div class="wrap-login100"> <form action="{% url 'register' %}" method="POST" class="login100-form validate-form"> {% csrf_token %} <span class="login100-form-logo"> <i class="zmdi zmdi-landscape"></i> </span> <span class="login100-form-title p-b-34 p-t-27"> Register </span> <div class="wrap-input100 validate-input" data-validate = "Enter username"> <input class="input100" type="text" name="username" placeholder="Username"> <span class="focus-input100" data-placeholder="&#xf207;"></span> </div> Here is a part of my views.py that manages register: def register(request): if request.method=="POST": username = request.POST["username"] password = request.POST["pass"] password_confirm = request.POST["pass-confirm"] email = request.POST["mail"] if len(username) < 7: messages.error(request,"Username must be more than 10 char.") #Don't get any error else: messages.success(request,"Success") return render(request, 'users/register.html') Here is my urls.py: urlpatterns = [ path('', views.register, name='register'), path('login/', views.login, name='login') ] Thanks for your help! -
How to get data from Django Rest Framework to GoogleMaps in JS
I am trying to build web app which should get data from Django Rest Framework (using Serializer) and pass it to JavaScript and generate markers of GoogleMaps. When I fetched the data from Django API then JS return me 'Promise'. To create markers on GoogleMaps I need GeoJson object. Please for advice where is my mistake. Django serializer: class LocationList(generics.ListAPIView): model = Homes queryset = Homes.objects.all() serializer_class = LocationSerializer API url: HTTP 200 OK Allow: GET, HEAD, OPTIONS Content-Type: application/json Vary: Accept { "type": "FeatureCollection", "features": [ { "id": 7, "type": "Feature", "geometry": { "type": "Point", "coordinates": [ 19.2800748, 50.2004355 ] }, "properties": { "property_type": 1, "name": "Zagłoby", "surface": 140.0, "price": 5600000.0, "home_number": "11", "street": "Zagłoby", "post_code": "43-600", "city": "Jaworzno", "country": "Polska", "lat_maps": 50.2004355, "lng_maps": 19.2800748, "add_date": "2022-04-17T15:05:18.274352Z", "active": 2 } }, My JS code: var endpoint = 'api/location' async function getLocalization() { try { const response = await fetch(endpoint); return await response.json(); } catch (error) { console.log(error); } } async function renderLocalization() { let address = await getLocalization(); return address }; function initMap() { // The location of Uluru const uluru = { lat: -25.344, lng: 131.031 }; // The map, centered at Uluru const map = new google.maps.Map(document.getElementById("map"), … -
Getting a Bad Request when making a POST request in djangorestframework
I'm getting the following error when I try to make a POST request to the server; "detail": "JSON parse error - Expecting value: line 1 column 1 (char 0)" The request is successful when I POST null content or input in a dictionary, i.e {"content": "Hello world"}. Any kind of help in trying to debug this issue will be greatly appreciated My views.py @api_view(['POST']) @permission_classes([IsAuthenticated]) def tweet_create_view(request, *args, **kwargs): serializer = TweetCreateSerializer(content=request.data) if serializer.is_valid(raise_exception=True): serializer.save(user=request.user) return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) My serializers.py class TweetCreateSerializer(serializers.ModelSerializer): likes = serializers.SerializerMethodField(read_only=True) class Meta: model = Tweet fields = ['id', 'content', 'likes',] def get_likes(self, obj): return obj.likes.count() def validate_content(self, value): if len(value) > MAX_TWEET_LENGTH: raise serializers.ValidationError("This tweet is too long") return value