Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to use Google Calendar API with Django without service account?
I am building a django app for an organisation where people can make appointments and I want to sync those details with Google Calendar. So to achieve it I need a token.json which we get when we authenticate using oAuth. When I try to use Google Calendar API with oAuth2.0 it gives bad request error in django and the oAuth consent screen won't appear ,but works fine when the same code is executed in a seperate python file.When I use service account, it's asking me to signup for Google workspace which I don't need. I have also tried generating the access token using a seperate python file and then use those to create events but still it throws the same error Bad request. When searching through web I have found a package called django-auth but I think it's used to authenticate the user to Google account,I don't need that I just need the organisation Gmail to get authenticated and then add the user as guests. So, Is this approach correct is yes then what am I missing here or is there any better approach. Here's one of my Assumption: Organisation have GCP project which is production so I guess the … -
What is causing my AssertionError when trying to implement Allauth with Django?
I am trying to implement Allauth to work in conjuction with my custom user model in Django. When I try to run the server I receive the following readout in the console: File "X:\Aidan Comer\Documents\Portfolio_Projects\game_ecommerce_site\venv\lib\site-packages\allauth\account\app_settings.py", line 373, in <module> app_settings = AppSettings("ACCOUNT_") File "X:\Aidan Comer\Documents\Portfolio_Projects\game_ecommerce_site\venv\lib\site-packages\allauth\account\app_settings.py", line 20, in __init__ assert ( AssertionError My custom user model is: class UserBase(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_('email address'), unique=True) first_name = models.CharField(max_length=150, blank=True) last_name = models.CharField(max_length=150, blank=True) country = CountryField() date_of_birth = models.DateField(max_length=8) phone_number = PhoneNumberField(null=False, blank=False, unique=True) town_city = models.CharField(max_length=150, blank=True) avatar = models.ImageField(upload_to='avatars', default='default-user-avatar.png') is_active = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) created = models.DateTimeField(auto_now=True) objects = CustomAccountManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['first_name', 'last_name', 'country', 'phone_number', 'date_of_birth', 'town_city',] Here are my settings concerning Allauth and google Oauth implementation: # Allauth and Oauth login settings SOCIALACCOUNT_LOGIN_ON_GET=True AUTHENTICATION_BACKENDS = [ 'django.contrib.auth.backends.ModelBackend', 'allauth.account.auth_backends.AuthenticationBackend', ] ACCOUNT_AUTHENTICATION_METHOD = "email" ACCOUNT_USER_MODEL_USERNAME_FIELD = None ACCOUNT_USER_MODEL_USERNAME_FIELD = False ACCOUNT_EMAIL_VERIFICATION = 'none' SOCIALACCOUNT_PROVIDERS = { 'google': { 'SCOPE': [ 'profile', 'email', ], 'AUTH_PARAMS': { 'access_type': 'online', } } } Why am I receiving this AssertionError? -
Unable to retrieve children from all parent objects inside ModelViewSet
These are classes in my Django project. ### Models ### class Course(models.Model): department = models.ForeignKey(Department, on_delete=models.CASCADE, null=True) class Department(models.Model): name = models.CharField(max_length=300) ### Serializers ### class DepartmentFromCourseSerializer(serializers.ModelSerializer): department = my_serializers.DepartmentSerializer() class Meta: model = models.Course fields = ('id', 'department') ### ViewSets ### class DepartmentFromCoursesViewSet(ReadOnlyModelViewSet): queryset = models.Course.objects.select_related('department') serializer_class = serializers.DepartmentFromCourseSerializer What I am receiving with my DepartmentFromCoursesViewSet is this response: { "count": 500, "next": "https://...", "previous": null, "results": [ "id": 1 "department": { "id": 150, "name": "My department1" }, "id": 2 "department": { "id": 151, "name": "My department2" } ]} But what I would like to get is list of Department objects of all Courses. Like this: "count": 500, "next": "https://...", "previous": null, "results": [ { "id": 150, "name": "My department1" }, { "id": 151, "name": "My department2" } ]} I do understand I need to change Serializer, to DepartmentSerializer which will have Meta: model=models.Department and fields=('id', 'name'). But I am unable to receive this object from ViewSet. -
Django REST Framework group by date field in nested model having many to many through relationship
Django REST Framework group by date field in nested model having many to many through relationship. Please, I am experiencing challenges implementing group by for my Django Rest Framework (DRF) project. How can I group by date field (schedule_date)? This is my models.py file class AvailableTimeSlotType(models.Model): id = models.UUIDField(primary_key = True,default = uuid.uuid4,editable = False) name = models.CharField(max_length=255, blank=True,null=True) image = models.ImageField(upload_to ='api/uploads/available_time_slot_types/%Y/%m/%d/',blank=True,null=True) description = models.TextField(blank=True,null=True) def __str__(self): return self.name class AvailableTimeSlot(models.Model): id = models.UUIDField(primary_key = True,default = uuid.uuid4,editable = False) name = models.CharField(max_length=255, blank=True,null=True) time_field = models.TimeField(default=timezone.localtime) slot_type = models.ForeignKey(AvailableTimeSlotType,on_delete=models.CASCADE,blank=True,null=True) image = models.ImageField(upload_to ='api/uploads/available_time_slots/%Y/%m/%d/',blank=True,null=True) description = models.TextField(blank=True,null=True) def __str__(self): return self.name class Doctor(models.Model): id = models.UUIDField(primary_key = True,default = uuid.uuid4,editable = False) user = models.OneToOneField(User, on_delete=models.CASCADE,related_name='doctor',blank=True,null=True) public_name = models.CharField(max_length=255, blank=True,null=True) biography = models.TextField(blank=True,null=True) image = models.ImageField(upload_to='api/uploads/doctors/%Y/%m/%d/', null=True, blank=True) slug = AutoSlugField(populate_from='public_name',blank=True,null=True) available_timeslots = models.ManyToManyField(AvailableTimeSlot,through="DoctorAvailableTimeSlot",blank=True) verification_date = models.DateTimeField(default=datetime.now, blank=True) years_of_experience = models.IntegerField(default=1,blank=True) rating = models.DecimalField(max_digits=10,decimal_places=2,default=1,blank=True,null=True) def __str__(self): return self.public_name class DoctorAvailableTimeSlot(models.Model): id = models.UUIDField(primary_key = True,default = uuid.uuid4,editable = False) doctor = models.ForeignKey(Doctor, on_delete=models.CASCADE,blank=True,null=True,related_name='doctor_available_timeslots') available_timeslot = models.ForeignKey(AvailableTimeSlot, on_delete=models.CASCADE,blank=True,null=True) schedule_date = models.DateField(default=datetime.now, blank=True) def __str__(self): return self.doctor.public_name +' - '+self.available_timeslot.name This is my serializer.py class AvailableTimeSlotTypeSerializer(serializers.ModelSerializer): class Meta: model = AvailableTimeSlotType fields = ("__all__") class AvailableTimeSlotSerializer(serializers.ModelSerializer): slot_type = AvailableTimeSlotTypeSerializer() class Meta: … -
cant make superuser and givin this error TypeError: MyUserManager.create_superuser() got an unexpected keyword argument 'id_code'
after customizing user model i cant create superuser (giving this error TypeError: MyUserManager.create_superuser() got an unexpected keyword argument 'id_code' )and when i try to create normal user it will be create but the password doesn't save for it the model is: from django.db import models from django.contrib.auth.models import ( BaseUserManager, AbstractUser,AbstractBaseUser ) class MyUserManager(BaseUserManager): def create_user(self, email, date_of_birth,password=None): """ Creates and saves a User with the given email, date of birth and password. """ if not email: raise ValueError('Users must have an email address') user = self.model( email=self.normalize_email(email), date_of_birth=date_of_birth, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, date_of_birth, password=None): """ Creates and saves a superuser with the given email, date of birth and password. """ user = self.create_user( email, password=password, date_of_birth=date_of_birth, ) user.is_admin = True user.save(using=self._db) return user class MyUser(AbstractBaseUser): full_name = models.CharField(null=True, max_length=200, verbose_name="نام ونام خانوادگی") id_code = models.CharField(max_length=200, null=True, unique=True, verbose_name='کدملی') email = models.EmailField( verbose_name='ایمیل', max_length=255, unique=True, ) date_of_birth = models.DateField(verbose_name='تاریخ تولد') password = models.CharField(max_length=20,verbose_name='گذرواژه') fathers_name = models.CharField(null=True,max_length=200,verbose_name='نام پدر') birth_loc = models.CharField(null=True,max_length=200,verbose_name='محل تولد') phone_number = models.CharField(null=True,unique=True,max_length=200,verbose_name='شماره موبایل') address = models.TextField(null=True,verbose_name='آدرس دقیق') is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) objects = MyUserManager() USERNAME_FIELD = 'id_code' REQUIRED_FIELDS = ['date_of_birth','full_name','fathers_name','birth_loc','phone_number','address','email'] class Meta: verbose_name = 'کاربر' verbose_name_plural = 'کاربران' def __str__(self): return self.email … -
Unable to pass kwarg into an inlineformset_factory?
THere is an answer here that doesnt solve my problem. Pass kwarg into an inlineformset_factory? This is my view class, error message inline class InvoiceCreateView(CreateView): model = Invoice fields = ( 'client', 'order_number', ) def get_form_kwargs(self): kwargs = super().get_form_kwargs() ########## ERROR MESSAGE "_init__() got an unexpected keyword argument 'form_kwargs'" kwargs['form_kwargs'] = {'request': self.request} ########## return kwargs def get_context_data(self, **kwargs): data = super(InvoiceCreateView, self).get_context_data(**kwargs) if self.request.POST: data['track_formset'] = InvoiceFormSet(self.request.POST) else: data['track_formset'] = InvoiceFormSet() return data def get_object(self, queryset=None): return get_object_or_404(self.model, username=self.request.user.pk) def get(self, request, *args, **kwargs): self.referer = request.META.get("HTTP_REFERER", "") request.session["login_referer"] = self.referer return super().get(request, *args, **kwargs) def post(self, request, *args, **kwargs): self.referer = request.session.get("login_referer", "") return super().post(request, *args, **kwargs) def form_valid(self, form): up = UserProfile.objects.get(username=self.request.user.pk) form.instance.profile = up bk = BankAccount.objects.get(profile=up) form.instance.user_bank = bk context = self.get_context_data(form=form) formset = context['track_formset'] if formset.is_valid(): response = super().form_valid(form) formset.instance = self.object formset.save() return response else: return super().form_invalid(form) def get_success_url(self): return self.request.path This is my form code (no errors here,added for completeness) class InvoiceForm(forms.ModelForm): name = forms.CharField(label='Description', initial='Some info') class Meta: model=Invoice exclude = ["username", "invoice_number", "invoice_status", "profile", "user_bank", "date_from", "date_to","total",] model=LineItem # readonly_fields = ['total'] # currency default changes if this is set exclude = ["user",] InvoiceFormSet = inlineformset_factory( Invoice, LineItem, form=InvoiceForm, min_num=1, … -
Django log rotate on google cloud engine throwing error - Read only file system
Planning to add django log rotate on my application, running on google compute engine.Adding log rotate is failing by throwing error **OSError: [Errno 30] Read-only file system: '/workspace/neo_app_backend/log' ** at the time of deployment.This is the path where the log files are keeping. When opening the path log file is created. LOG_PATH = f'{BASE_DIR}/log' if not os.path.exists(LOG_PATH): os.makedirs(LOG_PATH) LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'verbose': { 'format': '{levelname} {asctime} {module} {process:d} {thread:d} {message}', 'style': '{', } }, 'handlers': { 'file': { 'level': 'INFO', 'class': 'logging.handlers.RotatingFileHandler', 'filename': '{}/{:%Y-%m-%d}.log'.format(LOG_PATH, datetime.now()), 'maxBytes': 1024 * 1024 * 10, 'backupCount': 10, 'formatter': 'verbose' } }, 'loggers': { 'django': { 'handlers': ['file'], 'level': 'INFO', 'propagate': True, } } } This is the code added to the settings file. I have the requiement to add log rotate. -
Django: Is it possible to make a form with several models and view would be selected which one to take
as in the title. wants this to be done somehow nicely in code. I currently have several forms for individual categories and one general form. forms.py from django import forms from .models import Book, CD, Film class GenreChoiceField(forms.ChoiceField): def __init__(self, choices=()): super().__init__(choices=choices) current_choices = self.choices self.choices = (('alphabetical', 'Alphabetically'), ('popularity', 'By popularity')) self.choices += current_choices class HomeForm(forms.Form): choices = () genre = GenreChoiceField(choices=choices) class BookGenreForm(forms.ModelForm): genre = GenreChoiceField(choices=Book.GENRE_CHOICES) class Meta: model = Book fields = ('genre',) class CDGenreForm(forms.ModelForm): genre = GenreChoiceField(choices=CD.GENRE_CHOICES) class Meta: model = CD fields = ('genre',) class FilmGenreForm(forms.ModelForm): genre = GenreChoiceField(choices=Film.GENRE_CHOICES) class Meta: model = Film fields = ('genre',) model.py class CD(Product): GENRE_CHOICES = ( ('Rock', 'Rock'), ('Pop', 'Pop'), ('Reggae', 'Reggae'), ('Disco', 'Disco'), ('Rap', 'Rap'), ('Electronic music', 'Electronic music'), ) band = models.CharField(max_length=100, null=False, blank=False) tracklist = models.TextField(max_length=500, null=False, blank=False) genre = models.CharField(max_length=100, choices=GENRE_CHOICES, null=False, blank=False) class Book(Product): GENRE_CHOICES = ( ('Fantasy', 'Fantasy'), ('Sci-Fi', 'Sci-Fi'), ('Romance', 'Romance'), ('Historical Novel', 'Historical Novel'), ('Horror', 'Horror'), ('Criminal', 'Criminal'), ('Biography', 'Biography'), ) author = models.CharField(max_length=100, null=False, blank=False) isbn = models.CharField(max_length=100, null=False, blank=False) genre = models.CharField(max_length=100, choices=GENRE_CHOICES, null=False, blank=False) class Film(Product): GENRE_CHOICES = ( ('Comedy', 'Comedy'), ('Adventure', 'Adventure'), ('Romance', 'Romance'), ('Horror', 'Horror'), ('Thriller', 'Thriller'), ('Animated', 'Animated'), ) director = models.CharField(max_length=100, null=False, blank=False) … -
Multiple 'GET' Forms in one Django view
How to use multiple "get" forms in one view? Let's say I have forms: <form> {{form1}} <button>Send1</button> </form> <form> {{form2}} <button>Send2</button> </form> Now if I click on 'Send1' I will lose information about form with 'Send2' button because url will change In other words - How to proper set forms with get method so the data will combine in the url -
Django admin access error after deploying on railway
I have deployed Django app on railway and I'm having issues accessing my admin panel. I have tried CSRF_TRUSTED_ORIGINS and also django-cors-headers but the issue is still persisting. My seetings.py down below; INSTALLED_APPS = [ 'blog.apps.BlogConfig', 'users.apps.UsersConfig', 'crispy_forms', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'fontawesomefree', "corsheaders", ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', "corsheaders.middleware.CorsMiddleware", 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] CORS_ALLOWED_ORIGINS = ['https://web-production-8f9b.up.railway.app/',] CSRF_TRUSTED_ORIGINS = [ 'https://web-production-8f9b.up.railway.app' ] ROOT_URLCONF = 'help_project.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], '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 = 'help_project.wsgi.application' # Database # https://docs.djangoproject.com/en/3.2/ref/settings/#databases DATABASE_URL = os.getenv("DATABASE_URL") # DATABASES = { # 'default': { # 'ENGINE': 'django.db.backends.sqlite3', # 'NAME': BASE_DIR / 'db.sqlite3', # } # } DATABASES = { 'default': dj_database_url.config(default=DATABASE_URL, conn_max_age=1800), } # db_from_env = dj_database_url.config(default=DATABASE_URL, conn_max_age=1800) # DATABASES['default'].update(db_from_env) # Password validation # https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/3.2/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.2/howto/static-files/ STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, "static") # Default primary key field … -
Call CURD operation of a class from another class
I have a class with create, update, and delete functions of Django CRUD Can I use the create, and update functions of first in another class create function from example : class A(viewsets.ModelViewSet): def create(self, request, *args, **kwargs): some code def update(self, request, *args, **kwargs): some code Now as you can see the first class A have create and update function Now I have another class B which also a have create function now how can use call the create function of first class A class B(viewsets.ModelViewSet): def create(self, request, *args, **kwargs): some code -
Django Group by month and payment mode, get a report in template only for the datas present
In my database I have only data up to 'March' so I need only up to 'Mar' I want achiever monthly sum grouped by 'mode' def by_mode(request): all_modes = dict(Transactions.PAYMENT_MODE_CHOICES).keys() totals = Transactions.objects.annotate( month=TruncMonth('trans_date'), mode=F('trans_mode') ).values('month', 'mode').annotate( total=Sum('trans_amount') ) data = {} for total in totals: month = total['month'].strftime('%B') mode = total['mode'] if mode not in data: data[mode] = {} data[mode][month] = total['total'] return render(request, 'by_mode.html', {'data': data, 'modes': all_modes}) class Transactions(models.Model): TRANSACTION_TYPE_CHOICES = ( ('income', 'Income'), ('expense', 'Expense'), ) PAYMENT_MODE_CHOICES = ( ('cash', 'Cash'), ('enbd', 'ENBD'), ('nol', 'NOL'), ('sib', 'SIB'), ) trans_id = models.AutoField(primary_key=True) trans_date = models.DateField(verbose_name="Date") trans_type = models.CharField(max_length=10, choices=TRANSACTION_TYPE_CHOICES, verbose_name="Type") trans_details = models.ForeignKey(Details, on_delete=models.CASCADE, verbose_name="Details", related_name="trnsactions") trans_category = models.ForeignKey(MasterCategory, on_delete=models.CASCADE, verbose_name="Category", related_name="transactions") trans_mode = models.CharField(max_length=10, choices=PAYMENT_MODE_CHOICES, verbose_name="Payment Mode") trans_amount = models.DecimalField(max_digits=10, decimal_places=2, verbose_name="Amount") objects = models.Manager() class Meta: verbose_name_plural = "Transactions" def __str__(self): return f"{self.trans_id} - {self.trans_type} - {self.trans_details} - {self.trans_category} - {self.trans_amount}" -
How to perform a subquery in django's queryset for the following SQL-query?
class food(models.Model): restor_id = models.ForeignKey(restro, default='', on_delete=models.CASCADE) food_id = models.CharField('Food ID', max_length=20, primary_key=True) food_name = models.CharField('Food Name', max_length=50, default='') food_category = models.CharField('Food Category', max_length=50, default='') food_type = models.CharField('Food Type', max_length=50, default='') food_price = models.IntegerField('Food Price', default = 00) delivery_time = models.IntegerField('Delivery Time', default = 00) class cart(models.Model): user_id = models.CharField('User ID', max_length=50) food_id = models.CharField('Food ID', default='', max_length=50) quantity = models.IntegerField('Quantity', default = 1)` cart_details = cart.objects.filter(user_id = request.user.username).values_list('food_id').all() food_details = food.objects.filter(food_id__in = cart_details).values('food_id', 'food_name', 'food_price', 'delivery_time', 'quantity') I tried the above query but I am not getting 'quantity' in 'food_deatils' variable. I want ('food_id' 'food_name', 'food_price', 'delivery_time', 'quantity') inside a same query -
What is the best way to create an NBA stat tracking website?
I am very new to programming and want to create a website using Django and Vue where you can search for players or teams and find stats about the certain players/teams. I have a general idea about how to create this website but want to know what the best way is. Should I store all of the player/team information in my django database and use Vue to search and return the players or is it better to not store them locally but instead run search functions every time I search a player. I am very new to all of this so any help with figuring out the best way to start this would be great. I tried to create a function that automatically pulls player game logs and then store it into the Django local database but ran into quite a few issues doing that and am looking for extra help. I am using the NBA-api with python -
fetch in javascript doesn't let django to render to another page
i am facing a problem with fetch post in the front end javascript and the django back end i am sending a json form of data to the backend using the fetch method in javascript, and then i process the data and then pass the processed data to a returened render in django for another page. but the problem is the fetch i am using doesn't allow django to do a render it just stays at the same page. here is the code i am using in the front end: <script> const form = document.getElementById('fooorm'); form.addEventListener('submit', async (event) => { event.preventDefault(); const formData = new FormData(form); const query = formData.get('query'); const csrfToken = form.querySelector('input[name="csrfmiddlewaretoken"]').value; const position = await gps(); const data = { query: query, latitude: position.coords.latitude, longitude: position.coords.longitude }; fetch('/results/', { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-CSRFToken': csrfToken }, body: JSON.stringify(data) }); }); </scirpt> and here is the code i am using for the back end : def index(request): if request.method == 'POST': data = json.loads(request.body) query = data['query'] latitude = data['latitude'] longitude = data['longitude'] services = bricoler.objects.filter(service__icontains=query) return render(request, "results.html", {"nearby": services}) else: return render(request, 'index.html') -
Calculated table column data - better to calculate on the server or on the client side?
I have a ~20 column table where half of the columns consist of data from my database and the other half are simple calculated values based on two of the data columns (e.g "Costs", "Revenue" column from db and a "Profit" column I would have to calculate). How do I go about deciding when it would be best to calculate my calculated columns on the server vs on the client side? Originally I was going to calculate it on the server (Django backend) but in an MUI Datagrid example they show a column being calculated based off two other columns. Some points about the project that make me think frontend over backend: All of the data calculations are used for read only data (won't have to validate on the backend) All of the calculated columns are simple calculations (one column subtracted by another or divided by another) I'm already sending all of the data being used for calulcations to the client -
Cannot send React POST request to django api error
I am attempting to send a post request containing the name of a genre of music from react to my django api so that this genre can be put into a query param to be searched using the spotify api. Genre.js // Fetch and map list of genres, when a genre is clicked it is saved to state, then sent in a post request to my endpoint. import React, { useState, useEffect } from "react"; function Genres() { const [genres, setGenres] = useState([]); const [clickedGenre, setClickedGenre] = useState(""); const [type, setType] = useState("") useEffect(() => { fetch("http://localhost:8000/api/genres/") .then((response) => response.json()) .then((data) => setGenres(data.genres)) .catch((error) => console.log(error)); }, []); function handleClick(genre) { setClickedGenre(genre); const query_params = { genre: genre, }; // const csrftoken = document.querySelector('[name=csrfmiddlewaretoken]').value; fetch("http://localhost:8000/api/search/", { method: "POST", headers: { "Content-Type": "application/json", // "X-CSRFToken": csrftoken, // Add the CSRF token to the headers }, body: JSON.stringify(query_params), }) .then((response) => response.json()) .then((data) => console.log(data)) .catch((error) => console.log(error)); } return ( <div> <div className="genre-list-container"> <ul className="genre-list"> {genres.map((genre) => ( <li className="genre" onClick={() => handleClick(genre)} key={genre} > {genre} </li> ))} </ul> </div> </div> ); } export default Genres; views.py // Retrieve post request and put result into the "q" param. Then make spotify … -
How to know the size of my Django pages before deployment?
I am developing my very first website. I would like to know the page size before attempting to deploy it and whether I am doing something really silly/inefficient. Is there at least any tool similar to https://tools.pingdom.com/ while in development? -
Django Admin: Change status without updating the password
I am new to Django and I have a problem regarding Django custom user model. I am changing the status of the user to for example is_staff=True from admin panel but it requires password to made changes. I don't want to change or update the user password. So what's I am missing here. I also tried few things but didn't find anything. Thanks for your help in advance. -
Unit test in PyCharm fails if imported a class
With PyCharm, we are trying to create a unit test file tests/test_poc.py for a proof-of-concept class PocFunctional, and we have added DJANGO_SETTINGS_MODULE=applicationproject.settings into the "Python tests" section of the "Run/Debug Configurations". However, if we uncomment from app.poc import PocFunctional in the below sample source code to import the class under test, the unit test will get a run-time error saying django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.. Although the file runs OK if not imported the PocFunctional class. We are new to the unit test of Python in PyCharm environment, so we highly appreciate any hints and suggestions. Technical Details: Partial unit test source code: from unittest import TestCase # from app.poc import PocFunctional class TestPocEav(TestCase): def test_get_transaction(self): # self. Fail() return # ... other test methods Exception: /data/app-py3/venv3.7/bin/python /var/lib/snapd/snap/pycharm-professional/316/plugins/python/helpers/pycharm/_jb_unittest_runner.py --target test_poc.TestPocFunctional Testing started at 5:03 PM ... Launching unittests with arguments python -m unittest test_poc.TestPocFunctional in /data/app-py3/APPLICATION/tests Traceback (most recent call last): File "/var/lib/snapd/snap/pycharm-professional/316/plugins/python/helpers/pycharm/_jb_unittest_runner.py", line 35, in <module> sys.exit(main(argv=args, module=None, testRunner=unittestpy.TeamcityTestRunner, buffer=not JB_DISABLE_BUFFERING)) File "/usr/local/lib/python3.7/unittest/main.py", line 100, in __init__ self.parseArgs(argv) File "/usr/local/lib/python3.7/unittest/main.py", line 147, in parseArgs self.createTests() File "/usr/local/lib/python3.7/unittest/main.py", line 159, in createTests self.module) File "/usr/local/lib/python3.7/unittest/loader.py", line 220, in loadTestsFromNames suites = [self.loadTestsFromName(name, module) for name in names] File "/usr/local/lib/python3.7/unittest/loader.py", line … -
Requests multiplying with each interaction with input
I'm having trouble with requests that multiply undesirably and I haven't found a solution so far. It turns out that, I have a select html that when an option is chosen, it makes a request to the backend and returns the values of the db in the input below the form, so far so good, the query is being executed and returned correctly, however every changing the option of this select without reloading the page, the requests are multiplied, ex: when I select for the first time, the request is made 1 time, when I select again the request is made 2 times in a row, and this escalates, I tested changing the select 9 times sequences and the same request is performed 9 times in sequence with the same parameters, with the same response, as if there were a variable that at each interaction adds 1 and multiplies the request. here a sample of the select changed 3 times [15/Mar/2023 23:46:29] "GET /propriedades/atualiza_propriedade/17/ HTTP/1.1" 200 102 [15/Mar/2023 23:46:32] "GET /propriedades/atualiza_propriedade/20/ HTTP/1.1" 200 108 [15/Mar/2023 23:46:32] "GET /propriedades/atualiza_propriedade/20/ HTTP/1.1" 200 108 [15/Mar/2023 23:46:35] "GET /propriedades/atualiza_propriedade/22/ HTTP/1.1" 200 136 [15/Mar/2023 23:46:35] "GET /propriedades/atualiza_propriedade/22/ HTTP/1.1" 200 136 [15/Mar/2023 23:46:35] "GET /propriedades/atualiza_propriedade/22/ HTTP/1.1" … -
Django query gives "SELECT DISTINCT ON expressions must match initial ORDER BY expressions" error even specified the same order
VirtualMachine.objects.order_by('pool__customer').distinct('pool__customer') Been thru this ticket already also tried asking ChatGPT (lol), the answer doesn't have .all() but gave the same error, wouldn't think it made a difference anyway cos .order_by('pool__customer') should overwrite it already -
Django signal creates UserProfile from listening to User, but it's empty?
I'm new to Django and trying to create a signal that listens to a custom User model I've built. My intention is that when a new User is created, that a profile for them will also be automatically created. To me it seems that my signal itself works, as when I use the /admin screen I can add a User and it automatically creates their profile. However, when I try to add a new User through the front end of the application, it appears that the signal does indeed detect a new User being created and creates a Profile for them. But when I go into the /admin screen to have a look at it, it's empty. When I say empty, I mean that the Profile record is created, but none of the fields are populated. This is then causing further errors in my app, because I can't use the User to pull up the User's Profile and render it, because it's empty and not connected to a User. What am I doing wrong? My hunch is that something is wrong with my view function. registerUserParticipant and registerUserSupervisor are called when creating a new user in the front end. editAccount … -
how can i put a user's information in his profile
I work on django project, with another front-end developer, so it's not django that handles a lot of things in html. I created a user model with Abstractuser, now I want to display the information of users and super users but it does not work how to make it work can you help me please My views file @login_required def admin_profil(request): message='' user= request.user if user.is_superuser: print('________________________________________________________________dream________________________________________________') user = get_user_model().objects.all() else: print('________________________________________________________________false________________________________________________________________') message= 'You are not a superuser' return render(request , 'admin_app/admin_profil.html',{'message': message,'user': user}) my html file <div class="card bg-white profile-content"> <div class="row"> <div class="col-lg-4 col-xl-3"> <div class="profile-content-left profile-left-spacing"> <div class="text-center widget-profile px-0 border-0"> <div class="card-img mx-auto rounded-circle"> <img src="/static/admin_app/assets/img/user/u1.jpg" alt="user image"> </div> </div> <hr class="w-100"> <center> <div class="contact-info pt-4"> <h5 class="text-dark">Informations</h5> {% if user.is_authenticated %} <p class="text-dark font-weight-medium pt-24px mb-2">Adresse Mail</p> <p>{{user.email}}</p> <p class="text-dark font-weight-medium pt-24px mb-2">Numéro De Téléphone</p> <p>{{ user.phone}}</p> <p class="text-dark font-weight-medium pt-24px mb-2">Social Profil</p> <p class="social-button"> <a href="#" class="mb-1 btn btn-outline btn-twitter rounded-circle"> <i class="mdi mdi-twitter"></i> </a> <a href="#" class="mb-1 btn btn-outline btn-linkedin rounded-circle"> <i class="mdi mdi-linkedin"></i> </a> <a href="#" class="mb-1 btn btn-outline btn-facebook rounded-circle"> <i class="mdi mdi-facebook"></i> </a> <a href="#" class="mb-1 btn btn-outline btn-skype rounded-circle"> <i class="mdi mdi-skype"></i> </a> my uls files path('ajout_produit/', views.add_product, name='add'), … -
NOT NULL constraint failed null=True blank=True
despite having null and blank true in my models I always get NOT NULL constraint failed: user_mgmt_profile.user_id I've deleted the database, deleted migrations, run commands again, and the error still persist. Where do you see the issue Basically Im automatically connecting user to new profile on post request models class Profile(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) user = models.OneToOneField(User, on_delete=models.CASCADE) gym = models.OneToOneField(Gym, null=True, blank=True, on_delete=models.DO_NOTHING) create function in viewset def create(self, request): request.data['user'] = request.user.id serializer = ProfileSerializer(data=request.data) if serializer.is_valid(): serializer.save() data = serializer.data return Response(data, status=status.HTTP_201_CREATED) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) serializers class LocationSerializer(serializers.ModelSerializer): class Meta: model = Location fields = '__all__' class GymSerializer(serializers.ModelSerializer): place = LocationSerializer(read_only=True) class Meta: model = Gym fields = '__all__' class ProfileSerializer(WritableNestedModelSerializer, serializers.ModelSerializer): user = UserSerializer(read_only=True) gym = GymSerializer(read_only=True) class Meta: model = Profile fields = '__all__' depth = 1 edit I've printed out the request.data['user'] and i can see the UUID of the current user