Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Html content comes on top of navbar
I have a problem my html content comes on top of my navbar even tho I'm including it in my {%block content%} This is my base template <!DOCTYPE html> {% load static %} <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Homepage</title> <link href="https://cdn.jsdelivr.net/npm/remixicon@2.5.0/fonts/remixicon.css" rel="stylesheet"> <link rel="stylesheet" href="https://unpkg.com/boxicons@latest/css/boxicons.min.css"> <link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <link href="https://fonts.googleapis.com/css2?family=Raleway:wght@800&display=swap" rel="stylesheet"> <link rel="stylesheet" href='{% static "css/styles.css" %}'> </head> <body> {% include 'navbar.html'%} {% block content %} {% endblock %} <script type="text/javascript" src="js/script.js"></script> </body> </html> This is my navbar <div> <header> <a href="#" class="logo"> <i class="ri-home-2-fill"></i><span>LOGO</span></a> <ul class="navbar"> <li><a href="#" class="active">Home</a></li> <li><a href="#">About</a></li> <li><a href="#">Services</a></li> <li><a href="#">Contact</a></li> <li><a href="#">Soon</a></li> </ul> <div class="main"> <a href="#" class="user"><i class="ri-nurse-fill"></i>Sign in</a> <a href="#">Register</a> <div class="bx bx-menu" id="menu-icon"></div> </div> </header> </div> And this is a page of my app {% extends 'main.html'%} {% block content %} <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, … -
An unwanted and useless extraline in django crispy-forms
In Django, I have this forms.py : class ProfileForm(ModelForm): class Meta: model = Profile fields = [ 'sex','birth_date','civil_status', 'priv_tel','priv_email', 'priv_adr_l1','priv_adr_l2','priv_adr_zipcode','priv_adr_city','priv_adr_country', 'anamnesis','doctor'] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_id = 'id-profileForm' self.helper.form_class = 'blueForms' self.helper.form_method = 'post' # self.helper.form_action = reverse('hr:profile/profile_form') self.helper.layout = Layout( TabHolder(Tab('Généralités', 'sex','birth_date','civil_status'), Tab('Contact', 'priv_tel','priv_email', 'priv_adr_l1','priv_adr_l2','priv_adr_zipcode','priv_adr_city','priv_adr_country'), Tab('Médical','anamnesis','doctor'), ) ) self.helper.add_input(Submit('submitprofile', 'Mettre à jour')) class ChildForm(ModelForm): class Meta: model = Child fields = ['child_first_name', 'child_last_name','child_birth_date'] ChildFormSet = inlineformset_factory(User, Child, form=ChildForm, extra=0, can_delete=True, can_delete_extra=True) class ChildFormSetHelper(FormHelper): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_id = 'id-childForm' self.form_method = 'post' self.render_required_fields = True self.template = 'bootstrap/table_inline_formset.html' self.add_input(Submit('submitchild', 'Modifier')) And this views.py : class ProfileFormView(LoginRequiredMixin, TemplateView): model = Profile form_class = ProfileForm template_name = 'profile/profile_form.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) user_profile = get_object_or_404(Profile, user=self.request.user) context['user_form'] = ProfileForm(instance=user_profile) context['child_formset'] = ChildFormSet(instance=user_profile.user) context['child_formsethelper'] = ChildFormSetHelper() return context def post(self, request, *args, **kwargs): user_profile = Profile.objects.get(user=request.user) user_form = ProfileForm(request.POST, instance=user_profile) child_formset = ChildFormSet(request.POST, instance=user_profile.user) if user_form.is_valid() and child_formset.is_valid(): return self.form_valid(user_form, child_formset) else: return self.form_invalid(user_form, child_formset) def form_valid(self, user_form, child_formset): with transaction.atomic(): user_profile = user_form.save(commit=False) child_formset.instance = user_profile.user user_profile.save() child_formset.save() success_message = Profile._meta.verbose_name + " modifié avec succès." messages.success(self.request, success_message) return HttpResponseRedirect('/profile/') def form_invalid(self, user_form, child_formset): error_message = "Il y … -
dj_rest_auth (jwt) refresh token is empty when login - django rest framework
im having a trouble with dj_rest_auth jwt package. when i signup for a new account it gives me both access token and refresh token in response, but when i try to login with credentials, all i get is access token, and refresh token is entirely empty! i configured the code as described in the documentation and the the tutorial that im following. Any idea about this problem? please let me know. 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', 'rest_framework', 'rest_framework.authtoken', 'allauth', 'allauth.account', 'allauth.socialaccount', 'dj_rest_auth', 'dj_rest_auth.registration', 'accounts.apps.AccountsConfig', ] REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': [ 'accounts.permissions.IsStaffOrReadOnly', ], 'DEFAULT_AUTHENTICATION_CLASSES': [ 'dj_rest_auth.jwt_auth.JWTCookieAuthentication', ], } SITE_ID = 1 REST_AUTH = { 'USE_JWT': True, 'JWT_AUTH_COOKIE': 'access', 'JWT_AUTH_REFRESH_COOKIE': 'refresh', } Response: { "access_token": "eyJhbGciOiJ.....", "refresh_token": "", "user": { "pk": 2, "username": "test_user_0", "email": "test0@mysite.co", "first_name": "", "last_name": "" } } -
Cannot use POST and PUT request at the same time
I am trying to POST and UPDATE a new user using django forms. I have this function in my views.py beforehand and the POST request is working alright but then I realised I couldn't update: def user_form(request, id=0): if request.method == "GET": if id == 0: form = UserForm() else: user = NewUser.objects.get(pk=id) form = UserForm(instance=user) return render(request, "user_register/user_form.html", {'form':form}) else: form = UserForm(request.POST) if form.is_valid(): form.save() return redirect('/user/list') It'll redirect me to the right page - but won't update when I check. I changed the code to this, and the update request worked fine but the problem now is it errors when I try to create a new user: def user_form(request, id=0): if request.method == "GET": if id == 0: form = UserForm() else: user = NewUser.objects.get(pk=id) form = UserForm(instance=user) return render(request, "user_register/user_form.html", {'form':form}) else: user = NewUser.objects.get(pk=id) form = UserForm(request.POST, instance=user) if form.is_valid(): form.save() return redirect('/user/list') The error from the post request stems from the line after the else: and obviously the instance=user after request.POST, as that's what I've added from the original code -
error in django URLconf, I can't start the local server, an error pops up in the screenshot
enter image description here I have a ready-made html template with css. It seems to have done everything correctly, but it does not work. project location C:\Projects\brew\brewtopia location of the application C:\Projects\brew\brewtopia\users location of the main urls.py C:\Projects\brew\brewtopia\brewtopia\urls.py location urls.py in the app C:\Projects\brew\brewtopia\users\urls.py location of views.py in the app C:\Projects\brew\brewtopia\users\views.py html layout C:\Projects\brew\brewtopia\users\templates\users\Brewtopia. folder static C:\Projects\brew\brewtopia\users\static version django 4.1 python 3.11 I've been sitting with this problem for a day now, I've tried everything, people with experiences help me, I just started learning django here is the code in the urls,py of the main project `from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('"', include('users.urls')), ]` here is the code in urls,py in the application `from django.urls import path from . import views urlpatterns = [ path('Brewtopia', views.Brewtopia_view, name='brewtopia') ]` here is the code in views.py in the app `from django.shortcuts import render def Brewtopia_view(request): return render(request, 'Brewtopia.html')` in the main settings.py I have completed this `STATICFILES_DIRS = [BASE_DIR / "static"]` -
What determines what goes into validated_data
My question is fairly simple but I have not found the answer yet. When you send a bunch of post data to Django Rest Framework endpoint then what determines what goes into validated_data and what fields (more the values) are excluded? I have this model # A Product class Product(models.Model): title = models.CharField(max_length=100) category = models.ForeignKey(Category, on_delete=models.CASCADE, default=None, related_name="products") brand = models.ForeignKey(Brand, on_delete=models.CASCADE, default=None, null=True, blank=True, related_name="products") body = models.TextField(max_length=5000, null=True, blank=True) image = models.FileField(upload_to=image_directory_path, default='products/default.png', null=True, blank=True) video = models.FileField( upload_to=video_directory_path, blank=True, null=True ) price = models.DecimalField(max_digits=20, decimal_places=2) length = models.DecimalField(max_digits=20, decimal_places=2, blank=True, null=True) width = models.DecimalField(max_digits=20, decimal_places=2, blank=True, null=True) height = models.DecimalField(max_digits=20, decimal_places=2, blank=True, null=True) weight = models.DecimalField(max_digits=20, decimal_places=2, blank=True, null=True) volume = models.DecimalField(max_digits=20, decimal_places=2, blank=True, null=True) sku = models.CharField(max_length=20, null=True, blank=True) stock = models.DecimalField(max_digits=30, decimal_places=0) # user information user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name="products") created_at = models.DateTimeField(auto_now_add=True, verbose_name="created at") updated_at = models.DateTimeField(auto_now=True, verbose_name="updated at") class Meta: verbose_name = "product" verbose_name_plural = "products" db_table = "products" ordering = ["title"] def __str__(self): return self.title and this serializer to create a product: class CreateProductSerializer(ModelSerializer): class Meta: model = Product fields = '__all__' def create(self, validated_data): breakpoint() validated_data.pop("category") main_cat = self.context['request'].data['category'] sub_cat = self.context['request'].data['subcategory'] category = Category.objects.get(id=sub_cat, parent=main_cat) new_product = Product.objects.create(**validated_data, category=category) … -
Django "Detected change in ..., reloading" Error in Docker
I'm having a problem which I don't understand, and therefore can't resolve. I have a Dockerised Django project, which I created using Cookiecutter Django months ago. Today, my development environment has started displaying the following error on every request: I am not currently having this issue in production. I tried rolling back to commits that worked properly before (1 week old commits, for example), and I'm still getting this error. The reloading is causing connections to the database to close and therefore my project isn't working properly at all. Does anyone know what causes this, and how I might fix it? It feels like an issue with my Docker setup, but that hasn't changed in months, so I don't understand why that would change now. Many Thanks for any help anyone can offer! -
Problem with Session authentification with DJango REST with POST method
I am developing my first web app using Django REST Framework and Quasar, and Sessions for authentication. My problem is that GET/POST requests with no authentication required views are working, GET requests with authentication required views are working, but POST requests with authentication required views are not working. I get an error 403 and the request.user object is an AnonymousUser. The session cookies are transmitted in the POST response, as in the image below. Here is my request : const response = await this.$api.post('cardgames/', { name: this.name, privacy: this.privacy, user: userId.data.userId, }); (I get the user ID previously, because my request.user object is an AnonymousUser). Here is the code in the backend (GET request working) : class CardGameViewSet(viewsets.ModelViewSet): authentication_classes = [SessionAuthentication] permission_classes = [IsAuthenticated] queryset = CardGame.objects.all() serializer_class = ComplexCardGameSerializer def get_queryset(self): print("user get card game : ", self.request.user) return self.queryset.filter(user=self.request.user) def create(self, request, *args, **kwargs): print("user create card game : ", request.user) print("is auth : ", request.user.is_authenticated) user = User.objects.get(id=request.data['user']) userUrl = 'http:///api/users/' + str(user.id) + '/' request.data['user'] = userUrl print(request.data) serializer = self.get_serializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) Here is the code of the login : class LoginView(APIView): def post(self, request): data = request.data … -
Uploading a file from one django api to another on aws environment
Im developing my first microservice application, i created an api that work as a gateway, where i redirect the requests to another apis (inside aws private subnets). Json requests is working normaly, but multipart/form-data is not, the file reaches the gateway correctly,.gateway img, but in the other api, the files reaches there like this bug. It seems that that image is getting converted to binary when it reaches to the other api. This is the code in the gateway. class ProvidersMultipartGatewayView(APIView): url = os.environ.get("PROVIDERS_SYSTEM_URL") parser_classes = [MultiPartParser, FormParser, JSONParser] def post(self, request): token = request.META.get('HTTP_AUTHORIZATION') headers={'Authorization': f'{token}'} url_path = request.get_full_path() url_full = f"{self.url}{url_path}" response = requests.post(url_full, data=request.data, headers=headers, allow_redirects=True) status_code = response.status_code if status_code == 200 or status_code == 201 or status_code == 208: return Response(response.json(),status=status.HTTP_200_OK) return Response(status=status_code) And here, the code of the api that should save de file. class CompletedPaymentsView(APIView): authentication_classes = [TokenAuthentication] permission_classes = [IsAuthenticated] parser_classes = [MultiPartParser, FormParser, JSONParser] def post(self, request): serializers = CompletedPaymentsSerializers(data=request.data) if not serializers.is_valid(): return Response(serializers.errors, status=status.HTTP_400_BAD_REQUEST) if Handle_Board_Permissions(request, request.data["user_id"]): payment = CompletedPayments.objects.create(**serializers.data) payment.payment_file = request.data["payment_file"] payment.save() serializers = CompletedPaymentsSerializers(payment) return Response(serializers.data, status=status.HTTP_201_CREATED) return Response(status=status.HTTP_401_UNAUTHORIZED) If i make a request directly to the providers api, it works, but if i make a … -
Converting SQL query to Django ORM query
I'm trying to convert the following from a raw SQL query to use Django's ORM: SELECT count(size_id) AS id, count(size_id) as count, name, size_id, product.product_id FROM product JOIN product_size size ON product.size_id = size.id WHERE product_id = '123' AND product.id NOT IN ( SELECT item_id FROM order JOIN product i ON order.item_id = i.id WHERE i.product_id = '123' AND (startdate - interval '10 days', enddate + interval '10 days') OVERLAPS ('01-01-2023', '02-01-2023') ) GROUP BY size_id, name, product.product_id ORDER BY size_id ASC I know I can filter() on startdate__overlap or a DateTimeTZRange and I can also filter on a sub-query, but I'm really struggling to put it all together! Essentially what the query does is look for availability by excluding the results in the sub-query. Can anyone help? -
How to pass use sync_to_async with a chain of methods
I have a case like the following: async def handler(self): await sync_to_async(Stock.objects.filter)(id__in=product_stock).update(is_filled=False) Where I am trying to pass the product_stock to the filter method then call the update on the filtered queryset. I understand that I can wrap the logic in another method and just pass it the arg as in the following: @classmethod def update_stocks( cls, product_stock: List[uuid.UUID] ) -> None: """Update stocks for order products.""" cls.objects.filter(id__in=product_stock).update(is_filled=False) async def handler(self): await sync_to_async(Stock.update_stocks)(product_stock=product_stock) But is is possible to do it all as in my attempt above which doesn't work of course since the result is a courotine and django queryset? I want to avoid having to use another method just for this if it is possible. Thank you. -
Trouble with form validation on multi-form view in django, using form within a table
As the title says, I'm running into an issue with form validation. The table and form both seem to 'know' the correct values, but when it gets to the view, the validation fails. I have Jobs, Costs, and Vendors, all interrelated. The form I'm trying to validate is part of a table of Costs that pertain to a particular Job, and the field I'm trying to update is the Vendor field, via a dropdown menu, per row of the Costs table, with a single Update button that submits all forms at once via Javascript. Through a ton of troubleshooting via print statements, the table and form both seem to be able to print the correct cost and vendors, but when validating, I keep being told that the 'cost' field is a required field, so I guess it's not receiving the Cost object from the form. Been stuck on this for far too long, and I would appreciate some help. Here's the view: class CostCreateView(SuccessMessageMixin, SingleTableMixin, CreateView): model = Cost fields = ['vendor','description','amount','currency','invoice_status','notes'] template_name = "main_app/cost_form.html" table_class = CostTable simple_add_vendor_form = AddVendorToCostForm cost_form = CostForm update_vendor_form = UpdateVendorForm def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) self.object=None currentJob = Job.objects.get(pk=self.kwargs['pk']) context['currentJob'] = currentJob … -
Django queryset returns an empty result while i have data in my database
I'm new in django framework. I was using a database with postgres and implemented schemas in my tables. Now I have a problem regarding with getting my data from django. Here is what I've tried.. I have a model in my accounts_app class ProfileBasicInfo(BaseModel, SoftDeleteModel): # One to one with CustomUserModel user = models.ForeignKey(CustomUserModel, on_delete=models.CASCADE) sex = models.CharField(max_length=4) birthdate = models.DateField() civilstatus = models.CharField(max_length=100) height_meters = models.FloatField(null=True, blank=True) weight_kg = models.FloatField(null=True, blank=True) bloodtype = models.CharField(max_length=4) photo_path = models.ImageField(max_length=600, blank=True, null=True) class Meta: db_table = 'accounts_app\".\"profile_basicinfo' verbose_name = 'profile_basicinfo' now I tried to import it in my selectors.py and still gives me a null queryset. Here is how I did it. from accounts_app.models import ProfileBasicInfo def get_user(user): data = object() querysetProfile = ProfileBasicInfo.objects.all() profile_data = list(querysetProfile.values()) print(profile_data) The print gives me an empty queryset but I have already added a data in my database. -
ModuleNotFoundError: No module named 'main_app/urls', but it does exist
Error: Exception in thread django-main-thread: Traceback (most recent call last): File "/usr/local/Cellar/python@3.9/3.9.12_1/Frameworks/Python.framework/Versions/3.9/lib/python3.9/threading.py", line 973, in _bootstrap_inner self.run() File "/usr/local/Cellar/python@3.9/3.9.12_1/Frameworks/Python.framework/Versions/3.9/lib/python3.9/threading.py", line 910, in run self._target(*self._args, **self._kwargs) File "/Users/taylordarneille/Code/Django/newenv/lib/python3.9/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/Users/taylordarneille/Code/Django/newenv/lib/python3.9/site-packages/django/core/management/commands/runserver.py", line 134, in inner_run self.check(display_num_errors=True) File "/Users/taylordarneille/Code/Django/newenv/lib/python3.9/site-packages/django/core/management/base.py", line 475, in check all_issues = checks.run_checks( File "/Users/taylordarneille/Code/Django/newenv/lib/python3.9/site-packages/django/core/checks/registry.py", line 88, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "/Users/taylordarneille/Code/Django/newenv/lib/python3.9/site-packages/django/core/checks/urls.py", line 14, in check_url_config return check_resolver(resolver) File "/Users/taylordarneille/Code/Django/newenv/lib/python3.9/site-packages/django/core/checks/urls.py", line 24, in check_resolver return check_method() File "/Users/taylordarneille/Code/Django/newenv/lib/python3.9/site-packages/django/urls/resolvers.py", line 494, in check for pattern in self.url_patterns: File "/Users/taylordarneille/Code/Django/newenv/lib/python3.9/site-packages/django/utils/functional.py", line 57, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/Users/taylordarneille/Code/Django/newenv/lib/python3.9/site-packages/django/urls/resolvers.py", line 715, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/Users/taylordarneille/Code/Django/newenv/lib/python3.9/site-packages/django/utils/functional.py", line 57, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/Users/taylordarneille/Code/Django/newenv/lib/python3.9/site-packages/django/urls/resolvers.py", line 708, in urlconf_module return import_module(self.urlconf_name) File "/usr/local/Cellar/python@3.9/3.9.12_1/Frameworks/Python.framework/Versions/3.9/lib/python3.9/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 680, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 850, in exec_module File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "/Users/taylordarneille/Code/Django/newenv/clientDB2/clientDB2/urls.py", line 20, in <module> path('', include('main_app/urls')), File "/Users/taylordarneille/Code/Django/newenv/lib/python3.9/site-packages/django/urls/conf.py", line 38, in include urlconf_module = import_module(urlconf_module) File "/usr/local/Cellar/python@3.9/3.9.12_1/Frameworks/Python.framework/Versions/3.9/lib/python3.9/importlib/__init__.py", line 127, in … -
Django - how to create related models in new migrations for existing model objects
I'm adding couple of new models which have foreign key one-to-one relation to an existing model (existing model has thousands of objects already in database). The new models have default values for every field other than the foreign key. Example as below, class OldModel(models.Model): field1 = models.CharField(max_length=30) # As part of new migration class NewModel(models.Model): rel_field=models.OneToOneField(OldModel) value1=models.IntegerField(default=10) value2=models.IntegerField(default=10) So now 'OldModel' has upwards of 6000 objects in the database already, and I am adding the NewModel as part of a new migration. Is there any way that Django will autocreate the objects for NewModel for every existing object of OldModel? I have already written a receiver function using signals to autocreate the NewModel objects for future like below, @receiver(post_save,sender=OldModel) def create_new_rel(sender,instance,created,**kwargs): if created: NewModel.objects.create(rel_field=instance) I know we can write a script to query the old objects and create new one for each but just wondering if there is a proper "django way" to do this automatically? -
How to add a confirmation field in django form
I have an User abstract user model with some fields including mnemonic which is a CharField and an image that's an ImageField. I want to be able to use the mnemonic as a confirmation field to change the image in a form but I can't get the old mnemonic in the clean() method and so I get name 'user' is not defined. class User(AbstractUser): mnemonic = models.CharField(max_length=25, blank=True) image = models.ImageField(null=True, default='default.jpg', upload_to='pictures') def save(self, *args, **kwargs): super().save(*args, **kwargs) img = Image.open(self.image.path) if img.height > 300 or img.width > 300: output_size = (300, 300) img.thumbnail(output_size) img.save(self.image.path) class UserUpdateForm(forms.ModelForm): class Meta: model = User fields = ['image', 'mnemonic'] def clean(self): super(UserUpdateForm, self).clean() mnemonic = self.cleaned_data.get('mnemonic') if mnemonic != user.mnemonic: # name 'user' is not defined, line where I need to get the old mnemonic self._errors['mnemonic'] = self.error_class([ 'The mnemonic is wrong!']) return self.cleaned_data <form method="POST" enctype="multipart/form-data"> {% csrf_token %} <p class="article-title"><b>Profile Info</b></p> {{ profile_form }} <p class="article-title"><b>Site settings</b></p> {{ site_form }} <div> <button type="submit">Update</button> </div> </form> -
Object's unique sequencial index for each user - Django models
I have a table for users and another for what I call 'documents' in my database (I use postgresql). That last one has a 'user/author' column as a foreign key. How can I set a sequential index column for each user/author? Here's what's on my mind: user1 fills the table with 10 rows, then that column varies from 1 up to 10. user2 fills the same table with 5 more items. For those user2's rows that same column varies from 1 up to 5. If any row of a user gets deleted, that column (for that user's data) gets "re-indexed", i.e., if user2 deletes the 3rd entry, the former 4th gets re-indexed to 3, and the former 5th to 4. How I came up with this problem? I want to use that column as an index in the url's model-view. I could use a uuid key instead, but I find, for example, myapp.com/edit/1,myapp.com/edit/2 and so on more organized. Currently I perform the above described actions at view level: every time a row gets deleted all rows for that user gets re-indexed; every time a new row gets added, it's index is set. The problem is that I feel that this … -
How the calculate how many days lef to due date in a query?
I have a model that has due_date field and I want to create a query that annotates overdue value that counts how many days are left until due_date. but I can't implement it in my code I'm getting this error: Case() got an unexpected keyword argument 'default' and if I remove the default I get: TypeError: QuerySet.annotate() received non-expression(s): PS: Some of the objects have null due_date query_list = file.qs.annotate(overdue=Case( When(due_date__gt=timezone.now().date(), then=Value((F('due_date') - timezone.now().date()))), When(due_date__isnull=True, then=Value(None)), default=Value(0), output_field=DurationField())).values_list('overdue', ...) -
How can i stop making authentication requests per second?
I'm making a web app using django for backend and react for frontend. The proble is that when a I login in the app and enter with the user, the app is making a lot of authentication request per second and don't understand why. enter image description here enter image description here here's the function that use the auth/me url: enter image description here if u need more parts of the fronted or backend for trying to help me, just ask. I just wanna avoid making a lot of requests by seconds, but idk how and where's the loop :( -
How to check if a recurring periodicTask executed in a particular day in celery?
I am creating a project using Django, celery, celery beat, etc. I made some recurring periodic tasks that will run daily at a given crontab schedule. Now I want to know if the recurring task is executed successfully on a particular day. How can I query it? Is there any connection between PeriodicTask and TaskResult? -
How can i increase the width of a drop-down field in a django form?
I want to increase width of dropdown field in Django form, I tried both inline CSS as well as widgets, below is code I have tried index.html {% extends "base_generic.html" %} {% block content %} <form action = "" method = "post"> {% csrf_token %} **<center>Product: <h6 style="width: 350px;">{{ form.product }}</h6></center>** <br> <center>Rules: {{ form.rule }}</center> <input type="submit" value=Compute> </form> {% endblock %} forms.py from django import forms PRODUCTS = ( ('hp','HP'), ('wipro', 'WIPRO'), ) class InputForm(forms.Form): class Meta: **widgets = {'product': forms.Select(attrs={'style': 'width:200px'})}** product = forms.ChoiceField(choices=PRODUCTS) rule = forms.CharField(widget= forms.Textarea, label="Rules") How can I achieve this? -
Is there any bug or issues in Django 4.1.7 for static files?
while trying to load static files (mostly images) from static directory but I'm getting 404 error. I have created directory named 'static' in root directory and put all my images in 'shouldknow' directory within 'static' directory like '/static/shouldknow/logo.svg'. in my settings.py -- STATIC_URL = 'static/' and DEBUG = True 'django.contrib.staticfiles' is already placed in settings.py under apps. I'm using template inheritence and in my index.html template, i put these lines of code to load static files: {% load static %} <a href=""> <img src="{% static 'shouldknow/logo.svg' %}" alt="..." width="30" height="24"> </a> After doing this, still images are not loading from the static directory. Error shown by the server is -- 'GET /static/shouldknow/logo.svg HTTP/1.1" 404 1816' -
docker python can't find address postgres
I run a container with postgresql and after that I run a container with python (Django). I am trying to connect to the database and in some cases I get an error. This error happen after deleting compose project and trying to create that in 50% cases.If restart the backend container separately, then everything works fine. This is my first time working with a docker, I hope for your help and possible django.db.utils.OperationalError: could not connect to server: Connection refused Is the server running on host "postgres" (192.168.128.2) and accepting TCP/IP connections on port 5432? -
Django internationalisation and digits behaviour
I have a website in English, Spanish, German and French. One of the tables has a meter bar like: <meter value="{{fav.value}}" min="0" max="10"></meter> I found the meter bar only works in the English version, particularly, the meter goes from 0 to 10 with 2 decimals accuracy. If I override the value in view.py with an integer value (e.g. fav.value = 2), it works in all languages. If I override the value with a float (e.g. fav.value = 2.5), it would only show the green meter fill in the English version. Anyone has any idea what why this may be happening? -
Sidebar Menu is not displayed in custom page which is extending admin/base.html
I Have created a custom page which I want to display in Django Admin Panel. I am using jazzmin admin template for my django project. Problem: I am not getting the sidebar menu only option I can see is Dashboard. Why is this happening and how do I get full sidebar menu which I am getting for all the page for the models registered in admin.py My Views.py from confluent_kafka.admin import AdminClient, NewTopic from base.constants import KAFKA_CONFIG from django.views.generic import TemplateView # Create your views here. KAFKA_EXCLUDE_TOPICS = {'__consumer_offsets': True} class QueueOperationsView(TemplateView): template_name = 'dataprocessing/queue_management/queue.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) admin_client = AdminClient(KAFKA_CONFIG) topic_metadata = admin_client.list_topics() has_purge_permissions = self.request.user.has_perm('masters.purge_dataprocessingqueuemaster') # add your context data here context['topics'] = [i for i in topic_metadata.topics if i not in KAFKA_EXCLUDE_TOPICS] context['has_purge_permissions'] = has_purge_permissions return context My Urls.py from basics.admin import wrap_admin_view from masters.views import QueueOperationsView from django.conf.urls import url url(r'^admin/queue-management/$', wrap_admin_view(QueueOperationsView.as_view()), name="queue_operations_view"), wrap_admin_view(): def wrap_admin_view(view, cacheable=False): """ Use this to wrap view functions used in admin dashboard Note: Only the views that require a admin login """ from django.contrib import admin def wrapper(*args, **kwargs): return admin.site.admin_view(view, cacheable)(*args, **kwargs) wrapper.admin_site = admin.site return update_wrapper(wrapper, view) Template: {% extends 'admin/base.html'%} {% load static %} …