Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django React CSRF Issues
Building my first app using Django as back end and React as front end. Locally, I have both running on port 8000 and 3000 respectively. I have a short snippet of code I found online to help me test whether or not my CSRF and CORS policies are set correctly: const API_HOST = 'http://localhost:8000'; let _csrfToken = null; async function getCsrfToken() { if (_csrfToken === null) { const response = await fetch(`${API_HOST}/csrf/`, { credentials: 'include', }); const data = await response.json(); _csrfToken = data.csrfToken; } return _csrfToken; } async function testRequest(method) { const response = await fetch(`${API_HOST}/ping/`, { method: method, headers: ( method === 'POST' ? {'X-CSRFToken': await getCsrfToken()} : {} ), credentials: 'include', }); const data = await response.json(); return data.result; } class App extends Component { constructor(props) { super(props); this.state = { testGet: 'KO', testPost: 'KO', }; } async componentDidMount() { this.setState({ testGet: await testRequest('GET'), testPost: await testRequest('POST'), }); } render() { return ( <div> <p>Test GET request: {this.state.testGet}</p> <p>Test POST request: {this.state.testPost}</p> </div> ); } } export default App; When I run this code locally, I get the correct response which is, the "KO" gets changed to "OK" when the responses come back valid. This only works … -
SQL Query logic to Django ORM Query logic
I have tried to think about how the following SQL query would be structured as a Django ORM query but I have had no luck in my multiple attempts. Can anyone help? SELECT targets_genetarget.gene, count(targets_targetprediction.gene) as total FROM targets_genetarget LEFT OUTER JOIN targets_targetprediction on targets_targetprediction.gene = targets_genetarget.gene WHERE list_name LIKE %s GROUP BY targets_genetarget.gene -
Looping through list to store variables in dictionary runs in error
What I want to do: Get user input from HTML form, store input in variables within Django and perform calculations with variables. To accomplish that, I use following code: my_var = requst.POST.get('my_var') To prevent having 'None' stored in 'my_var' when a Django page is first rendered, I usually use if my_var == None: my_var = 1 To keep it simple when using a bunch of variables I came up with following idea: I store all variable names in a list I loop through list and create a dictionary with variable names as key and user input as value For that I wrote this code in python which works great: list_eCar_properties = [ 'car_manufacturer', 'car_model', 'car_consumption',] dict_sample_eCar = { 'car_manufacturer' : "Supr-Duper", 'car_model' : "Lightning 1000", 'car_consumption' : 15.8, } dict_user_eCar = { } my_dict = { 'car_manufacturer' : None, 'car_model' : None, 'car_consumption' : None, } for item in list_eCar_properties: if my_dict[item] == None: dict_user_eCar[item] = dict_sample_eCar[item] else: dict_user_eCar[item] = my_dict[item] print(dict_user_eCar) Works great - when I run the code, a dictionary (dict_user_eCar) is created where user input (in this case None simulated by using a second dictionary my_dict) is stored. When User leaves input blank - Data from dict_sample_eCar … -
Django/Ajax/Javasdript JSON.parse convert string to JavaScript object
I am using Ajax to to send a get request from the sever, i am querying and getting a particular product from the product model, i want to return result as JavaScript objects but its return this '{' as i try to access the first value from the responseText[0]. How can i convert data return to js object. here is my code views.py def edit_product(request): product_id = request.GET.get('product_id') print('THIS IS PRODUCT ID ', product_id) product = Product.objects.get(pk=product_id) data = [ { 'name':product.name, 'brand':product.brand, 'price':product.price, 'description':product.description } ] return HttpResponse(data) ajax.js function getProductEditId(product_id){ //alert(id) document.getElementById('gridSystemModalLabel').innerHTML='<b> Edit product </b>'; //change modal header from Add product to Edit product var request = new XMLHttpRequest(); request.open('GET', '/edit_product/?product_id=' + product_id, true); request.onload = function(){ console.log('hello world', product_id) //var data = request.responseText var data = JSON.parse(JSON.stringify(request.responseText)); console.log(data[0]) } request.send(); } -
How can I redirect to a Thank you for contacting us page after user submits a form with Django?
I need to redirect the user to a new page that says, "Thank you for contacting us" after submitting a form with Django. I have tried using HttpResponseRedirect, reverse but I don't know how to implement it to all of the necessary files of my project.enter image description here When I click submit, it sends the data to the Django database so the form does work but the user does not know that because after they click submit it doesn't redirect to a thank you page. -
how to fix Argument 'api_key' passed by position and keyword in constructor call
i'm connecting my django web app with airtable api and i have two error one on my editor vscode [Argument 'api_key' passed by position and keyword in constructor call] and thr second in CMDER [init() got multiple values for argument 'api_key'] here is my code AT = Airtable(os.environ.get('AIRTABLE_MOVIESTABLE_BASE_ID'), 'Movies', api_key=os.environ.get('AIRTABLE_API_KEY')) -
Media files are not loading properly in the template (HTML <img>). Static files / images are working correctly
Media files are not loading properly when pulling from database. Although, when inspecting page, source seems to be correct. I have preformed migrations, collectstatic. static files are loaded to the html file settings.py STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') urls.py urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^', cars.views.index_page, name='index_page'), ] urlpatterns += static(settings.STATIC_URL, documnet_root = settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, documnet_root = settings.MEDIA_ROOT) models.py nuotrauka = models.ImageField(default='default.jpg', blank=True) index.html {% for detail in carDetails %} <img src="{{detail.nuotrauka.url}}" alt="detail-image"> {% endfor %} Image is simple not loading. It seems like image src is not able to locate the image. I might be just simple missing something but at this point I am not able to see it. -
How to connect with postgresql database after deployment to Heroku?
I'm new to Django but I'm deploying a Django-based website to Heroku, using Postgresql. The deployment was successful, and the website is online. However, the front page should populate with some data from my database, but currently does not. I checked the database state, and it is available, with my data migrated successfully from my local database to the database on heroku. I'm assuming that the problem is that I didn't update my database settings, specifically the name of the database. Since heroku assigns a new database name once it's migrated, do you have to update the NAME to the heroku-given database name (e.g. postgresql-sample-27522)? I've tried using dj_database, because that is supposed to automatically update the database setting once it's deployed to Heroku. However, that doesn't work. How do I properly update the database settings so that my webpage properly retrieves data from the database, as it does on my localhost? Thank you in advance Here is my current database setting: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'sample_database', 'USER': 'sample_user', 'PASSWORD': 'sample_database', 'HOST': 'localhost', 'PORT': '5432', } } -
Django simple form request 'GET', datefield validation error
So I have a simple listview and override the queryset to include form fields for the user to search for specific available items. To filter the list results, I'm using; request.method == 'GET', I know I can check if any field are empty and show all results or none. I'm having trouble using the DateField(), When I'm not using the dateformat "YYYY/MM/DD", Django throws an ValidationError; ["'02/10/2019' value has an invalid date format. It must be in YYYY-MM-DD format."] How can we validate the user input with request.method =='GET'? (similar to using "clean_method" on POST) Thanks in advance! views.py class BookingListView(generic.ListView): model = Item template_name = 'booking.html' def get_queryset(self): from_date = self.request.GET.get('from_date') to_date = self.request.GET.get('to_date') guests_qty = self.request.GET.get('guests_qty') booked = ( Q(booking__from_date__gte=from_date) | Q(booking__to_date__lte=to_date) ) if from_date and to_date and guests_qty: return Item.objects.filter(persons=guests_qty).exclude(booked) elif from_date and to_date: return Item.objects.exclude(booked) else: return Item.objects.all() HTML <form action="{% url 'availability' %}" method="GET" novalidate> <formset> <legend><h6>Available items</h6></legend> <div class="row"> <div class="input-field col s12"> <input id="id_from_date" type="text" name="from_date" autocomplete="off"> <label class="" for="id_from_date">Arrival:</label> </div> <div class="input-field col s12"> <input id="id_to_date" type="text" name="to_date" autocomplete="off"> <label class="" for="id_to_date">Departure:</label> </div> <div class="input-field col s5"> <input id="id_guests_qty" type="number" min="1" max="5" name="guests_qty" autocomplete="off"> <label class="" for="id_guests_qty">Persons:</label> </div> <div class="input-field col s12"> … -
How to make current user the foreign key in Django Model
I am using Django admin as a dashboard for clients (restricted permissions). I am allowing them to add new products via the admin site, and wish to use the current user as a foreign key in the Products model. I am using "exclude" in the ProductAdmin so the client won't have the choice of changing it. When the "exclude" is not used the user is the default selection and it works. When I include "exclude" the form returns an error saying the field is null. How can I make the current user the foreign key in the Products model whether they add items via the admin form or upload via csv? Here is my Product model: #models.py from django.db import models from datetime import datetime from django.contrib.auth.models import User class Product(models.Model): client_id = models.ForeignKey(User, on_delete=models.DO_NOTHING) title = models.CharField(max_length=200) asin = models.CharField(max_length=200, blank=True) sku = models.CharField(max_length=200, blank=True) date_added = models.DateTimeField(default=datetime.now, blank=True) in_report = models.BooleanField(default=True) def get_queryset(self, request): qs = super().get_queryset(request) if request.user.is_superuser: return qs return qs.filter(client_id=request.user) def __str__(self): return self.title #admin.py from django.contrib import admin from .models import Product class ProductAdmin(admin.ModelAdmin): list_display = ('title', 'asin', 'sku', 'in_report') list_display_links = ('title', 'asin', 'sku') list_editable = ('in_report',) search_fields = ('title', 'asin', 'sku', 'in_report') … -
DRF - API list view - parent with most recent child
I'm trying to make a custom list view for my Django rest API. This list should contain all articles (parent) with its most recent price (child). My Django models look like this: class Article(models.Model): id = models.AutoField(primary_key=True, verbose_name="Article ID") name = models.CharField(max_length=250, verbose_name="Name") class Price(models.Model): article = models.ForeignKey(Article, on_delete=models.CASCADE, verbose_name="Article", related_name="prices") price = models.DecimalField(max_digits=6, decimal_places=2, verbose_name="Price") With the following serializers: class PriceSerializer(serializers.ModelSerializer): class Meta: model = Price fields = '__all__' class ArticleSerializer(serializers.ModelSerializer): prices = PriceSerializer(many=True) class Meta: model = Article fields = '__all__' Now I'd like to make a @list_route() to access the list via a GET request: class ArticleViewSet(viewsets.ModelViewSet): queryset = Article.objects.all().order_by('id') serializer_class = ArticleSerializer @list_route(methods=['GET']) def recentprices(self, request, *args, **kwargs): ?...? class PriceViewSet(viewsets.ModelViewSet): queryset = Price.objects.all() serializer_class = PriceSerializer Can someone help me out trying to fill in the dots? -
django debug toolbar showing SQL as None
We use the django-debug-toolbar on two replated apps, one serving our legacy django app and the other serving our newer API. Recently, the debug-toolbar on the API has been showing SQL queries as None (see screen shot) The other app is working as expected. The debugsqlshell which ships with the debug-toolbar is also reporting queries as None: In [8]: user = User.objects.last() None [0.85ms] In [9]: rather than showing the queries as expected, and as seen here (working on the legacy app side): In [3]: user = User.objects.last() SELECT @@SQL_AUTO_IS_NULL [1.96ms] SELECT `auth_user`.`id`, `auth_user`.`password`, `auth_user`.`last_login`, `auth_user`.`is_superuser`, `auth_user`.`username`, `auth_user`.`first_name`, `auth_user`.`last_name`, `auth_user`.`is_staff`, `auth_user`.`is_active`, `auth_user`.`date_joined`, `auth_user`.`email` FROM `auth_user` ORDER BY `auth_user`.`id` DESC LIMIT 1 [10.00ms] In [4]: I have checked some obvious things. No settings have changed recently on the affected app, and in particular, middlewares have not been reordered in any way, which seems like a potential cause of the problem. The debug-toolbar has not been updated recently, and updating the debug-toolbar to the current version does not affect the situation. I am able to see queries using the CaptureQueriesContext (from django.test.utils) when running in a test context, but not in the debugsqlshell. I'm currently trying to find the point in history … -
How to migrate from sqllite to postgres
I already have a django project live on heroku. I am now wanting to migrate the database from sqllite to postgres because of some issues regarding heroku like when I set DEBUG=True, the site runs without any issues but as soon as I set DEBUG to False, I get server error 500. I'd hard time finding any working solution, so I've decided to move to postgres. So, I have changed my settings.py file to have default db as postgres. I don't know about any other change in this file regarding the production settings.Also, I'm on windows machine and have installed postgres, also installed the psycopg2 library.I have created the db manually in postgres. The issue I'm facing is, as soon as I run makemigrations command, it creates an sqllite db. Why does this happen? -
Expected a `Response`, `HttpResponse` or `HttpStreamingResponse` to be returned from the view, but received a `<class 'NoneType'>`
models.py class Wishlist(models.Model): home = models.ForeignKey(Home, on_delete=models.CASCADE, blank=False, null=False) user = models.ForeignKey(User, on_delete=models.CASCADE, blank=False, null=False) def __str__(self): return "{} - {}".format(self.user.username, self.home.address) class Meta: ordering = ('user',) urls.py urlpatterns = [ path(r'wishlist/<int:pk>/', views.WishlistGetUserItems.as_view(), name='wish-user-list'), ] views.py class WishlistGetUserItems(APIView): def get(self, request, pk): wishlist = get_list_or_404(Wishlist, user=pk) data = serializers.UserWishlistSerializer(wishlist).data Response(data, status=status.HTTP_200_OK) I've tried also to print message but seems like the method is not called -
Can I pass data through two different django projects?
After an otree survey, I start with subprocess another django app, specially a django-oscar shop. It runs on another port. Now, I want to pass some data from the survey (first app, otree) to the shop (second app, django-oscar). I tried this in app2/views.py: from survey.models import Player class CatalogueView(TemplateView): """ Browse all products in the catalogue """ model = Player context_object_name = "products" template_name = 'catalogue/browse.html' But I just get this error: ModuleNotFoundError: No module named 'otree' I also tried to import otree.api and I put otree to installed_apps. Any ideas, how to handle this? -
Nginx settings for webservics with SSL (https)
Nginx newbie here! I have the following dummy code: <button onclick="myFunction()">Click me</button> <p id="demo_id"></p> <script> function myFunction() { var loc = window.location; var wsStart = 'ws://'; if (loc.protocol == 'https:') { wsStart = 'wss://' } var port =":8080" <!-- var endpoint = wsStart + loc.host + port+'/personal/my_random_number/'; socket = new WebSocket(endpoint); socket.onmessage = function(e) { document.getElementById("demo_id").innerHTML = e.data; } socket.onopen = function() { socket.send("hello world #"); } </script> and nginx settings like this (ssl commented out): server { listen 80; #listen 443 ssl; server_name 157.200.0.100; #ssl_certificate /etc/letsencrypt/live/mydomain.com-0002/fullchain.pem; #ssl_certificate_key /etc/letsencrypt/live/mydomain.com-0002/privkey.pem; # serve static files location /static/ { alias /www/static_3/; } # serve media files location /media/ { alias /www/media_3/; } location / { proxy_pass http://$server_name:8080; proxy_set_header X-Forwarded-Host $server_name; } } #server { # listen 80; # server_name 157.200.0.100; # return 301 https://$host$request_uri; #} while the web service works perfectly on http (non secure) I couldn't figure how to allow wss to work with ssl (I commented out the SSL settings, when I use the SSL setting, the site works ok but not the WSS). Question: how to 'upgrade' my nginx settings where the WS can work with SSL? -
Django + Angular or Django + React
I would like to get better understanding on how to chose between Django and angular our Django and react. I want to create a full stack Web application and a mobile application for android and iOS -
Couldn't load 'BCryptSHA256PasswordHasher' algorithm library: No module named 'bcrypt'
As I was trying to test the register page I am building using Django, I got this error when I pressed the submit button: ValueError at /rubies/register/ Couldn't load 'BCryptSHA256PasswordHasher' algorithm library: No module named 'bcrypt' I have installed bcrypt. This is the part of my settings file that contains the hashers: PASSWORD_HASHERS = [ 'django.contrib.auth.hashers.BCryptSHA256PasswordHasher', 'django.contrib.auth.hashers.PBKDF2PasswordHasher', 'django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher', 'django.contrib.auth.hashers.Argon2PasswordHasher', ] Mind you that there is a green underlining under the word hashers, telling me there is a typo. I don't see it though. Can someone help? Thank you! -
Follower System in Django
i am trying to implement a follower system in Django. I achieved this by doing class FollowBridge(models.Model): follower = models.ForeignKey(User, on_delete= models.CASCADE, related_name= 'm_follower') followed = models.ForeignKey(User, on_delete= models.CASCADE, related_name= 'm_followed') date = models.DateTimeField(auto_now_add = True) def __str__(self): return f'{self.follower} and {self.followed}' With this every follow activity is logged into the dB. My question is will my method be healthy for the database in the long term?. -
Requests on an external API with from Django Channels
I would like to make calls to an external API from my websocket consumers (asynchronous). I thought about using requests but it is synchronous. Would that work? Is there another way to deal with that? -
how to add value to the existing one via update?
I have tried the following: how to add value to the existing one via update? view if test=='' : p = models.accounts(date=b,value=a) p.save() else: up=models.accounts.objects.filter(date=b).update(value=value+a) -
How can I save a PDF from local OS to Django FileField?
I have a program which writes on and saves PDFs into a directory. I need to take PDF files from this directory and save them as FileFields in a Document model class. My MEDIA ROOT is connected to S3 and already works with other models using upload_to=. I tried to use the django.core.files.File as shown here! but I get an encoding error. I also get an encoding error with .jpeg images but not .txt files. So I have reason to believe it's a file type problem. from django.core.files import File def upload_file(self, file_path): f = open(file_path) document = Document.objects.create() document.file.save(NewFile.pdf, File(f)) I want the file to get on my S3 bucket. However, I get 'utf-8' codec can't decode byte 0xe2 in position 10: invalid continuation byte I get this too if I try: f.read() I think it has to do with image content inside the pdf, but I'm stuck. Thanks for the help! -
Django forms - is there a way to dynamically edit a FilePathField?
I have a django form which I am using to access a directory. However I would like to access two different directories based on a given input, but have one FilePathField. As an example - I have two panels - 'panel1' and 'panel2'. The directory I would like to access is the analysis directory of each of these panels as such: /path/destination/panel1/analysis/ /path/destination/panel2/analysis/ In each of these analysis directories are directories starting with "Experiment" which I would like a user to be able to choose to obtain some results. I have my form: class RunUploadForm(forms.Form): directory_path = forms.FilePathField( path='/path/destination/panel1/analysis', required=True, allow_folders=True, allow_files=False, recursive=True, match="Experiment*", label="Pick folder for results:" ) class Meta: fields = ('directory_path',) This only allows the user to access panel1 directory as it is hardcoded into the path arg. Is there a way to dynamically change this path argument, maybe with a choicefield? -
django Web-Service design and in-memory data storage
Objective: to provide end-user number of 'notifications' in (almost) real time. To keep it simple, notifications should come when userX submits form XYZ and all other users should see that the number of notifications incremented by 1 (if userY see the number 50 that means there are 50 NEW XYZ forms). Question #1: given my django channels web-service, where should I iterate to get the result? At the moment I placed it under websocket_connect with an endless loop such that: class EchoDiscussionNotificationConsumer(AsyncConsumer): async def websocket_connect(self, event): await self.send({ "type": "websocket.accept", }) # NOT SURE THIS IS A GOOD DESIGN! while True: await asyncio.sleep(2) rand = random.randint(1,100) mesg = "#"+str(rand) await self.send({ 'type': 'websocket.send', 'text': mesg, }) This works great but I don't think this is a good design. Question #2: I don't want to query the db every 2 seconds what I had in mind is to query only when (1) the user logs in and (2) another user submits form XYZ. So once I have a 'table of notifications' from the db where should I store it (in-memory) to have faster access? (session?) -
500 Internal Server Error on Ajax Submission
I'm getting a 500 error on the submission of an ajax call. I was wondering if you could help me figure out why. Please note that the csrf_token is added to the data on a seperate javascript (using code under the 'AJAX' section of this page: https://docs.djangoproject.com/en/dev/ref/csrf/#ajax). My understanding is that if there is a problem with the csrf_token, a 403 error would be thrown. Template <form class="userorder" method='POST' action='.' data-url='{{ request.build_absolute_uri|safe }}'> {{ form.non_field_errors }} {% csrf_token %} {{ form.couponcode.errors }} <div class="coupon_message"></div> <div id="couponcodevalue">{{form.couponcode}}</div> <div id="couponcodeapply">Apply</div> <button type="submit">Submit</button> </form> Javascript <script> $("#couponcodeapply").click(function(){ var coupon = $("#id_couponcode").val() var data = {coupon: coupon,} $.ajax({ type: "POST", url: "/getcoupon/", data: data, success: function(data) { $("#coupon-message").text("Coupon Added") }, error: function(response, error) { $("#coupon-message").text("Coupon Not Added") } }) }); </script> views.py def getcoupon(request): print("I am in getcoupon") if request.is_ajax(): message = "hi" data = { 'message': message, } return JsonResponse(data) Error in Console (Chrome) jquery.min.js:4 POST http://localhost:8000/getcoupon/ 500 (Internal Server Error) send @ jquery.min.js:4 ajax @ jquery.min.js:4 (anonymous) @ (index):1636 dispatch @ jquery.min.js:3 r.handle @ jquery.min.js:3 Is there any way to get additional detail on why this 500 code is being thrown? Thanks!