Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Filter serialized data with SerializerMethodField value in ModelSerializer in Django
There is SerializerMethodField 'schedule_name' in ModelSerializer in Django. schedule_name = serializers.SerializerMethodField() def get_schedule_name(self, obj): schedule_name = obj.name if obj.department is not None: schedule_name = obj.department.name + '-' + obj.name return schedule_name I want to filter by passing value for this 'schedule_name' in the serialized data. -
Is there a way to add the date field in models in a "from to" pattern for billing periods - Django
I am trying to add a billing period in the invoices that I am generating. Currently my model contains two seperate date fields, one that stores the start date of the billing period and the other stores the end date of the billing period. The model looks as below class Bill(models.Model): billing_period_start = models.DateField(null=True, blank=True) billing_period_end = models.DateField(null=True, blank=True) Question : Is there a way to add the two seperate date fields in a same model field so that I can get a from "DateField" to "DateField" pattern in the admin pannel and have the billing period in a single field. -
Cannot do axios PUT request in Django REST+ React framework - Request failed with status code 400
When i try to update data in my Django SQLite database through reactJS it shows an error like this, but it works the last day fine even though I didn't change any code here now it's now working and it shows error that I had mentioned below PUT http://127.0.0.1:8000/employee/1 400 (Bad Request) AxiosError {message: 'Request failed with status code 400', name: 'AxiosError', code: 'ERR_BAD_REQUEST', config: {…}, request: XMLHttpRequest, …} // Update Employee const updateEmployee = (id) => { Axios.put("http://127.0.0.1:8000/employee/"+id, { name: name, age: age, email: email, designation: designation }); console.log(Axios.put); Swal.fire("Updated!", "", "success"); // window.location.reload(); }; return( <> <h1 className="text-left text-danger">Update Employee</h1> <div className="container"> <div className="row"> <div className="col-md-12"> <div className="form-group"> <label>Name</label> <input type="text" className="form-control" placeholder="Enter Name" defaultValue={data.name} onChange={(e) => setName(e.target.value)} /> </div> <div className="form-group"> <label>Age</label> <input type="text" className="form-control" placeholder="Enter Age" defaultValue={data.age} onChange={(e) => setAge(e.target.value)} /> </div> <div className="form-group"> <label>Email</label> <input type="text" className="form-control" placeholder="Enter Email" defaultValue={data.email} onChange={(e) => setEmail(e.target.value)} /> </div> <div className="form-group"> <label>Designation</label> <input type="text" className="form-control" placeholder="Enter Designation" defaultValue={data.designation} onChange={(e) => setDesignation(e.target.value)} /> </div> <div className="mt-2"> <button className="btn btn-primary" onClick={() => updateEmployee(data.id)}>Update</button> <Link className="btn btn-danger mx-2" to="/">Cancel</Link> </div> </div> </div> </div> </> ) -
Django, relating model to another app models field
First off this may not be the best way to set this up, however, I'm learning as I go and struggling to find the correct answer. I have an Account app which handles the user signup, I added the couple_choice option which I'm trying to get in another app's model. ACCOUNT model class Account(AbstractBaseUser): COUPLE_CHOICE = Choices('single', 'couple') email = models.EmailField(verbose_name="email", max_length=60, unique=True) username = models.CharField(max_length=30, unique=True) date_joined = models.DateTimeField(verbose_name='date joined', auto_now_add=True) last_login = models.DateTimeField(verbose_name='last login', auto_now=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) profile_image = models.ImageField(max_length=255, upload_to=get_profile_image_filepath, null=True, blank=True, default=get_default_profile_image) hide_email = models.BooleanField(default=True) couple_choice = models.CharField(choices=COUPLE_CHOICE, default='single', max_length=20) I then have another app Profile, which I want to make the couple = to the Account.account.couple_choice, or if the Account.couple.choice is 'couple' then Profile.couple = True from account.models import Account class Profile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE,blank=True, null=True, related_name="swinger") couple = models.ManyToManyField(Account, to_field="couple_choice", blank=True, null=True,related_name="is_couple", on_delete=models.CASCADE) PLease let me know the best way to do this? Thanks -
ModuleNotFoundError: No module named 'my_site': when AWS CodePipeline (GitHub) deploy to Elastic Beanstalk (Django)
I've been stuck on this problem for 3 weeks. I've connected my GitHub to AWS CodePipeline and AWS CodePipeline is trying to deploy the code to AWS Elastic Beanstalk, but I keep getting the same error and can't figure out the solution. My ProcFile: web: gunicorn my_site.wsgi:application My file structure: -- .ebextensions -- django.config -- ProcFile -- tq_django -- my_site -- wsgi.py My wsgi.py import os import sys sys.path.insert(0, '/var/app/current/tq_django/my_site') from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'my_site.settings') application = get_wsgi_application() My django.config within .ebextensions option_settings: aws:elasticbeanstalk:container:python: WSGIPath: my_site.wsgi:application aws:elasticbeanstalk:application:environment: DJANGO_SETTINGS_MODULE: my_site.settings aws:elasticbeanstalk:environment:proxy:staticfiles: /tq: static -
Use original template under admin directory
I have django script with administration page /admin Now I want to make another page /customdata for administration purpose. However in this page , customdata is not related to specific model, it just shows the system overview data. It is just the normal template. Now I have two ideas. Making independent www.myexample.com/customdata page and set authentication. Linking this under www.myexample.com/admin/customdata and treat it as admin page 2 sounds usefule to me, because pages for administration purpose should be togetter. However is it possible? or is it not good behaivor? -
Django (django-rest-framework) with Bootstrap Autocomplete. Filed Nameing
I want to autocomplate a field. But i can't figure out how i can accomplish properly because i don't know yet what is the industry standard. Seems to be the Bootstrap Autocomplete expect an particular field naming like this. I think this is hardcoded. (the "text" at least): [ { "value": 1, "text": "Google Cloud Platform" }, { "value": 2, "text": "Amazon AWS" }, { "value": 3, "text": "Docker" }, { "value": 4, "text": "Digital Ocean" } ] How i can alter/mask the filed names from ['id','provider'] to ['value','text'] in Django side? Let say i have: #modell class CloudProviders(models.Model): provider = models.CharField(max_length=255, blank=True, null=True) #id come by default ... #Serializer class CloudProvidersAutocompleteSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = CloudProviders fields = ['id','provider'] #view class CloudProvidersAutocomplete(viewsets.ModelViewSet): model = CloudProviders serializer_class = CloudProvidersAutocompleteSerializer def get_queryset(self): query= self.request.query_params.get('search') if query : data = CloudProviders.objects.filter(provider__contains=query) return data UPDATE I have a solution but the question still open, because i don't know if this is a proper solution: #modell class CloudProviders(models.Model): provider = models.CharField(max_length=255, blank=True, null=True) #id come by default def _getProvider (self): return self.provider text = property(_getProvider ) ... -
Django Rest Framework Serializers causing errors while Creating Serializers for circular dependent Models
I have these models in my app class Social_Data(models.Model): sdid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) youtube = models.CharField(max_length = 400) twitter = models.CharField(max_length = 400) github = models.CharField(max_length = 400) class Company(models.Model): name = models.CharField(max_length = 100) logo = models.FileField(upload_to = "media/") summary = models.CharField(max_length = 400, default="") advocates = models.ManyToManyField('Advocate', related_name="advocates", default="", blank=True) href = models.CharField(max_length = 100,default = "", blank = True, null=True) class Advocate(models.Model): name = models.CharField(max_length = 200) profile_pic = models.FileField(upload_to = "media/") short_bio = models.CharField(max_length = 300, blank=True) long_bio = models.CharField(max_length = 400, null=True, blank=True) advocate_years_exp = models.IntegerField(default = 0) company = models.ForeignKey(Company, null = True, on_delete=models.SET_NULL) links = models.OneToOneField(Social_Data, null = True, on_delete=models.SET_NULL) and these are my serializers.py from rest_framework import serializers from .models import * class SocialDataSerializer(serializers.ModelSerializer): class Meta: model = Social_Data # fields = "__all__" exclude = ["sdid"] class AdvocateSerializer(serializers.ModelSerializer): company = CompanySerializer() links = SocialDataSerializer() class Meta: model = Advocate fields = "__all__" class CompanySerializer(serializers.ModelSerializer): advocates = AdvocateSerializer(many=True) class Meta: model = Company fields = "__all__" How could I solve the issue regarding the lazy reference of advocates in company model while serializing data in serializers ? and for now my serializers shows the error "name Company is not defined" -
Is it possible to store aware datetime objects in django with different timezones for the values?
I've seen many different posts across SO about aware timezones in django (i.e. datetimes with a timezone value). Even converting naive datetime to aware I've read online that many applications that deal with timezones usually store everything in UTC to avoid any Day light savings conversions and then use frontend to handle the conversions. I'd like to know if it's possible to store an aware datetime with the actual timezone in my database. If so, how would I go about it? So instead of storing something like: 2022-10-13 13:56:00+00:00 I'd like to store: 2022-10-13 13:56:00+04:30 (US/Eastern) -
Related Field got invalid lookup: icontains - Django
Admin.py @admin.register(models.Student) class StudentAdmin(admin.ModelAdmin): list_display = ['first_name', 'last_name', 'city'] @admin.register(models.CourseTake) class CourseTakeAdmin(admin.ModelAdmin): list_display = ['student', 'course', 'grade', 'performance'] list_editable = ['grade'] search_fields = ['student'] def student(self, student): return student.first_name models.py class Student(models.Model): first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) date_adimitted = models.DateField(auto_now=True) address = models.CharField(max_length=255) city = models.CharField(max_length=255) state = models.CharField(max_length=255) def __str__(self) -> str: return f'{self.first_name} {self.last_name}' class CourseTake(models.Model): student = models.ForeignKey(Student, on_delete=models.CASCADE, related_name='coursetake') #similar to reviews in the product class course = models.ForeignKey(Course, on_delete=models.CASCADE) grade = models.DecimalField(max_digits=5, decimal_places=2) class Meta: unique_together = [['student', 'course']] def __str__(self) -> str: return f'{self.student.first_name} {self.student.last_name}' Admin panel where I tried searching for the names I have a search bar which I want to use to search for student names, but it keeps saying "Related Field got invalid lookup: icontains". However, student in the search_fields is a foreign key and I don't know how to manipulate it so I can search for any name. 'Request URL: http://127.0.0.1:8000/admin/student/coursetake/?q=kj' -
Error 403 on Heroku when deploying a Django project
I want to delete the repository inside my Heroku app by typing: -heroku plugins:install heroku-repo -heroku repo:reset -a appname after that i get the error: -Expected response to be successful, got 403 -
ProgrammingError at / after depploying my django project to heroku but wotking well on local host
I have made all the migrations as recommended in previous posts. I have also updated my settings.py as recommended inj previous posts. here is my console message; 2022-10-13T22:36:21.289647+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.10/site-packages/django/db/backends/utils.py", line 84, in _execute 2022-10-13T22:36:21.289648+00:00 app[web.1]: with self.db.wrap_database_errors: 2022-10-13T22:36:21.289648+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.10/site-packages/django/db/utils.py", line 91, in __exit__ 2022-10-13T22:36:21.289648+00:00 app[web.1]: raise dj_exc_value.with_traceback(traceback) from exc_value 2022-10-13T22:36:21.289648+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.10/site-packages/django/db/backends/utils.py", line 89, in _execute 2022-10-13T22:36:21.289648+00:00 app[web.1]: return self.cursor.execute(sql, params) 2022-10-13T22:36:21.289648+00:00 app[web.1]: django.db.utils.ProgrammingError: relation "freelanceapp_post" does not exist 2022-10-13T22:36:21.289648+00:00 app[web.1]: LINE 1: ...t"."slug", "freelanceapp_post"."category_id" FROM "freelance... 2022-10-13T22:36:21.289648+00:00 app[web.1]: ^ 2022-10-13T22:36:21.289649+00:00 app[web.1]: 2022-10-13T22:36:21.290265+00:00 app[web.1]: 10.1.23.15 - - [13/Oct/2022:22:36:21 +0000] "GET / HTTP/1.1" 500 196793 "https://dashboard.heroku.com/" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/106.0.0.0 Safari/537.36" 2022-10-13T22:36:21.289879+00:00 heroku[router]: at=info method=GET path="/" host=victorkiprono.herokuapp.com request_id=b9f45047-6c65-44e5-975d-b0f71a4c023b fwd="105.161.25.118" dyno=web.1 connect=0ms service=133ms status=500 bytes=197110 protocol=https -
How can I make a django form field value not refresh if the field is not validated and user hits submit
I have created an HTMl register form template, and designed it such that if there is any validation error, it outputs the error and that works fine. Register form showing "passwords do not match" error The problem I'm having is the whole form fields clear once I hit submit and the errors show up, this was if a user has a "passwords do not match error" he'd have to input all his details from scratch. I want the user to input only the fields that has errors. The register HTML form ` {% csrf_token %} <div class="col-md-12"> <input class="form-control" type="text" name="first_name" placeholder="Firstname" required> {% if form.first_name.errors %} {% for error in form.first_name.errors %} <span style="color:#DC3545;"> {{error}} </span> {% endfor %} {% endif %} </div> <div class="col-md-12"> <input class="form-control" type="text" name="last_name" placeholder="Lastname" required> {% if form.last_name.errors %} {% for error in form.last_name.errors %} <span style="color:#DC3545;"> {{error}} </span> {% endfor %} {% endif %} </div> <div class="col-md-12"> <input class="form-control" type="text" name="email" placeholder="Email address" required> {% if form.email.errors %} {% for error in form.email.errors %} <span style="color:#DC3545;"> {{error}} </span> {% endfor %} {% endif %} </div> <div class="col-md-12"> <input class="form-control" type="password" name="password1" placeholder="Enter Password" required> {% if form.password1.errors %} {% for error in … -
How can i add like function with Django rest framework
0 Hey guys I try make blog app I wonder How can i add Like function I realy dont know how can i do it Add like on first press, remove like on second press like the instagram, twitter or youtube . That is The Models class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField() image = models.URLField(max_length=300) publish_date = models.DateTimeField(auto_now_add=True) author = models.ForeignKey(User, on_delete=models.CASCADE) That is serializers class PostSerializer(serializers.ModelSerializer): author = serializers.StringRelatedField() class Meta: model = Post fields = ( 'title', 'content', 'image', 'author', 'id', 'like_count' ) That is views class PostView(viewsets.ModelViewSet): queryset = Post.objects.all() serializer_class = PostSerializer def perform_create(self, serializer): serializer.save(author=self.request.user) that is Urls from django.urls import path from .views import ( PostView, PostView_View, LikesView, CommentView ) from rest_framework import routers router = routers.DefaultRouter() router.register('', PostView) urlpatterns = [ ] + router.urls -
Django object.filter returns Object (1) on search bar
So I have a Django website Project that contains a database of all the different books stored in it. With my search bar, if I type in the name it will show results from the database. The problem is that whenever I type in said name (One Piece or Attack On Titan), instead of showing its title name, it will either show Book Object (1) or Book Object (2) depending on what name I type and I don't know why. This is where I defined my classes: class Book(models.Model): title = models.CharField(max_length=255) author = models.CharField(max_length=255) editor = models.CharField(max_length=255) year_published = models.IntegerField() number_in_stock = models.IntegerField() daily_rate = models.FloatField(null=True) genre = models.ForeignKey(Genre, on_delete=models.CASCADE) date_created = models.DateTimeField(default=timezone.now) manga_image = models.ImageField(null=True, blank=True, upload_to='images/') And this is where I defined my requests: def search_manga(request): if request.method == "POST": searched = request.POST[('searched')] mangas = Book.objects.filter(title__contains=searched) return render(request, 'books/search_manga.html', {'searched': searched, 'mangas': mangas}) else: return render(request,'books/search_manga.html', {}) Also this is the HTML document I'm trying to show the results on: {% extends 'base.html' %} {% block content %} <style> h1 { text-align: center; } </style> {% if searched %} <h1>You Searched For {{searched}}</h1> <br/> {% for manga in mangas %} {{ manga }}<br/> {% endfor %} {% … -
How can we specify graphql schema to use a custom db for saving objects in Django?
Graphql Schema Mutations happen to use the default DB specified in settings.py. Since I have a Django project with multiple apps and db's , how can I specify graphql mutation to use a different db and not the default one. -
How to create a database using Django and Cloudant
Please, I need to implement a web-based tool that was created using the Django framework but there is no database yet and I would like to use Cloudant. As Cloudant uses JSON, how could I get input for the user and convert it to JSON? Thank you! -
coukies django python cart
How can i do a cart for a long time on django-python using cookies please response to me !! it's an emergency def Cart(request) try: customer = request.user.customer except: device = request.COOKIES['device'] customer, created = Customer.objects.get_or_create(device=device) order, created = Order.objects.get_or_create(customer=customer,complete=False) # print(order.product) categories = Category.objects.all() context={'order':order,'categories':categories} response = render (request,'store/cart.html',context) set_cookie(response, 'cart',device) return response -
Cannot add user in django rest framework
Im trying to make an API to register a new user, but I can't and I really don't know why. Im beginner. Views.py: def register_view(request): s = serializers.CreateUserSerializer(data=request.data) if s.is_valid(): s.save() return Response(s.errors) Serializers.py: class CreateUserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['email', 'username', 'password'] extra_kwargs = {'password': {'write_only': True}} def create(self, validated_data): user = User( email=validated_data['email'], username=validated_data['username'] ) user.set_password(validated_data['password']) user.save() return user Error i get: {"username":["This field is required."],"password":["This field is required."]} im simply sending data using postman -
Allowing post request through Nginx
Trying to serve a react app, django with nginx and docker. I am not able to make a post call from docker on port 8080 to nginx on port 8082. Following is the error thrown by Nginx iris-frontend-frontend-1 | 2022/10/13 20:16:18 [error] 35#35: *4 open() "/usr/share/nginx/html/add-to-waiting" failed (2: No such file or directory), client: 172.18.0.1, server: localhost, request: "POST /add-to-waiting HTTP/1.1", host: "localhost:8080", referrer: "http://localhost:8080/" Nginx configurations are: add-to-waiting is the api call. upstream django { server website:8000; } upstream react_app { server frontend:8080; } server { listen 80; client_max_body_size 100M; proxy_set_header X-Forwarded-Proto $scheme; location / { proxy_pass http://react_app; } location /admin { proxy_pass http://django; } location /add-to-waiting { proxy_pass http://django; } location /media/ { alias /app/media/; } location /static/ { alias /app/forex/static/admin/; } } What configurations need to change to make frontend able to call the api? -
Need help displaying data in a specific format using Django and Python
I am very much a newbie at Django and python, so please be gentle! I have a database with a table that has date, time, position, group number, and the names of the people in each group. This table is for scheduling purposes. The table has several lines with date, depending on the total number of people scheduled per day, three different shifts at the moment (time), and three positions. Each group that fills each position can have a varying number of people in it, and each position has a different number of groups for each time slot. What I want is something that has the date on the first row, the three times on the second row, the three positions under each of the three times on the third row, then list the group number and each person. Row 1: 1 column (date) Row 2: 3 columns (time) Row 3: 9 columns (position) Row 4-? 9 columns (group number, names listed under each group number) Honestly, I have no idea how to accomplish this layout. Any ideas? Here's the code I have so far. Thanks! View: def index(request): context = {} sched= Schedule.objects.all() context['sched'] = sched return render(request, 'index.html', … -
ModuleNotFoundError while deploying django server on heroku
I am having trouble while deploying server on heroku (ModuleNotFoundError: No module named 'screen_sender') I think it may be because I use django-channels you can see my directories below and files: Procfile web: gunicorn websocket_image_sender.wsgi settings.py import os from pathlib import Path BASE_DIR = Path(__file__).resolve().parent.parent SECRET_KEY = 'key' IS_HEROKU = "DYNO" in os.environ if not IS_HEROKU: DEBUG = True if IS_HEROKU: ALLOWED_HOSTS = ["*"] else: ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'screen_sender', 'channels', ] ASGI_APPLICATION = 'websocket_image_sender.asgi.application' 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', ] ROOT_URLCONF = 'websocket_image_sender.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 = 'websocket_image_sender.wsgi.application' # Database # https://docs.djangoproject.com/en/4.0/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } # Password validation # https://docs.djangoproject.com/en/4.0/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.0/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.0/howto/static-files/ STATIC_URL = 'static/' # Default primary key … -
Can I deploy a Django App if there is no "" (empty) url?
I'm trying to deploy a Django App with railways for the first time and I was wondering where exactly will be my landing page. So basically my urls.py looks something like this: path('home/', views.home, name="home"), path('blogposts/', views.blogposts, name="blogposts"), path('posts/', views.posts, name="posts"), After deploying my Blog website, let's say with the domain 12345xxx.com, where will I land? -
Python WSGI Server for Kubernetes?
I want to run my Django application in Kubernetes. In Kubernetes the available ressources could limited, and the amount of CPUs you get with traditional methods could be wrong. For Go this gets handled with https://github.com/uber-go/automaxprocs Up to now I use gunicorn, but I could switch to a different wsgi server. Which wsgi server is recommended to run Django applications in Kubernetes? -
Admin approval and email verification with all-auth
I want to implement an admin approval and email confirmation system for the signup process. For now, I am using the 'is_active' field set False by default, until the admin sets it manually to True. It works so far, the only problem is that the confirmation mail is not being sent out when 'is_active' is False. The email-confirmation flag is actually in another table called accounts_emailaddress, so I am wondering why this is not working? Depending on which flag is set to False, the user should be redirected to the corresponding Templates. The user should not be able to log in, unless the email is verified and his profile approved by the administrator. How can I achieve this result?