Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Getting JSON out of JSONfield in django
I'm using Django rest framework 3.9.1 and am trying to get just the JSON, in JSON format, from a JSONfield. My model looks like: class Metadata(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) data = JSONField() def __str__(self): return "%s %s" % (self.id) but when I get the data through an endpoint by calling: Metadata.objects.values('data') I get: [ { "data": "{\"name\":\"test1\"}" }, { "data": "{\"name\":\"test2\"}" } ] How do I return the raw JSON in the JSONfield in JSON format? so like: [ { "name":"test1" }, { "name":"test2" } ] -
Django http site serves media files but https site does not
Serving django media files on http site is OK. Serving django media files on https site is not working. I have the copied the alias and directories from the myproject_http.conf to myproject_https.conf. The media files are served on http site without any problems. HTTP conf: <VirtualHost *:80> ServerAdmin myproject.co@gmail.com DocumentRoot /home/ubuntu/bulbasaur/bulbasaur/ ServerName myproject.net ServerAlias www.myproject.net ErrorLog ${APACHE_LOG_DIR}/myproject_error.log CustomLog ${APACHE_LOG_DIR}/myproject_access.log combined Alias /media/ /home/ubuntu/bulbasaur/bulbasaur/media/ Alias /static/ /home/ubuntu/bulbasaur/bulbasaur/static_root/ <Directory /home/ubuntu/bulbasaur/bulbasaur/alpha> <Files wsgi_myproject.py> Require all granted </Files> </Directory> <Directory /home/ubuntu/bulbasaur/venv> Require all granted </Directory> <Directory /home/ubuntu/bulbasaur/bulbasaur/media> Require all granted </Directory> <Directory /home/ubuntu/bulbasaur/bulbasaur/static_root> Require all granted </Directory> WSGIDaemonProcess myproject.net python-home=/home/ubuntu/bulbasaur/venv/ python-path=/home/ubuntu/bulbasaur/bulbasaur/ WSGIScriptAlias / /home/ubuntu/bulbasaur/bulbasaur/alpha/wsgi_myproject.py process-group=myproject.net WSGIProcessGroup myproject.net </VirtualHost> HTTPS conf: <IfModule mod_ssl.c> <VirtualHost *:443> ServerAdmin myproject.co@gmail.com DocumentRoot /home/ubuntu/bulbasaur/bulbasaur/ ServerName myproject.net ServerAlias www.myproject.net ErrorLog ${APACHE_LOG_DIR}/myproject_error.log CustomLog ${APACHE_LOG_DIR}/myproject_access.log combined Alias /media/ /home/ubuntu/bulbasaur/bulbasaur/media/ Alias /static/ /home/ubuntu/bulbasaur/bulbasaur/static_root/ <Directory /home/ubuntu/bulbasaur/bulbasaur/alpha> <Files wsgi_myproject.py> Require all granted </Files> </Directory> <Directory /home/ubuntu/bulbasaur/venv> Require all granted </Directory> <Directory /home/ubuntu/bulbasaur/bulbasaur/media> Require all granted </Directory> <Directory /home/ubuntu/bulbasaur/bulbasaur/static_root> Require all granted </Directory> WSGIDaemonProcess myproject.net python-home=/home/ubuntu/bulbasaur/venv/ python-path=/home/ubuntu/bulbasaur/bulbasaur/ WSGIScriptAlias / /home/ubuntu/bulbasaur/bulbasaur/alpha/wsgi_myproject.py process-group=myproject.net WSGIProcessGroup myproject.net Include /etc/letsencrypt/options-ssl-apache.conf SSLCertificateFile /etc/letsencrypt/live/myproject.net/fullchain.pem SSLCertificateKeyFile /etc/letsencrypt/live/myproject.net/privkey.pem </VirtualHost> </IfModule> May I know what I got wrong? -
Django API - XMLHttpRequest cannot load
I get a XMLHttpRequest cannot load www.mysite.com/api-data due to access control checks. I have set up an api on my website and now I want to stream data from it. How can I solve this issue? Thanks -
ssl certificate for django project on heroku
I am learning how to create a app using django. i deployed my app on heroku(without credit card). now i need to add the functionality to sign up using any social media like github, but i am getting 'ERR_SSL_PROTOCOL_ERROR'. i tried getting free ssl certificate from CloudFlare but adding my webiste url 'https://udaydjangoproject.herokuapp.com' shows invalid domain and then i tried 'udaydjangoproject.herokuapp.com', then it shows not a registered domain. I don't have any credit card/debit card. is there any way to get get free ssl certificate from anywhere? -
NoReverseMatch at / Django template rendering
I have this problem and been stuck for few hours. NoReverseMatch at / Reverse for 'hotovo' with arguments '('',)' not found. 1 pattern(s) tried: ['hotovo/(?P[^/]+)$']. urls: urlpatterns = [ path('', views.index, name='index'), path('hotovo/<jedlo_id>', views.hotovo, name='hotovo') ] views: def hotovo(request, jedlo_id): jedlo = VyberJedla.objects.get(pk=jedlo_id) jedlo.vybrane = True jedlo.save() return redirect('') html: <h1><a href="{% url 'hotovo' jedlo.id%}" class="este_nie"> {{zoznam.nazov_jedla}}</a><input type="checkbox" name="cekbox"> . -
Which is a best book to start learning Django?
I want to learn more about how django handles databases, could you plz recommend me a good book for that..... -
Override function without if statement
Three models have ImageField which refers to one function, with if. Is there any suggestions how to perform this function without if? def upload_location(instance, filename): _, extension = os.path.splitext(filename) if isinstance(instance, (Story,)): return f'stories/{instance.id}/cover{extension}' elif isinstance(instance, (Episode,)): return f'stories/{instance.story.id}/{instance.index}/cover{extension}' elif isinstance(instance, (EpisodeSlide,)): return f'stories/{instance.episode.story.id}/{instance.episode.index}/{instance.id}{extension} -
How to use in Django a register form made with html and css
I have a responsive register and login made with HTML and CSS. I don't want to use the common register form and login that Django creates when you configure it. Summarizing my problem, I know how to make the register form in Django and configure it but I don't know how to apply my template on it. I've been reading about how to use templates on django but I still didn't figure out on how to use correctly in my case. My register html <!DOCTYPE html> <html lang="es"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <link href="https://fonts.googleapis.com/css?family=Manjari&display=swap" rel="stylesheet"> <link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous"> <link rel="stylesheet" href="reg.css"> <title>Document</title> </head> <body> <div class="back"></div> <div class="registration-form"> <header> <h1>Registrarse</h1> <p>Completa la información</p> </header> <form> <div class="input-section email-section"><input class="email" type="email" placeholder="Ingresa tu EMAIL aquí" autocomplete="off" /> <div class="animated-button"><span class="icon-paper-plane"><i class="fa fa-envelope-o"></i></span><span class="next-button email"><i class="fa fa-arrow-up"></i></span></div> </div> <div class="input-section password-section folded"><input class="password" type="password" placeholder="Ingresa tu CONTRASEÑA aquí" /> <div class="animated-button"><span class="icon-lock"><i class="fa fa-lock"></i></span><span class="next-button password"><i class="fa fa-arrow-up"></i></span></div> </div> <div class="input-section repeat-password-section folded"><input class="repeat-password" type="password" placeholder="Repita la CONTRASEÑA" /> <div class="animated-button"><span class="icon-repeat-lock"><i class="fa fa-lock"></i></span><span class="next-button repeat-password"><i class="fa fa-paper-plane"></i></span></div> </div> <div class="success"> <p>CUENTA CREADA</p> </div> </form> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <script src="reg.js"></script> </body> </html> -
Django model name with underscore?
I have subtly different entities that are important enough with respect to the relationships, flexibility, and expression of my schema that they warrant separate models. How should I name/ case these? a) Layerinput, Layerhidden, Layeroutput b) Layer_Input, Layer_Hidden, Layer_Output c) LayerInput, LayerHidden, LayerOutput Right now I am leaning option a so that Django doesn't do anything too automagically incorrect with them, but that won't look great in documentation and code. Will use them with either DRF or graphql. -
Why can't I find my static folder in my project
I'm working on a Django project and I can't see my static folder, I'm also having a problem displaying images. And when I inspect the image div in the src it's written unknown, Here's how I display the image from the admin ``<img class="rounded-circle account-profile" src="{{ user.Profile.profile_photo.url }}" alt="profile">`` User is the current user, the profile and then the name of the column. My folder structure is route-folder( project-folder, media-folder and app-folder ) My static settings ```STATIC_URL = '/static/' SITE_ROOT = os.path.dirname(os.path.realpath(__file__)) STATICFILES_DIRS = [ os.path.join(SITE_ROOT, "static/"), ]``` The Url: ```if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) -
Daphne error __call__() got an unexpected keyword argument 'scope' using systemctl
I'm running Daphne using systemctl and when doing sudo systemctl start daphne I'm getting this Oct 13 00:43:08 ip-172-31-18-50 daphne[24358]: 2019-10-12 19:43:08,907 ERROR [Failure instance: Traceback: <class 'TypeError'>: __call__() got an unexpected keyword argument 'scope' Oct 13 00:43:08 ip-172-31-18-50 daphne[24358]: /home/ubuntu/django_apps/startmexico/startmexicoenv/lib/python3.6/site-packages/autobahn/websocket/protocol.py:2801:processHandshake Oct 13 00:43:08 ip-172-31-18-50 daphne[24358]: /home/ubuntu/django_apps/startmexico/startmexicoenv/lib/python3.6/site-packages/txaio/tx.py:429:as_future Oct 13 00:43:08 ip-172-31-18-50 daphne[24358]: /home/ubuntu/django_apps/startmexico/startmexicoenv/lib/python3.6/site-packages/twisted/internet/defer.py:151:maybeDeferred Oct 13 00:43:08 ip-172-31-18-50 daphne[24358]: /home/ubuntu/django_apps/startmexico/startmexicoenv/lib/python3.6/site-packages/daphne/ws_protocol.py:82:onConnect Oct 13 00:43:08 ip-172-31-18-50 daphne[24358]: --- <exception caught here> --- Oct 13 00:43:08 ip-172-31-18-50 daphne[24358]: /home/ubuntu/django_apps/startmexico/startmexicoenv/lib/python3.6/site-packages/twisted/internet/defer.py:151:maybeDeferred Oct 13 00:43:08 ip-172-31-18-50 daphne[24358]: /home/ubuntu/django_apps/startmexico/startmexicoenv/lib/python3.6/site-packages/daphne/server.py:200:create_application daphne.service [Unit] Description=daphne service After=network.target [Service] WorkingDirectory=/ProjectDir Environment=DJANGO_SETTINGS_MODULE=settings.prod ExecStart=/ProjectDir/env/bin/daphne -b 0.0.0.0 -p 8001 config.wsgi:application Restart=always [Install] WantedBy=multi-user.target Module versions channels 2.3.0 Twisted 19.7.0 redis 2.10.6 daphne 2.3.0 The interesting part is that if I run manually from the env daphne -b 0.0.0.0 -p 8001 config.asgi:application` it's working without errors. Also if I change in daphne.service this line ExecStart=/ProjectDir/env/bin/daphne -b 0.0.0.0 -p 8001 config.wsgi:application to ExecStart=/ProjectDir/env/bin/daphne -p 8001 config.wsgi:application the error is not show, but of course the connection is not stablished. Any clue? -
How to get all Posts from Communities that User has joined in Django REST
So I have a User model, Community model, Post model and UserJoinedCommunity model. What I want to do is get all Posts from Communities that User has joined so I can display them on home page. UserJoinedCommunity model that controlls which user has joined which community: class UserJoinedCommunity(models.Model): """DB Model for users joined communities""" user = models.ForeignKey(User, on_delete=models.CASCADE) community = models.ForeignKey(Community, on_delete=models.CASCADE) class Meta: constraints = [ UniqueConstraint(fields=['user', 'community'], name="user-joined-community") ] def __str__(self): return f"{self.user.username}|{self.community.name}" Community and Post models are just simple models with fields like name, title etc. So now I would like to create a APIView or ViewSet that would return all posts from communities that user has joined. Something like this: class UserRelevantPosts(APIView): authentication_classes = (TokenAuthentication,) def get(self, request): user_relevant_posts = "?" return Response({'posts': user_relevant_posts}, status=200) Tell me if you need more code samples. -
How to display something in the web page when downloading file in Django
I am very very new to Django and i am getting my feet wet with it. I have a use case in which i want the user to download a file when they go to the home page of the Django website but at the same time i want to show some text as well. Below is the definition of my view: from django.http import HttpResponse def home(request): my_data = "<h1>This will be an attachement to download!</h1>" response = HttpResponse() response.content = my_data response['Content-Disposition'] = 'attachment; filename="<some-file>"' return response The issue is the file is getting downloaded but i cannot see anything getting printed to the screen . I mean i need this message (This will be an attachement to download!) to also be in the screen . I am sure i am doing some simple mistake but i cannot figure out what it is. Can someone please help me. -
Real-time Geolocation Tracking
I'm using the google maps javascript API to render a map. I'm using Python's Django v2 but the actual code for the API interaction and map creation is just Javascript. The client has have a fleet of trucks and I'd like to suggest a new feature: tracking the trucks' real-time location on the map. If each of the trucks had an tablet I imagine I could somehow get near-real-time geolocation information from that device. Question: Should I be trying to send geolocation info from the tablets to the server (if so how?) or should I be trying to GET/retrieve the geolocation from the tablets (if so how?)? Thinking of apps like Uber or Lyft what is the best practice/tried-and-true protocol to use with IOT & geolocation? -
Using PostgreSQL Arrayfield as ManyToMany -like lookup?
I have two models: class Authors(models.Model): name = models.CharField() class Books(models.Model): title = models.CharField() author_ids = ArrayField(Integerfield()) I would like to be able to look about the authors of the books by doing books.authors. Is there some way to do this? I can't seem to find a way to do this. This database is already prepopulated with the author_ids so reworking it to something else, like using an intermediary table, would be difficult. -
Django model allow multiple
So I want to create a model, let's say "Cars" I want to implement the field detail_name and detail_desc detail_name = models.CharField(max_length=200) detail_desc= models.CharField(max_length=200) But I want an admin to be able to add another detail_name and detail_desc if they wish to. How can I implement that? -
Inserting a Django URL into a custom email template
I'm trying to send a Django email in a custom template that I made for my site. However, I can't get the Django URL link to work properly. Without the template, I can get the link to work. The username works for reference. Does anyone know how to make this work? Here is my views.py: #This code is in the view that sends the email from django.core.mail import EmailMessage from django.core.mail import EmailMultiAlternatives from django.template.loader import get_template from django.template import Context subject, from_email = 'subject', '<info@mysite.com>' plaintext = get_template('email.txt') htmly = get_template('email.html') username = user.username d = { 'username': username } text_content = plaintext.render(d) html_content = htmly.render(d) msg = EmailMultiAlternatives(subject, text_content, from_email, [user.email]) msg.attach_alternative(html_content, "text/html") msg.send() This setup is based on this answer: Creating email templates with Django Here is the email.html file: <h3>Hi <strong>{{ username }}</strong>,</h6> <p> disown kvdsvnsdov vknvisodvnsdv dsdov siod vsd. Here is a link:</p> <a href="http://domain{% url 'home' %}">Check Now</a> Here is the email.txt: Hi {{ username }}, disown kvdsvnsdov vknvisodvnsdv dsdov siod vsd. Here is a link: http://domain{% url 'home' %} -
Redirecting buttons with values to other django templates/views
Firstly, I am getting a csv file from the user. (Template file:) <form method="post" action="{% url 'rowcol' %}" enctype="multipart/form-data"> {% csrf_token %} <input type="file" name="file" accept=".csv"> <button type="submit">Upload File</button> </form> Then i am generating a list of all the columns present in the file and then calling another html file. (views.py:) def rowcol(request): if request.method == 'POST': file = request.FILES['file'] dataset=pd.read_csv(file) lst=list(dataset) return render(request, 'Link5_rc.html', {'arr':lst}) return HttpResponse('') In that html file, i am creating buttons for all the columns present.(Link5_rc.html:) {% for link in arr %} <form action=" " method="post"> <button name="{{link}}" type="submit" value="{{link}}">{{link}}</button> </form> {% endfor %} Now the following is the part where i am stuck: I want these buttons to redirect to another html page or maybe a view in views.py , where i can show to the user which column he/she selected and then perform further actions on that particular column. -
How can I send javascript arrays values into django database
I'm working on a app were the user add activities and time and it will display it on a chart. But when I save an activity, it only save the last input. I want the user to save all the input as an array. I not sure how to proceed from there. I was thinking using a XMLhttpRequest but I'm getting a an error saying "rest_framework.exceptions.ParseError: JSON parse error - Expecting value: line 1 column 1 (char 0)" View.py import json from django.shortcuts import render from django.core import serializers from django.http import HttpResponse, JsonResponse from django.views.decorators.csrf import csrf_protect from page.templates.forms import ActivitiesForm from page.models import Activities from .serializers import ActivitiesSerializer from rest_framework.parsers import JSONParser from rest_framework.decorators import api_view from rest_framework.decorators import parser_classes @parser_classes([JSONParser]) @csrf_protect def page_list(request): if request.method == 'GET': activities = Activities.objects.all() serializer = ActivitiesSerializer(activities, many=True) return JsonResponse(serializer.data, safe=False) elif request.method == 'POST': data = JSONParser().parse(request) serializer = ActivitiesSerializer(data=data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data, status=201) return JsonResponse(serializer.errors, status=400) @csrf_protect def page_detail(request, pk): try: activities = Activities.objects.get(pk=pk) except Activities.DoesNotExist: return HttpResponse(status=404) if request.method == 'GET': serializer = ActivitiesSerializer(activities) return JsonResponse(serializer.data) elif request.method == 'PUT': data = JSONParser().parse(request) serializer = ActivitesSerializer(activities, data=data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data) return JsonResponse(serializer.errors, status=400) elif … -
Working with csv data for web development
I am trying to build a webpage which will display some data from a csv file. Preferably, I want to be able to load the csv data, and then able to select from the data and plot it. I am new to web-development, and have set-up a simple site using django. However, I cannot see the easiest way to access the data from the csv files in the html/js files. Are there any existing frameworks by which this can be done- dash seems like a potential candidate but I am unsure. Alternatively, it seems that I may be able to load csv files via the static files directory in django, but this also seems like a lot of hassle. Many thanks in advance. -
How to get JSON API response for call made from twilio?
I am unable to fetch the JSON response as shown in the tutorial. I have implemented a Programmable Voice program. I want to show the user the details of the call and if I get the JSON response I would be able to get all of them (cost, duration, status, etc). # views.py def start_campaign(request, campaign_id): try: campaign = Campaign.objects.get(pk=campaign_id) account_sid = 'XXX' auth_token = 'XXX' client = Client(account_sid, auth_token) phone_numbers = Contact.objects.filter(phone_book=campaign.phone_book) custom_url = 'http://XXX.ngrok.io/assets/' + str(campaign_id) for phone_number in phone_numbers: call = client.calls.create( method='GET', status_callback='http://XXX.ngrok.io/events', status_callback_event='completed', status_callback_method='GET', url=str(custom_url), to=str(phone_number), from_='+1XXX' ) detail = client.calls(str(call.sid)).fetch() print(detail.price) except Campaign.DoesNotExist: raise Http404("Campaign Does Not Exist") context = { 'all_campaigns': campaign } return render(request, "CallCenter/start_campaign.html", context) def events(request): status = request.GET.getlist('CallStatus', default=None) duration = request.GET.getlist('CallDuration', default=None) print("Duration:{}\nStatus:{}".format(duration, status)) return render(request, "CallCenter/events.html") In the terminal, I get a output which prints out the status and duration of the call from "GET /events?Called=%2BXX&ToState=&CallerCountry=US&Direction=outbound-api&Timestamp=Sat,+12+Oct+2019+19:11:50+%2B0000&CallbackSource=call-progress-events&SipResponseCode=200&Ca llerState=AL&ToZip=&SequenceNumber=0&CallSid=XXX&To=%2BXXX&CallerZip=35766&ToCountry=IN&CalledZip=&ApiVersion=2010-04-01&CalledCity=&CallStatus=completed&Duration=1&From= %2BXXX&CallDuration=5&AccountSid=XXX&CalledCountry=IN&CallerCity=ESTILLFORK&ToCity=&FromCountry=US&Caller=%2B12563804721&FromCity=ESTILLFORK&CalledState=&FromZip=35766&Fro mState=AL HTTP/1.1" 200 123 printing out Duration:['5', '5'] Status:['completed', 'completed'] Unfortunately, I don't know how to ask for the JSON response from Twilio. -
Efficiently synchronizing Django with localStorage (push notifications for a lot of JSON data)
I have an app that is heavily based on reading data from a database. The backend is written in Django and I am currently using django-rest-framework for the API through which I get my data. The frontend is written in React (without Redux at the moment). Since I need most of this data to be always up-to-date, whenever I load it, I store it in localStorage, and then take from there. This means that on page load, I load whatever is in localStorage, and, if necessary (a predefined timeout), I make a request to the server for fresh data. The issue with this is that since I am doing this for roughly 10 API endpoints right now, every 5 minutes, the number of requests to the server grows rapidly even when the data doesn't change. On top of that, I also check for notifications every 40 seconds, so 99% of my access log is just "GET /api/notifications/ HTTP/1.1" 200 2. The question: how do I make this more efficient for the server? I still want to have near-instant access to data when I load the page (so keep localStorage and just update it on demand) but I don't want to … -
Implement database transaction management in Django while using classes
In Django, I want to implement db transaction management that spans multiple methods in a class. I want to implement to types of transactions: status updates and inserts of data from a file. Transaction management should only involve the inserts from data that is read from a file. Status updates should always be written to a database, because these log whether the import was successful or has failed. Below is an example of my intended implementation. I cannot find a way to implement this transaction management. Does anyone have a suggestion? class ImportFile: def __init__(self, f): this.f = f # file path self.start_activity() self.read_file() self.end_activity() def start_activity(self): WRITE TO DATABASE THAT FILE f IS BEING IMPORTED def read_file(self): with open(this.f, 'r') as fi: for line in fi.readlines(): self.save_line_to_db(line) def save_line_to_db(self, line): STORE line IN DB def end_activity(self): 1. PERFORM SOME CHECK TO TEST INTEGRITY OF IMPORTED FILE. IF CORRECTLY IMPORTED: COMMIT, ELSE: ROLLBACK 2. WRITE TO DATABASE THAT IMPORT WAS SUCCESSFUL/FAILED -
How to retrieve data from Form to Views
i can't Retrieving data from my Form choices(nationality) to check the values. models.py NATIONALITY_CHOICES = (('1', 'خليجي'), ('2', 'ليس خليجي')) nationality = models.CharField(max_length=250, choices=NATIONALITY_CHOICES, null=True) when i check my fields in views it only redirect thank_you_not ! views.py def form_page(request): if request.method == 'POST': form = UserForm(request.POST) if form.is_valid(): form.save() if form.fields['nationality'].choices == 1: return redirect('LandingPage:thank_you') else: return redirect('LandingPage:thank_you_not') else: form = UserForm() posts = Article.objects.filter(published_date__lte=timezone.now()).order_by('published_date') return render(request, 'LandingPage/form_page.html', {'form': form, 'posts': posts,}) how can i solve it ? -
Please help me implement Student , Faculty Registration and login for my project
I have created two models : Student having attributes onetoonefeild(User),roll number , studyYear , Department Faculty having attributes onetoonefeild(User),Branch And I dont understand how to handle their Registration form , login form , .