Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why do I get "Reverse for '' with arguments '()' not found"?
I am beginner at Django. In fact, I'mtrying to create a dashboard from which it is possible to go to every model. A single "page-config.html" reads the model concerned and diplays its content. From this page I want to be able to create a new row or update or delete. THe page in charge of it is called "page-config-detail". let's see it. My urls.py urlpatterns = [ path('home/', home, name="home"), path('prestations/', prestations, name="prestations"), path('realisations/', realisations, name="realisations"), path('contact/', contact, name="contact"), path('dashboard/', dashboard, name="dashboard"), path('dashboard/<page_name>', pageConfig, name="page-config"), path('dashboard/<page_name>/<action>/<int:element_id>', pageConfigDetail, name="page-config-detail"), ] My views.py def pageConfig(request, page_name): create = 'create' for page in MY_CONFIG_PAGES: if page[0] == page_name: model = page[1].objects.all() else : return HttpResponseRedirect('dashboard') return render(request, "pages/page-config.html", {'model' : model, 'create' : create, 'category': 'category'} ) def pageConfigDetail(request, page_name=None, action=None, element_id=None): for page in MY_CONFIG_PAGES: if page[0] == page_name: if action == "create" or action == "update" or action == "delete" : try: model = page[1].objects.get(pk=element_id) if request.method == "POST": if action == "update": form = page[2](request.POST, instance=model) elif action =="delete": """faudra faire une redirection""" else: """faire un http redirect vers l'update et pas create""" pass if form.is_valid(): form.save() return HttpResponseRedirect(f'dashboard/{page[0]}') else: form = page[2](instance=model) except ObjectDoesNotExist : if request.method == "POST": … -
How can I loop django model fields in form
I have a model called 'Column' that has a relationship with my 'Type' model. I want to loop the 'Column' model by 30 in the form. Instead of showing 2 fields in the form, I want to show 30 fields in the column form. How can I do this? class Type(models.Model): TYPE_OF_DATA = ( ('Number', 'Number'), ('character', 'character'), ('check_box', 'check_box'), ('date', 'date'), ('image', 'image'), ) data_type = models.CharField(max_length=1000, choices= TYPE_OF_DATA) class Column(models.Model): name = models.CharField(max_length=100) selec_type = models.ForeignKey(Type, on_delete= models.CASCADE) -
Is there an extension that can enable me access the inherited python django class from my vs code
Lets say this is some file open on my vs code and has this code. from django.contrib.auth.models import AbstractBaseUser, PermissionsMixins class User(AbstractBaseUser, PermissionsMixins): pass i want an extension or a way in which i can hover on 'AbstractBaseUser' or 'PermissionsMixins' and hen i get some clickable information about the parent class o which when i click i can access it. i want to access the parent class. any help?. Hope i am clear enough. I have tried a few extensions but i dont seem to get one that works for me -
try sending mail from yahoo mail to any other email , using django-allauth thatis
from django.shortcuts import redirect # from allauth.socialaccount.providers.yahoo.views import YahooOAuth2Provider from allauth.socialaccount.providers.yahoo.provider import YahooProvider from urllib.parse import urlencode from allauth.socialaccount.providers.oauth2.client import OAuth2Client from django.core.mail import send_mail from rest_framework import views, status from rest_framework.response import Response from myapp.serializers import EmailSerializer class YahooMailView(views.APIView): permission_classes = [] def post(self, request, format=None): serializer = EmailSerializer(data=request.data) serializer.is_valid(raise_exception=True) email = serializer.validated_data['email'] yahoo_provider = YahooProvider(request) yahoo_client = OAuth2Client( request, consumer_key='XXXXXXX', consumer_secret='XXXXXXX', access_token_method='POST', access_token_url='https://api.login.yahoo.com/oauth2/get_token', callback_url='https://pulpstrategy.com/test/test.php', scope=['sdct-r'] ) # if the user has been redirected back from Yahoo with a code parameter, # use it to get an access token and send the email if 'code' in request.GET: code = request.GET['code'] token = yahoo_client.get_access_token(code) headers = { 'Authorization': f'Bearer {token.token}', 'Content-Type': 'application/json' } data = { 'personalizations': [ { 'to': [ { 'email': email } ] } ], 'from': { 'email': 'zha.aashu0002@yahoo.com' }, 'subject': 'Test email', 'content': [ { 'type': 'text/plain', 'value': 'Test email body' } ] } response = yahoo_client.post('https://api.mail.yahoo.com/ws/mail/v1.1/createMessage', headers=headers, json=data) if response.status_code == 201: return Response({'message': 'Email sent successfully'}, status=status.HTTP_200_OK) else: return Response({'message': 'Failed to send email'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) # if the user hasn't been redirected back from Yahoo, redirect them to Yahoo's # authorization page to grant permission to the application else: redirect_uri = request.build_absolute_uri('/yahoo/mail/') params = … -
Django channel using daphne running on production server closed frequently
CRITICAL Listen failure: 'NoneType' object has no attribute 'fcntl' while running daphne as separate process in windows server. How can I sole this problem to run asynchronous jobs -
in react and django existing project. I have to run 'npm run watch' command. But it is not working
I need to run "npm run watch" in an existing react enter image description here project. but npm is not working perfectly.enter image description here why it is happening and what is the solution. please it is very urgent and have to solve within 2 hours -
Django sending Email in Html format
hi ive created the SMT for django and installed django-templated-mail==1.1.1 django-templated-email==2.3.0 and it has worked perfectly and it is even sending the message but it is sending the message in a html format instead of a perfect user interface page enter image description here thats how the message is being sent. what might be the problem I tried to see if the problem was in the settings but cant see anything -
How to filter by another model with django-filter
I have request json api from 3rd party and i was looking way to filter my json by another model I have model ObjectList with GUID and in json i got Dicts of Object_Guid and other data: I dont want to create new model for this json i already parsed that in my get_queryset ListView but im looking for way to get form and then filter by name or this is not possible? I want to get parsed queryest and filtered by name from another model: ObjectList.objects.get(GUID=parsed_json.ObjectGUID) And the main question is how to pass queryset of parsed info and got name of objects from another model and filter my queryset by that names? views.py def get_queryset(self): session = requests_cache.CachedSession('project_budget_cache') url = config('REPORT_PROJECT_BUDGET') response = requests.get(url, auth=UNICA_AUTH).json() # response = session.get(url=url, auth=UNICA_AUTH).json() queryset = [] for item in response: my_js = json.dumps(item) parsed_json = ReportProjectBudgetSerializer.parse_raw(my_js) obj = parsed_json.ObjectGUID # obj_model = ObjectList.objects.get(GUID=obj) # context['response_object'].append(obj_model) for budget in parsed_json.BudgetData: budget.SectionGUID = CleanSections.objects.get(GUID=budget.SectionGUID) budget.СompletedContract = budget.СompletedContract * 100 budget.СompletedEstimate = budget.СompletedEstimate * 100 queryset.append(budget) # I had my own ListViewFilter there but it didnt help # I got something like that ListFilter(self.request.GET, queryset=queryset) return queryset -
How can i use django context processor to search through my model and display according to the return object of the contexxt processor?
i have a project in which i want to use Django context processor to search through my model can anyone help me to figure out how to do so i tried some of the things but it didn't work -
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