Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Python & Django web app - auto emails not sending - troubleshooting Cron
I have a webapp running on an ubunti vps. Cron is scheduled to run a task evry sunday morning, however, I found it ran once and not again the next week. I have been reading about cron and how to troubleshoot but need help understanding what is shown when I run sudo systemctl status cron. Please describe what the lines below are telling me. Is there a reason it only ran my script once? sudo systemctl status cron ● cron.service - Regular background program processing daemon Loaded: loaded (/lib/systemd/system/cron.service; enabled; vendor preset: enabled) Active: active (running) since Thu 2024-04-04 19:50:25 UTC; 2 days ago Docs: man:cron(8) Main PID: 605 (cron) Tasks: 1 (limit: 4647) Memory: 1016.0K CPU: 3.943s CGroup: /system.slice/cron.service └─605 /usr/sbin/cron -f -P Apr 07 11:17:01 Software CRON[12453]: pam_unix(cron:session): session closed for user root Apr 07 12:00:01 Software CRON[12521]: pam_unix(cron:session): session opened for user root(uid=0) by (uid=0) Apr 07 12:00:01 Software CRON[12522]: (root) CMD (test -x /usr/bin/certbot -a \! -d /run/systemd/system && perl -e 'sleep int(rand(43200))' && certbot -q r> Apr 07 12:00:01 Software CRON[12521]: pam_unix(cron:session): session closed for user root Apr 07 12:17:01 Software CRON[12528]: pam_unix(cron:session): session opened for user root(uid=0) by (uid=0) Apr 07 12:17:01 Software CRON[12529]: … -
AttributeError: 'set' object has no attribute 'decode'
I started learning Django for a school project and I'm doing a chat project using websocket server, but when reloading the app I get this error even tho I'm not calling decode() anywhere. I'm using Django Channels with Daphne. here is my consumers.py from channels.generic.websocket import WebsocketConsumer class ChatConsumer(WebsocketConsumer): def connect(self): self.accept() def disconnect(self, code): pass here is my routing.py from django.urls import path from . import consumers websocket_urlpatterns = [ # path('chat/', consumers.ChatConsumer.as_asgi()) path('chat/', consumers.ChatConsumer.as_asgi()) ] here is my asgi.py import chat.routing import os from channels.routing import ProtocolTypeRouter, URLRouter from channels.security.websocket import AllowedHostsOriginValidator from django_channels_jwt_auth_middleware.auth import JWTAuthMiddlewareStack from django.core.asgi import get_asgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'core.settings') application = ProtocolTypeRouter({ 'http': get_asgi_application(), 'websocket': AllowedHostsOriginValidator( JWTAuthMiddlewareStack( URLRouter(chat.routing.websocket_urlpatterns) ) ) }) I received this traceback WebSocket HANDSHAKING /chat/ [127.0.0.1:49878] WebSocket CONNECT /chat/ [127.0.0.1:49878] Exception inside application: 'set' object has no attribute 'decode' Traceback (most recent call last): File "/Users/macbook/programacao/pap/env/lib/python3.12/site-packages/django/contrib/staticfiles/handlers.py", line 101, in __call__ return await self.application(scope, receive, send) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/macbook/programacao/pap/env/lib/python3.12/site-packages/channels/routing.py", line 62, in __call__ return await application(scope, receive, send) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/macbook/programacao/pap/env/lib/python3.12/site-packages/channels/security/websocket.py", line 37, in __call__ return await self.application(scope, receive, send) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/macbook/programacao/pap/env/lib/python3.12/site-packages/django_channels_jwt_auth_middleware/auth.py", line 36, in __call__ return await self.app(scope, receive, send) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/macbook/programacao/pap/env/lib/python3.12/site-packages/channels/sessions.py", line 47, in __call__ return await self.inner(dict(scope, cookies=cookies), … -
why i cannot login with new registered users in django while i can login with previous users
in django i create a user then click the activation link to activate the account, after it is activated, I cannot login, i get DoesNotExist at / error class VerificationView(View): def get(self, request, uidb64, token): try: # ! fixed force_text to force_str as it has been removed from later Django Versions id = force_str(urlsafe_base64_decode(uidb64)) user = User.objects.get(pk=id) if not token_generator.check_token(user, token): return redirect("login"+"?message"+"User already activated") if user.is_active: return redirect("login") user.is_active = True user.save() messages.success(request, "Account activated successfully") return redirect("login") except Exception as ex: pass return redirect("login") class LoginView(View): def get(self, request): return render(request, "authentication/login.html") def post(self, request): username = request.POST["username"] password = request.POST["password"] if username and password: user = auth.authenticate(username=username, password=password) if user: if user.is_active: auth.login(request, user) messages.success( request, "Welcome, "+user.username+" you are now logged in to your account") return redirect("expenses") else: messages.error( request, "Account is not active, please check your email!") return render(request, "authentication/login.html") else: messages.error(request, "Invalid credentials, try again") return render(request, "authentication/login.html") else: messages.error( request, "Please provide both username and password.") return render(request, "authentication/login.html") with previous logins all is fine, only new registered users are getting this error -
Webapp in pure Pyton resp. without JS?
I search a Language and / or Framework to develop a professional Webapp in (for example) pure Python. My prefered language is python, but i could also use somethin other. The point is, that I don't want to use JavaScript, because i probably hate that shit. (sorry for that statement). I was flirting with Django and recently read about Reflex. But I'm not sure if I can develop a really stunning frontend with Django (without a JS framework) and Reflex perhaps seems to be a bit immature (I'm not sure about this...). So the goal is to develop a whole Webapp (but more or less small and simple) without using JS, and ideally with python. Since i perhaps wanna do some numerical calculations or data science stuff in the backend / background, i think python would be easy and straight forward. Constraints: I don't want to use the Microsoft dotnet stuff. It's important, that i can use nearly any database in the background. Perhaps I wanna use a Graph-Database at the end. But i'ts open now. (... open arch, freedom to choose...) Optional: I could also use some other langauge? (sic!) It should be fully OpenSource to use, perhaps with … -
Unable to create UserProfile object for User
I have a User model and a UserProfile model with a one-to-one relationship. I'm using a serializer to create users, and I want to automatically create a corresponding UserProfile object for each user upon creation. However, I'm encountering an issue where the UserProfile object is not getting created when I create a new user. Despite setting up the UserProfile model with a OneToOneField relationship to the User model and specifying the related name as "userprofile", I keep getting an error stating that there is no related object. Additionally, when I retrieve user data using the GET method with this serializer, the userprofile field shows as null, even though I expect it to contain the related UserProfile object. Here's my UserSerializer: class UserSerializer(serializers.ModelSerializer): userprofile = UserProfileSerializer(read_only=True) profile_data = serializers.JSONField(write_only=True) class Meta: model = account_models.User fields = ( "id", "username", "password", "email", "is_premium", "premium_time", "userprofile", "profile_data" ) extra_kwargs = { "password": {"write_only": True}, } def create(self, validated_data): profile_data = validated_data.pop('profile_data') image_path = profile_data.pop("image_path", None) password = validated_data.pop("password") user = account_models.User.objects.create(**validated_data) user.set_password(password) user.save() userprofile = profile_models.UserProfile.objects.create(user=user, **profile_data) if image_path: save_image(instance=userprofile, image_path=image_path) send_notification(user=user, action="CREATE_ACCOUNT") return user And here's the relevant part of my UserProfile model: class UserProfile(models.Model): def image_path(self, filename): return f"Users/user_{self.user.id}/{filename}" user = … -
Display a field form a foreign key onto a template
class Product(models.Model): model=models.CharField(max_length=50, null=True) serial=models.CharField(max_length=50, null=True) hd_size=models.CharField(max_length=50,null=True) ram=models.CharField(max_length=50, null=True) processor=models.CharField(max_length=50, null=True) product_type = models.CharField(max_length=10, null=True) date_purchased = models.DateField(null=True) date_created = models.DateTimeField(default=timezone.now) date_updated = models.DateTimeField(auto_now=True) employee = models.ForeignKey(Employee, on_delete=models.SET_NULL, null=True) I am trying to display the data from this model but the foreign key column "employee" is not showing on the template -
Facing this error "TypeError: Completions.create() got an unexpected keyword argument 'headers'"
Code was running fine previously , but dont know what happened now. I tried upgrading my langchain versions , but still got this error. Code is breaking on the line "response=chain.invoke({"question":question, "table_info":self.db.get_table_info()})". Previous langchain versions were supporting chain.invoke , but i guess they have changed something now . please check and help me resolve this problem. from langchain import OpenAI, SQLDatabase from langchain.chains import create_sql_query_chain from dotenv import load_dotenv import os from urllib.parse import quote_plus from langchain.chat_models import AzureChatOpenAI from langchain.prompts import ChatPromptTemplate import re class CventDemo: def __init__(self): load_dotenv() try: azure_openai_endpoint = os.getenv('OPENAI_API_BASE') os.environ["OPENAI_API_TYPE"] = os.getenv('OPENAI_API_TYPE') os.environ["OPENAI_API_VERSION"] = os.getenv('OPENAI_API_VERSION') os.environ["OPENAI_API_BASE"] = azure_openai_endpoint[:-1] if azure_openai_endpoint.endswith('/') else azure_openai_endpoint os.environ["OPENAI_API_KEY"] = os.getenv('OPENAI_API_KEY') self.deployment_name = os.getenv('DEPLOYMENT_NAME') self.llm = AzureChatOpenAI( model_kwargs={ "headers": {"User-Id": os.getenv("USER_ID")} }, deployment_name=self.deployment_name, model=os.getenv('MODEL_NAME'), temperature=0.0, ) self.username= os.getenv('username') self.password=os.getenv('password') self.host= os.getenv('host') self.database=os.getenv('database') self.encoded_password=quote_plus(self.password) self.mysql_uri = f"mysql+mysqlconnector://{self.username}:{self.encoded_password}@{self.host}/{self.database}" self.db = SQLDatabase.from_uri(self.mysql_uri) except Exception as e: print("An error occurred during initialization:", str(e)) exit() def run_query(self, question): try: template=""""Write a SQL query for the given task by following the listed steps: Task: {question} Follow these steps: First, create your definition of the problem. And the understood meaning. Then, prepare the logic that you will be using to solve the task using SQL. Do not make … -
Issue with Django CMS Icon Module: Missing Static Path and Extra Class in Generated Markup
I am attempting to utilize the djangocms-icon module to incorporate my own SVG icons into my Django CMS project. Following the documentation, I have successfully added Material Design icons. However, I encounter issues when adding my custom SVG icons. In my settings.py, I added the following code: with open('iconset.json') as fh: ICONSET = fh.read() DJANGOCMS_ICON_SETS = [ ('fontawesome5regular', 'far', 'Font Awesome 5 Regular', 'latest'), ('fontawesome5solid', 'fas', 'Font Awesome 5 Solid', 'latest'), ('fontawesome5brands', 'fab', 'Font Awesome 5 Brands', 'latest'), ('materialdesign', 'zmdi', 'Material Design'), (ICONSET, 'svg-icon', 'My Icons'), ] DJANGOCMS_ICON_TEMPLATES = [ ('svg', 'SVG template'), ] I have created an iconset.json file at the root of my project: { "svg": true, "spritePath": "sprites/icons.svg", "iconClass": "svg-icon", "iconClassFix": "svg-icon-", "icons": [ "svg-icon-card", "svg-icon-card-add" ] } I have also created my icons.svg file in static/sprites/icons.svg: <svg width="0" height="0" class="hidden"> <symbol xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" id="svg-icon-card"> <!-- path data --> </symbol> <symbol xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" id="svg-icon-card-add"> <!-- path data --> </symbol> </svg> Additionally, I created templates/djangocms_icon/svg/icon.html: {% load cms_tags static %} <span class="icon {{ instance.attributes.class }}"> <svg role="presentation"> <use xlink:href="{% static 'sprites/icons.svg' %}#{{ instance.icon }}"></use> </svg> </span> The issue arises in the generated markup. In the icon addition widget inspection, there … -
Websocket secure connection error in browser
can anyone tell me why the websocket connection showing error? How to fix this? //script.js Code snippet error in browser: WebSocket connection to 'wss://pdfsahakari.online:8443/sahakari/landing/ws/document-uploader/' failed: uploadFile @ script.js:16 onclick @ landing/:36 script.js:33 how to fix the issue ? -
How to send confirmation emails and scheduled emails in Django
I'm working on a Django project involving a custom user registration form. My goal is to implement a two-step email notification process upon form submission: Immediate Email Confirmation: Automatically send a customized email to the user immediately after they submit the form. Scheduled Email Notification: Send a second customized email at a later date, which is determined by the information provided when the form is created (e.g., a specific date for event reminders). The scheduling of the second email needs to be dynamic, allowing for different dates based on the form's context, such as varying event dates. How can I achieve this with Django? especially for scheduling emails to be dispatched at a future date. Note that I expect a volume of 1000 submissions per month. Thanks for your help in advance. -
Django authenticate() always returns None wile login
model.py class CustomUserManager(BaseUserManager): def create_user(self, email, name, password=None, role='user'): if not email: raise ValueError('Users must have an email address') if not name: raise ValueError('Users must have a name') user = self.model( email=self.normalize_email(email), name=name, role=role, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, name, password): user = self.create_user( email=self.normalize_email(email), name=name, password=password, role='admin', # Set the role to 'admin' for superuser ) user.is_admin = True user.is_staff = True user.save(using=self._db) return user class CustomUser(AbstractBaseUser): email = models.EmailField(verbose_name='email address', max_length=255, unique=True) name = models.CharField(max_length=255) address = models.CharField(max_length=255) country = models.CharField(max_length=255) qualifications = models.TextField(blank=True) skills = models.TextField(blank=True) exprence = models.IntegerField(max_length=255) exp_details = models.CharField(max_length=255) role = models.CharField(max_length=50, default='user') # Add the 'role' field is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) objects = CustomUserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['name'] def __str__(self): return self.email def has_perm(self, perm, obj=None): return self.is_admin def has_module_perms(self, app_label): return True forms.py class SignUpForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput) confirm_password = forms.CharField(widget=forms.PasswordInput) qualifications = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Enter qualifications as comma-separated values'}), required=False) skills = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Enter skills as comma-separated values'}), required=False) class Meta: model = CustomUser fields = ['email', 'name', 'address', 'country', 'qualifications', 'skills', 'exprence', 'exp_details', 'password', 'confirm_password'] def clean_confirm_password(self): password = self.cleaned_data.get('password') confirm_password = self.cleaned_data.get('confirm_password') if password != confirm_password: raise forms.ValidationError("Passwords do not … -
What is the best approach for class inheritance and custom view tracking in Django?
I'm trying to figure out how to properly use class inheritance in Django. One thing I'm struggling with is making a custom view that keeps track of what users are doing. The main thing I'm stuck on is the class I made: class Tracker: activity = None def action(self, *login_user: User, whom: User, is_current: bool) -> None: """Create Action model""" ... def visitor(self, login_user: User, whom: User) -> None: """create a Visitor model""" ... @validate_view_inheritance def tracker(self, login_user: User, whom: User): url_user = self.kwargs.get("username") login_user: User = self.request.user is_current_user = login_user.username == url_user self.action(login_user=login_user, whom=whom, is_current=is_current_user) self.visitor(whom, login_user) You can noticed that I'm trying to get info about request and kward, but they're not part of the class itself. It seems to work only when I inherit this class with certain Views. Is this the right way to do it? Additionally, I use a custom decorator that checks if this class is a subclass of View. If not, it raises an ImproperlyConfigured error. In the future, I want to use this class to make custom views like this: class CustomDetailView(DetailView, EpulsTracker): activity = ActionType.PROFILE def get(self, request, *args, **kwargs): """Overrides the get method.""" self.object = self.get_object() context = self.get_context_data(object=self.object) # … -
How we can implement the share button on our website so that while sharing
when we are trying the implementation of the sharing then we are stuck to share the link of the current page but we want the code, to send only the content without the page link. We want the code, to send only the content without the page link. -
Why do I get an error when migrating the module about the absence of the path_to_storage module?
Why do I get an error when migrating the module about the absence of the path_to_storage module? there is no word about this module on google. I wanted to add a django-ckeditor-5 editor and was guided by this article - enter link description here. Below I am sending my actions and what errors I received. What did I do wrong? $ pip install django-ckeditor-5==0.2.12 $ cat Project1/settings.py from pathlib import Path import os ... INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'portfolio', #'ckeditor', #'ckeditor_uploader', 'django_ckeditor_5', ] ... # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/5.0/howto/static-files/ STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), ] # Default primary key field type # https://docs.djangoproject.com/en/5.0/ref/settings/#default-auto-field DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' MEDIA_URL = "/media/" #MEDIA_ROOT = BASE_DIR / "media/" MEDIA_ROOT = os.path.join(BASE_DIR, 'media') customColorPalette = [ { 'color': 'hsl(4, 90%, 58%)', 'label': 'Red' }, { 'color': 'hsl(340, 82%, 52%)', 'label': 'Pink' }, { 'color': 'hsl(291, 64%, 42%)', 'label': 'Purple' }, { 'color': 'hsl(262, 52%, 47%)', 'label': 'Deep Purple' }, { 'color': 'hsl(231, 48%, 48%)', 'label': 'Indigo' }, { 'color': 'hsl(207, 90%, 54%)', 'label': 'Blue' }, ] CKEDITOR_5_CUSTOM_CSS = 'path_to.css' # optional CKEDITOR_5_FILE_STORAGE = "path_to_storage.CustomStorage" # optional CKEDITOR_5_CONFIGS = { 'default': { 'toolbar': ['heading', … -
Trouble with Django Authentication: Instead of showing templates it show admin page
I'm currently learning Django authentication and have encountered an issue with customizing HTML templates. Instead of displaying my custom templates, Django redirects me to the admin dashboard. For instance, when I modify LOGOUT_REDIRECT_URL to logout and name in TemplateView to logout, I expect to see my custom logout page located at templates/registration/logout.html. However, Django continues to redirect me to the default admin dashboard logout page. But when i set both to customlogout then it directs me correctly. Similarly, I face a problem with the "Forgotten your password?" button. When clicking on it, I anticipate being directed to templates/registration/password_reset_form.html, but instead, I'm redirected to the Django admin dashboard. Below is my code setup: settings.py: LOGIN_REDIRECT_URL = 'home' LOGOUT_REDIRECT_URL = "customlogout" app urls.py: from django.urls import path from django.views.generic import TemplateView urlpatterns = [ path('', TemplateView.as_view(template_name='home.html'), name='home'), path('logout/', TemplateView.as_view(template_name='logout.html'), name='customlogout'), ] project urls.py: from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('account.urls')), path("accounts/", include("django.contrib.auth.urls")), ] Password reset template templates/registration/password_reset_form.html: <h1>Password Reset</h1> <p>Enter your email ID to reset the password</p> <form method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">Reset</button> </form> -
Template code not showing in Django template file despite moving from base.html to sports.html
I have a Django project where I initially wrote all the HTML and template code in the base.html file. However, as my project grew, I decided to organize my templates better by moving specific code to separate template files. I created a new template file named sports.html and copied the relevant code from base.html to sports.html. However, when I view the sports.html page in my browser, I only see the contents of base.html being rendered, and the code I moved to sports.html is not showing up. Here's the structure of my sports.html file: {% extends 'BTXApp/base.html' %} {% block content %} <!-- My content code goes here --> <!-- But it's not showing up in the rendered page --> {% endblock %} I have double-checked the paths and the configuration in my Django settings, and everything seems to be correct. I can see the code perfectly fine in my text editor (Sublime Text), but it's not rendering in the browser. What could be causing this issue, and how can I resolve it? Any help or insights would be greatly appreciated. Thank you! -
Django-React App not finding manifest.json file
I am working on a Django + React powered system. I have encountered this manifest not found error for a while now. The frontend page shows nothing at all. Help me find the root cause. I have shared the images as follows: 1.) The image of the error: enter image description here 2.)Image of the admin working perfectly: enter image description here Any help will really be appreciated. Here is the link to my github where the files are:https://github.com/FelixOmollo/FourthYearProject Here is my navbar code: import AuthContext from '../context/AuthContext' import {useContext} from 'react' import jwt_decode from "jwt-decode"; import { Link } from 'react-router-dom' function Navbar() { const {user, logoutUser} = useContext(AuthContext) const token = localStorage.getItem("authTokens") if (token){ const decoded = jwt_decode(token) var user_id = decoded.user_id } return ( <div> <nav class="navbar navbar-expand-lg navbar-dark fixed-top bg-dark"> <div class="container-fluid"> <a class="navbar-brand" href="#"> <Navbar.Brand href='/'>SPORRMS</Navbar.Brand> </a> <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarNav"> <ul class="navbar-nav "> <li class="nav-item"> <a class="nav-link active" aria-current="page" href="/s">Home</a> </li> <li class="nav-item"> <Link class="nav-link" to="/about">About</Link> </li> {token === null && <> <li class="nav-item"> <Link class="nav-link" to="/login">Login</Link> </li> <li class="nav-item"> <Link class="nav-link" to="/register">Register</Link> </li> </> } {token !== null && <> <li … -
RelatedObjectDoesNotExist at /account/edit/ User has no profile
I can edit other users with no admin status with no issues but this error message saying RelatedObjectDoesNotExist at /account/edit/ User has no profile when i try to edit superuser. I created this superuser AFTER I have added Profile module class with its attributes, and making migrations. Spent hours trying to figure it out but couldn't. Thank yall for any help Models.py from django.db import models from django.contrib.auth.models import User from django.conf import settings class Profile(models.Model): print(f'------->{settings.AUTH_USER_MODEL}') user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) date_of_birth = models.DateField(blank=True, null=True, default=None) photo = models.ImageField(blank=True, upload_to="users/%Y/%m/%d/") def __str__(self): return f'Profile of {self.user.username}' Views.py from account.models import Profile @login_required def Edit(request): if request.method == "POST": user_form = UserEditForm(instance= request.user, data=request.POST) profile_form = ProfileEditForm(instance= request.user.profile,data=request.POST, files=request.FILES) if user_form.is_valid(): user_form.save() profile_form.save() return render(request,'account/dashboard.html') else: user_form = UserEditForm(instance= request.user) profile_form = ProfileEditForm(instance= request.user.profile) return render(request, "account/edit.html",{'user_form':user_form}) forms.py class UserEditForm(forms.ModelForm): class Meta: model = User fields = ['first_name', 'last_name','email'] def clean_email(self): data = self.cleaned_data['email'] qs = User.objects.exclude(id=self.instance.id).filter(email=data) if qs.exists(): raise forms.ValidationError('email already in use') else: return data class ProfileEditForm(forms.ModelForm): class Meta: model = Profile fields = ['date_of_birth','photo'] edit.html {% extends "base.html" %} {% block content %} <html> <p>Please enter correct information bellow to edit</p> <form method="POST" enctype="multipart/form-data"> {{user_form.as_p}} {{profile_form.as_p}} {% csrf_token … -
Django REST Framework: can't properly annotate values to many-to-many model, keep getting error Field name <field> is not valid for model <m2m model>
I have a model for recipes and many-to-many model that represents favorite recipes by users: class Recipe(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=LENGTH_FOR_TEXTFIELD) image = models.ImageField() text = models.TextField(max_length=LENGTH_FOR_TEXTFIELD) cooking_time = models.PositiveSmallIntegerField() def __str__(self): return self.name class FavoriteRecipe(models.Model): recipe = models.ForeignKey(Recipe, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.recipe.name After POST request an entry in that model is created (recipe ID and user ID) and i am trying to write a serializer for response that will contain info about recipe itself: class FavoriteRecipeSerializerForRead(serializers.ModelSerializer): class Meta: model = FavoriteRecipe fields = ('id', 'name', 'image', 'cooking_time') So the problem is that i cannot insert into this serializer any recipe-field because i keep getting error: django.core.exceptions.ImproperlyConfigured: Field name `name` is not valid for model `FavoriteRecipe` I tried to imply select_related() and .annotate(field=Value(Query)) in my viewset like this but nothing seems to work: class FavoriteRecipeViewSet(viewsets.ModelViewSet): queryset = FavoriteRecipe.objects.all() serializer_class = FavoriteRecipeSerializerForRead def get_queryset(self): queryset = FavoriteRecipe.objects.all().annotate( recipe=Value( Recipe.objects.filter(id=self.id).values('cooking_time',) ) ) return queryset The question is: how could i do this the proper way? -
Can I Register a Django Project's Inner Directory as an App Within the Same Project?
Within a Django project, such as "myproject," where a subdirectory named "myproject" is automatically created, I've registered this subdirectory as an app with the intention of using it as a control app for the entire project. For instance, if my project directory structure looks like this: myproject/ ├── myproject/ │ ├── __init__.py │ ├── settings.py │ ├── urls.py │ ├── apps.py <!-- the odd addition --> │ ├── wsgi.py │ └── asgi.py ├── myapp1/ │ ├── __init__.py │ ├── models.py │ ├── views.py │ └── ... └── ... I've registered the inner "myproject" directory as an app within the Django project. Despite this setup functioning smoothly, I'm curious about the community's thoughts or any considerations regarding this approach. Are there any insights, opinions, or best practices associated with registering the project directory as an app within a Django project? -
JQuery .show() working, but .hide() not working
I am trying to build a dropdown select box in js, which I have to use js as it includes images. The problem is, when I click on the "input box" i made the jquery code to open it works i.e. $('#ratingDropdownContainer').on('click', function() { if ($('#dropdownListContainer').css('display') == 'none') { $('#dropdownListContainer').show(); } }) and there is no problem. But when the user selects one of the options, the .hide() won't work. The in-line style of style="display: block;" doesn't change when I do $('#dropdownListContainer').hide(); I have tried many things such as: making sure its wrapped in a $(document).ready(function(), checking if js recognizes its display is block (which it is as the console.log("okokoko"); prints as seen in my code below), I make sure my jquery is loaded before my js file, I tried using vanilla js instead, but none of those have worked, and I don't understand why the .show() would work but not the .hide(). Any help would be appreciated. Thank you. js: $('#ratingDropdownContainer').on('click', function() { if ($('.dropdown-list-container').css('display') == 'none') { $('.dropdown-list-container').show(); } }) $('.avg-rating-select').on('click', function() { var selectedRatingImg = $(this).find('img').prop('outerHTML'); var selectedRatingText = $(this).find('p').prop('outerHTML'); var newDiv = $("<div>" + selectedRatingImg + selectedRatingText + "</div>"); newDiv.addClass("rating-selected-container"); if ($('.rating-selected-container').length) { $('.rating-selected-container').replaceWith(newDiv); } else … -
Django modeltranslation not working properly on templates
I have set up and configured django-modeltranslation for a project according to the documentation as follows: urls.py from django.conf.urls.i18n import set_language from django.conf.urls.i18n import i18n_patterns urlpatterns = i18n_patterns( ... path('set_language/', set_language, name='set_language'), ) settings.py from django.utils.translation import gettext_lazy as _ INSTALLED_APPS = [ 'modeltranslation', ... ] MIDDLEWARE = [ ... 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', ... ] TIME_ZONE = 'CET' LANGUAGE_CODE = 'en' LANGUAGES = [ ('en', _('English')), ('cz', _('Czech')), ] LOCALE_PATHS = [ BASE_DIR / 'Project/locale/', ] USE_I18N = True Homepage language switcher <form id="languageForm" action="{% url 'set_language' %}" method="post"> {% csrf_token %} <input name="next" type="hidden" value="{{ request.get_full_path|slice:'3:' }}" /> <input id="languageInput" name="language" type="hidden" value="" /> </form> onclick="setLanguage('en')" onclick="setLanguage('cz')" function setLanguage(lang) { document.getElementById('languageInput').value = lang; document.getElementById('languageForm').submit(); } In .html templates {% load i18n %} ... {% trans "Text" %} ... I collected the strings for translation using: python manage.py makemessages -l cz Then translated them in the locale django.po file and compiled them using: python manage.py compilemessages Now when running the project and switching the language to cz, only one translated string and date strings are displayed. Thank you for your help, and I hope I provided everything needed. I tried setting up the django-modeltranslation using its documentation as I provided before. -
getting error while installig python packeges
in a Django project I faced an strange error , every thing functions so smoot but whenever I want to install a package I get this error , I'm totaly sure about my network conaction and I have tried using VPN but it didn't help (using Pycharm) WARNING: Retrying (Retry(total=2, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ProxyError('Cannot connect to proxy.', NewConnectionError('<pip._ven dor.urllib3.connection.HTTPSConnection object at 0x000001FF6F9617D0>: Failed to establish a new connection: [WinError 10061] No connection could be made because the target machine acti vely refused it'))': /simple/pillow/ what's wrong ? -
Django: Redirect to object's change (admin) page while overriding save_related
I am uploading a temporary file while changin my object, and this file might have problems which I can determine after it is fully read. I want my page to be rediretded to the object's change page whenever an error occures. here's the code i wrote: def save_related(self, request, form, formsets, change): try: cleaned_data = form.cleaned_data if cleaned_data['file_field']: DEFAULT_COLUMN_INDEX = 0 try: # read file logic here that might raise an error return super().save_related(request, form, formsets, change) except ValidationError as e: messages.error(request, f"Error while proccessing data: {str(e)}") redirection_url = reverse('admin:mymodel_change', args=[form.instance.id]) return HttpResponseRedirect(redirection_url) except TimeoutError as e: messages.error(request, f"Timeout in uploading file: {str(e)}") redirection_url = reverse('admin:mymodel_change', args=[form.instance.id]) return HttpResponseRedirect(redirection_url) Note that i can not just raise the error because it is set to response 500 because of other parts of the project (long story... i just cant change them!) Here's my problem: This code redirects to the mymodel admin page, not the change page of the object. So, here's my questions: Am i doing the right approach (since I'm new to django)? If the approach's fine, how can i fix it? -
NameError at /admin/ name 'process_request' is not defined
when i try to access to admin pannel in django project i face problem : NameError at /admin/ name 'process_request' is not defined: Internal Server Error: /admin/ Traceback (most recent call last): File "C:\Users\HP\IdeaProjects\Weather_Backend\venv\Lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) ^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\HP\IdeaProjects\Weather_Backend\venv\Lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\HP\IdeaProjects\Weather_Backend\venv\Lib\site-packages\django\contrib\admin\sites.py", line 259, in wrapper return self.admin_view(view, cacheable)(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\HP\IdeaProjects\Weather_Backend\venv\Lib\site-packages\django\utils\decorators.py", line 181, in _view_wrapper result = _pre_process_request(request, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\HP\IdeaProjects\Weather_Backend\venv\Lib\site-packages\django\utils\decorators.py", line 127, in _pre_process_request result = process_request(request) ^^^^^^^^^^^^^^^ NameError: name 'process_request' is not defined i'm expecting to access to django admin panel as normal