Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django rest framework simple jwt custom handler not work with InvalidToken
I use drf simple jwt and works fine,but i need all data in json format, when the token is invalid django returns a default exception format (html, not in json): InvalidToken at /api/v1/data {'detail': ErrorDetail(string='Given token not valid for any token type', code='token_not_valid'), 'code': ErrorDetail(string='token_not_valid', code='token_not_valid'), 'messages': [{'token_class': ErrorDetail(string='AccessToken', code='token_not_valid'), 'token_type': ErrorDetail(string='access', code='token_not_valid'), 'message': ErrorDetail(string='Token is invalid or expired', code='token_not_valid')}]} I make my own exception handler according to this documentation: https://www.django-rest-framework.org/api-guide/exceptions/#custom-exception-handling but not working. How can i handle this exception to make a json response? i think about override django\core\handlers\exception class but i don't know how. -
How build page in django
I'm new in django. I wonder, how should i build many views in django? Actually i have code like that: views.py: # BACKEND from django.shortcuts import render from django.http import HttpResponse, HttpRequest # Create your views here. CSRF_COOKIE_SECURE = True postData: dict = {} # INDEX - MAIN PAGE def indexPage(request): print(postData) return render(request, "index.html") # REGISTER PAGE def registerPage(request): postData = request.POST But i think that the code can be wrapped by class, like below class ServiceMap(object): # INDEX - MAIN PAGE def indexPage(self): return render("index.html") def registerPage(self): return render("registerPage.html") def loginPage(self): return render("loginPage.html") # ETC class RequestHandler(object): postData = {} def captureRequest(self,request): postData = request.POST def getPostData(self): if self.__postData is not None: return postData else: postData = None return postData I don't sure then is a right approach, because i can't dealing with data become from POST request. I would like know , what is the most elegant way to build views. -
how to show datepicker in crispy forms?
i work with automated crispy forms and i want make datepicker for datefield i will show you my forms and register template thank you for your help #forms.py class ImmobRegistrationForm(ModelForm): class Meta: model = Immob fields = ['immo_code', 'immo_desig', 'immo_qte', 'immo_datemes','immo_cptimmob'] labels = { 'immo_code': _('Code immobilisation :'), 'immo_desig': _('Désignation :'), 'immo_qte': _('Quantité :'), 'immo_datemes': _('Date de mise en service :'), 'immo_cptimmob': _('Compte comptable :') } def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper() self.helper.layout = Layout( Row( Column('immo_code', css_class='form-group col-md-3 mb-0'), Column('immo_desig', css_class='form-group col-md-6 mb-0'), Column('immo_qte', css_class='form-group col-md-3 mb-0'), css_class='form-row' ), Row( Column('immo_datemes', css_class='form-group col-md-6 mb-0'), Column('immo_cptimmob', css_class='form-group col-md-6 mb-0'), css_class='form-row' ), Submit('submit', 'Enregistrer') ) #register.html {% extends 'base.html' %} {% load crispy_forms_tags %} {% block content %} {% crispy form %} {% endblock %} -
Django template, how to call two model in one table html
There my template the second variable shows the aligned data, it does not continue below with the row: <table class="table user-list"> <thead> <tr> <th class="text-center"><span>Produktet</span></th> <th>buy</th> <th>sell</th> </tr> </thead> <tbody> {% for produkti in produktblerje %} <tr> <td>{{ produkti.choice_text }}</td> <td>{{ produkti.totals }}</td> <td> {% for produkti in produktshitje %} {{ produkti.totals }} {% endfor %}</td> </tr> {% endfor %} </tbody> </table> -
How to implement Zappa Django Cognito authentication
I am developing a Django app and using Zappa to deploy on AWS. I could not find any tutorial to implement the integration with AWS Cognito. I've found some people on StackOverflow saying they have implemented, but none of them available to provide some way of learning/getting it through. Any help would be much appretiated. Thanks.. -
Can't get gunicorn service to start with socket
I have a Django and Gunicorn setup. If I start the Gunicorn service from the command line like this: gunicorn --bind 0.0.0.0:8000 first.wsgi from the following working directory: ~/code/firstdjangoproject/first everything works as expected. However when I try to setup a service with systemd for gunicorn with the following gunicorn.service configuration: [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=pi Group=www-data WorkingDirectory=/home/pi/firstdjangoproject ExecStart=/usr/local/bin/gunicorn \ --access-logfile - \ --error-logfile - /home/pi/error.log \ --workers 3 \ --bind unix:/run/gunicorn.sock \ first.wsgi:application [Install] WantedBy=multi-user.target I get the following error when trying to access the site with curl --unix-socket /run/gunicorn.sock localhost: curl: (56) Recv failure: Connection reset by peer When I look at the logs sudo systemctl status gunicorn I get the following: ● gunicorn.service - gunicorn daemon Loaded: loaded (/etc/systemd/system/gunicorn.service; disabled; vendor preset: enabled) Active: failed (Result: exit-code) since Mon 2019-09-30 22:14:14 CEST; 7s ago Process: 3070 ExecStart=/usr/local/bin/gunicorn --access-logfile - --error-logfile - /home/pi/error.log --workers 3 --bind uni Main PID: 3070 (code=exited, status=210/CHROOT) sep 30 22:14:14 raspberrypi systemd[1]: Started gunicorn daemon. sep 30 22:14:14 raspberrypi systemd[1]: gunicorn.service: Main process exited, code=exited, status=210/CHROOT sep 30 22:14:14 raspberrypi systemd[1]: gunicorn.service: Unit entered failed state. sep 30 22:14:14 raspberrypi systemd[1]: gunicorn.service: Failed with result 'exit-code'. sep 30 22:14:14 raspberrypi systemd[1]: gunicorn.service: … -
geodjango - construct json from foreigk key geometry
I'm trying to visualize a webmap with a django model whose geometry info is a foreign key, I've tried to update the value with a funtion to contruct a json and call the foreign key, but -I got this error: SyntaxError: expected expression, got '<' it read the json literally the type of the foreignkey object: 'coordinates': []}, how can I turn the foreignkey object as a lat and long value and insert in the json function? models.py class Info_Proy_eyd(models.Model): nom_proy = models.CharField(max_length=50) rol_fk = models.ForeignKey(D_Base_Roles, on_delete=models.CASCADE, blank=True, null=True, verbose_name="Rol") def json(self): return { 'nombre_proy':self.nombre_proyecto, 'geom':self.rol_fk.geom, } views.py def map_eyd(request): serie_t = Info_Proy_eyd.objects.all() json_s = [] for t in serie_t: json_s.append(Info_Proy_eyd.json(t)) p_json = { "type": "FeatureCollection", "features": [ { "type": "Feature", "geometry" : { "type": "Point", "coordinates": [d["geom"]], }, "properties" : d, } for d in json_s] } return render(request, 'b_seco_eyd/mapa_eyd.html', {'serie_t':serie_t, 'p_json':p_json, 'json_s':json_s}) page.html leaflet js var proy_eyd = {{p_json|safe}}; var mrk = L.geoJson(proy_eyd , { style: { } } ).addTo(map); thanks -
Why is Heroku running dev.py by force in Wagtail?
I deployed my Wagtail app on Heroku and want the variable 'DEBUG' to be False on production. I wrote some code in an init.py file that tests an environment variable 'ENV' to decide which python file to execute. In production, it should execute only production.py, but it does not. The code actually seems to work because it is not printing my debug message in the case i'm in the development environement, but somehow, dev.py is executed after production.py I tried removing the variable 'DEBUG' from both files (production.py and dev.py) to put them in init.py and define its value according to the environment. It works, DEBUG becomes False in production but it seems like my static files aren't loaded anymore. #__init__.py import os ENV = os.getenv('GLITCHYWARE_ENV', 'dev') if ENV == 'dev': print('DEV') from .dev import * elif ENV == 'prod': print('PROD') from .production import * The log: $ python manage.py collectstatic --noinput PROD The production.py code is executed The dev.py code is executed #1 As you can see, dev.py is executed after production.py, not six times though, i just put many print statements. -
Django: Q Objects concatenation
Been trying to filter with Q Objects and be able to search for "Firstname" + "Lastname", but only able to search for one or the other. Could anyone tell me what I'm doing wrong? Evaluation search view For clarification: ma = employee number fornavn = firstname efternavn = lastname fagnavn = subject name aktivitetnavn = aktivity name vuderingsnavn = grade delingnavn = department (integer) class SearchEvalueringer(ListView): model = Evaluering template_name = 'evalsys/categories/søg_evalueringer.html' def get_queryset(self): query = self.request.GET.get('q') if len(query) > 1: eval_list = Evaluering.objects.filter( Q(ma__ma__regex=query) | Q(ma__fornavn__iregex=query) | Q(ma__efternavn__iregex=query) | Q(fagnavn__fagnavn__iregex=query) | Q(aktivitetnavn__aktivitetnavn__iregex=query) | Q(vuderingsnavn__vuderingsnavn__iregex=query) | Q(ma__holdnavn__holdnavn__iregex=query) ) else: eval_list = Evaluering.objects.filter( Q(ma__delingnavn__delingnavn__exact=query) ) return eval_list I tried doing this: Q(ma__fornavn__iregex=query) & Q(ma__efternavn__iregex=query) But this does not let me search for "John Smith" still only "John" or "Smith". -
"[Errno 8] nodename nor servname provided, or not known" when using django-ses
I'm trying to plug django-ses into my project. I've followed instructions laid out in this tutorial: https://kholinlabs.com/the-easiest-way-to-send-emails-with-django Although I believe I've followed these closely, when sending a test email I receive this error: File "/usr/local/Cellar/python/3.6.5_1/Frameworks/Python.framework/Versions/3.6/lib/python3.6/socket.py", line 745, in getaddrinfo for res in _socket.getaddrinfo(host, port, family, type, proto, flags): socket.gaierror: [Errno 8] nodename nor servname provided, or not known I've successfully registered with SES and validated the email I'm using to send. The error occurs either when sending from the python console or from the app. These are my relevant settings: EMAIL_BACKEND = 'django_ses.SESBackend' AWS_SES_REGION_NAME = 'eu-west-2' AWS_SES_REGION_ENDPOINT = 'email.eu-west-2.amazonaws.com' AWS_SES_ACCESS_KEY_ID = '{secret key}' AWS_SES_SECRET_ACCESS_KEY = '{secret access key}' AWS_SES_AUTO_THROTTLE = 0.5 How can I fix this? -
Django: Attempting to write a string directly into FileField, when backed by Amazon S3
I am attempting to write a string directly into a Django FileField by way of ContentFile. In doing so, I get a reproducible TypeError: Unicode-objects must be encoded before hashing error when attempting to save the contents of this file to the database, which traces through the s3boto3 lib. The exact source of this error is difficult to suss out. But let's state the question plainly, in Python 3, on Django 2.2.x, what is the correct way to take a csv file created with the csv lib from Python, and save that into a Django FileField backed by Amazon S3? Example code producing the error in question, truncated for privacy and relevance def campaign_to_csv_string(campaign_id): csv_string = io.StringIO() campaign = Campaign.objects.get(pk=campaign_id) checklist = campaign.checklist completed_jobs = JobRecord.objects.filter(appointment__campaign=campaign) writer = csv.writer(csv_string) # A bunch of writing to the writer here # string looks good at this point return csv_string.getvalue() calling function csv_string = campaign_to_csv_string(campaign_report.campaign.pk) campaign_report.last_run = datetime.datetime.now() campaign_report.report_file.save(str(campaign_report_pk) + '.report', ContentFile(csv_string)) campaign_report.processing = False campaign_report.save() My guess here is that s3boto3 is taking issue with ContentFile but the debugging information sent back to me gives me no clear path forward. -
Request headers in APITestCase
I have a test (APITestCase), and I need to specify custom headers: class ListAppsAPITest(APITestCase): def test_list_apps_versions(self): response = self.client.get(reverse('api:applications:list'), None, **{'Device-Id': 'deadbeef'}) I've tried different combinations of arguments, but it did not work. How to specify custom headers in tests? -
How do I create a persistent volume in docker for my postgresql database?
I am creating a docker image of a Django server that uses a postgresql database to keep track of login information, uploaded/downloaded files, etc. I want the data in my database to stick around even when I exit and relaunch the docker image. I created a docker-compose file and entrypoint file that successfully launches the server docker image and creates a volume for the database. Every tutorial that I've read online has said that having persistent data is as simple as mapping your database volume from the location you want it stored on the host to the /var/lib/postgresql/data location in the docker image. docker-compose.yml: version: '3.7' services: web: build: ./ command: python manage.py runserver 0.0.0.0:8000 ports: - 8000:8000 environment: - DEBUG=1 - SECRET_KEY=foo - SQL_ENGINE=django.db.backends.postgresql - SQL_DATABASE=app_db - SQL_USER=app_user - SQL_PASSWORD=changeme - SQL_HOST=db - SQL_PORT=5432 - DATABASE=postgres depends_on: - db db: image: postgres volumes: - ./postgres_data:/var/lib/postgresql/data/ environment: - POSTGRES_USER=app_user - POSTGRES_PASSWORD=changeme - POSTGRES_DB=app_db ports: - 5432:5432 volumes: postgres_data: docker-entrypoint.sh: #!/bin/sh if [ "$DATABASE" = "postgres" ] then echo "Waiting for postgres..." while ! nc -z $SQL_HOST $SQL_PORT; do sleep 0.1 done echo "PostgreSQL started" fi python manage.py flush --no-input python manage.py migrate exec $@ Dockerfile: FROM python:3.7.4-alpine ARG PROJECT=EchoNine ARG … -
django-ckeditor - cannot edit image size
I've an instance of django-ckeditor where I seem unable to change image sizes. Quite simple the popup allows me to select and load images BUT I cannot resize them or set any of the properties (height, width, border, hspace, vspace, alignment). I am loading the form with ajax which I mention simply because I don't know if that has an impact -
Use django forms to create a new file
I apologize if this is obvious, but I'm relatively new to Django and couldn't find any resources for this. Goal I would like to create unique invoices that are stored on my server (or a CDN) when a form is filled out. Question Would it be possible to use Django forms to create an HTML file with a unique URL (or upload the newly created file to AWS) I understand how to upload files, I just can't quite figure out how to create a new file using a form. -
Can I serialize in Django without knowing the field name?
If there is a better approach to solving this problem than what I am attempting, please let me know. I have a Django web app where people can get pre-signed urls from s3 for viewing and uploading files. After the backend does some work, it returns JSON, part of which is an dictionary that ha key/value pairs in this format: {filename: s3-pre-signed-url}. Because the file name is different every time, I don't know how to set up my serializer. Is there an easy way to build a serialzier that accounts for different field names like this? I realize that another solution would be to reformat the object I am passing to the serializer. I could create a dictionary that has a fileName and s3URL field, and then build a serializer that looks for both of those fields. For example, if I create a dictionary with one key/value pair, the key being urls and the value being my dictionary with the key/value pairs, like this: urls = {'urls': name_and_url_dict}, and pass it to this serializer: class UrlSerializer(serializers.Serializer): urls = serializers.ListField(child=serializers.CharField()) I get a response (from Postman) like this: { "9": "Long Thought", "10": "Feeling", "11": "Memory", "12": "attachment test", "15": "Document … -
Django Messages - Message to all / specific users
Is it possible to configure Django Messages in a way so that the message is shown to all and or specific users? -
Django: NoReverseMatch but URL and keywords are there
I'm setting up an activation system so when a user registers, he receives an email with the activation link in it. For some kind of reason, it keeps throwing me a NoReverseMatch when I'm trying to generate the activation URL inside the email. What is strange, is that this does work on my local version of the project, but when deployed to my webserver it is throwing this error. So, what happens, when a user gets registered he is being sent an activation email: # views.py # User registers here def registreren(request): # .... f.is_active = False f.save() # Send the mail sendActivationEmail(request, f) def sendActivationEmail(request, user): data = { 'user': user, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': account_activation_token.make_token(user), } sendEmail(request, 'XXX: activeer uw gebruiker', user.email, 'registration/activation_email.html', data) # Helper function for sending the email def sendEmail(request, subject, to, template, data): current_site = get_current_site(request) data['domain'] = current_site.domain html_message = render_to_string(template, data) plain_message = strip_tags(html_message) send_mail(subject, plain_message, 'XXX <' + settings.EMAIL_HOST_USER + '>', [to], html_message=html_message) This all works as expected. But when I try to render the template: XXX Hey {{ user.get_short_name }}, Bedankt voor je inschrijving bij het online inschrijvingssysteem van XXX. Om jouw registratie te confirmeren, kan je klikken op de volgende … -
Not Recieving Email Id in User Model in admin section when using social-auth-django for authentication
Here is my pipeline. I want to use the default User for now. SOCIAL_AUTH_PIPELINE = ( 'social_core.pipeline.social_auth.social_details', 'social_core.pipeline.social_auth.social_uid', 'social_core.pipeline.social_auth.auth_allowed', 'social_core.pipeline.social_auth.social_user', 'social_core.pipeline.user.get_username', # 'social_core.pipeline.mail.mail_validation', #I don't need it. # 'social_core.pipeline.social_auth.associate_by_email', 'social_core.pipeline.user.create_user', 'social_core.pipeline.social_auth.associate_user', 'social_core.pipeline.social_auth.load_extra_data', 'social_core.pipeline.user.user_details', 'accounts.pipeline.save_profile', ) Scopes SOCIAL_AUTH_FACEBOOK_SCOPE = [ 'email', 'user_friends', ] SOCIAL_AUTH_FACEBOOK_PROFILE_EXTRA_PARAMS = { 'fields': 'id,name,email', } accounts/pipeline.py I just wanted to know what the response is. Here is the response: {'id': '521205608677881', 'name': 'Rishabh Jain', 'access_token': 'EAAFF2gP28aQBALgmqXQhM4eKKaAJ9mhLj76S9cYgVYniWAC1KsQI1ML8BZBhOxRpP7UIjOaZBUfNfd9awFzY4S6RlhcmfKLxEsPsAbSdQcld2vQhJmWmX1z3Ww7iG0kKAcJVFvoADsrmPDgikPiaAp9cgTjYIu5MuwYQvHAQZDZD', 'expires': 5183744, 'granted_scopes': ['user_friends', 'email', 'public_profile']} Clearly the granted scopes include the email-id. But I am not able to see the email-ids in the User in Django/admin. I know I should create a new question, but in case you can help. I want to know if the user logging in using fb is coming on the website first time or not so that I can greet him. Any variable in User or User Social Auth to do so. -
Language switcher list without button
I am trying to make a list of available languages and I am not able to as close I got to was this but the language upon choosing is not being changed, the page refreshes but nothing. <form action="/i18n/setlang/" method="post" style="display: inline;">{% csrf_token %} <div style="display: inline;"> <select name="language" onchange="javascript:form.submit()"> {% for lang in LANGUAGES %} <option value="{{ lang.0 }}"{% ifequal LANGUAGE_CODE lang.0 %} selected="selected"{% endifequal %}>{{ lang.1 }}</option> {% endfor %} </select> </div> </form> I get this error in log POST /i18n/setlang/ HTTP/1.1" 302 0 I have tried to make it as a list with button but thats just ugly to have a button to change the language with. -
What's wrong with my indentation at server?
Everything works on my local machine but when I uploaded my project at server I'm getting this error at second "if" statment line: TabError at /home/ inconsistent use of tabs and spaces in indentation def scrape_weather(request): if request.method == 'POST': old_weather = Weather.objects.all() old_weather.delete() api_adress = "http://api.openweathermap.org/data/2.5/weather?q=" api_key = "***" city = request.POST.get("city") url = api_adress + city + api_key if url == (api_adress + api_key): url = api_adress + "warsaw" + api_key json_data = requests.get(url).json() new_weather = json_data['weather'][0]['main'] degree_kelvin = int(json_data['main']['temp']) degree = degree_kelvin-273 pressure = json_data['main']['pressure'] new_weather = Weather() new_weather.degree = degree new_weather.pressure = pressure new_weather.weather = new_weather new_weather.save() return redirect('/home/') -
What should I do and learn after Django Basics?
I have learnt basics and more than basics(I guess) of django. I can make a blogging website,Ecommerce Website(without payment option).I have knowledge of HTML,CSS,Sass,javascript.Now I want to learn and do more things and I want to make a facebook clone using Django. It will have systems including liking and commenting without reloading pages,security,2 step verification,ID deactivating etc.Please suggest me what should I need to learn to make that project. -
How to manage to serve media files with Django, Nginx, Docker and Traefik?
I'm trying to upload and persist media files (images, pdfs) in an application with Django. It's working fine in development mode, but I'm getting a "404 Not Found The requested URL /mediafiles/images/test.jpg was not found on this server." when deployed on a server. "Funny" thing to note : I manage to upload files, I see them on my host, and both containers (nginx and webserver), but whenever I try to access them I get the Not Found error. I've read and tries many things without success such as modifying the nginx conf file, playing with the docker-compose file.. would you have any idea where I should look from now on? Here's what I think are pertinent informations : Server : Ubuntu 16.04 Docker-Compose services: nginx: image: nginx depends_on: - webserver volumes: - ./config/nginx/conf.d:/etc/nginx/conf.d - ./static:/usr/share/nginx/html:ro - ./mediafiles:/mediafiles labels: - "traefik.backend=${TRAEFIK_HOST}_static" - "traefik.frontend.rule=Host:${TRAEFIK_HOST}; PathPrefixStrip: /static/" - "traefik.enable=true" - "traefik.port=80" webserver: image: ${MY_IMAGE} volumes: - ./static:/tmp/html/static - ./mediafiles:/code/server/mediafiles labels: - "traefik.backend=${TRAEFIK_HOST}" - "traefik.frontend.rule=Host:${TRAEFIK_HOST}" - "traefik.enable=true" - "traefik.port=8000" volumes: mediafiles: Nginx Config server { listen 80; server_name localhost; location / { root /usr/share/nginx/html; index index.html index.htm; } error_page 500 502 503 504 /50x.html; location = /50x.html { root /usr/share/nginx/html; } location /mediafiles { … -
Django Calculate Average From Model Fields and Store in Another Model
I have a model where I hold at least 3 scores, but which in the future may hold more. The scores can be blank or contain a value, meaning different schools can have a different number of entries. My challenge is I'd like then to have a field that's based off a function of the above scores so I can call this on my views rather than have to calculate it every time. I'm trying to find the best way to ensure that the main score is calculated and saved every time one of the contributing scores is updated, but only then. class Marks(models.Model): school = models.ForeignKey(School, null=True, on_delete=models.SET_NULL) marks_2016 = models.DecimalField(name='2016 Marks', max_digits=12, decimal_places=3, blank=True, null=True) marks_2017 = models.DecimalField(name='2017 Marks', max_digits=12, decimal_places=3, blank=True, null=True) marks_2018 = models.DecimalField(name='2018 Marks', max_digits=12, decimal_places=3, blank=True, null=True) def __str__(self): return self.school.name class Score(models.Model): school = models.ForeignKey(School, null=True, on_delete=models.SET_NULL) score = models.DecimalField(max_digits=5, decimal_places=2) def __str__(self): return self.school -
Static file not load in django template?
Problem is STatic file not load. CRM/ | |-- CRM/ | |-- next_crm/ | |-- static/ | | +-- css/ | | +-- bootstrap.min.css <-- here | +-- manage.py This is my static variables defined in the next_crm/settings/settings.py file. STATIC_ROOT = '' STATIC_URL = '/static/' STATICFILES_DIRS = [os.path.join(BASE_DIR, "static")]