Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
raise ValueError("Cannot use None as a query value") ValueError: Cannot use None as a query value
views.py def search_available_rooms(request): if request.method == 'GET': check_in_date = request.GET.get('check_in_date') check_out_date = request.GET.get('check_out_date') if check_in_date and check_out_date: overlapping_bookings = Booking.objects.filter(start_date__lte=check_out_date, end_date__gte=check_in_date) booked_rooms = [booking.room for booking in overlapping_bookings] available_rooms = Room.objects.exclude(id__in=[room.id for room in booked_rooms]) context = { 'available_rooms': available_rooms, 'check_in_date': check_in_date, 'check_out_date': check_out_date } return render(request, 'cat_hotel/cat_hotels.html', context=context) else: # Handle the case where one or both dates are missing return render(request, 'cat_hotel/cat_hotels.html', context={}) urls.py path('cat_hotels/', views.search_available_rooms, name='search_available_rooms'), raise ValueError("Cannot use None as a query value") ValueError: Cannot use None as a query value How do I solve this? -
Django React App, when inspecting the webpage it shows different code than in VSCode. It calls a get request, when my code references a post
It is a library management system with books and eventually users. The books hold simple information like title, author, genre, number of pages, and the ISBN number. Code from VSCode import React, { Component } from "react"; import Button from "@material-ui/core/Button"; import Grid from "@material-ui/core/Grid"; import Typography from "@material-ui/core/Typography"; import TextField from "@material-ui/core/TextField"; import FormHelperText from "@material-ui/core/FormHelperText"; import FormControl from "@material-ui/core/FormControl"; import { Link } from "react-router-dom"; export default class Book extends Component { constructor(props) { super(props); this.state = { title: null, author: null, genre: null, pages: null, }; this.isbn = this.props.match.params.isbn; this.getBookDetails(); } getBookDetails() { fetch("/api/get-book" + "?isbn=" + this.isbn) .then((response) => { if (!response.ok) { this.props.history.push("/"); } return response.json(); }).then((data) => { this.setState({ title: data.title, author: data.author, genre: data.genre, pages: data.pages, }); }); } render() { return ( <Grid container spacing={1}> <Grid item xs={12} align="center"> <Typography component="h2" variant="h2"> {this.state.title} </Typography> </Grid> <Grid item xs={12} align="center"> <Typography component="h5" variant="h5"> {this.state.author} </Typography> <Typography component="h5" variant="h5"> {this.state.genre} </Typography> <Typography component="h5" variant="h5"> Pages: {this.state.pages} </Typography> <Typography component="h5" variant="h5"> ISBN: {this.isbn} </Typography> </Grid> <Grid item xs={12} align="center"> <Button color="secondary" variant="contained" to="/" component={Link} > Back </Button> </Grid> </Grid> ); } } Code in browser inspect class Book extends react__WEBPACK_IMPORTED_MODULE_0__.Component { constructor(props) { super(props); this.state … -
Setting similarity threshold for trigram_similar Django PostgreSQL lookups?
We're using Django's trigram similarity __trigram_similar lookup and it works nicely, except we want to adjust the similarity threshold and don't know how. Queries are currently filtered like so: class MarkerViewSet(viewsets.ReadOnlyModelViewSet): queryset = tablename.objects.all() def filter_queryset(self, queryset): queryset = super().filter_queryset(queryset) queryset = queryset.filter(colname__trigram_similar= search_value) We thought we could add something like similarity__gt=0.1 to the args for filter() like this answer does, but it throws the error "django.core.exceptions.FieldError: Cannot resolve keyword 'similarity_gt' into field". They are using the .filter() function in a different way we don't understand which might be the problem. What's the argument and how can we supply it? Seems we might be able to adjust it manually in PostgreSQL with set_limit (previously SET pg_trgm.similarity_threshold), but we'd prefer to set this in Django. -
Django app failing on Vercel even when following tutorial video
I am trying to get a very basic Django app running on Vercel. I am following this tutorial and am following it almost exactly. https://www.youtube.com/watch?v=ZjVzHcXCeMU&t=930s But I just get that the serverless function crashed and a 500 error. You can see it here: https://django-vercel-exmaple.vercel.app/ When I check the logs in Vercel, it says: Unknown application error occurred Runtime.Unknown I tried changing the install command to pip install -r requirements.txt (which the tutorial video didn't have to do it seems). -
Error Invalid block tag on line 4: 'else'. Did you forget to register or load this tag? django
I'm doing a basic webpage with Django for a tutorial and when adding the following code to my base.html file i get the 'Invalid block tag on line 4: 'else'. Did you forget to register or load this tag?'. What might be the reason? <p> <a href="{% url 'learning_logs:index' %}">Learning Log</a>- <a href="{% url 'learning_logs:topics' %}">Topics</a>- {% if user.is_authenticated %} Hello, {{user.username}} {% else %} <a href="{% url 'accounts:login' %}">Log in</a> {% endif %} </p> {% block content %}{% endblock content %} Invalid block tag on line 4: 'else'. Did you forget to register or load this tag? -
Django could not perform queries on Postgres when request sent from fastapi
I use Django as ORM and fastapi as endpoint layer. Here is my Docker-compose file: version: "3" services: db: image: postgres volumes: - ./data/db:/var/lib/postgresql/data environment: - POSTGRES_DB=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres web: build: . env_file: - .env.dev command: bash -c "python manage.py makemigrations && python manage.py migrate && python manage.py runserver 0.0.0.0:8000" volumes: - .:/code ports: - "8000:8000" depends_on: - db api: build: . volumes: - .:/code environment: - POSTGRES_DB=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres command: bash -c "uvicorn contlika.asgi:celestial --host 0.0.0.0 --port 8001" ports: - "8001:8001" depends_on: - db the connections between web (Django Backend) and db (Postgres) is ok. So when I do queries within web container after the below command: python manage.py shell the object is created successfully and record is set in db tables. But when I send request from fastapi - through swagger interface - I get this error: django.db.utils.OperationalError: could not connect to server: No such file or directory Is the server running locally and accepting connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"? I have included the user and pass correctly in setting.py. Again the objects are being created successfully through Django command line utility. It's worth nothing to say, everything was working fine when I … -
Appending quantity of shopping cart with Jquery and DRF
I am trying to get my API to work on the front end of my django app, I have got to the point at which it successfully creates a new cart and adds the initial item to it, but once the button is clicked again it creates a brand new cart. I am getting zero errors so I think this is just down to lack of knowledge, any guidance and advice would be great. <script> const updateBtns = document.querySelectorAll('.update-cart'); const user = '{{request.user}}'; for(let i = 0; i < updateBtns.length; i++) { updateBtns[i].addEventListener('click', function(){ event.preventDefault(); // prevent page from refreshing const productId = this.dataset.product; const action = this.dataset.action; console.log('productId:', productId, 'action:', action); console.log('USER:', user); createCart(productId, action); addCartItem(productId, action); }); } function addCartItem(productId, action){ if(action === 'add'){ if(cart[productId] === undefined){ cart[productId] = {'quantity':1}; }else{ cart[productId]['quantity'] += 1; } } if(action === 'remove'){ cart[productId]['quantity'] -= 1; if(cart[productId]['quantity'] <= 0){ console.log('Remove Item'); delete cart[productId]; } } console.log('Cart:', cart); document.cookie = `cart=${JSON.stringify(cart)};domain=;path=/`; location.reload(); } function createCart(productId, action){ var csrftoken = getCookie('csrftoken'); console.log('User is logged in, sending data...'); const url = `http://127.0.0.1:8000/api/carts/`; fetch(url, { method: 'POST', headers:{ 'Content-Type':'application/json', 'X-CSRFToken':csrftoken, }, body:JSON.stringify({'productId':productId, 'action':action}), mode: 'same-origin', }) .then((response) =>{ return response.json(); }) .then((data) =>{ console.log('CartDATA', data); const … -
How to call django view onclick then redirect
I'm trying to make a searchbar in my django app. When I click on a result from the searchbar I want it to call my view. I want the view to keep the context from what was clicked, perform a function, and then redirect me. In my views.py def search(request): query = request.GET.get('q', '') if query: sp = SpotipyConnection(client_id=sp_client_id, client_secret=sp_client_secret) #context = {'search': sp.searchbar(query)} context = {'search': sp.songSearch(query)} return render(request,'main/search.html',context=context) return render(request,'main/search.html',{}) def search_results(request): if request.method == 'POST': #TODO how do i get the context of what was clicked songName = None songArtist = None context = openAISearch(artist=songArtist,song=songName) return render(request,'main/search_results.html',context=context) In my search.html: {% block title %} Search {% endblock %} {% block content %} <script> function redirectToHome(songName, songArtist) { <!-- TODO how do I call my search_results function then return the redirect --> } </script> <form method="GET" action="{% url 'search' %}"> <input type="text" name="q" id="search-input"> <button type="submit">Search</button> </form> </form> {% if search %} {% for result in search %} <p onclick="redirectToHome({{ result.name }},{{ result.artists.0.name }})"> {{result.name}} by {{ result.artists.0.name }} <img src="{{ result.album.images.0.url }}" alt="{{result.name}} image" style="width: 200px; height: 200px;"> </p> {% endfor %} {% endif %} {% endblock %}``` -
How to call variable processed in forloop function (views) in django template?
I am trying to refer a variable p in my django template after some logic was applied to it. Since it seems templates are only a place for making a page look nice, there must be a way to assign a value to a variable in a forloop and refer it into the template. views def function(request): q = Model.objects.all p = None for model in q : for in_model in ... if something: p = 1 return render(request,"template.html", {'q ':q , 'p':p}) template {%for model in q %} {% for in_model in ... %} {% if p == 1 %} P=1 {%else%} {%endif%} {%endfor%} {%endfor%} Following an example like this, how do I can I test if p=1? It seems whatever I try p=None because this is where the variable is first mentioned in the view. I tried to keep my example as generic as possible, I am hoping it wont affect the clarity of my question. Happy to provide more code if necessary. -
How can i only send and verify Tokens only in Djoser Django and not a pair of Token and Uid
I am trying to make a mobile app, and I only want to use Djoser to send the token once a user registers on the app. The most significant issue I have is that Djoser sends both a UID and a token, which I don't want. I only want it to send the Token a user can enter into the verify email field on the mobile app. How can I do that using Djoser in Django? DJOSER = { 'LOGIN_FIELD': 'email', 'USER_CREATE_PASSWORD_RETYPE': True, 'USERNAME_CHANGED_EMAIL_CONFIRMATION': True, 'PASSWORD_CHANGED_EMAIL_CONFIRMATION': True, 'SEND_CONFIRMATION_EMAIL': True, 'SET_USERNAME_RETYPE': True, 'SET_PASSWORD_RETYPE': True, 'PASSWORD_RESET_CONFIRM_URL': 'password/reset/confirm/{uid}/{token}', 'USERNAME_RESET_CONFIRM_URL': 'email/reset/confirm/{uid}/{token}', 'ACTIVATION_URL': 'activate/{uid}/{token}', 'SEND_ACTIVATION_EMAIL': True, 'SERIALIZERS': { 'user_create': 'users.serializers.UserCreateSerializer', 'user': 'users.serializers.UserCreateSerializer', 'user_delete': 'djoser.serializers.UserDeleteSerializer', } } -
What is sequence of ERD and models generation?
When going to define relational database tables, what is sequence of generating ERD and django models? Why almost discussions are about converting django models to ER diagram? It not should be first creating ERD, then generating django models from this concepts? -
What is the best car history check application in the UK?
I am looking for cost efficient and extensive car history check application for the UK based cars. What is the best car history check application ? The car history report should include if the vehicle Used Before First Registration data and It should also provide MOT history, tax information, Mileage issues, Exported, Type Approval Category and other vehicle basic informations as free I've tried so much application but they are generally very expensive and do not contains requested informations -
Selected field only some users
I have a Tasks model. One of its fields is status. How can I make the NEW and COMPLITED statuses be selected only by the author of the task, while these statuses were not available to performers? models.py class Tasks(models.Model): STATUS_CHOICE = ( ('new', 'new'), ('in progress', 'in progress'), ('on finish', 'on finish'), ('completed', 'completed') ) title = models.CharField(max_length=255) text = models.TextField() status = models.CharField(max_length=255, choices=STATUS_CHOICE) author = models.ForeignKey(User, on_delete=models.CASCADE) performers = models.ManyToManyField(User, blank=True, related_name='performers') date_create = models.DateField(default=now) date_update = models.DateField(blank=True, null=True) serializers.py class TasksSerializer(ModelSerializer): author = SlugRelatedField(read_only=True, slug_field='username') performers = SlugRelatedField(many=True, read_only=True, slug_field='username') class Meta: model = Tasks fields = '__all__' views.py class TasksViewSet(ModelViewSet): permission_classes = [IsAuthenticated, IsPerformers] queryset = Tasks.objects.all() .select_related('author') .prefetch_related('performers') serializer_class = TasksSerializer filter_backends = [DjangoFilterBackend, SearchFilter, OrderingFilter] filterset_fields = ['status'] search_fields = ['title', 'text'] ordering_fields = ['date_create', 'date_update', 'author', 'status'] Can you tell me how to implement this? -
How to fetch and post data with DRF and Jquery
I am very new to using API and JS so please go easy on me. I have done tons of trouble shooting but I can't seem to find any reliable information that I can personally comprehend. I have all of my viewsets and serializers set up and the API works perfectly. I am trying to get it work on the front end now. I am currently at the point where I can Post my cart to the database and it generates an ID, but the items aren't been added. I am not asking for anyone to do it all for me but any guidance would be very much appreciated, at the very least a decent guide to follow. Here is my current JS: const updateBtns = document.querySelectorAll('.update-cart'); const user = '{{request.user}}'; for(let i = 0; i < updateBtns.length; i++) { updateBtns[i].addEventListener('click', function(){ event.preventDefault(); // prevent page from refreshing const productId = this.dataset.product; const action = this.dataset.action; console.log('productId:', productId, 'action:', action); console.log('USER:', user); createCart(productId, action); // Pass cartId to the function }); } function createCart(productId, action){ var csrftoken = getCookie('csrftoken'); console.log('User is logged in, sending data...'); const url = `http://127.0.0.1:8000/api/carts/`; fetch(url, { method: 'POST', headers:{ 'Content-Type':'application/json', 'X-CSRFToken':csrftoken, }, body:JSON.stringify({'productId':productId, 'action':action}), mode: … -
Django Login system breaks the javascript
So I am creating a Django application and so far I have a nice template using HTML, CSS, and Javascript, however once I implemented an authentication system the javascript only works when a user is logged in but stops working once they are logged out. Before I implemented the login system, the javascript used localStorage in order to store theme preferences and it worked perfectly but now the javascript only works if a user is currently logged in, so I decided to try to use cookies in order to store a user's theme preferences but that also only works once user is logged in. I'm not sure how to proceed any help is much appreciated. Here is the javascript file using localStorage const body = document.body; const themeToggleBtn = selectElement('#theme-toggle-btn'); const currentTheme = getCookie('currentTheme'); // Check to see if there is a theme preference in the cookie, if so add the light theme to the body if (currentTheme) { body.classList.add('light-theme'); } themeToggleBtn.addEventListener('click', function () { // Add light theme on click body.classList.toggle('light-theme'); // If the body has the class of light theme then add it to cookie with a longer expiration time, if not remove it if (body.classList.contains('light-theme')) { setCookie('currentTheme', … -
Python Django Model.save() saved wrong value in column
I'm new in Django, and maybe question is dumb, but anyway... I've problems with MyModel.save() saving in database, i'm trying to save some specific column which is used as filter in another part of my code... but this calue is not saving properly in Database as i expected from saving query... models.py: class MyModel(models.Model): ..other code.. country = models.CharField('countryName', max_length=5, default='CH') views.py, here I'm trying to save specific column in database: template = MyModel.objects.get(id=template_id) currentCountry = settings.COUNTRY template.country = currentCountry template.save() but when I'm doing SELECT country from table I got different value from what I'm saving in views.py... also this value is different from SQL query which I've got from logging queryies in Django console... logged query: (0.005) UPDATE "my_app_templateadvert" SET "profile_id" = 60, "category_id" = 14, "category2_id" = 213, "category3_id" = 2120, "category4_id" = NULL, "subject" = 'test comment LV', "description" = 'test comment LVtest comment LVtest comment LVtest comment LVtest comment LVtest comment LVtest comment LVtest comment LVtest comment LVtest comment LVtest comment LVtest comment LVtest comment LVtest comment LVtest comment LVtest comment LVtest comment LVtest comment LVtest comment LVtest comment LVtest comment LVtest comment LVtest comment LVtest comment LVtest comment LVtest comment LVtest comment LVtest comment … -
Can I use Django as backend framework for my blockchain website
I am a beginner and wanted to make a blockchain project. I don't have any knowledge of blockchain as of now. I have a basic understanding of Django and have made a few projects. I was wondering can I make a blockchain website with react.js as the front-end and Django as the backend framework. Is Django viable for web3 or should I use Node.js (I don't know Node.js)? This is my final year of college and I have to make a decent project, so learning a new library like node.js will be very time-consuming. -
waiting for websocket connection in django channels consumer
I am using Celery and Channels to notify a user when a certain action is performed on the server by another user. On the browser, I am using WebSockets to connect the user to the consumer. Unfortunately, if the user is not online (which means the WebSocket is closed) when an event occurs, they will miss the notification, which I store in the database. How can I check if the user is still connected and send the information, or if not, wait for the connection to be established and then send the notification? consumer.py class MyConsumer(AsyncWebsocketConsumer): async def connect(self): self.user_inbox = f'inbox_{self.scope["user"].username}' # Check if user is anonymous and close the connection when true if self.scope["user"].is_anonymous: await self.close() self.connected_user = self.scope["user"] self.room_name = self.scope["url_route"]["kwargs"]["room_name"] self.room_group_name = "chat_%s" % self.room_name # Join room group await self.channel_layer.group_add(self.room_group_name, self.channel_name) await self.accept() async def disconnect(self, close_code): # Leave room group await self.channel_layer.group_discard(self.room_group_name, self.channel_name) async def chat_message(self, event): """FIRES WHEN MESSAGE IS SENT TO LAYERS""" event_dict = { "message_header": event["message_header"], "message_body": event["message_body"], "sender": event["sender"], "subject": event["subject"], } # Send message to WebSocket await self.send(text_data=json.dumps(event_dict)) tasks.py @shared_task def send_notification_to_ws(ws_channel, ws_event): channel_layer = get_channel_layer() async_to_sync(channel_layer.group_send)(ws_channel, ws_event) signals.py ws_event = { "type": "chat_message", "message_header": message_header, "message_body": message_body, "sender": … -
Converting from Flask to Django
What is Django's equivalent of the data type flask.wrappers.Response? if request.method == "GET": data = open("print.txt","r") response_r = app.response_class( response=data, status=200, mimetype='text/plain' ) As shown in the code above, response_r's datatype() is flask.wrappers.Response and I want to use this code in Django (not flask). -
FUNCTION_INVOCATION_FAILED Error when deploying django application to vercel, but on localhost everything works
I connect freedb remote mysql database, it is works on localhost, but not on vercel. Displayed this error in vercel logs And this is Js Console errors, but I think that the server cannot fail to start because of this this is my first time uploading django to versel and i can't imagine what could be causing this error. I would really appreciate your help, thanks in advance I changed the database, because already vercel not suported sqlite database.Connect the remote mysql database.If it works, it should show a screen like this -
Correct way to handle database errors in Django
I have doubts about how to implement certain things in a Django Rest API (I'm using DRF), and I want to ask you for guidelines. Imagine two models, for example, Employee, and Department. Each employee belongs to a Department, so the model should contain a foreign key in Employee pointing to the Department to which he belongs. We cannot save an Employee if we do not assign a valid Department. So, the scenarios we need to handle are, from the top of my head: An Employee with no Department An Employee with an invalid Department Now, because this is a REST API, I assume that the data that feeds the application came from the POST call. So, both scenarios can be represent as: bad_payload = { "employee_name": "John Doe", } inconsistent_payload = { "employee_name": "John Doe", ... "department": "Invalid Department" } Assuming Invalid Department is not on the database. So, my questions: Would the view be the best place to validate, or would it be better to trust the error that the database will throw when trying to insert the data into the table? (Remember, the foreign key has the NOT NULL restriction. If the validation is done on the … -
Generating and storing sitemaps for a django-tenants project
I am currently working on a Django SaaS project powered by django-tenants having a few tenants. What is the best way to generate sitemaps for a multi-tenancy app? Is it preferable to save the sitemap file for each tenant in disk storage or to cache each sitemap in memory? -
Cannot reinitialise DataTable in Django
I'm confused on how can I infuse my json format from django to Datatable , what I tried below using loop in the script {% for json in company %} <script>..</script> {% endfor% } but It persist error DataTables warning: table id=DataTables_Table_0 - Cannot reinitialise DataTable. Is there's any wrong with my implementation, Am I correct? to fetch all data from views.py json to datatable , is there anyway? Javascript {% block footer_scripts %} {% for row in company %} <script> $(function () { var dt_basic_table = $('.datatables-basic'), dt_complex_header_table = $('.dt-complex-header'), dt_row_grouping_table = $('.dt-row-grouping'), dt_multilingual_table = $('.dt-multilingual'), dt_basic; // DataTable with buttons // -------------------------------------------------------------------- if (dt_basic_table.length) { dt_basic = dt_basic_table.DataTable({ ajax: assetsPath + 'json/table-datatable_example.json', //I want to infused here the json format from views.py columns: [ { data: '' }, { data: 'id' }, { data: 'id' }, { data: 'full_name' }, { data: 'email' }, { data: 'start_date' }, { data: 'salary' }, { data: 'status' }, { data: '' } ], columnDefs: [ { // For Responsive className: 'control', orderable: false, searchable: false, responsivePriority: 2, targets: 0, render: function (data, type, full, meta) { return ''; } }, { // For Checkboxes targets: 1, orderable: false, searchable: false, … -
Unable to display continuous output from a python script to HTML view in django
I am trying to display the continuous output from a python script on the HTML page but the output is being displayed once the entire execution of the script is completed. I have used subprocess to run the python script(test.py) and when I execute the python script independently I could see the output line by line but the same is not working when I use it along with websockets. Can anyone please help me fix the problem? Here is my code: consumers.py import os import subprocess from channels.generic.websocket import AsyncWebsocketConsumer class MyAsyncWebsocketConsumer(AsyncWebsocketConsumer): async def connect(self): print("Websocket connected") print("Channel name...", self.channel_name) print("Channel layer...", self.channel_layer) await self.channel_layer.group_add('programmers', self.channel_name) await self.accept() async def receive(self, text_data=None, bytes_data=None): print("Message received from the client", text_data) current_dir = os.getcwd() script = current_dir + '/' + 'test.py' try: p = subprocess.Popen(['python', script], stdout=subprocess.PIPE, bufsize=3) for line in iter(p.stdout.readline, b''): line = line.decode("utf-8").strip() await self.send(text_data=line) except subprocess.CalledProcessError as e: print(e) async def disconnect(self, code): print("Websocket disconnected", code) index.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Index</title> </head> <body> <h3>Count Page</h3> <textarea id="chat-log" cols="100" rows="20"> </textarea><br> <input type="button" value="Submit" id="script-run-submit"> <script> var ws = new WebSocket('ws://127.0.0.1:8000/ws/awsc/') ws.onopen = function() { console.log("Websocket connection opened") } ws.onmessage = function(event) { console.log("Message received … -
Django Package on virtual environment Malfunction after a certain time after reinstallation on cPanel share hosting server on deployment
I'm hosting a django project on a Shared hosting server cpnal that use CloudLinux. I've respect all the step and requirements to host a django project on a shared hosting server using passanger_wsgi.py. When I create a python application, getting a virtual enviromnent and installing all required package for my django project to work properly everything work very well and my application itself doesn't have any error and I have done all the test. But after a certain time, takes one or two weeks my python app get some packages error, some of them(mysqlclient, pillow, ....) and I'm obliged to delete the application, recreate it again and reinstall all the package to make everything work again. I've try to solve the error with the hosting service admin -> installing the lsapi and also install the python development package for Mysql. By my side I've tried to change the Mysql client package with pymsql and other. But still getting that error but it's periodic after one or two weeks after reinstallation. So please what can I do. I need some help before taking the decison of trying another hosting service. Is there something i'm missing, please help me.