Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Preventing certain values adding to Django model
I'm trying to put a restriction on my Django model. I have a user model and then a model which allows one user to "follow" another. I want to put a restriction so the user cannot follow themselves. It's not really working at all but I'm sort of stuck what to do. When I try to add a new object. It will let me alter an existing entry but if I try to create a new one I get the error: Follower: Follower object (None)>" needs to have a value for field "id" before this many-to-many relationship can be used. It's like I have to save it somehow before I check for the items but I'm not sure how to go about it. Models class User(AbstractUser): pass class Follower(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE, related_name="followers", unique=True) follows = models.ManyToManyField(User,blank=True,related_name="follows") # Prevent User from following themselves def save(self, *args, **kwargs): if self.follows.contains(self.user): return else: super().save(*args, **kwargs) I've tried variations of the if statement and I've tried using a for loop to go through the ManytoMany field but I can see the object doesn't exist yet -
Get n value with n parameter with Django Queryset
this is my first question. If my question is not clear, let me know :) So I learn Django (learning by doing) for 4 Months in my project. I have one table name material, which is the table contains material name and price. Here I will describe my table: id materialName price 1 Not Required 0 2 Material 1 123 3 Material 2 456 4 Material 3 900 I want to calculate the total material price by getting the price from the table. It looks ok if I only want to get 1 price only. But, I need to get 4 values of prices from what the user wants in input. Let's say the user chooses Material 3, Material 2, Not Required and Not Required. So there is 4 material price. Then, I use a queryset like this: x = rawmaterial.objects.filter(Q(materialName = 'Material 3') | Q(materialName = 'Material 2') | Q(materialName = 'Not Required') | Q(materialName = 'Not Required')).values_list('price',flat=True) but the result is (900, 456, 0) not like (900, 456, 0, 0). I have been trying with SQL query using OR, is there any possibility to get 4 values? Thank you :) -
XMLParser.__init__() takes 1 positional argument but 4 were given
I am getting this error while running the below command:- Python version=3.10.8 Django version=2.1 openpyxl=2.6.2 python manage.py runserver 127.0.0.1:8000 Error:- Exception ignored in thread started by: <function check_errors.<locals>.wrapper at 0x118793400> Traceback (most recent call last): File "/Users/chandanvarma/Desktop/project/retailer-backend/venv/lib/python3.10/site-packages/django/utils/autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "/Users/chandanvarma/Desktop/project/retailer-backend/venv/lib/python3.10/site-packages/django/core/management/commands/runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "/Users/chandanvarma/Desktop/project/retailer-backend/venv/lib/python3.10/site-packages/django/utils/autoreload.py", line 248, in raise_last_exception raise _exception[1] File "/Users/chandanvarma/Desktop/project/retailer-backend/venv/lib/python3.10/site-packages/django/core/management/__init__.py", line 337, in execute autoreload.check_errors(django.setup)() File "/Users/chandanvarma/Desktop/project/retailer-backend/venv/lib/python3.10/site-packages/django/utils/autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "/Users/chandanvarma/Desktop/project/retailer-backend/venv/lib/python3.10/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/chandanvarma/Desktop/project/retailer-backend/venv/lib/python3.10/site-packages/django/apps/registry.py", line 89, in populate app_config = AppConfig.create(entry) File "/Users/chandanvarma/Desktop/project/retailer-backend/venv/lib/python3.10/site-packages/django/apps/config.py", line 90, in create module = import_module(entry) File "/opt/homebrew/Cellar/python@3.10/3.10.8/Frameworks/Python.framework/Versions/3.10/lib/python3.10/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 688, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 883, in exec_module File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "/Users/chandanvarma/Desktop/project/retailer-backend/venv/lib/python3.10/site-packages/tablib/__init__.py", line 3, in <module> from tablib.core import ( File "/Users/chandanvarma/Desktop/project/retailer-backend/venv/lib/python3.10/site-packages/tablib/core.py", line 15, in <module> from tablib import formats File "/Users/chandanvarma/Desktop/project/retailer-backend/venv/lib/python3.10/site-packages/tablib/formats/__init__.py", line 12, in <module> from . import _xlsx as xlsx File "/Users/chandanvarma/Desktop/project/retailer-backend/venv/lib/python3.10/site-packages/tablib/formats/_xlsx.py", line 14, in <module> import openpyxl File "/Users/chandanvarma/Desktop/project/retailer-backend/venv/lib/python3.10/site-packages/openpyxl/__init__.py", line 6, in <module> from openpyxl.workbook import Workbook … -
django rest_framework error MultipleObjectsReturned get method return more than one
I making a project where everytime someone create an Item, in the ClearingOffice it will increment office_serial +1, but it's saying get() returned more than one ClearingOffice -- it returned 14! so when I try filter it increment all office_serials models.py class CustomUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_('email address'), unique=True) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) date_joined = models.DateTimeField(default=timezone.now) userid = models.CharField(null=True, max_length=9) office = models.ForeignKey('ClearingOffice', models.DO_NOTHING, blank=True, null=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = CustomUserManager() def __str__(self): return self.email class ClearanceItem(models.Model): cl_itemid = models.CharField(primary_key=True, max_length=20, default=get_default_id) studid = models.CharField(max_length=9, blank=True, null=True) office = models.ForeignKey('ClearingOffice', models.DO_NOTHING, blank=True, null=True) class Meta: managed = False db_table = 'clearance_item' class ClearingOffice(models.Model): # this should be office_id office = models.OneToOneField('Office', models.DO_NOTHING, primary_key=True) staff = models.TextField(blank=True, null=True) office_serial = models.IntegerField(blank=True, null=True) class Meta: managed = False db_table = 'clearing_office' signals.py @receiver(post_save, sender=ClearanceItem) def create_transaction_log(sender, instance, created, **kwargs): if created: TransactionLog.objects.create(cl_itemid=ClearanceItem.objects.get(cl_itemid=instance.cl_itemid), trans_desc="Add Clearance Item", trans_recorded=str(datetime.now().strftime('%Y-%m-%d'))) ClearingOffice.objects.get(office_serial=instance.office.office_serial).update(office_serial=F('office_serial') + 1) the strange part is I have two users one of them is working currectly incrementing his office_serial while the other increments all of them can anyone explain why this is happening? Edit: I added the serializer.py class ClearanceItemSerialize(serializers.ModelSerializer): class Meta: model = ClearanceItem fields = '__all__' def … -
"invalid literal for int() with base 10:" error while changing DateTimeField to DateField in models.py | Django
I want to show how many posts are being made each day so i wrote this code: class ServerInsightsView(View): def get(self, request, server_tag): server = Server.objects.get(tag=server_tag) post_daily_count =server.posts.all().values('created').annotate(dailycount=Count('created')).order_by() #to get the number of posts each day depending on the DateTimeField return render(request, 'servers/insights.html', {'server':server, 'post_daily_count': post_daily_count}) This code is working but since created is a DateTimeField it groups the data depending on both date and time so for example (2022, 11, 15, 16, 24, 10, 577648) and (2022, 11, 15, 16, 40, 39, 224605) are in the same day but in different Time. so in order to fix this i've changed DateTimeField to DateField: Here is the models.py: class Post(models.Model): title = models.CharField(max_length=200) text = models.TextField(null=True, blank=True) saved = models.ManyToManyField(User, blank=True, related_name='saves') upvotes = models.ManyToManyField(User, blank=True, related_name='upvotes') downvotes = models.ManyToManyField(User, blank=True, related_name='downvotes') votes_count = models.IntegerField(default=0) server = models.ForeignKey(Server, on_delete=models.CASCADE, related_name='posts') creator = models.ForeignKey(User , on_delete=models.CASCADE, related_name='posts', null=True) created = models.DateField(auto_now_add=True) #was DateTimeField updated = models.DateField(auto_now=True) #was DateTimeField and now i get this error after this change: invalid literal for int() with base 10: b'15 16:24:10.577648' -
DJango displaying incorrect view
I am trying my best to learn Django for the past few days, and I came across an unusual problem. I know this is very basic form some, so I'm asking for your help on this one. I created two different views that will show two different outputs. from django.shortcuts import render from django.template import loader from django.http import HttpResponse # Create your views here. def computers(request): template_name = loader.get_template('computers/computers.html') context = { 'a':[ { 'sample1': 'WMCD0001', 'sample2': 'Desktop', 'sample3': 'Lenovo ThinkPad', 'sample4': '10.10.10.100', 'sample5': 'Active', }, ] } return HttpResponse(template_name.render(context, request)) def newdevice(request): return render(request, 'computers/newdevice.html') # return HttpResponse(template.render(request, context)) I also configured the urls file on the app which goes like this from django.urls import path from . import views urlpatterns = [ # path('', views.index, name='computers'), path('', views.computers, name='computers'), path('computers/newdevice/', views.newdevice, name='computers/newdevice') ] The last this I wrote was the urls in the project which is like this from django.contrib import admin from django.urls import include, path urlpatterns = [ path('computers/', include('computers.urls')), path('computers/newdevice/', include('computers.urls')), path('admin/', admin.site.urls), ] When I try to go to the localhost:8000/computers, it shows the correct view. The problem is when I try to view the page under localhost:8000/computers/newdevice it shows the same view … -
Multiple small API call vs single API call in Django Rest Framework
I have an application with user data associated with multiple models. All associated models need to be populated with certain data when a user is created. Should I create multiple APIs called at the same time from frontend or should I create a single API that does it all -
Handling notification Redirects to mobile apps and the frontend with Django Rest Framework
My project is in Django rest framework. It have web with react as well as android and ios. I am using Firebase push notification for notification purpose. Since I have to show my notification in app also, I have stored the notification in database and the notification database is as below: class Notification(models.Model): """ model to manage all notification """ receiver = models.UUIDField(max_length=255) title = models.CharField(max_length=255) body = models.TextField(blank=True, null=True) type = models.CharField(max_length=255) # order_type, registration_type is_read = models.BooleanField(default=False) redirect_url = models.CharField(max_length=255) Now the main problem I am facing is setting a redirect url for every notification. I want to redirect to specific page for different type of notification. For example for order_type notification i want to redirect user to order page, for comment_type notification I want to redirect user to comment page. How can I do that since i cannot just simply redirect to html url since there is react app, ios app as well as android app. I did not find much resource regarding this. Any help will be very much appreciated. Thanks. -
Does Django Headless CMS provide fronted Interface Templates?
I am new in Python/Django Framework and i want use CMS for my website so i can use fronted and admin ready-made templates. please suggest. -
Only Owner of the Profile able to Update the data
Using class Based (APIView) in Django rest framework for Getting and Patch (Updating) UserInfo data. views.py class getUserInfo(APIView): permission_classes = [permissions.IsAuthenticated] def get(self, request, format=None): user = request.user userinfos = user.userinfo_set.all() serializer = UserInfoSerializers(userinfos, many=True) return Response(serializer.data) def patch(self, request, pk, format=None): user = UserInfo.objects.get(id=pk) serializer = UserInfoSerializers(instance=user, data=request.data, partial=True) 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) serializers.py from django.contrib.auth.models import User from .models import UserInfo class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'first_name', 'username') class UserInfoSerializers(serializers.ModelSerializer): user = UserSerializer(many=False, required=True) class Meta: model = UserInfo fields = ('id', 'picture', 'profession', 'user') Everything is working so far so good. Able to GET and PATCH (Update) logged-in user data. While Testing the API in Postman, I found out that if User1 is logged in he can change the data of User2 by only using the pk of User2. urls.py urlpatterns = [ path('userinfo/', views.getUserInfo.as_view(), name="UserInfo"), path('userinfo/<str:pk>/', views.getUserInfo.as_view()), path('api/token/', views.MyTokenObtainPairView.as_view(), name='token_obtain_pair'), path('api/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'), path('register/', views.RegisterView.as_view(), name='auth_register'), ] Using rest_framework_simplejwt for Auth models.py from django.contrib.auth.models import User class UserInfo(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) picture = models.ImageField(upload_to="profile_pics", null=True) profession = models.CharField(max_length=200, null=True) def __str__(self): return "%s's Profile Picture" % self.user Any help would be appreciated -
How to compare two serializer field and show whichever is higher in django rest
I have product serializer which return category_offer_price & product_offer_price, before getting this response I want to compare both price and only return whichever is highest price. #Serilaizer.py class ProductSerializer(ModelSerializer): category = CategorySerializer() product_offer_price = SerializerMethodField() category_offer_price = SerializerMethodField() class Meta: model = Products fields = [ "id", "product_name", "slug", "category", "description", "category_offer_price", "product_offer_price", "base_price", "stock", "is_available", "created_date", "images", "images_two", "images_three", ] def get_product_offer_price(self, obj): try: product_offer = ProductOffer.objects.get(product=obj) if product_offer.is_active: offer_price = product_offer.product_offer_price() return offer_price except Exception: pass return None def get_category_offer_price(self, obj): try: category_offer = CategoryOffer.objects.get(category=obj.category) if category_offer.is_active: offer_price = category_offer.category_offer_price(obj) return offer_price except Exception: pass return None #Models.py class Products(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE) product_name = models.CharField(max_length=50, unique=True) slug = models.SlugField(max_length=100, unique=True) description = models.TextField(max_length=500) base_price = models.IntegerField() images = models.ImageField(upload_to="photos/products") images_two = models.ImageField(upload_to="photos/products") images_three = models.ImageField(upload_to="photos/products") stock = models.IntegerField() is_available = models.BooleanField(default=True) created_date = models.DateTimeField(auto_now_add=True) modified_date = models.DateTimeField(auto_now=True) class Meta: verbose_name_plural = "Products" def __str__(self): return self.product_name I'd like to know is it possible to compare serializer fields in a serializer class? -
dfr TypeError: unsupported operand type(s) for +: 'Office' and 'str'
I'm trying to concatenate some fields ex. When I do this in postman { "sem": "2", "sy": "2021-2022", "remarks": "test", "resolution": "test", "studid": "2012-5037" } this is the customuser I made The cl_itemid shoud be OSA-2021-2022-2 class ClearanceItemSerialize(serializers.ModelSerializer): class Meta: model = ClearanceItem fields = '__all__' def create(self, validated_data): validated_data["office"] = self.context["request"].user.officeid validated_data["recorded_by"] = self.context["request"].user.userid validated_data["cl_itemid"] = self.context["request"].user.officeid + '-' + validated_data.get('sy') + '-' + validated_data.get('sem') return super().create(validated_data) above is the code but it's throwing me an error TypeError: unsupported operand type(s) for +: 'Office' and 'str' if I use userid instead validated_data["cl_itemid"] = self.context["request"].user.userid + '-' + validated_data.get('sy') + '-' + validated_data.get('sem') it's working 321-05 2021-2022-2 What's happening here can somebody explain? Edit: I added the models incase that's the problem class ClearanceItem(models.Model): cl_itemid = models.CharField(primary_key=True, max_length=20, default=get_default_id) studid = models.CharField(max_length=9, blank=True, null=True) office = models.ForeignKey('Office', models.DO_NOTHING, blank=True, null=True) sem = models.CharField(max_length=1, blank=True, null=True) sy = models.CharField(max_length=9, blank=True, null=True) remarks = models.TextField(blank=True, null=True) -
django postgres different values
Hi Django + Postgresql While studying aware datetime, I had a question and asked a question. Postgresql document For timestamp with time zone, the internally stored value is always in UTC (Universal Coordinated Time, traditionally known as Greenwich Mean Time, GMT). An input value that has an explicit time zone specified is converted to UTC using the appropriate offset for that time zone. If no time zone is stated in the input string, then it is assumed to be in the time zone indicated by the system's TimeZone parameter, and is converted to UTC using the offset for the timezone zone. Are you changing only the output differently according to the timezone setting value? (internally stored value is UTC ?) SET TIME ZONE 'KST' (Asia/Seoul +9) Why is the same query but different values? Django Settings TIME_ZONE = "Asia/Bangkok" # ( +7 ) USE_TZ = False Postgres Settings SET TIME ZONE 'KST' (Asia/Seoul +9) Django Server TimeZone UTC Django ORM Create Query INSERT INTO "timezone_timezone" ("datetime") VALUES ('2022-11-22T01:58:14.373201'::timestamp) RETURNING "timezone_timezone"."id"; args=(datetime.datetime(2022, 11, 22, 1, 58, 14, 373201),) psql select query psql insert Django ORM Query INSERT INTO "timezone_timezone" ("datetime") VALUES ('2022-11-22T01:58:14.373201'::timestamp) RETURNING "timezone_timezone"."id"; psql select query -
Django - Get ID before ensuring form is valid
I am facing an issue where I have multiple forms on one page. What I am trying to do is update an item using an update form. When I request the pk, it comes from a different model that is not related to this one. I need to get the ID before ensuring that the form is valid so I can filter and get the correct item based on the ID in order to display the data that I need. models.py class DevIssues(models.Model): ISSUE_CODE = [ ('BUG', 'Bug'), ('BACKLOG', 'Backlog'), ('REQUEST', 'Request'), ('TODO', 'To-Do'), ] ISSUE_STATUS = [ ('NEW', 'New'), ('WIP', 'In Progress'), ('Complete', 'Complete'), ] project = models.ForeignKey(DevProjects, on_delete=models.CASCADE, related_name='issue') issue = models.CharField(max_length=100) issue_desc = models.CharField(max_length=500) issue_code = models.CharField(max_length=9, choices=ISSUE_CODE, null=True, blank=True) issue_status = models.CharField(max_length=15, choices=ISSUE_STATUS, default='New') created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateField(auto_now=True) created_by = models.ForeignKey(User, on_delete=models.CASCADE) forms.py class AddProjectIssues(forms.ModelForm): class Meta: model = DevIssues fields= ["issue", "issue_desc", "issue_code"] labels = { 'issue': 'Issue', 'issue_desc': 'Issue Description', 'issue_code': 'Issue Code', } class UpdateProjectIssues(forms.ModelForm): class Meta: model = DevIssues fields= ["issue_status"] views.py issue_project = get_object_or_404(DevProjects, pk=pk) issues = DevIssues.objects.filter(project=issue_project).order_by('-created_at') if request.method == 'POST' and 'addissue' in request.POST: issue_form = AddProjectIssues(request.POST or None) if issue_form.is_valid(): content = request.POST.get('issue') content2 = request.POST.get('issue_desc') … -
how to solve ValueError at /register in django
I am trying to create a sign up with Django but after filling the form, I keep getting this ValueError at /register as an error requesting that the username be set. I am new to Django and I don't seem to understand what is expected Below are my codes for signup form, the views.py and the resulting error respectively Signup form: {% for message in messages %} <h5>{{message}}</h5> {% endfor %} <form method="POST" action="register" name="registerForm"> {% csrf_token %} <p>Username:</p> <input type="text" name="username "/> <p>Email:</p> <input type="email" name="email "/> <p>Password:</p> <input type="password" name="password"/> <p>Repeat Password:</p> <input type="password" name="confirm_password"/><br> <input type="submit"/> </form> views.py def register(request): if request.method == 'POST': username = request.POST.get('username') email = request.POST.get('email') password = request.POST.get('password') confirm_password = request.POST.get('confirm_password') if password==confirm_password: if User.objects.filter(username=username).exists(): messages.info(request, 'Username Taken') return redirect('register') elif User.objects.filter(email=email).exists(): messages.info(request, 'Email Taken') return redirect('register') else: user = User.objects.create_user(username=username, email=email, password=password) user.save() return redirect('/') else: messages.info(request, 'Password does not match') return redirect('register') else: return render(request, 'register.html') Error: ValueError at /register The given username must be set Request Method: POST Request URL: http://127.0.0.1:8000/register Django Version: 4.1.3 Exception Type: ValueError Exception Value: The given username must be set Exception Location: C:\Users\User\Envs\myapp\lib\site-packages\django\contrib\auth\models.py, line 144, in _create_user Raised during: myapp.views.register Python Executable: C:\Users\User\Envs\myapp\Scripts\python.exe Python … -
Django logging missing while testing through the interactive shell
We added the below to show the SQL queries on the console. And, as a proof of concept, we are following the online tutorial to build a testing project. LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'console': { 'level': 'DEBUG', 'class': 'logging.StreamHandler', }, }, 'loggers': { 'django.db.backends': { 'level': 'DEBUG', 'handlers': ['console'], } }, } At the step of "Explore the free admin functionality", for example, the console SQL logging works as exacted. So, when clicking on the button, we see sample SQL logs like attached below. However, when using the interactive shell through the command python manage.py shell, and calling python commands like Choice.objects.filter(question__pub_date__year=current_year), we did not see any SQL log. We wonder if we missed anything for the backend logging on the interactive shell. We are testing with Django v3.1.4 and Python v3.7.6. Just let us know if you need more details. Sample Django backend logging records: ... (0.000) SELECT "django_session"."session_key", "django_session"."session_data", "django_session"."expire_date" FROM "django_session" WHERE ("django_session"."expire_date" > '2022-11-21 23:03:45.762894' AND "django_session"."session_key" = 'dd9uy7q873cijz0603l5uu9zl3wujr2f') LIMIT 21; args=('2022-11-21 23:03:45.762894', 'dd9uy7q873cijz0603l5uu9zl3wujr2f') (0.000) SELECT "auth_user"."id", "auth_user"."password", "auth_user"."last_login", "auth_user"."is_superuser", "auth_user"."username", "auth_user"."first_name", "auth_user"."last_name", "auth_user"."email", "auth_user"."is_staff", "auth_user"."is_active", "auth_user"."date_joined" FROM "auth_user" WHERE "auth_user"."id" = 1 LIMIT 21; args=(1,) (0.000) BEGIN; args=None (0.000) SELECT … -
UnboundLocalError - local variable 'emprendedores' referenced before assignment
I can't figure out why am I getting this error message: "UnboundLocalError - local variable 'emprendedores' referenced before assignment" enter image description here Hey fellows, i'm building an app in Django and almost is pretty well. However, I cannot find solution to a problem in my search view. The main idea is allowing the user to indicate the word and to select the desired fields to search into from an form, and returning the registered users that satisfy the criteria. The html file looks like this: enter image description here This is the model: enter image description here and this is the view I'm working on: enter image description here But I can't figure out why am I getting this error message: "UnboundLocalError - local variable 'emprendedores' referenced before assignment" enter image description here I'll be glad if someone can help my out. -
Django login fails because of too many redirect
I have a pretty basic instance of a Django app serving an hybrid React app. I wanted to protected this app behind a login using the default authentification module of Django but when I try to access the app on http://127.0.0.1:8000/ I get redirected to: http://127.0.0.1:8000/accounts/login/?next=/accounts/login/%3Fnext%3D/accounts/login/%253Fnext%253D/accounts/login/%25253Fnext%25253D/accounts/login/[...] And the browser display ERR_TOO_MANY_REDIRECTS. Python 3.11.0 Django 4.1.3 config/urls.py from django.contrib import admin from django.urls import include, path from rest_framework import routers from maapi import views router = routers.DefaultRouter() router.register(r'users', views.UserViewSet) router.register(r'groups', views.GroupViewSet) urlpatterns = [ path('admin/', admin.site.urls), path('routers/', include(router.urls)), path('api-auth/', include('rest_framework.urls', namespace='rest_framework')), path('api/', include('maapi.urls')), path('', include('frontend.urls')), ] frontend/urls.py from django.urls import path from . import views urlpatterns = [ path(r'', views.ReactAppView.as_view(), name='react_app'), path(r'<path:path>', views.ReactAppView.as_view(), name='react_app_with_path'), ] frontend/views.py from django.views.generic import TemplateView from django.utils.decorators import method_decorator from django.contrib.auth.decorators import login_required # Create your views here. @method_decorator(login_required, name='dispatch') class ReactAppView(TemplateView): template_name = 'app.html' # Get url parameter (Note that removing this doesn't solve the issue) def get_context_data(self, **kwargs): return {'context_variable': 'value'} Can you identify what is wrong or point me to what to test? Thank you. -
Python calling a property from inside a class
I'm trying to call the property protocolo on a new imagefield's upload_to argument What I'm trying to accomplish is to have the saved images use a custom filename. class biopsia(models.Model): paciente = models.CharField(max_length=50) creado = models.DateTimeField(auto_now_add=True) foto = models.ImageField(upload_to=f'fotos_biopsias/%Y/{*protocolo*}', blank=True) def __str__(self): return str(self.protocolo) @property def protocolo(self): return 'BIO' + str(self.creado.year) + '-' + str(biopsia._base_manager.filter( creado__year=self.creado.year, creado__lt=self.creado ).count() + 1) File "C:\Users\LBM\Documents\virtualenviorements\clinico\biopsia\models.py", line 30, in biopsia foto = models.ImageField(upload_to=f'fotos_biopsias/%Y/{protocolo}', blank=True) NameError: name 'protocolo' is not defined* I've tried defining an outside method for upload_to but still I cannot use it inside my class -
How to skip if empty item in column in Django DB
I;m new to learning Django and ran into a small issue: I'm working on a product display page where some products are in a subcategory. I want to be able to display this subcategory when needed but I do not want it to show up when unused. Right now it will show up on my page as 'NONE' which I do not want. How do I fix this? My model looks like this: class Category(models.Model): category_name = models.CharField(max_length=200) sub_category = models.CharField(max_length=200,blank=True,null=True) On my webpage I use the {{category}} in a for loop to display the different categories. Unfortunately is shows 'NONE' when there is no subcategory. -
Form Submitting with Jquery in Django
I wanna submitting form with jquery append. But it doesn't work. I am adding fields but when i click the submit, only original fields sent. Duplicate fields not sending. How can i fix this. And also when i delete the fields, it only delete one field instead of three fields. first image is original fields. Seconda image is clone the fields with jquery Third is datas which are sent with form Here is my codes... models.py from django.db import models # Create your models here. class Contact(models.Model): full_name=models.CharField(max_length=100) email=models.CharField(max_length=200) mesaj=models.CharField(max_length=200) def __str__(self): return self.full_name views.py from django.shortcuts import render from .models import Contact #from django.contrib import messages # Create your views here. def contact(request): if request.method=='POST': full_name=request.POST['full_name'] email=request.POST['email'] mesaj=request.POST['mesaj'] contact=Contact.objects.create(full_name=full_name,email=email,mesaj=mesaj) # messages.success(request,'Data has been submitted') return render(request,'contact.html') contact.html <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> </head> <body> <div class="input_fields_wrap"> <form method="post" action=""> {% csrf_token %} <input type="text" name="full_name" class="field-long" /> <input type="text" name="email" class="field-long" /> <input type="text" name="mesaj" class="field-long" /> <button type="button" class="add_field_button">Add Field</button> <button type="button" class="remove_field_button">Remove Field</button> </div><input type="submit" value="Submit" /></form> </body> <script> var max_fields = 10; var wrapper = $(".input_fields_wrap"); var add_button = $(".add_field_button"); var remove_button = $(".remove_field_button"); $(add_button).click(function(e){ e.preventDefault(); var total_fields = wrapper[0].childNodes.length; if(total_fields < max_fields){ $(wrapper).append('<input type="text" name="full_name" class="field-long" … -
Hi! I need help. I'm trying to figure it out how I can do this and I'm getting frustrated because I know that it will be solve with just little thing
I explain: I have two models called Diagram and Parts respectability. manage.py This is my Diagram Model: from django.db import models import random, string def id_generator(size=10, chars=string.digits): return ''.join(random.choice(chars) for _ in range(size)) class Diagram(models.Model): fuel_type_choices = [('liquid_propane', 'L.P.'), ('natural_gas','N.G.'),] item_type_choices = [ ('conversion_kits','CONVERSION KITS'), ('griddle_parts','GRIDDLE PARTS'), ('grill_parts','GRILL PARTS'), ('kegorator_parts','KEGORATOR PARTS'), ('outdoor_kitchen_parts','OUTDOOR KITCHEN PARTS'), ('pizza_oven_parts','PIZZA OVEN PARTS'), ('power_burner_parts','POWER BURNER PARTS'), ('refrigerator_parts','REFRIGERATOR PARTS'), ('rotisserie_parts','ROTISSERIE PARTS'), ('searing_station_parts','SEARING STATION PARTS'), ] diagram_id = models.CharField(primary_key=True, max_length = 10, blank = True, unique = True) mpn = models.CharField(max_length = 50, blank = False, unique=True) model = models.CharField(max_length = 50, blank = False) name = models.CharField(max_length = 500, blank = False) image = models.ImageField(upload_to = 'img/diagrams/') number_of_references = models.IntegerField(null=True, blank=False) fuel_type = models.CharField(max_length = 15, choices = fuel_type_choices, default = False) item_type = models.CharField(max_length = 25, choices = item_type_choices, default = False) map_area = models.TextField(null=True) def save(self): if not self.diagram_id: # Generate ID once, then check the db. If exists, keep trying. self.diagram_id = id_generator() while Diagram.objects.filter(diagram_id=self.diagram_id).exists(): self.diagram_id = id_generator() super(Diagram, self).save() def __str__(self): return self.name And this is my Part Model: from django.db import models import random, string def id_generator(size=10, chars=string.ascii_uppercase + string.digits): return ''.join(random.choice(chars) for _ in range(size)) class Part(models.Model): warranty_choices = ( ('0','0'), … -
How to implement a user customizable and personalized dashboard with django
I've created a django website with user accounts and a database containing data and I would like each user to be able to create their own personalized dashboard to view only the data that they care about. How can this be implemented where each dashboard is connected to the specific user that created it? My question is a little vague because I don't know how to implement a feature that is created by a user, is viewable only by that user, and is persistent. Any help or guidance would be much appreciated! I haven't tried anything yet because I don't know how to get started. Online search results are things like creating a custom admin dashboard or a dashboard that is shared across all users, which is not what I'm looking for. -
Problem with redirecting to login page after successful authorization in django-microsoft-auth
I am using django-microsoft-auth to log in with Microsoft account. The problem I am facing is that I want to use it in my login.html and I've managed to add this button to my html, however it redirects me to admin page. My URL that I added in Azure is default one: https://<mydomain_name>.com/microsoft/auth-callback/ I found this solution on Stackoverflow but it requires changing URL on Azure AD. Is there any other way to change reditect from /admin to /home other than changing URL in Azure AD? I was thinking if I could change it somehow directly in library. -
django does not load CSS file in HTML-file which extends from "base.html"
I have a base.html which my options.html extends from like this //options.html {% extends "webpage/base.html" %} {% load static %} <link rel="stylesheet" type="text/css" href="{% static 'webpage/options.css' %}"> {% block content %} <div class="test"> foo </div> {% endblock content %} //base.html {% load static %} <!DOCTYPE html> <html> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.0.0/dist/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"> <link rel="stylesheet" type="text/css" href="{% static 'webpage/base.css' %}"> <!-- jQuery--> <script src="https://code.jquery.com/jquery-3.6.1.slim.js" integrity="sha256-tXm+sa1uzsbFnbXt8GJqsgi2Tw+m4BLGDof6eUPjbtk=" crossorigin="anonymous"></script> <title>:)</title> </head> <body> hello world {% block content %} {% endblock content %} <!-- Optional JavaScript --> <!-- jQuery first, then Popper.js, then Bootstrap JS --> <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/popper.js@1.12.9/dist/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.0.0/dist/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script> </body> </html> the issue is that the CSS is not loaded/applied. In the web-console (when I run python manage.py runserver) and go to the "options" page, then I can see that the webpage/base.css is loaded (i.e GET /static/webpage/base.css is printed), but the webpage/options.css is not. I thought I had something wrong in the static- path, but if I move the <link rel="stylesheet" type="text/css" href="{% static 'webpage/options.css' %}"> into my base.html(and go to my home page) then I see that GET …