Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
The current path, api/v1/users, didn’t match any of these
I am experiencing this problem following a tutorial and I can't identify the error in my "SignUpView.vue" page. Tried changing to re_path and did not work. Not Found: /api/v1/users [15/Oct/2023 22:30:42] "POST /api/v1/users HTTP/1.1" 404 7646 Code: URLS.PY from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('api/v1/', include('djoser.urls')), path('api/v1/', include('djoser.urls.authtoken')) ] ERROR images: enter image description here enter image description here SignUpView.vue: if everything goes right. I'm supposed to get forward on localhost:8080/log-in methods: { submitFrom(e) { const formData = { username: this.username, password: this.password } axios .post("/api/v1/users", formData) .then(response => { console.log(response) this.$router.push('log-in') }) Please help me to solve this problem. Thanks in Advance. (..) -
Login form, django and react send data with post method but I cant get it in the server
I'm currently working on a web application using Django and React. I'm specifically facing an issue with handling form data. I have created a login form in my React application, and when I submit the form, I'm sending the form data to the server. However, on the server side (using Django), I'm having trouble receiving and processing the form data correctly. After submitting the form, I'm expecting to receive the form data on the server and perform some authentication logic. But when I try to access the received data on the server, I'm getting an empty dictionary instead of the expected form data. I have checked my client-side code and ensured that the form data is being sent correctly from the React application. However, I'm not sure why the server is not able to receive and process the data properly. I would greatly appreciate it if anyone could provide guidance or suggestions on how to properly handle and receive form data on the server side using Django. If you have any experience with Django and React and have encountered a similar issue before, your insights would be invaluable. Thank you in advance for any help or advice you can provide!" … -
SystemCheckError: System check identified some issues
ERRORS: auth.User.groups: (fields.E304) Reverse accessor 'Group.user_set' for 'auth.User.groups' clashes with reverse accessor for 'user.User.groups'. HINT: Add or change a related_name argument to the definition for 'auth.User.groups' or 'user.User.groups'. auth.User.user_permissions: (fields.E304) Reverse accessor 'Permission.user_set' for 'auth.User.user_permissions' clashes with reverse accessor for 'user.User.user_permissions'. HINT: Add or change a related_name argument to the definition for 'auth.User.user_permissions' or 'user.User.user_permissions'. user.User.groups: (fields.E304) Reverse accessor 'Group.user_set' for 'user.User.groups' clashes with reverse accessor for 'auth.User.groups'. HINT: Add or change a related_name argument to the definition for 'user.User.groups' or 'auth.User.groups'. user.User.user_permissions: (fields.E304) Reverse accessor 'Permission.user_set' for 'user.User.user_permissions' clashes with reverse accessor for 'auth.User.user_permissions'. HINT: Add or change a related_name argument to the definition for 'user.User.user_permissions' or 'auth.User.user_permissions'. my models class User(AbstractUser): name = models.CharField(max_length=50, verbose_name=('name')) profile = models.ImageField(upload_to='images/profile/', verbose_name=('profile')) phone = models.CharField( _('Phone'), max_length=11, unique=True, ) USERNAME_FIELD = 'phone' REQUIRED_FIELDS = [] objects = UserManager() username = None class Meta: app_label = 'user' verbose_name = _("user") verbose_name_plural = _(" users") def __str__(self) -> str: return str(self.phone) -
Fetching Data from PostgreSQL DB and displaying in form of pie chart in Django App
I am trying to fetch the data from Progress Table(Model) that is in my PostgreSQL database.. but it shows nothing where I want to show that data in form of pie-chart. the only error it gives is something like data is being not fetched from database: **settings.py: # Django database configuration DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', # Database engine (PostgreSQL in this case) 'NAME': 'ProgressDB', # Name of the database 'USER': 'postgres', 'PASSWORD': 'postgres', 'HOST': 'localhost', 'PORT': '', # Leave empty to use the default PostgreSQL port (usually 5432) } } MODEL.py: class Progress(models.Model): name = models.CharField(max_length=30) PercentageDownload = models.PositiveIntegerField() VIEW.py: # function to fetch data from progress table and use in Progress picharts on epidemiological_data page def pie_chart(request): labels = [] data = [] print("This is executed."); queryset = Progress.objects.all() for obj in queryset: labels.append(obj.name) data.append(obj.percentagedownload) print("This is executed."); return render(request, 'django_blog/epidemiological_data.html', { 'labels': labels, 'data': data, }) **HTML page: ** <div class="progressCircles"> <div id="container" style="width: 100%;"> {% for label in labels %} <div class="chart-container"> <canvas class="chart" id="pie-chart-{{ forloop.counter }}" style="width: 100%;"></canvas> <p class="chartText">{{ label }}</p> <!-- Display label below the chart --> </div> {% endfor %} </div> </div> <script src="https://cdn.jsdelivr.net/npm/chart.js@2.9.3/dist/Chart.min.js"></script> <script> // Get the data as … -
What are best practices for implementing an admin panel?
I'm implementing an admin panel for my Django (API) & SvelteKit (frontend only) web application. What are the best practices for implementing an admin panel, security wise? I'm torn between multiple options right now: Setting up a different django project that accesses the database of my main project (kinda having trouble finding out how to apply my main projects' models and migrations to the panel though) Just adding (additional) admin panel functionality to my main django project Adding an admin panel to my SvelteKit frontend My main concern with no. 2 and 3 is that I'm not sure if it could be a security risk giving users the option to access even just the login panel to the admin interface if the application and the admin panel are both running within the same context, accessible to the user. If I'd go for the first option I'd restrict access to the django admin panel project entirely and make it only accessibly from within the intranet. Am I overthinking too much here and making a whole fuzz about nothing? What would "best practice" to safely implement an admin panel in an environment like mine? -
I am not being able to import views from an app
I am completely new to Django and I am following this freecodecamp tutorial: https://www.youtube.com/watch?v=F5mRW0jo-U4 I am trying to import views from an existing app, but the app is not being recognised So far I have done: python manage.py startapp pages to create the app called pages. Its apps.py file looks like this: enter image description here Add pages to settings.py: enter image description here Create the view in views.py (pages): enter image description here I am now trying to import the app in urls.py: enter image description here This is an overview of my directory: enter image description here I do not seem to have this issue with my other app called "products". Am I missing something essential here? Thanks in advance! -
When inheriting from two classes, I have functionality from only one
When inheriting from two classes, in the admin panel I only have the functionality of the class that comes first. For example, it will only show entity shift (Django MPTT) or only the "Load data" button (DjangoObjectActions). Is there any way to have both functionalities? My code: from django.contrib import admin from mptt.admin import MPTTModelAdmin from .models import Category, Image from django_object_actions import DjangoObjectActions, action from scripts.load_csv_to_db import run class CategoryAdmin(MPTTModelAdmin, DjangoObjectActions): @action(label='Load data') def load_data(self, request, queryset): run() changelist_actions = ('load_data', ) admin.site.register(Category, CategoryAdmin) admin.site.register(Image) Thank you. -
Why are tables not created during migration?
Authorization tables were created normally. When I try to create and apply a migration, it says that everything was successful. But there are no new tables in the database settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'start_page' ] file 0001_initial.py in folder migrations # Generated by Django 4.2.5 on 2023-10-15 14:17 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Person', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=20)), ('age', models.IntegerField()), ], ), ] in console (.venv) C:\django-on-docker\app>python manage.py makemigrations start_page Migrations for 'start_page': start_page\migrations\0001_initial.py - Create model Person (.venv) C:\django-on-docker\app>python manage.py migrate start_page Operations to perform: Apply all migrations: start_page Running migrations: Applying start_page.0001_initial... OK but there is no new table in the database, there are only tables created for authorization And there is no new entry in the table django_migrations -
Lets say I have index.html page with a button and a H2 tag element. I want to update the H2 tag with the button text using django python when clicked
I have a button with text "startups" and a H2 element with no text. I want to update the H2 element with button text when I click on it. Iam able to get the text of the button using Ajax with POST request into views.py in django project. Iam trying to render the page with "return render(request, 'index.html', {'text':text})". Value of text is that button text. Iam able to print that value in console after clicking on that button. But iam not able to see that text in the html page for H2 tag. I thought it's because of not reloading the page after update. Please suggest me what to do for this issue. If possible it would be very helpful if u can give me some examples on this. ThankYou. Hoping for the resolution.!! I just need to update the text in html page once clicked on that button on the html page using django views.py -
Get the value of 'button.url'
Where does Wagtail get the value of 'url' in 'button.url' in 'home_page.html'? models.py: class HomePage(Page): button = models.ForeignKey( 'wagtailcore.Page', blank=True, null=True, related_name='+', help_text='Select an optional page to link to', on_delete=models.SET_NULL, ) button_text = models.CharField( max_length=50, default='Read More', blank=False, help_text='Button text', ) home_page.html: href="{{ page.button.url }}" -
django-allauth redirects to a weird page before third part login
I'm using django-allauth to provide login with google accounts. When I click to login with Google, I'm sent to a page of alert that I'm about to use a third part account. This page will scare many users if left untouched. How can I skip this page or, at least be able to edit this page so it become more user friendly? My url file looks like this: urlpatterns = [ path('admin/', admin.site.urls), path('', include('pairs_trading.urls')), path('accounts/', include('allauth.urls')), ] My template file looks like this: {% load socialaccount %} <a href="{% provider_login_url 'google' %}"> My settings.py file looks like this: SITE_ID = 1 INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'storages', 'pairs_trading.apps.PairsTradingConfig', 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.google' ] SOCIALACCOUNT_PROVIDERS = { 'google': { 'SCOPE': [ 'profile', 'email', ], 'AUTH_PARAMS': { 'access_type': 'online', } } } MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'allauth.account.middleware.AccountMiddleware' ] AUTHENTICATION_BACKENDS = ( 'django.contrib.auth.backends.ModelBackend', 'allauth.account.auth_backends.AuthenticationBackend', ) LOGIN_REDIRECT_URL = '/' LOGOUT_REDIRECT_URL = '/' Thanks for any suggestions that may help! -
Custom User Edit Form not working with is valid method
im new to django (doing my first project) and i can't figure out what goes wrong in my Custom User Edit Form. class TestEditForm(ModelForm): old_password = forms.CharField(widget=forms.PasswordInput(attrs={"autofocus": True})) new_password1 = forms.CharField(widget=forms.PasswordInput(attrs={"autofocus": True})) new_password2 = forms.CharField(widget=forms.PasswordInput(attrs={"autofocus": True})) class Meta: model = CustomUser fields = ("email", "username", "old_password", "new_password1", "new_password2") def __init__(self, user, *args, **kwargs): self.user = user super().__init__(*args, **kwargs) def clean(self): super(TestEditForm, self).clean() email = self.cleaned_data.get('email') username = self.cleaned_data.get('username') old_password = self.cleaned_data.get('old_password') new_password1 = self.cleaned_data.get('new_password1') new_password2 = self.cleaned_data.get('new_password2') if CustomUser.objects.filter(username=username).exists(): raise ValidationError(u'Username "%s" is not available.' % username) if CustomUser.objects.filter(email=email).exists(): raise ValidationError(u'E-mail "%s" is not available.' % email) if not self.user.check_password(old_password): raise ValidationError('Incorrect password') if new_password1 and new_password2 and new_password1 != new_password2: raise ValidationError('Passwords do not match') return self.cleaned_data def save(self, commit=True): new_password = self.cleaned_data.get('new_password1') self.user.email = self.cleaned_data.get('email') self.user.username = self.cleaned_data.get('username') self.user.set_password(new_password) if commit: self.user.save() return self.user CustomUser Model: class CustomUser(AbstractBaseUser, PermissionsMixin): username_validator = UnicodeUsernameValidator() email = models.EmailField(_("email address"), unique=True) username = models.CharField(_("username"), unique=True, max_length=30, validators=[username_validator], error_messages={ "unique": _("A user with that username already exists."), }, ) country = models.CharField(_("country"), max_length=40) liked_recipes = models.ManyToManyField(Recipe, default='', blank=True) is_staff = models.BooleanField(_("staff status"), default=False) is_active = models.BooleanField(_("active"), default=True) date_joined = models.DateTimeField(_("date joined"), default=timezone.now) USERNAME_FIELD = "email" REQUIRED_FIELDS = [] objects = CustomUserManager() def __str__(self): … -
I'm getting a "AttributeError: module 'django.views' has no attribute 'my_form'" even though I have defined the function
I'm very new to django and python and I was making a form to accept values from the user to store in the database and I keep running into a ModuleNoFoundError, even though I have written the module in views.py which I am importing. I am creating my own module and the html for the form and not using django form formats at all. This is my views.py: `from django.shortcuts import render # Create your views here. from .models import My_Model from .forms import MyForm def my_form(request): if request.method == "POST": form = MyForm(request.POST) if form.is_valid(): form.save() else: form = MyForm() return render(request, 'form.html', {'form': form}) This is my urls.py: `from django import urls from django import views from django.contrib import admin from django.urls import path urlpatterns = [ path('admin/', admin.site.urls), urls(r'form', views.my_form , name='form') ] ` This is the models.py: `from django.db import models # Create your models here. class My_Model(models.Model): firstname = models.CharField(max_length=100) lastname = models.CharField(max_length=100) PRN = models.CharField(max_length=8) Phone = models.IntegerField(max_length=10) Email = models.EmailField() Department = models.CharField(max_length=50) S_Year = models.CharField(max_length=2) def __str__(self): return self.name` This is the forms.py: `from django import forms from .models import My_Model class MyForm(forms.ModelForm): firstname = forms.CharField(widget=forms.TextInput(attrs={ "class": "form-control", "placeholder": "firstname" })) lastname … -
How to combine objects in a full outer join with Django?
Let's use Django's standard users and groups. I have a couple of users and groups and each user can be assigned to several groups via a M2M relation. Now, I want to construct a single query which cross joins users x groups. The purpose is a view that shows all groups with it's members, when users are members of several groups then I want them to be shown in each group. I currently have this query, which appears to give me a cross join: groups = list(Group.objects.all()) queryset = User.objects.filter(groups__in=groups) However, the query only contains data about the users. How can I include the data for each group into the queryset? -
How to host / deploy a Django Project Online Free Version?
i have been trying to host a django web app online but it has not been successfuly deployed online. I want a help from you guys to give me the best opsions and step by step guide how to host / deploy a django web app (not static project) -
How to Custom User model inherit and serialize them in Django
Got AttributeError when attempting to get a value for field ProDetails on serializer UserSerializer. The serializer field might be named incorrectly and not match any attribute or key on the CustomUser instance. Original exception text was: CustomUser object has no attribute ProDetails. Models.py class CustomUser(AbstractBaseUser, PermissionsMixin): username=None email = models.EmailField(unique=True) password = models.CharField(max_length=128, null=True) first_name = models.CharField(max_length=255, null=True, blank=True) last_name = models.CharField(max_length=255, null=True, blank=True) created_at = models.DateTimeField(auto_now_add=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_shopCreated = models.BooleanField(default=False) last_login = models.DateTimeField(null=True, blank=True) last_logout = models.DateTimeField(null=True, blank=True) objects = UserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] def __str__(self): return self.email def has_module_perms(self, app_label): return True def has_perm(self, perm, obj=None): return True class ProDetails(models.Model): user = models.OneToOneField(CustomUser, on_delete=models.CASCADE) mobile = models.CharField(max_length=14) address = models.CharField(max_length=500, null=True, blank=True) pincode = models.CharField(max_length=10, null=True, blank=True) profileimage = models.ImageField( upload_to='photos', max_length=100, null=True, blank=True) coverImg = models.ImageField( upload_to='photos', max_length=100, null=True, blank=True) Serializer.py class ProDetailsSerializer(ModelSerializer): class Meta: model = ProDetails fields = ['id','pincode'] class UserSerializer(ModelSerializer): ProDetails = ProDetailsSerializer(required=True) class Meta: model = CustomUser fields = ['email', 'first_name', 'created_at', 'ProDetails'] View.py class profiledata(mixins.RetrieveModelMixin, mixins.ListModelMixin, generics.GenericAPIView): serializer_class = UserSerializer lookup_field = 'id' authentication_classes = [ JWTAuthentication, TokenAuthentication, SessionAuthentication, BasicAuthentication] permission_classes = [IsAuthenticated, ] def get_queryset(self): user = CustomUser.objects.all() return user … -
Django doesn't show yellow page
So I have initialized a django project (v4.2.5) and every thing works fine and debug is set to True, but I never get the yellow page when errors occur, instead I always get this: A server error occurred. Please contact the administrator. I do have django.middleware.common.CommonMiddleware and DEBUG_PROPAGATE_EXCEPTIONS is set to true as well and I have to check what is the problem in terminal all the time, any idea what could be the problem? -
Why does it give an error even though I created the template filter according to the Django documentation?
from django import template register = template.library() # in here, pycharm say : 'library' is not callable @register.filter(name='LIM') def limited_index(val, arg): return val[:arg] terminal : Cannot find reference 'assignment_tag' in 'library.py' -
Django linkedIn Social authentication
Someone please help, Please read it fully(I have tried a lot of methods lately from different sources) its been more than 30 days I'm trying to get 'Sign in with LinkedIn' button, but no good.. ill just show you my code: My LinkedIn id n key(have tried without REDIRECT_URL line as well) #MY LINKEDIN APP SOCIAL_AUTH_LINKEDIN_OAUTH2_KEY = 'ID' SOCIAL_AUTH_LINKEDIN_OAUTH2_SECRET = 'KEY' REDIRECT_URI = 'http://localhost:8000/oauth/complete/linkedin-oauth2/'` URLS `urlpatterns = [ path('admin/', admin.site.urls), path('', include('home.urls')), path('oauth/', include('social_django.urls', namespace='social')), ]` LinkedIn Button `<!--LINKEDIN BUTTON--> <li class="linkedin"> <a href="{% url "social:begin" backend="linkedin-oauth2" %}"> Sign in with Linkedin </a> </li>` Nothing's wrong with the coding.. `INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'home', 'social_django', ] LOGIN_REDIRECT_URL = 'dashboard' LOGOUT_REDIRECT_URL = 'login' LOGIN_URL = 'login' LOGOUT_URL = 'logout' AUTHENTICATION_BACKENDS = ( 'django.contrib.auth.backends.ModelBackend', 'social_core.backends.github.GithubOAuth2', 'social_core.backends.google.GoogleOAuth2', 'social_core.backends.linkedin.LinkedinOAuth2', ) LinkedIn app is okay, Redicrect URI mathces as well` `Error after Clicking Sign in with LinkedIn Bummer, something went wrong. In five seconds, you will be redirected to: localhost Django error AuthFailed at /oauth/complete/linkedin-oauth2/ Authentication failed: Scope &quot;r_liteprofile&quot; is not authorized for your application I understand it needs the "r_liteprofile" scope, But I cant see that anywhere, neither inside OAuth 2.0 tools . HELP Appreciated. solution to this … -
Static and Media files are not shown in django website - nginx & gunicorn
I'm trying to deploy a django website on a vps and it's now up and running(after a lot of trouble!), but now my media and static files are not shown in my website and I really tried a lot of ways but none of them worked. My nginx configuration: server { listen 80; server_name domain_name; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /var/www/real_estate/static/; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } gunicorn.service: [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=shahriar Group=www-data WorkingDirectory=/home/shahriar/Amlak/real_estate ExecStart=/home/shahriar/Amlak/env/bin/gunicorn \ --access-logfile - \ --workers 3 \ --bind unix:/run/gunicorn.sock \ real_estate.wsgi:application [Install] WantedBy=multi-user.target settings.py: # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/4.2/howto/static-files/ STATIC_URL = '/var/www/real_estate/static/' STATIC_ROOT = '/var/www/real_estate/static/assets' STATICFILES_DIRS = [ 'static/', BASE_DIR/'static/', '/var/www/real_estate/static/' ] # Default primary key field type # https://docs.djangoproject.com/en/4.2/ref/settings/#default-auto-field DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' # Media Settings MEDIA_URL = '/media/' MEDIA_ROOT = BASE_DIR.joinpath('media') And eventually I restarted every service possible but not a single static file was shown. I tried changing settings.py from this: STATIC_URL = 'static/' STATIC_ROOT = 'assets/' STATICFILES_DIRS = [ 'static/', BASE_DIR/'static/' ] to this: STATIC_URL = '/var/www/real_estate/static/' STATIC_ROOT = '/var/www/real_estate/static/assets' STATICFILES_DIRS = [ 'static/', BASE_DIR/'static/', '/var/www/real_estate/static/' ] I tried changing from this : server … -
how to Prevent Automatic Disconnection from Django Channels Server After a Period of Inactivity
I'm working on a Django project where I'm using AsyncWebsocketConsumer on the server side to manage python build-in WebSockets connections. but unfortunately, after sending first message, in my python websockets app(client side) i should send message each 50 second to my connection don't close. To prevent this, I've tried adjusting the arguments when connecting using websockets.connect as follows: import json import asyncio import websockets async def connect_to_server(): url = 'ws://localhost:8000/ws/socket-server/' async with websockets.connect(url, open_timeout=None, ping_interval=1, ping_timeout=120, close_timeout=1) as websocket: try: while True: # My code here... except KeyboardInterrupt: pass asyncio.get_event_loop().run_until_complete(connect_to_server()) Despite these, I'm still facing disconnection after a period of inactivity. Am I missing something in my approach? Specifically, how can I ensure that the connection remains active and prevent it from disconnecting due to inactivity? Any guidance on this would be greatly appreciated. Thanks in advance for your help! -
Problem using dj rest auth: dj-rest-auth/registration return http 204 no content
I am having the same problem as in this question (dj-rest-auth/registration return http 204 no content) but it still hasnt been answered so I wanted to post a new one to update it so maybe someone can give a solution. I were following the book Django for APIs by William.S.Vincent. In Chapter 8: User Authentication, I make Implementing token authentication and use dj-rest-auth and django-allauth to make registration. In the book after register the http return 201 created, it created new account and return API auth key token, save that in db. enter image description here With my it return http 204 no content( not return API auth key token ), it still created a new account but don't create key token for account. My url.py urlpatterns = [ path('admin/', admin.site.urls), path('api/v1/', include("posts.urls")), # v1 for api version 1. (Name for each api route) path('api-auth/', include('rest_framework.urls')), # build-in log in/out rest path("api/v1/dj-rest-auth/", include("dj_rest_auth.urls")), #url for dj_rest_auth path("api/v1/dj-rest-auth/registration/", include("dj_rest_auth.registration.urls")), ] My settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', #3party "rest_framework", "corsheaders", "rest_framework.authtoken", "allauth", "allauth.account", "allauth.socialaccount", "dj_rest_auth", "dj_rest_auth.registration", #local 'accounts.apps.AccountsConfig', 'posts.apps.PostsConfig',] REST_FRAMEWORK = { # new "DEFAULT_PERMISSION_CLASSES": [ "rest_framework.permissions.IsAuthenticated", ], "DEFAULT_AUTHENTICATION_CLASSES": [ "rest_framework.authentication.SessionAuthentication", "rest_framework.authentication.TokenAuthentication", ],} I compared with … -
django cookiecutter project generating error
I am following the quickstart of django cookiecutter tutorial. I've installed cookiecutter's latest version and pulled the cookiecutter django repo and the promts were properly filled. But after the last prompt, I always get this error: "ERROR: Stopping generation because pre_gen_project hook script didn't exit successfully Hook script failed (exit status: 1)" Honestly, I have no idea what is wrong. Please help :( -
How to combine multiple querysets in a Django view?
I am developing an exam page, where the user can take an exam several times and the results will be saved in the Score model. Currently I can store the results of the logged in user, but I need it to show me the entire list of scores they have achieved when I enter the details of each user. I have access to the list of users with the userList view, and I can access the details of each user with the userDetail view, but I want to know if there is a way to show all the scores of the selected user in the same details view. Here's de Score model: MODELS class Score(models.Model): #The user field is a foreign key from User(AbstractUser) user = models.ForeignKey(User, on_delete=models.CASCADE) score = models.IntegerField(default=0) evaluation_date = models.DateTimeField() These are the views I'm using for the user list, user detail and saving the new score: VIEWS class userList(LoginRequiredMixin, ListView): template_name = "users/list.html" queryset = User.objects.all() context_object_name = "users" class userDetail(LoginRequiredMixin, DetailView): template_name = "users/detail.html" queryset = User.objects.all() context_object_name = "user" @csrf_protect def send(request): if request.method == 'POST': if 'answers' in request.POST: answers = request.POST['answers'] time = datetime.datetime.now() current_user = request.user Note.objects.create( user = current_user, … -
When trying to deploy Django project on Azure through GitHub Repository, I'm getting "ModuleNotFoundError: No module named 'django'"
After I tried to deploy my Django website on Azure through GitHub, Deployment got successful and I'm not able to see the output, I'm getting Application Error. I'm using CONDA environment to run my project so I do not have requirements.txt file but I do have environment.yml file. I tried checking in diagnostics it says Application crashed and the error is Application Crashed 2023-10-15T00:05:56.422910225Z from django.core.wsgi import get_wsgi_application2023-10-15T00:05:56.422913932Z ModuleNotFoundError: No module named 'django'2023-10-15T00:05:56.423461446Z [2023-10-15 00:05:56 +0000] [76] [INFO] Worker exiting (pid: 76) and the it says that "This error is due to the missing package 'django' in the requirements.txt file. To resolve this, add the missing package in the requirements.txt file and redeploy the application." I've attached image for application logs.Application Logs my environment.yml file is name: SERVIR_AppTemplate channels: defaults conda-forge dependencies: python=3.9 django=4.1 django-allauth django-import-export netcdf4 shapely earthengine-api beautifulsoup4 whitenoise aiohttp pip=23.2.1 pip: climateserv==0.0.24 prefix: C:\ProgramData\Anaconda3\envs\SERVIR_AppTemplate