Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Use of django-modeltranslation with django-filter
I'm constructing Django-based 4-language website for a real estate agency. I'm using django-modeltranslation for translation and django-filter package to filter property objects by certain parameters, such as type (house, apartment, etc.), city and some others. The 'type' of a property is a foreign key of the related model 'Type'. It uses ModelChoiceFilter to select all available types from the database, and render them as a select element with options, which is and is displayed as a drop list with options, which is good so far. class SalePropertyFilter(FilterSet): ... type = ModelChoiceFilter( queryset=Type.objects.all(), empty_label=_("Any type"), label="", widget=forms.Select(attrs={'class': 'form-control'}), ) However, the drop-down list looks ugly, since the field label is not translated, and the options are displayed as slug names of the related model. What I want is that options are displayed as common names of types (which are in the field 'name') instead of slug names, and they should be translated. That means, in the English version of the site options should be rendered from the field 'name_en', in the Spanish version - from 'name_es', etc. There should be a proper way to do it. Please, help, I'm stuck! -
django.db.utils.OperationalError: no such table: auth_user; but works with django admin
i am beginner to django and learn how to create custom user model using abstractuser in my accounts app. But while creating registration system I got this issue: django.db.utils.OperationalError: no such table: auth_user Request URL: http://localhost:8000/accounts/register/ Django Version: 4.2.6 Python Version: 3.11.6 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'accounts.apps.AccountsConfig'] Installed 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'] Traceback (most recent call last): File "/data/data/com.termux/files/usr/lib/python3.11/site-packages/django/db/backends/utils.py", line 89, in _execute return self.cursor.execute(sql, params) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/data/data/com.termux/files/usr/lib/python3.11/site-packages/django/db/backends/sqlite3/base.py", line 328, in execute return super().execute(query, params) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ The above exception (no such table: auth_user) was the direct cause of the following exception: File "/data/data/com.termux/files/usr/lib/python3.11/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) ^^^^^^^^^^^^^^^^^^^^^ File "/data/data/com.termux/files/usr/lib/python3.11/site-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/data/data/com.termux/files/usr/lib/python3.11/site-packages/django/views/generic/base.py", line 104, in view return self.dispatch(request, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/data/data/com.termux/files/usr/lib/python3.11/site-packages/django/views/generic/base.py", line 143, in dispatch return handler(request, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/data/data/com.termux/files/home/qrkeeper/accounts/views.py", line 55, in post user.save() ^^^^^^^^^^^ File "/data/data/com.termux/files/usr/lib/python3.11/site-packages/django/contrib/auth/base_user.py", line 76, in save super().save(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/data/data/com.termux/files/usr/lib/python3.11/site-packages/django/db/models/base.py", line 814, in save self.save_base( ^ File "/data/data/com.termux/files/usr/lib/python3.11/site-packages/django/db/models/base.py", line 877, in save_base updated = self._save_table( File "/data/data/com.termux/files/usr/lib/python3.11/site-packages/django/db/models/base.py", line 1020, in _save_table results = self._do_insert( File "/data/data/com.termux/files/usr/lib/python3.11/site-packages/django/db/models/base.py", line 1061, in _do_insert return manager._insert( File "/data/data/com.termux/files/usr/lib/python3.11/site-packages/django/db/models/manager.py", line 87, in … -
Django profile update comes out as an error
I have been developing a blog and facing the same issue again and again. "" p_form = ProfileUpdateForm(instance=request.user.profile) "" This part of the code is showing an error and I have no idea what to do. I have tried everything. The error is ""Exception Value: User has no profile."" I tried manually creating a profile. No use. Please help -
How can I add my python code to my django web app?
So I'm building a website using django and what it's supposed to do is detect emotions in real time, like there should be a button to start and stop detecting and it will use the device's webcam. I've already built both the django project and app and written the python code to do that but i wrote them separately. The problem comes when I'm trying to add the python code to my web app views.py and template(html). This is my code, could someone help me out? #mood detection python code import cv2 import numpy as np from deepface import DeepFace def detect_emotions(): face_cascade_name = cv2.data.haarcascades + 'haarcascade_frontalface_alt.xml' face_cascade = cv2.CascadeClassifier() if not face_cascade.load(cv2.samples.findFile(face_cascade_name)): print("Error loading xml file") cap = cv2.VideoCapture(0) while True: ret, frame = cap.read() resized_frame = cv2.resize(frame, (48, 48), interpolation=cv2.INTER_AREA) gray_frame = cv2.cvtColor(resized_frame, cv2.COLOR_BGR2GRAY) img = gray_frame.astype('float32') / 255.0 img = np.expand_dims(img, axis=-1) img = np.expand_dims(img, axis=0) analyze = DeepFace.analyze(frame, actions=['emotion'], enforce_detection=False) cv2.rectangle(frame, (0, 0), (200, 30), (0, 0, 0), -1) first_data = analyze[0] dominant_emotion = first_data['dominant_emotion'] text = str(dominant_emotion) cv2.putText(frame, text, (10, 20), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 2) cv2.imshow('Real-time Emotion Detection', frame) if cv2.waitKey(1) & 0xFF == ord('q'): break cap.release() cv2.destroyAllWindows() if __name__ == "__main__": detect_emotions() … -
How to display a non-default value in django-admin?
I have the Model: class Question(models.Model): type = models.CharField( choices=[["text", "Text"], ["choice", "Choice"]], max_length=6, ) structure = models.JSONField( default=dict, ) def get_default_structure(self) -> dict: if self.type == "text": return {"maxLength": None} if self.type == "choice": return {"variants": []} return dict() @receiver(post_init, sender=Question) def set_default_structure(sender: Type[Question], **kwargs): instance = kwargs["instance"] if not instance.structure: instance.structure = instance.get_default_structure() Also there is Form and ModelAdmin: class QuestionForm(ModelForm): class Meta: model = Question fields = "__all__" @admin.register(Question) class QuestionAdmin(admin.ModelAdmin): form = QuestionForm By logic, after initializing an empty Question, the structure field should be overwritten, and it is. But still the admin form for some reason displays the {} value gotten from default=dict. Why does this happen and how can I make the structure widget display not the {} value, but the value taken from the get_default_structure method? -
Static files not loaded when deploy a django web page in vercel(with whitenoise)
when the project is deployed shows this error here is my settings.py: import os from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-^30@=wx2m&2q6l48hxb*y6c%0negga@@eixcj5%-rn^3yzo#^k' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['*'] # Application definition INSTALLED_APPS = [ 'me', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', "whitenoise.runserver_nostatic", 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', "whitenoise.middleware.WhiteNoiseMiddleware", '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', ] ROOT_URLCONF = 'Matheus.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [BASE_DIR, 'templates'], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'Matheus.wsgi.application' # Database # https://docs.djangoproject.com/en/4.2/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } # Password validation # https://docs.djangoproject.com/en/4.2/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/4.2/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/4.2/howto/static-files/ STATIC_URL = '/static/' STATIC_ROOT … -
Django Q() for filtering returns the same objects multiple times
I am making a tutoring dashboard in Django. The tools used are htmx,jquery, bootstrap. In the tutors.html page, there is a searchbar. When an user types something, it will send a request to the server and it would call the view search_tutor. The following is the code: <form method="POST"> {% csrf_token %} <div class="form-floating mb-3"> <input class="form-control" id="search-input" hx-get="{% url 'search_tutor' %}" hx-target="#tutors" hx-trigger="keyup changed" name="q" placeholder="Search Tutor" data-sb-validations="required"> <label class="text-muted" for="q"> Search Tutor</label> </div> </form> <div id="tutors" style="transition:1s"> {% include "templates/partials/tutors.html" %} </div> The Tutor Model is the following: class Account(models.Model): token = models.CharField(max_length=50, unique=True) user = models.OneToOneField(User, on_delete=models.CASCADE) profile_picture = models.ImageField(upload_to=upload_prof_pic, blank=True, null=True) school = models.ForeignKey(School, on_delete=models.CASCADE , null=True) country = models.ForeignKey(Country, on_delete=models.DO_NOTHING, related_name='account_country', null=True) phone = models.CharField(max_length=20, blank=False) added = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) stripe_account = models.CharField(max_length=300, blank=True) stripe_client = models.CharField(max_length=300, blank=True) is_tutor = models.BooleanField(default=False) description = models.TextField(max_length=600, blank=False) tutor_subject = models.ManyToManyField(Subject, blank=True, null=True ) def __str__(self): return str(self.user) def get_phone(self, *args, **kwargs): if self.country != None: return f"+{self.country.phone_extension} ({self.phone1})-{self.phone2}-{self.phone3}" else: return "NONE" def rating_score (self, *args, **kwargs): total = 0 amount = 0 r = Rating.objects.filter(user=self.user) if r.count() == 0 : return 0 else: for i in r.all(): total += i.rating amount +=1 return total/amount def … -
How can i save cart in session if user logout?
I store users carts in sessions, but when they log out their accounts, they are deleted. I decided to save the keys when they logout of their account in the database, and restore them in the sessions when they login. Is this method reliable and secure today, and are there any other methods? class UserLoginView(View): def post(self, request): email = request.POST.get('username') password = request.POST.get('password') if email and password: user = auth.authenticate(email=email, password=password, request=request) if user is not None and user.is_active: login(request, user) if SessionKey.objects.filter(user=request.user).exists(): session_key = SessionKey.objects.get(user=request.user) if session_key.key: cart = json.loads(session_key.key) request.session[settings.CART_SESSION_ID] = cart return JsonResponse({'status': 200}) return JsonResponse({'status': 400}) return JsonResponse({'status': 400}) def logout(request): cart = request.session.get(settings.CART_SESSION_ID, None) session_key, created = SessionKey.objects.get_or_create(user=request.user) auth.logout(request) if cart: session_key.key = json.dumps(cart) session_key.save() return HttpResponseRedirect(reverse('home')) -
What is the most secure way to store sessions with Django?
What Django session storage should I use for enhanced security? -
You cannot call this from an async context - use a thread or sync_to_async. Django ORM
I wrote the following code: class BookmakerA: def __init__(self) -> None: self.bookmaker = None async def _init(self): self.bookmaker, _ = await Bookmaker.objects.aget_or_create(name="BookmakerA", defaults={"name": "BookmakerA"}) I call this class from a Celery task which looks as follows: @shared_task def get_bookmaker_matches(): start = time.time() bookmakera = BookmakerA() loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) loop.run_until_complete(bookmakera._init()) This however results in the following error: django.core.exceptions.SynchronousOnlyOperation: You cannot call this from an async context - use a thread or sync_to_async. Why does this happen and how do I resolve this. Using Django 4.2.6 which supports async ORM (acreate_or_create, aget, so on) -
Declare Instance variables in django-formtools SessionWizardView
Using SessionWizardView, I want to declare Instance variables, that persist between steps. However, they are not persistent, when using: def __init__(self): self.variable = {} -
ValueError in Django. Invalid literal for int() with base 10: ' '
I'm creating a portfolio website using Django where I created a superuser and implemented a user interface for myself from where I can login and update my skills or add projects instead of manually updating the frontend of the website. I deployed it on Railway. When I login on the website, I get the following error: Environment: Request Method: POST Django Version: 4.2.6 Python Version: 3.8.18 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'whitenoise.runserver_nostatic', 'django.contrib.staticfiles', 'base'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "/opt/venv/lib/python3.8/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) File "/opt/venv/lib/python3.8/site-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/opt/venv/lib/python3.8/site-packages/django/views/generic/base.py", line 104, in view return self.dispatch(request, *args, **kwargs) File "/opt/venv/lib/python3.8/site-packages/django/utils/decorators.py", line 46, in _wrapper return bound_method(*args, **kwargs) File "/opt/venv/lib/python3.8/site-packages/django/views/decorators/debug.py", line 92, in sensitive_post_parameters_wrapper return view(request, *args, **kwargs) File "/opt/venv/lib/python3.8/site-packages/django/utils/decorators.py", line 46, in _wrapper return bound_method(*args, **kwargs) File "/opt/venv/lib/python3.8/site-packages/django/utils/decorators.py", line 134, in _wrapper_view response = view_func(request, *args, **kwargs) File "/opt/venv/lib/python3.8/site-packages/django/utils/decorators.py", line 46, in _wrapper return bound_method(*args, **kwargs) File "/opt/venv/lib/python3.8/site-packages/django/views/decorators/cache.py", line 62, in _wrapper_view_func response = view_func(request, *args, **kwargs) File "/opt/venv/lib/python3.8/site-packages/django/contrib/auth/views.py", line 90, in dispatch return super().dispatch(request, *args, **kwargs) File "/opt/venv/lib/python3.8/site-packages/django/views/generic/base.py", line 143, in dispatch return handler(request, *args, **kwargs) … -
custom permissions in django DRF class based view
I'm trying to set custom permissions in a ModelViewSet. I want to allow any authenticated user to list and retrieve items but only Admin and Manager can create, update, and destroy. Here is the relevant code in views.py from rest_framework import viewsets from .serializers import MenuItemSerializer from rest_framework import viewsets from .permissions import IsManager from rest_framework.permissions import IsAuthenticated, IsAdminUser class Showitem(CustomThrottleMixin, viewsets.ModelViewSet): queryset = MenuItem.objects.all() serializer_class = MenuItemSerializer authentication_classes = [TokenAuthentication] permission_classes = [] filterset_fields = ['category', 'title','price','featured'] ordering_fields = ['title','title', 'category'] search_fields=['title','category__title'] def get_permissions(self): #Override default method. Set custom permissions for each action if self.action in ['update', 'partial_update', 'destroy', 'create']: self.permission_classes = [IsAdminUser, IsManager] elif self.action in ['list', 'retrieve']: self.permission_classes = [IsAuthenticated] #return default method if none of the above is true return super().get_permissions() Here permissions.py class IsManager(permissions.BasePermission): def has_permission(self, request, view): if request.user.is_authenticated: return request.user.groups.filter(name='manager').exists() return False when I try to post a new Item as admin user via the api endpoint everything works. If I try the same as Manager I get " "detail": "You do not have permission to perform this action."" -
Django Duplicate object with inline object
I have recipe model with ingredients and ingredients quantities. MEAL_TYPES = (("midi", "Midi"), ("soir", "Soir"), ('all', 'Non spécifié')) class Ingredient(models.Model): name = models.CharField(max_length=100) # Vous pouvez ajouter d'autres champs pour stocker des informations supplémentaires sur les ingrédients def __str__(self): return self.name class Recipe(models.Model): """ A model to create and manage recipes """ user = models.ForeignKey( User, related_name="recipe_owner", on_delete=models.CASCADE ) title = models.CharField(max_length=300, null=False, blank=False) description = models.CharField(max_length=500, null=False, blank=False) instructions = RichTextField(max_length=10000, null=False, blank=False) ingredients = RichTextField(max_length=10000, null=False, blank=False) image = ResizedImageField( size=[400, None], quality=75, upload_to="recipes/", force_format="WEBP", blank=False, null=False, ) image_alt = models.CharField(max_length=100, default="Recipe image") meal_type = models.CharField(max_length=50, choices=MEAL_TYPES, default="all") calories = models.IntegerField(default=0) posted_date = models.DateTimeField(auto_now=True) newingredient = models.ManyToManyField(Ingredient, through='IngredientQuantite') class Meta: ordering = ["-posted_date"] def __str__(self): return str(self.title) class IngredientQuantite(models.Model): recipe = models.ForeignKey(Recipe, on_delete=models.CASCADE) ingredient = models.ForeignKey(Ingredient, on_delete=models.CASCADE) quantity = models.FloatField(default=0) unite = models.CharField(default="g", max_length=20, choices=[("g", "g"),('mg', 'mg'), ("ml", "ml"),('kg', "kg"), ('cl', "cl"), ('l', "l"), ('caf', "cuillère à café"), ('cas', "cuillère à soupe"), ('verre', "verre"), ('bol', "bol"), ('pincee', "pincée"), ('unite', "unité")]) # Le champ "quantity" stocke la quantité de cet ingrédient dans la recette. # 'g', 'kg', 'ml', 'cl', 'l', 'cuillère à café', 'cuillère à soupe', 'verre', 'bol', 'pincée', 'unité' def __str__(self): return f"{self.quantity} {self.ingredient} in {self.recipe}" To add … -
Django REST: endpoint for creating multiple models
In my service, when registering a user, two entities must be created: the user and the company, to which the user entity will be immediately linked. To do this, I created an endpoint in which I use two serializers (for the user and for the company). But there are some problems with this solution: Fields for one of the serializers are not displayed in Django Spectacular (Swagger); Fields for one of the serializers are not available in the DRF BRowsable API; Ugly code; class UserCreateViewSet(mixins.CreateModelMixin, viewsets.GenericViewSet): """ Creates user accounts """ queryset = User.objects.all() serializer_class = CreateUserSerializer permission_classes = (AllowAny,) REQUIRED_FIELDS = ( 'email', 'password', 'position', 'company_name', 'phone_number' ) def create(self, request, *args, **kwargs): data = request.data provided_fields = set(data.keys()) for field in self.REQUIRED_FIELDS: if field not in provided_fields: return Response( {"detail":f"{field} not provided"}, status=400 ) # --- Creating company for user data['name'] = data['company_name'] company_serializer = CompanyReducedSerializer(data=request.data) company_serializer.is_valid(raise_exception=True) self.perform_create(company_serializer) data['company'] = company_serializer.data['id'] # --- # Code from super() # --- Creating user user_serializer = self.get_serializer(data=request.data) user_serializer.is_valid(raise_exception=True) self.perform_create(user_serializer) headers = self.get_success_headers(user_serializer.data) # --- return Response( status=201, data=user_serializer.data, headers=headers ) I considered options using multi-table inheritance, but for some reasons, this solution does not suit me. The company and user entities … -
how do solve this 'TypeError: Object of type ValueError is not JSON serializable' in my program?
in windows 10 , i am using Django==4.2.4 and visual studio code and **djangorestframework==3.14.0 **, react 17.0.2. BACKEND: views.py: section1 @api_view(http_method_names=['POST']) def register_user(request): data = request.data print(data) try: CustomUser = get_user_model() email_exists = CustomUser.objects.filter(email=data.get('email')).first() if not email_exists: random_username_list = generate_username(1) random_username = None for random_value in random_username_list: random_username = str(random_value) print(random_username) user = CustomUser.objects.create(first_name=data.get('name'), last_name=data.get('family'),username=random_username, email=data.get('email'),password=make_password(data.get('password'))) print(user.id) user = get_object_or_404(CustomUser , username=user) print(user) srz_data = UserSerializerWithToken(instance=user, many=False) print(srz_data.data) return Response(srz_data.data, status=status.HTTP_201_CREATED) else: return Response({"detail": "user with this email already exists"}, status=status.HTTP_400_BAD_REQUEST) except ValueError as error: message = { "detail": "internal error of the server !!! , please you're waiting or contacting to admin of the server", } return Response(error, status=status.HTTP_500_INTERNAL_SERVER_ERROR) else: print("Nothing went wrong") finally: print("The 'try except' is finished") section2 class MyCreatorTokenSerializer(TokenObtainPairSerializer): def validate(self, attrs): data = super().validate(attrs) serializer = UserSerializerWithToken(self.user).data for k, v in serializer.items(): data[k] = v return data class MyCreatorTokenView(TokenObtainPairView): serializer_class = MyCreatorTokenSerializer serializers.py: class UserSerializer(serializers.ModelSerializer): name = serializers.SerializerMethodField(read_only=True) family = serializers.SerializerMethodField(read_only=True) _id = serializers.SerializerMethodField(read_only=True) isAdmin = serializers.SerializerMethodField(read_only=True) sex = serializers.SerializerMethodField(read_only=True) userPicture = serializers.SerializerMethodField(read_only=True) userIp = serializers.SerializerMethodField(read_only=True) userInfo = serializers.SerializerMethodField(read_only=True) class Meta: model = get_user_model() # fields = "__all__" fields = ['_id', 'name', "family", 'email', 'sex' ,'userIp','userInfo' , 'userPicture','isAdmin' ] def get_name(self, obj): name = obj.first_name … -
error: NoReverseMatch at / Reverse for 'add_time_slot' with arguments '('',)' not found. 1 pattern(s) tried: ['add_time_slot/(?P<turf_id>[0-9]+)/\\Z']
i getting an error while doing python django project. error NoReverseMatch at / Reverse for 'add_time_slot' with arguments '('',)' not found. 1 pattern(s) tried: ['add_time_slot/(?P<turf_id>[0-9]+)/\Z'] <a class="nav-link" href="{% url 'add_time_slot' turf_id %}">Add Time Slots</a> i was tried many things but nothing works. Please help me guys....enter image description here models.py class TimeSlot(models.Model): turf = models.ForeignKey(Venue, on_delete=models.CASCADE) start_time = models.DateTimeField() end_time = models.DateTimeField() price = models.DecimalField(max_digits=10, decimal_places=2) booked = models.BooleanField(default=False) def __str__(self): return f"{self.turf.name} - {self.start_time} to {self.end_time}" views.py def add_time_slot(request, turf_id): turf = Venue.objects.get(pk=turf_id) if request.method == 'POST': form = TimeSlotForm(request.POST) if form.is_valid(): timeslot = form.save(commit=False) timeslot.turf = turf timeslot.save() return redirect('add_time_slot', turf_id=turf_id) else: form = TimeSlotForm() return render(request, 'add_time_slot.html', {'form': form, 'turf': turf}) urls.py urlpatterns = [ path('add_time_slot/<int:turf_id>/', views.add_time_slot, name='add_time_slot'), ] html ` Add Time Slots ` -
Docker-based hosting unable to reach database
I am a junior developer using django as my first web development framework. During a boilerplate construction, I am not able to host and reach a postgres database using docker. The app content is available on repository https://github.com/trouchet/tarzan. The docker daemon outputs error django.db.utils.OperationalError: could not translate host name "db" to address: Temporary failure in name resolution after I run command docker-compose build followed by command docker-compose run. I use the variable DATABASE_HOST the same as docker service db. I also make sure, there is no other postgres service on current machine. Thanks in advance for any provided help. -
How to get specific values in Django UpdateView?
I have a generic UpdateView where the leaders can manage the settings of the users whom connected to the leaders's company. I like to have only that values in the select field where the company_id is equal to the the company_uuid in the url. Now the leader who want to set the team can access to all of the companies teams. Thank you in advance models.py class Company(models.Model): def __str__(self): return str(self.company_name) def generate_uuid(): return uuid.uuid4().hex company_name = models.SlugField(max_length=100) company_uuid = models.CharField(default=generate_uuid, editable=True, max_length=40) class Team(models.Model): def __str__(self): return str(self.team) team = models.CharField(max_length=200, blank=True, null=True) company = models.ForeignKey(Company, null=True, blank=True, on_delete=models.CASCADE) class Profile(models.Model): def __str__(self): return str(self.user) user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) date = models.DateField(auto_now_add=True, auto_now=False, blank=True) company = models.ForeignKey('Company', on_delete=models.CASCADE, blank=True, null=True) team01 = models.ForeignKey('Team', on_delete=models.CASCADE, null=True, blank=True, related_name="eteam") views.py class UpdateProfileView(SuccessMessageMixin, UpdateView): model = Profile form_class = UpdateProfileForm template_name = 'users/management/update_profile.html' success_message = 'Változtatások mentve' def get_success_url(self): return self.request.META.get('HTTP_REFERER') urls.py ... path('management/update_profile/<pk>/<uuid>', login_required(UpdateProfileView.as_view()), name='UpdateProfile'), ... In the forms I don't using any widget. -
Problems when performing a query set of those leagues that have events filtered by a date timestamps
We have two models where we need to make a filter of those leagues that have games on a given date, this date is a timestamp example =: 1698292800 all this works fine, the problem is that when we get the results of this filter it brings events from other dates including the one that was filtered. Models FootballLeague model contains all soccer leagues. class FootballLeague(UUIDModel, TimeStampedModel): name = models.CharField(_("Name"), max_length=255, db_index=True) country_name = models.CharField( _("Country"), max_length=255, db_index=True, null=True, blank=True ) country_id = models.IntegerField(_("Country ID"), null=True, blank=True) def __str__(self): return self.name class Meta: verbose_name = _("Football League") verbose_name_plural = _("Football Leagues") ordering = ["name"] EventsFootball model contains all games related to a league. class EventsFootball(UUIDModel): event_id = models.CharField(max_length=255) start_time = models.IntegerField(null=True, blank=True) home_score_current = models.CharField(max_length=255, null=True, blank=True) home_score_part_1 = models.CharField(max_length=255, null=True, blank=True) home_score_part_2 = models.CharField(max_length=255, null=True, blank=True) home_images = models.JSONField(null=True, blank=True) away_score_current = models.CharField(max_length=255, null=True, blank=True) away_score_part_1 = models.CharField(max_length=255, null=True, blank=True) away_score_part_2 = models.CharField(max_length=255, null=True, blank=True) info_notice = models.CharField(max_length=255, null=True, blank=True) away_images = models.JSONField(null=True, blank=True) league = models.ForeignKey( FootballLeague, related_name="events", on_delete=models.CASCADE ) start_date = models.DateField(null=True, blank=True) def __str__(self): return f"{self.league.name} - {self.round}" The relationship or query performed so far where the games of the filtered date are brought here everything … -
Can we extend a template in multiple templates?
In Django while making templates, I created a master template where I used 3 template block tags and 2 different html files for extending (using extends template tag) and code for them. only one html code is added to master template, the other one is not added. Can we simultaneously extend a template in multiple templates? I was trying to make 2 files that extends a master template. but only one template's code is being added when I see in 'view source code'. -
NoReverseMatch at / Reverse for 'add_time_slot' with arguments '('',)' not found. 1 pattern(s) tried: ['add_time_slot/(?P<turf_id>[0-9]+)/\\Z']
I getting an error while doing python django project. The error: 'NoReverseMatch at / Reverse for 'add_time_slot' with arguments '('',)' not found. 1 pattern(s) tried: ['add_time_slot/(?P<turf_id>[0-9]+)/\Z']'. Several things i tried but nothing works please help me... view.py def add_time_slot(request, turf_id): turf = Venue.objects.get(pk=turf_id) if request.method == 'POST': form = TimeSlotForm(request.POST) if form.is_valid(): timeslot = form.save(commit=False) timeslot.turf = turf timeslot.save() return redirect('add_time_slot', turf_id=turf_id) else: form = TimeSlotForm() return render(request, 'add_time_slot.html', {'form': form, 'turf': turf}) url.py path('add_time_slot/int:turf_id/', views.add_time_slot, name='add_time_slot'), html Add Time Slots -
Switch to another subdomain in django on a click of a button
I am actually having issues with template link of a button to point to my subdomain which actually if I enter it manually on a browser, it works just fine. I need something like this {% load hosts %} <a href="{% host_url 'homepage' host 'www' %}">Home</a> But it doesn't work if i place the code above on a button. Am I missing anything?. Appreciate the help guys -
connect failed (111: Connection refused) reverse proxy using Nginx
I'm trying to revert ports to 8000 using docker, nginx and django but I get connection refused error. The docker build and compose works fine. Here is my nginx.conf file: worker_processes auto; events { worker_connections 4; } http { upstream backend { # web is the docker-compose.yml backend service server web:8000; } server { listen 80; server_name 127.0.0.1; location / { proxy_pass http://127.0.0.1:8000; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; } } } and my docker-compose.yml file: services: db: image: postgres volumes: - ./data/db:/var/lib/postgresql/data environment: - POSTGRES_DB=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres web: build: . command: python manage.py runserver 127.0.0.1:8000 volumes: - .:/code ports: - "8000:8000" environment: - POSTGRES_NAME=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres depends_on: - db nginx: image: nginx ports: - 80:80 volumes: - ./nginx/config/nginx.conf:/etc/nginx/nginx.conf depends_on: - web The error I'm getting: `2023/10/28 08:22:33 [error] 22#22: *1 connect() failed (111: Connection refused) while connecting to upstream, client: my_pc_ip, server: 127.0.0.1, request: "GET / HTTP/1.1", upstream: "http://127.0.0.1:8000/", host: "127.0.0.1"` I tried changing the nginx.conf and .yml file but nothing changed -
Free online solutions for testing python frameworks on web
I'm looking for a free online solution to test python frameworks like django and flask. From what I have searched so far, I have not found any that do not involve additional expenses.