Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Query for chatapp in django
I need to query this model for a chat app(like WhatsApp). The question is how can I group the result of the query/queries ? class TimeStamp(models.Model): created = models.DateTimeField(auto_now_add=True, blank=True, null=True) modified = models.DateTimeField(auto_now=True, blank=True, null=True) class Messages(TimeStamp): sender = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="sender" ) receiver = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="receiver" ) message = models.TextField(max_length=1000) seen = models.BooleanField(default=False, blank=True) accepted = models.BooleanField(default=False, blank=True) The result should combine the messages where the sender/receiver is x without duplicate so I can show the user each conversation. Do I need to design the model differently? Thanks. -
How to create a DBMS project using django?
I have to make a project which includes making tables using sql in postgresql . Django makes its tables in models.py so I am not able to understand where is sql actually used? -
Create a register page with django
I have 2 problems, my css is not showing when i load my page and my register page is giving out error 404. At this point I am frustrated, I have tried fixing them but to no avail my index.html that shows the login page <body> <header class="header"> <div class="header-text"><a href="{% url 'login' % }">Login</a></div> <div class="header-text"><a href="{% url 'register' % }">Register</a></div> </header> my register.html {% extends 'index.html'} {% block content} <h2>Register</h2> <form method="post"> {% csrf_token %} {% for field in form %} <p> {{ field.label_tag }}<br> {{ field }} {% if field.help_text %} <small style="color: grey">{{ field.help_text }}</small> {% endif %} {% for error in field.errors %} <p style="color: red">{{ error }}</p> {% endfor %} </p> {% endfor %} <button type="submit">Register</button> </form> {% endblock %} my views.py from django.shortcuts import render, redirect from django.contrib.auth import login, authenticate from django.contrib.auth.forms import UserCreationForm from django.urls import reverse_lazy from django.views import generic from.models import Post def index(request): return render(request, 'index.html') class SignUpView(generic.CreateView): form_class = UserCreationForm success_url = reverse_lazy('login') template_name = 'register.html' and my urls.py from django.urls import path from django.conf import settings from django.conf.urls.static import static from .views import index, SignUpView urlpatterns = [ path('', index, name='index'), path('register/', SignUpView.as_view(), name='register'), ] Is … -
How do I pass data to success template from views with form.cleaned_data.get() in django?
I'm building an basic covid test appointment. Everything is working fine I am getting data from users in a form and saving it to database. But I'm trying to show some of that data to the form success page. Like when user enter their details in form such as name, data, time etc after clicking on submit button. I want the name, date, time of the form to render on success page. I even tried this but I'm getting an error like: NoReverseMatch at /covid_test Reverse for 'success' with arguments '({'name': 'Popes', 'test_date': datetime.date(2021, 4, 23), 'test_time': datetime.time(18, 0)},)' not found. 1 pattern(s) tried: ['success$'] Here is the screenshot of the error. Below is my code for the same. Models.py from django.db import models # Create your models here. class Covid_Test_Model(models.Model): gender_chooice = [ ('Male', 'Male'), ('Female', 'Female') ] name = models.CharField(max_length=100, null=False) age = models.IntegerField(null=False) gender = models.CharField(max_length=20, choices=gender_chooice, default='Male', null=False) phone = models.CharField(max_length=15, null=False) email = models.EmailField(max_length=100, null=False) adhaar_no = models.CharField(max_length=16, null=False) address = models.TextField(null=False) date = models.DateField(null=False) Time = models.TimeField(auto_now=False, auto_now_add=False, null=False) def __str__(self) -> str: return self.name Views.py from django.shortcuts import render, redirect # Create your views here. from covid_test_app.forms import Covid_Test_Form def covid_test(request): if request.method … -
running the 'python manage.py makemigrations' command is giving me syntax error
I am beginner to python and django and I following an online course 'CS50' so this is what I get when I run the command C:\Users\ramma\airlines>python manage.py makemigrations Traceback (most recent call last): File "C:\Users\ramma\airlines\manage.py", line 22, in <module>main() File "C:\Users\ramma\airlines\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\ramma\OneDrive\Desktop\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line utility.execute() File "C:\Users\ramma\OneDrive\Desktop\lib\site-packages\django\core\management\__init__.py", line 363, in execute settings.INSTALLED_APPS File "C:\Users\ramma\OneDrive\Desktop\lib\site-packages\django\conf\__init__.py", line 82, in __getattr__ self._setup(name) File "C:\Users\ramma\OneDrive\Desktop\lib\site-packages\django\conf\__init__.py", line 69, in _setup self._wrapped = Settings(settings_module) File "C:\Users\ramma\OneDrive\Desktop\lib\site-packages\django\conf\__init__.py", line 170, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "C:\Users\ramma\OneDrive\Desktop\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 680, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 786, in exec_module File "<frozen importlib._bootstrap_external>", line 923, in get_code File "<frozen importlib._bootstrap_external>", line 853, in source_to_code File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "C:\Users\ramma\airlines\airlines\settings.py", line 35 'django.contrib.admin', ^ SyntaxError: invalid syntax The code I wrote was class Flight(models.Model): origin = models.CharField(max_length=64) destination = models.CharField(max_length=64) duration = models.IntegerField() Pls help me find the mistake in this -
Django real time
I'm trying to build social media app as part of my django practicing, is there a JavaScript Framework or a library to help send real time events to other users? I tried ajax but it only updates for the user who sent request not to others Like notification system i commented on a post it sends a notification for post author but he has to reload the page to see it, is there a way to reload the notification div every few seconds instead of the whole page? And is it efficient or server overload will happen if this approach is used in production? -
expected string or bytes-like object in predict function of Fashion-mnist
I'm trying to deploy fashion-mnist model in django and i got this error when trying to test the predict function of the model with a local image . predict Function here any help will be appreciated . -
How can a call be made to the Google API from within Django?
I am currently trying to build a web app using Python and Django which will require information from the Google Calendar API. I've successfully managed to create the specific API credentials that I need using the Google Cloud Console, and downloaded the client secret JSON file to use for authentication. I have also been able to successfully access the API using the following code snippet: from googleapiclient.discovery import build from google_auth_oauthlib.flow import InstalledAppFlow scopes = ['https://www.googleapis.com/auth/calendar'] flow = InstalledAppFlow.from_client_secrets_file(r"client secret file location", scopes=scopes) flow.run_console() When I run it in VSCode, it creates a link in the terminal that I can click to go to the Google site and login. The issue I'm now having though is that the API is treating this as a PC app call, and once it opens in my browser it's asking me to recreate the API key (since the one I created is for Web Apps). A picture of the error can be seen here: Authorization Error Message from Google Now my question is, is there a way to call the API and have the user login be verified using Django? I am hesitant to remake the API credential as a desktop app because what … -
How to save and append input in the HTML render for the user in Django?
I want to save and render the input from the user at the withdrawals page, where the user should see previous withdraw amounts and the dates of the withdrawals that the user has made. @login_required def withdraw(request): if request.method == 'POST': if 'withdraw-amount' in request.POST: profile = Customer.objects.get(user=request.user) withdraw_amount = request.POST.get('withdraw-amount') if withdraw_amount > profile.credit: messages.error( request, 'You dont have enough Credit to withdraw!') else: profile.credit -= withdraw_amount profile.save() return render(request, 'withdraw.html') -
How can I set model items in html properly?
I have a form with which I intend to capture student marks. I have an issue like I don't know the best way to put it so that I have student name and markfield beside it for all the students. calling {{ form }} brings the form with select dropdown items(not what I want). Specifying form fields do not populate anything.i.e {% for field in form %} {{ field.student }} {{ field.marks }} {% endfor %} This is the form class AddMarksForm(forms.ModelForm): def __init__(self, school,klass,term,stream,year, *args, **kwargs): super(AddMarksForm, self).__init__(*args, **kwargs) self.fields['student'] = forms.ModelChoiceField( queryset=Students.objects.filter(school=school,klass__name__in=klass,stream__name=stream[0])) class Meta: model = Marks fields = ('student','marks') This is how I tried the html rendering <form method="post" enctype="multipart/form-data" action="{% url 'add_marks' %}"> {% csrf_token %} {% if form %} <table> <tr> <td>Student</td> <td>Marks</td> </tr> {% for field in form %} <tr> <td>{{ field.student }}</td> <td>{{ field.marks }}</td> </tr> </table> {% endfor %} <button class="btn btn-outline-primary">Save</button> </form> -
Django Form initial Value For Foreignkey Field
I have two django models which are : class Dataset(models.Model): name = models.CharField(max_length = 200) description = models.CharField(max_length=1000) owner = models.ForeignKey(Profile, null=True, on_delete=models.SET_NULL) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Source(models.Model): name = models.CharField(max_length = 200) description = models.CharField(max_length=1000) dataset = models.ForeignKey(Dataset, null=True, on_delete=models.SET_NULL) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) When saving a Source, I would like to initiate the value of the corresponding Dataset. I tried to initiate the value of my form as suggested here : foreign key as initial value not passed to the ModelForm in django def create_source(request, dataset_id): user = request.user dataset = Dataset.objects.get(id=dataset_id) form = SourceForm(initial={"dataset" : dataset, }) if request.method == "POST": form = SourceForm(request.POST or None, initial={"dataset" : dataset, }) if form.is_valid(): source = form.save() # dataset.source_set.add(source) # Only works if I add this line return redirect("source", dataset_id=dataset_id, source_id=source.id) context = {"form": form} return render(request, "sources/source_form.html", context) The suggested way does not work. I was able to achieve the desired result by adding the commented line above. It is not a recommended solution since it makes a second call to the database. Any idea how to give properly the dataset object to the source ? -
Django No Module Named With Inner Package Using
I want to write my own python package inside django's app. It looks like that: I have secondary app. It totally works except one thing. Someday I'd decided to make my app more structured. And there where problems started. First of all, I've added python package(with simple init.py inside directory) to the app. Then I've added second package inside that package. And when I try to run django.setup() inside packages' files, I'm getting this error: ModuleNotFoundError: No module named '<primary settings container module name goes here>' How to make my custom package's functions working properly? -
How to ban users in Django?
so I want to have a ban system in Django. For now, I have a Django app, and I want a system to ban users as long as I want to. So what I'm looking for is: is there any package or module to install, so it will be updated in the admin, so I can use to ban any user. And in the ban system, there could be an option for how many days to ban. Like weeks, months, days and more. And after I ban, when that user tries to log in, they should get a message saying you are banned. So please let me know how to do this. IF there is a module or package to install, or if there's any other way to do it. Any type of ban system is good. Thanks! -
Django Rest Framework endpoint does not work with SPA and axios, but works with other client like vscode REST Client extension
I bootstrapped this project with cookiecutter-django, and did not make any changes to the security settings or DRF endpoints. You can find settings/base.py and settings/local.py below. Currently both Django and React work on localhost. I am trying to do a crossorigin setup. E.g. React static will be served by Firebase in www.mydomain.com, and Django app will be on some other host. Thanks. I call Axios in a React SPA like this (handleLogin is the onClick handler): const domain = "http://localhost:8000/"; const handleLogin = () => { axios .post(domain + "auth-token/", { username: username, password: password, }) .then((res) => { setErrorMessage("Success res:" + JSON.stringify(res)); }) .catch((err) => { setErrorMessage("Error err:" + JSON.stringify(err)); }); }; And I get the error: Error err:{"message":"Network Error", "name":"Error", "stack":"Error: Network Error\n at createError (https://localhost:3000/taskpane.js:15266:15)\n at XMLHttpRequest.handleError (https://localhost:3000/taskpane.js:14751:14)", "config":{"url":"http://localhost:8000/auth-token/","method":"post", "data":"{\"username\":\"johndoe\",\"password\":\"mypass\"}", "headers":{"Accept":"application/json, text/plain, */*", "Content-Type":"application/json;charset=utf-8"}, "transformRequest":[null],"transformResponse":[null], "timeout":0,"xsrfCookieName":"XSRF-TOKEN", "xsrfHeaderName":"X-XSRF-TOKEN", "maxContentLength":-1,"maxBodyLength":-1}} Following vscode REST Client extension request works, e.g. I get a token: # Send Request POST http://127.0.0.1:8000/auth-token/ Content-Type: application/json { "username": "johndoe", "password": "mypass" } settings/base.py: """ Base settings to build other settings files upon. """ from pathlib import Path import environ ROOT_DIR = Path(__file__).resolve(strict=True).parent.parent.parent # mysite/ APPS_DIR = ROOT_DIR / 'mysite' env = environ.Env() READ_DOT_ENV_FILE = env.bool('DJANGO_READ_DOT_ENV_FILE', default=False) … -
Can I make multiple child models "likeable" in Django?
This is my first post here at Stackoverflow. I got a Post model containing 1 or more Article(child) models. I want to be able to like/dislike each child model seperatly. Here is the models: class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) class Article(models.Model): publisher = models.CharField(max_length=100) url = models.URLField(max_length = 200) likes = models.ManyToManyField(User, related_name='article_like') dislikes = models.ManyToManyField(User, related_name='article_dislike') blog_post = models.ForeignKey(Post, on_delete=models.CASCADE) -
Wrapping Django Backend and Node frontend into executable (.exe)
I have managed to wrap my Django backend(REST framework) into an executable using pyinstaller and wrap my Node frontend (HTML, JS and CSS) into an executable with pkg. Both of them can be run separately and can communicate with each other. Currently, I have tried using a bat file to run them at once but there will be two terminal windows appear for backend and frontend respectively. I am thinking whether there is a way to combine them both and run with a click on icon. And it is possible to not show the terminal? -
How to install Python with Sqlite3 on a hosted server
I'm a bit green where it comes to app deployment and I'm trying to deploy a Django app on a hosted server (app written in Python 3.8.8 win 32-bit). Since the server does not have any Python packages yet, I tried to install Python the following way through SSH bash: wget https://www.python.org/ftp/python/3.8.8/Python-3.8.8.tgz tar xvzf Python-3.8.8.tgz cd Python-3.8.8 ./configure --prefix=$HOME/.local make make install It does seem to install Python 3.8.8 so I then proceed to clone the code from Git and create virtual environment. The problem comes up when I try to install packages from requirements.txt and, specifically, for psycopg2 it shows an error that there is a missing module "_ctypes". I found that sometimes that reinstalling Python may help, but it didn't. Instead, I tried to install psycopg2-binary by pip install psycopg2-binary and it did work. However, when I try to run python manage.py collectstatic it's showing that Sqlite3 is missing. From what I learned, sqlite3 should be included in Python3 (it is when I install it on my PC). checked the folder directory and it indeed seems to be missing. Reinstalling did not help here either. Could those errors be caused by the fact that I'm installing Python incorrectly? … -
Template does not exist, django paths
Trying to run my server, but it doesn't seem to be cooperating. This is the text displayed when I tried running it: django.template.loaders.app_directories.Loader: /Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/contrib/admin/templates/rest_framework/api.html (Source does not exist) I have 'rest_framework' in my settings, 'INSTALLED APPS', I'm not sure what's going on -
How to add an array object to nested object in Django?
I need to add an array of objects to an another object whose structure has been shown below. Here is current response from Album: [ { "id": "1", "name": "Skin", "artists": [ { "id": "1", "name": "Flume", } ], "tracks": [ { "id": "1", "name": "Take A Chance" } ] } ] I need to transform tracks object from Album's response to this: [ { "id": "1", "name": "Skin", "artists": [ { "id": "1", "name": "Flume", } ], "tracks": { "items": [ { "id": "1", "name": "Take A Chance" } ] } } ] Here is my current models: class Artist(models.Model): name = models.CharField(max_length=300) albums = models.ManyToManyField('albums.Album', related_name='artists') tracks = models.ManyToManyField('tracks.Track', related_name='artists') class Album(models.Model): name = models.CharField(max_length=400) class Track(models.Model): name = models.CharField(max_length=400) album = models.ForeignKey('albums.Album', related_name='tracks', on_delete=models.CASCADE) -
Django 3.2 Model not instantiating properly in the register function
I apologize if my mistake is incredibly simple but I am completely new to Django. Currently, my models.py currently contains 2 types of profiles extending off of the default Django User model: from django.db import models from django.contrib.auth.models import User class UserProfile(models.Model): user = models.OneToOneField(User, on_delete = models.CASCADE) first_name = models.CharField(max_length = 50) last_name = models.CharField(max_length = 50) def __str__(self): return self.user.username class PCOProfile(models.Model): user = models.OneToOneField(User, on_delete = models.CASCADE) org_name = models.CharField(max_length = 100) org_phone = models.CharField(max_length = 20) is_active = models.BooleanField(default = False) def __str__(self): return f"{self.user.username} | {self.org_name}" I have a views.py file which contains 2 functions, one called register and another register-pco that collects base user information, as well as information related to only one of of these models as a form on the same page which will be submitted at the same time as the base user information: from django.shortcuts import render, redirect from django.contrib import messages from django.contrib.auth.decorators import login_required from .forms import UserRegistrationForm, UserProfileForm, PCOProfileForm def register(request): if request.method == 'POST': user_form = UserRegistrationForm(request.POST) profile_form = UserProfileForm(request.POST) if user_form.is_valid() and profile_form.is_valid(): user = user_form.save() # Hooking up user_profile model to django default user model profile = profile_form.save(commit=False) profile.user = user profile.save() username = … -
I need to go to new page when reload this page button in browser is clicked in django
I am doing a web application using django framework. In a form in my app I need to go or redirect to a new page when reload this page button on the browser is clicked. Really appreciate the community for your answers. app.html <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> </head> <body> <form method="post"> {% csrf_token %} #somecode <button type="submit" class="btn btn-primary">YES</button> </form> </body> </html> When this page is relaoded or refreshed I need to go to a new page(my home page in views.py) -
Next js Django Djoser Google authentication/
I am creating a website using next js and django and trying to authenticate with Google social auth . For this I am using djoser library and other library for JWT like django-simple-jwt. At first everting is okay . I can select my google account but it retuns bad request as 400 status . When I tried using postman it gives following error : ** "non_field_errors": [ "State could not be found in server-side session data." ]** Google.tsx file import React, { useEffect } from 'react'; import { connect } from 'react-redux'; import { googleAuthenticate } from '../actions/auth.action'; import { useRouter } from 'next/router' const Google = ({ googleAuthenticate }) => { const router = useRouter(); const code = router.query.code; const state = router.query.state; useEffect(() => { if (state && code) { googleAuthenticate(code, state) } }, [state, code]); return ( <div className='container'> <div className='jumbotron mt-5'> <h1 className='display-4'>Welcome to Auth System!</h1> <p className='lead'>This is an incredible authentication system with production level features!</p> <hr className='my-4' /> <p>Click the Log In button</p> <Link href='/LoginApi' ><button>Login</button></Link> </div> </div> ); }; export default connect(null, { googleAuthenticate })(Google); my redux action file as : export const googleAuthenticate = (state, code) => async dispatch => { console.log("GoogleAuthenticate … -
how can i filter with Django gabarit a condition on through model
In Django i would like to apply in a template a filter regarding a condition on a through model. I have the following models class Article(models.Model): txt_article = models.TextField(unique=True) teacher = models.ManyToManyField(User, through='Teacher_article', related_name='articles') class Teacher_article(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) article = models.ForeignKey(Article, on_delete=models.CASCADE) order_teacher = models.IntegerField() the view : select_article = Article.objects.get(txt_article=txt_ask) In the gabarit, i want to show for one article the teacher in the order : order_teacher but this solution is not working {% for teacher_i in select_article.teacher.all|dictsort:"order_teacher" %} {% endfor %} thanks a lot, Gonzague -
Django, how to test migration without creating new files / django_session row
I have an app called Sliders and have created the models. How do i run the migration, so just the database tables get created but no new entries in django_session table and no directory migrations created in app directory. This is what i normally do: After model is created then make migration file: python manage.py makemigrations sliders Then i run migration file: python manage.py migrate sliders This makes a migration directory in the Sliders app and inserts rows to django_sessions table. How do i prevent this? Just want the table to be created in database. -
Update model field ( SearchVector ) using signals.py
I am trying to update search vector field using post_save signal. Through "Admin.py", It is working perfectly, but through "Form page" , the searchVector field or any other field is not getting updated. In form page, I have many to many field - "Tag" that I save through "form.save_m2m" method Please review my code and suggest .. https://dpaste.org/ujPi Thanks in advance #models.py class JobPostManager(models.Manager): def search(self, search_text): search_vectors = ( SearchVector( 'job_title', weight='A', config='english' ) ) search_query = SearchQuery( search_text, config='english' ) search_rank = SearchRank(search_vectors, search_query) trigram_similarity = TrigramSimilarity( 'job_title', search_text ) qs = ( self.get_queryset() .filter(search_vector=search_query) .annotate(rank=search_rank + trigram_similarity) .order_by('-rank') ) return qs class JobPost(models.Model): job_title = models.CharField(max_length=100, db_index=True) job_description = models.TextField() tags = TaggableManager() author = models.ForeignKey(User, on_delete=models.CASCADE, db_index=True) company_name = models.CharField(max_length=100,blank=True,null=True, db_index=True) objects = JobPostManager() def __str__(self): return self.job_title def get_absolute_url(self): return reverse('job_post_detail', kwargs={'slug': self.slug, 'pk':self.pk}) #################################################################################### #################################################################################### # views.py class JobPostCreateView(LoginRequiredMixin, CreateView): model = JobPost fields = ['job_title','job_description','tags'] widgets = { 'tags' : forms.TextInput(attrs={'data-role':'tagsinput'}), } def get_form(self): form = super().get_form() form.fields['tags'].widget = forms.TextInput(attrs={'value': 'all'}) return form def form_valid(self, form): print("views - form valid - run ") newpost = form.save(commit=False) form.instance.author = self.request.user form.instance.company_name = self.request.user.company_name print("form---------------------------") print(form.instance.author) print(form.instance.job_title) print(form.instance.company_name) print("form end---------------------------") newpost.save() print('newpost') print('--------------------------------',newpost) print('newpost',newpost.author) print('newpost',newpost.job_title) …