Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I optimize this Django query to get faster result?
items = Items.objects.filter(active=True) price_list = [] for item in items: price = Price.objects.filter(item_id = item.id).last() price_list.append(price) Price model can have multiple entry for single item, I have to pick last element. How can we optimize above query to avoid use of query in loop. -
Djagno: How to define __init__ function to django modelformset_factory?
I am trying to create a model formset and also for the field where users have to select a product, i don't want to show all the products in the database, i want to filter the products based on the logged in users. by doing something like this on the ModelForm class CartOrderItemsInvoiceForm(forms.ModelForm): class Meta: ... def __init__(self, *args, **kwargs): super(CartOrderItemsInvoiceForm, self).__init__(*args, **kwargs) self.fields['product_obj'].queryset = Product.objects.filter(user=self.request.user) but is it possible to do this on a modelformset_factory AuthorFormset = modelformset_factory( Author, fields=('name', 'age', 'gender', 'product'), extra=1, widgets={ 'name': forms.TextInput(attrs={ 'class': 'form-control', 'placeholder': 'Enter Author Name here' }), 'age': forms.TextInput(attrs={ 'class': 'form-control', 'placeholder': 'Enter Author age' }), 'gender': forms.TextInput(attrs={ 'class': 'form-control', 'placeholder': 'Enter Author Gender' }) } ) How do i def the __init__ on the AuthorFormset = modelformset_factory() this is how my models looks class Products(models.Model): title = models.CharField(max_length=255) user = models.ForeignKey(User, on_delete=models.CASCADE) class Book(models.Model): name = models.CharField(max_length=255) isbn_number = models.CharField(max_length=13) user = models.ForeignKey(User, on_delete=models.CASCADE) class Author(models.Model): name = models.CharField(max_length=255) age = models.CharField(max_length=255) gender = models.CharField(max_length=255) product = models.ForeignKey(Products, on_delete=models.CASCADE) book = models.ForeignKey(Book, related_name='authors', on_delete=models.SET_NULL, null=True) -
How to write complex filter queries on M2M models in Django?
I have an app matching candidates (Candidate) with jobs (Job). For both of these models I have an m2m relationship with a Language. A language can be required for a specific job. class JobLanguage(models.Model): language = models.ForeignKey(Language, on_delete=models.CASCADE) job = models.ForeignKey(Job, related_name='languages', on_delete=models.CASCADE) is_mandatory = models.BooleanField(default=False) And a candidate speaks a language with a certain level of "mastery". class CandidateLanguage(models.Model): language = models.ForeignKey(CandidateComponentLanguage, on_delete=models.CASCADE) candidate = models.ForeignKey(Candidate, on_delete=models.CASCADE, related_name='languages') mastery = models.PositiveSmallIntegerField(blank=True, choices=MasteryLevel.choices, null=True) Now in my matching algorithm I need at some point to filter candidates based on the languages required for a specific job. Let's say I have list of mandatory languages for a job : job_mandatory_languages_ids = [1, 2]. How would you write in the most efficient way a method that only returns candidates who master (meaning mastery=1) at least all the languages in this list ? I would like to avoid having to iterate on each candidate to remove them from the list and just use something like filter(Q()) This obviously does not work but it is an idea of what I want to achieve. def filter_on_languages(candidates, job_mandatory_languages_ids): return candidates.filter(languages__language__contains=job_mandatory_languages_ids, languages__language__mastery=1) Thank you :) -
PostgreSQL table partitioning using Djano
Using PostgreSQL database and django-postgres-extra for creating a table partitioning in Django 4.2 application. The database settings are { "default": { "ENGINE": "psqlextra.backend", "NAME": "example1", "USER": "example1", "PASSWORD": "example1", "HOST": "database", "PORT": "5432", "ATOMIC_REQUESTS": False, "AUTOCOMMIT": True, "CONN_MAX_AGE": 0, "CONN_HEALTH_CHECKS": False, "TIME_ZONE": None, } } PSQLEXTRA_PARTITIONING_MANAGER = 'app.partitioning.manager' and the model to be partitioned class TrackingData(PostgresPartitionedModel): id = models.UUIDField(default=uuid.uuid4, primary_key=True, editable=False) dynamic_url_object_id = models.IntegerField(blank=True, null=True) ip_address = models.GenericIPAddressField(blank=False) user_agent = models.TextField(null=True, blank=True) scan_time = models.DateTimeField(blank=True, default=datetime.now) created = models.DateTimeField(auto_now_add=True) modified = models.DateTimeField(auto_now=True) class Meta: verbose_name_plural = 'Tracking Data' class PartitioningMeta: method = PostgresPartitioningMethod.RANGE key = ['scan_time'] then generated migration using the command python manage.py pgmakemigrations but when running python manage.py migrate, it is giving error django.db.utils.NotSupportedError: unique constraint on the partitioned table must include all partitioning columns DETAIL: UNIQUE constraint on table "tracking_trackingdata" lacks column "scan_time" which is part of the partition key. Also tried the following update in the Meta class class Meta: verbose_name_plural = 'Tracking Data' constraints = [ models.UniqueConstraint( fields=['id', 'scan_time'], name='unique_scan_time_per_partition' ) ] -
django_plotly_dash, plotly dash url navigation not working
I am building dashboard using plotly dash. For the web framework I have used Django framework for authentication and embedding other applications. Integrated the plotly dash with the Django using the django_plotly_dash library. I tried integrating the dash app into django using the django_plotly_dash package. plotly dash navigation: from django_plotly_dash import DjangoDash app = DjangoDash('SimpleExample', external_stylesheets=[dbc.themes.SOLAR, dbc.themes.SPACELAB, dbc.themes.BOOTSTRAP]) profile_menu = dmc.Menu( [ dmc.MenuTarget(dmc.Avatar("BR", color="blue",radius="xl",id="user_profile_dropdown")), dmc.MenuDropdown( [ dmc.MenuItem( "Profile", href="/my-profile", # target="_blank", icon=DashIconify(icon="streamline:interface-user-profile-focus-close-geometric-human-person-profile-focus-user"), ), dmc.MenuItem( "Logout", icon=DashIconify(icon="majesticons:logout-half-circle"), href='/logout', id='logout-button' ), ] ), ], trigger="hover", # position='top-end', style=right_align_style, ) app.layout = html.Div([ profile_menu ]) welcome.html <!DOCTYPE html> <html lang="en"> <head> <script src="https://cdn.plot.ly/plotly-latest.min.js"></script> </head> {% comment %} <h1>Dash Home page</h1> {% endcomment %} <body> {% load plotly_dash %} <div class="{% plotly_class name='SimpleExample' %} card" style="height: 100%; width: 100%"> {% plotly_app name='SimpleExample' ratio=0.65 %} </div> </body> </html> SimpleExample is my DjangoDash app name. Django urls: urlpatterns = \[ path('',views.home, name='home-page'), path('login',views.login_user.as_view(), name='login-url'), path('plotly_home',views.dash, name='plotly-home'), path('logout',views.logout_user, name='logout-url'), path('django_plotly_dash', include('django_plotly_dash.urls')) \] plotly_home endpoint will render the welcome.html page which shows the dash app. Output: Problem: By default it renders my dash app inside the html Iframe. Thus, any changes or URL changes won't be reflected outside that Iframe. So the plotly dash navigation links are not … -
How to implement two factor authentication over simplejwt in django?
I have implemented authentication using simple jwt and Now I want to implement 2 factor authentication. I am using react for frontend. 2-fa will be introduced only when there is change in browser/device/ip address. I store this information I have thee field in my user model last_login_location, last_login_device, last_login_browser. To get the token: class CookieTokenObtainPairView(TokenObtainPairView): def finalize_response(self, request, response, *args, **kwargs): if response.data.get('refresh'): cookie_max_age = 3600*24*24 # 14 days response.set_cookie('refresh_token',response.data['refresh'],max_age=cookie_max_age,httponly=True) del response.data['refresh'] return super().finalize_response(request,response,*args,**kwargs) serializer_class = CookieTokenObtainPairSerializer Serializer class: class CookieTokenObtainPairSerializer(TokenObtainPairSerializer): @classmethod def get_token(cls, user): token = super().get_token(user) return token def validate(self, attrs): data = super().validate(attrs) refresh = self.get_token(self.user) data['refresh'] = str(refresh) data['access'] = str(refresh.access_token) data['mail'] = self.user.mail return data I want to check for change in location/device/browser during login and apply 2-fa by sending OTP over mail. I could not find anything online. Is there any way I can implement over this ? -
Find closed Trangular lat long around a give lat long point
I have data set which contains thousands of latitude and longitude points How can I write a program in which I input a random lat long and from the date base it finds and creates a closed triangle with its closed 3 lats long and the input lat long should be inside that created tringle 1 Got input A(lat, long) 2 find the nearest point of A named B(lat, long) 3 find the second nearest point named C(lat, long) 4 Liksewise get the 3rd point named as D(lat, long) 5 create a triangle with B, C, and D points and make sure point A should be inside the triangle area, if point A is outside the area then there is no sense of that triangle as an output show me that three lat long points from the DATABASE -
How do I run a Django project database with phpMyAdmin and MAMP?
I'm new to both Django and MySQL (I am more used to Node and Mongo). I want to write my project's backend with Django, but I need to work with phpMyAdmin. I managed to start a sql server from my backend django test app, but it seems to be non-related to my MAMP-phpMyAdmin settings. I tried to run MAMP and phpMyAdmin and create my db on phpMyAdmin then use my Django app settings to relate to my phpMyAdmin test db but it didn't work so my guess is I didn't understand how to use Django settings correctly. Also I got an error saying that my mySql version should be at least 8. It is on my computer, but phpMyAdmin's version is stuck to 5.7 and I couldn't find a way to update it. Then I created and launched a mysql db from my VSCode shell and migrated Django default apps on it and it works... but it's not on phpMyAdmin >< Do you have a tutorial or could you guide me step by step to do this ? I am using the latest version of Django. -
self.assertEqual(response.status_code, 200) AssertionError: 302 != 200 in django
Here i am creating a Login api and if login is success then redirect to csv_import view I am not write in my unit test as i am new to django here is my urls.py urlpatterns = [ path('', LoginAPIView.as_view(), name='login_api'), path('register/',views.register, name="register"), path('books/details/',login_required(views.csv_import),name="csv_import"), path('logout/',views.logout,name="logout"), ] Here is my views.py class LoginAPIView(View): def get(self, request): return render(request, 'login.html') def post(self, request): email = request.POST.get('email') password = request.POST.get('password') user = authenticate(request, email=email, password=password) print("USERRR",user) if user is not None: print("USERR") login(request, user) print("CREATED") return redirect('csv_import') else: messages.info(request,'Invalid credentials..') return redirect('login_api') def csv_import(request): print("CSV IMPORT") csv_file = os.path.join('static','books.csv') with open(csv_file,'r') as f: reader = csv.DictReader(f) for row in reader: title = row['title'] author = row['author'] authors = row['authors'] isbn13 = int(row['isbn13']) isbn10 = row['isbn10'] try: price = float(row['price'].replace('$','')) except: price = None publisher = row['publisher'] pubyear = row['pubyear'] subjects = row['subjects'] try: pages = int(row['pages']) except ValueError: pages = None dimensions = row['dimensions'], x, books = BooksDetails.objects.get_or_create(title=title,author=author,authors=authors,isbn13=isbn13, isbn10=isbn10,price=price,pages=pages, publisher=publisher,pubyear=pubyear,subjects=subjects, dimensions=dimensions) books_list = BooksDetails.objects.get_queryset().order_by('-id') flag = request.POST.get('flag_value') if flag == '1': try: rows = int(request.POST.get('row','')) print("ROWS",rows) if rows is not None: books_list = books_list[:rows] else: books_list = books_list except ValueError: books_list = books_list else: books_list = books_list print("HERE") paginator = Paginator(books_list, 30) print("NEAR") … -
MultipleObjectsReturned at /rants/first-rant/ get() returned more than one Rant -- it returned 2
I'm getting the error because I have two first-rant slug's on the database. I expected this to come. I have a solution in mind to add random numbers at the end of the url. Can anyone help me implement this using the RandomCharField of https://django-extensions.readthedocs.io/en/latest/field_extensions.html. Here are my models: class Category(models.Model): title = models.CharField(max_length=50) slug = models.SlugField(max_length=50) def __str__(self): return self.title def save(self, *args, **kwargs): self.slug = slugify(self.title) super(Category, self).save(*args, **kwargs) return self.slug def get_context_data(self, **kwargs): context = super(self).get_context_data(**kwargs) context['rants'] = Rant.objects.filter('category') return class Rant(models.Model): title = models.CharField(max_length=150) slug = models.SlugField(max_length=150) categories = models.ManyToManyField( Category, related_name='rants_categories') user = models.ForeignKey(User, default='', null=True, related_name='users_rant', on_delete=models.PROTECT) created_at = models.DateTimeField(default=timezone.now) updated_at = models.DateField(auto_now=True) class Meta: verbose_name = "rant" verbose_name_plural = 'rants' def __str__(self): return self.title def save(self, *args, **kwargs): self.slug = slugify(self.title) super(Rant, self).save(*args, **kwargs) return self.slug def get_absolute_url(self): from django.urls import reverse return reverse('main:detail', kwargs={'slug': self.slug}) Here are my views: class RantListView(ListView): model = Rant template_name = 'rants/list.html' context_object_name = 'rants' class RantDetailView(DetailView): model = Rant template_name = 'rants/detail.html' def rant_category(request, slug): rants = Rant.objects.filter( categories__slug__contains=slug ) context = { "slug": slug, "rants": rants } return render(request, "rants/category_list.html", context) And finally my urls path('', RantListView.as_view(), name='list'), path('<slug:slug>/', RantDetailView.as_view(), name='detail'), path('category/<slug:slug>/', rant_category, name='categories'), My … -
'NoneType' object has no attribute 'id'
Added a form to the DetailView, I'm trying to create an entry through the form, I get an error My views I don’t even know why this problem got out, it seems that I did everything according to the dock class CardDetailView(SuccessMessageMixin, ModelFormMixin, DetailView): model = Card template_name = 'cards/detail.html' success_message = 'Ваше сообщение об ошибке получено. Мы обязательно займемся этим.' form_class = WrongCardsForm def get_success_url(self): return reverse_lazy('detail', kwargs={'pk': self.object.id}) def get_context_data(self, **kwargs): context = super(CardDetailView, self).get_context_data(**kwargs) context['form'] = self.get_form() return context def post(self, request, *args, **kwargs): self.object = self.get_object() form = self.get_form() if form.is_valid(): form = form.save(commit=False) form.author = self.request.user form.card = self.get_object() form.save() super(CardDetailView, self).form_valid(form) else: return super(CardDetailView, self).form_valid(form) My forms class WrongCardsForm(ModelForm): class Meta: model = WrongCards fields = ['mistake_in', 'error_text',] # fields = '__all__' My urls urlpatterns = [ path('', views.CardsListView.as_view(), name='index'), path('<int:pk>/', views.CardDetailView.as_view(), name='detail'), ] My models class WrongCards(models.Model): """Карточки с ошибками""" CHOICE = ((None, 'Выберите в чем ошибка'), ('a', 'терминe'), ('b', 'определение'), ('c', 'произношение')) mistake_in = models.CharField('Ошибка в', choices=CHOICE, max_length=3) card = models.ForeignKey('Card', on_delete=models.CASCADE, verbose_name='Ошибка', related_name='wrong_cards') error_text = models.TextField('Подробнее об ошибки') author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, verbose_name='Автор') def __str__(self): return self.mistake_in class Card(models.Model): """Карточки слов""" term = models.CharField('Термин', max_length=100) transcription = models.CharField('Транскрипция', max_length=100) definition = … -
Djanog Filter by field values of the reverse reference model of 1:N relationship
The Branch and Subsidy models have a 1:N relationship, In the Subsidy model, the 'related_name' of the branch field is set to 'subsidy'. I'm trying to filter the Branch query set with the 'price' field value of Subsidy, but I get the following error. Branch.objects.filter(subsidy__price__gt=0) Cannot resolve keyword 'subsidy' into field. Choices are: brand_idx, idx, is_active, name, order, province_idx, sido, sido_id As shown below, individual instances seem to have good access to the related_name called 'subsidy', but I don't know why I couldn't find the field "subsidy" when filtering the query set. Branch.objects.get(idx=1).subsidy.all() my models.py class Branch(models.Model): idx = models.AutoField(primary_key=True) name = models.CharField(max_length=128, null=True, blank=True) province_idx = models.IntegerField(default=0, null=True, blank=True) sido = models.ForeignKey("self", on_delete=models.SET_NULL, null=True, blank=True, related_name='sigungu') brand_idx = models.IntegerField(default=0, null=True, blank=True) order = models.IntegerField(default=0, null=True, blank=True) is_active = models.IntegerField(default=1, null=True, blank=True) def save(self, *args, **kwargs): if self.province_idx: self.sido_id = self.province_idx else: self.sido_id = 0 super().save(*args, **kwargs) class Meta: managed = False db_table = 'branch' class Subsidy(models.Model): idx = models.AutoField(primary_key=True) car = models.ForeignKey(Car, on_delete=models.CASCADE, blank=True, null=True, db_column='car_idx', related_name='car_subs') lineup = models.ForeignKey(Lineup, on_delete=models.CASCADE, blank=True, null=True, db_column='lineup_idx', related_name='lineup_subs') trim = models.ForeignKey(Trim, on_delete=models.CASCADE, blank=True, null=True, db_column='trim_idx', related_name='trim_subs') branch = models.ForeignKey(Branch, on_delete=models.CASCADE, default=None, null=True, blank=True, related_name='subsidy') price = models.IntegerField(default=0, blank=True, null=True) is_state = models.IntegerField(default=0, … -
How to architecture a Python Backend with constant Background Taks
i would like to design a Python Backend where i have one Task that is running the whole time logging data from several Serial ports. Also there should be other background tasks running when there are certain request and they would accedd the data from the constant background task (maybe over an db). So there are some questions: I have a little experience in Flask so i would like to use it, but i stumbled across FastAPI which has backgroundjobs already implemented. So which Framework would you recommend? For the background tasks or threads what is the best Solution? Celery? Or should i outsource the constant background task to its own standalone python app? Thanks for your help! -
Django - How to import a model from another app into another app's views
I am working in an app called 'lineup', and I have another app called 'market' that has a model called 'Inventory' which I need to import into the lineup app's views.py How can I do that? -
TypeError: unsupported type for timedelta hours component: NoneType
I am getting this error in production (heroku/postgres) but not in local(sqlite). class ModelC(models.Model): model_c_field_1 = models.ForeignKey(Venue, null = True, blank= True, on_delete=models.CASCADE) class ModelB(models.Model): model_c_field_2 = models.ForeignKey(ModelA, blank=True, null=True, on_delete=models.CASCADE) model_c_field_1= models.ForeignKey(Venue, blank=True, null=True, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True, null=True, blank=True) def function(request, userprofile_id): latest_model_object = ModelB.objects.filter(user=userprofile_id).order_by('-id')[:1] time_delta = () for ModelB in latest_model_object: time_delta = timezone.now() - modelb.created_at time_delta_rule = ModelC.objects.filter(venue=request.user.userprofile.venue) timedelta_test=timedelta() for ModelC in time_delta_rule: timedelta_test = timedelta(hours = ModelC.timeframe) print(timedelta_test) examples of print result: 0:00:00 or 1 day, 0:00:00 Giving the below error. 2023-04-14T04:26:40.379344+00:00 app[web.1]: timedelta_test = timedelta(hours = modelc.timeframe) 2023-04-14T04:26:40.379344+00:00 app[web.1]: TypeError: unsupported type for timedelta hours component: NoneType -
How to use a dictionary with annotate in django?
I have a model: class Hero(models.Model): # ... name = models.CharField(max_length=100) category = models.ForeignKey(Category, on_delete=models.CASCADE) benevolence_factor = models.PositiveSmallIntegerField( help_text="How benevolent this hero is?", default=50 ) and a dictionary: sample_dict = { 1: 'A', 2: 'B', 3: 'C' } I tried to use annotate like below: hero = Hero.objects.annotate(sample_id=Value(sample_dict[F('id)], output_field=CharField())) but there is an key error <django.db.models.expressions.Subquery object at 0xffff8d014438> I want to use value of field 'id' of Hero model as a key of sample_dict. but Subquery does not return a value. -
Email verification error in Django registration
I am creating an application using Django. The user registration page includes email verification, but I am encountering an error here. When a user registers for the application by providing their email address and password, an email verification is triggered, and a verification code URL is sent to the user's email from the Django application. However, when the user clicks on this URL, an ERR_CONNECTION_TIMED_OUT error occurs. I just mentioned the above settings in this question but still if more code is required then tell me I'll update my question with that information. Thank you -
Displaying nested dictionary data without known key names in html table using Django
Using Django 3.0.6 I am trying to display this dictionary in a html table. data = { 'Exception': { 'business': { 'Renewed': 73, 'Manual': 15, 'Automatic': 3}, 'Aviation Sector': { 'Automatic': 6, 'Renewed': 6, 'Manual': 2} } } The names of these values (for easier understanding) are: Task is 'Exception' Products are 'Business', 'Aviation Sector' Classifications are 'Renewed', 'Manual', 'Automatic' And the numbers are how many times that classification occurred for that Product. I need the table to look like the attached image WITHOUT hardcoding any of the values as the values will change every time the function pulls new data. I can modify the dict if needs be before sending to the html page. The code that creates the initial dict is set up so if a different type of 'Task' were pulled in the query it would be the main key for another set of key values so the table html code would create a second table under the first with the same format just different task name. I cannot upgrade my version of django and I cannot use template filters that are not standard with Django. Here is what the table should look like Ive tried too … -
Page not found 404 Django The current path , didn’t match
I tried to run Django for the first time and got this Request Method: GET Request URL: http://127.0.0.1:8000/hello/new Using the URLconf defined in test.urls, Django tried these URL patterns, in this order: hello/ [name='index'] hello/ [name='new'] admin/ The current path, hello/new, didn’t match any of these. hello/views.py from django.http import HttpResponse from django.shortcuts import render def index(request): return HttpResponse("hello, 1") def new(request): return HttpResponse("hello, 2") hello/urls.py from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), path('', views.new, name='new') ] urls.py in my project directory urlpatterns = [ path('hello/', include('hello.urls')), path('admin/', admin.site.urls) ] -
How to login with multiple email addresses when using django-allauth
I have a django project with the django-allauth app. I want to authenticate by username or emailA or emailB. I set ACCOUNT_AUTHENTICATION_METHOD to username_email and I confirmed that I can authenticate by username or email address. Reading the documentation, it looks like I can use ACCOUNT_MAX_EMAIL_ADDRESSES, but I don't know how to use it. the documentation django-allauth: ACCOUNT_MAX_EMAIL_ADDRESSES(=None) The maximum amount of email addresses a user can associate to his account. It is safe to change this setting for an already running project – it will not negatively affect users that already exceed the allowed amount. Note that if you set the maximum to 1, users will not be able to change their email address as they are unable to add the new address, followed by removing the old address. I am new to django and am struggling with this. Can someone provide an example? -
django - Load template and add a load spinner while Django data is loading
When I open my Django project, I want first to load body.html and then dashboard.html. dashboard.html is a heavy file as its working with python dataframes in the script tag. So first I want to display body.html and once body.html is render, add a load spinner while dashboard.html and its python Django data are loading This actual code is not showing the Highcharts data as the body Class (DashboardGraphs) does not contain the Django data so there's no data for show in body.html So, the question is how can I load first body.html AND then dashboard.html which Is inside body.html (dashboard-container). With the code I showed, that Is happening but the charts are not showing data. Thanks. # urls.py ########################################## path('dashboard_graphs', DashboardViewFinal.as_view() , name='dashboard_graphs'), path('dashboard', DashboardGraphs.as_view() , name='dashboard'), # views.py ########################################## class DashboardViewFinal(LoginRequiredMixin, TemplateView): def __init__(self): self.dashboard_view_23 = DashboardView(2023,'2023') self.year_int_2023 = 2023 self.year_str_2023 = str(2023) self.dashboard_view_22 = DashboardView(2022, '2022') self.year_int_2022 = 2022 self.year_str_2022 = str(2022) template_name = 'dashboard.html' @method_decorator(csrf_exempt) def dispatch(self, request, *args, **kwargs): return super().dispatch(request, *args, **kwargs) # ----------------------------------------------- # Conexion con HTML # ----------------------------------------------- def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['panel'] = 'Panel de administrador' context['month_total_2022'] = self.dashboard_view_22.get_graph_month_total() context['alumnos_mens_total_valor_2022'] = self.dashboard_view_22.get_graph_alumnos_mensual() context['month_total_2022'] = self.dashboard_view_22.get_graph_month_total() context['ingresos_total_2022'] = self.dashboard_view_22.get_ingresos_total()[0] context['egresos_total_2022'] … -
Django dictionary key value access
I got the below response via api to a text field, how can I access the pin and reference no.. I tried separating it but it's not looking safe I want to be able to access the pin with key "pin" Thanks in anticipation { "success":"true", "message":"E-pin was Successful", "pin":"1211ggg3322", "amount":775, "transaction_date":"29-03-2023 12:18:33 pm", "reference_no":"I11767", "status":"Successful" } -
Django: how to generate random number inside a slug field
I have a model called Product, when the user create an objects inside a Product model, I want to generate some random number inside a Product model field Slug like this: https://stackoverflow.com/questions/76010275/cryptography-python-installation-error-with-rush-airgapped-installation Take a look at this Stack Overflow question, you may see the domain name at first, and some path name called questions, and some random number at the end of the questions, I think it should look like this in django path: path('question/random_number/<slug:slug>/', views.some_views_name, name='Redirect-name') All the examples i found in the internet does not do something like this, so how can i do this in django? model: class Product(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=50) image = models.ImageField(upload_to='product-image') price = models.FloatField(max_length=11) category = models.ForeignKey(Category, on_delete=models.CASCADE) slug = models.SlugField(max_length=100, unique=True) def get_user_public_url(self): return reverse('Public-Profile', kwargs={'slug': self.user.profile.slug}) def save(self, *args, **kwargs): self.slug = slugify(self.name) super().save(*args, **kwargs) def __str__(self): return str(self.user) -
Nested Relationships in DRF Serializers
AttributeError at /api/register/ Got AttributeError when attempting to get a value for field user_profile on serializer UserRegistrationSerializer. The serializer field might be named incorrectly and not match any attribute or key on the UserProfile instance. Original exception text was: 'UserProfile' object has no attribute 'user_profile'. UserProfile model looks like this from django.db import models from django.contrib.auth.models import User # Create your models here. class UserProfile(models.Model): user = models.OneToOneField(User, models.CASCADE) date_of_birth = models.DateField() phone_number = models.CharField(max_length=20, blank=False) is_phone_verified = models.BooleanField(default=False) is_email_verified = models.BooleanField(default=False) phone_code = models.CharField(max_length=20, blank=False) email_code = models.CharField(max_length=20, blank=False) serializers.py file looks like this from django.contrib.auth.models import User from .models import UserProfile from django.core.exceptions import ValidationError from datetime import datetime from rest_framework.validators import UniqueValidator from rest_framework import serializers from django.core import validators class UserModelSerializer(serializers.ModelSerializer): first_name = serializers.CharField( required=True, max_length=50, error_messages={ 'required': 'Please enter your name.', 'max_length': 'Please enter a valid name.' } ) last_name = serializers.CharField( required=True, max_length=50, error_messages={ 'required': 'Please enter your name.', 'max_length': 'Please enter a valid name.' } ) username = serializers.CharField( required=True, max_length=30, validators=[UniqueValidator(queryset=User.objects.all())], error_messages={ 'required': 'Please enter a username.', 'max_length': 'Username should be no more than 30 characters.', 'unique': 'This username is already taken. Please choose a different one.', } ) email = serializers.EmailField( … -
Using dynamic select2 field within formsets in Django
I use django-formset-js-improved which works nicely to add, delete and reoreder my formsets. However, I would like to have a dynamic select2 formfield. I looked into different packages (i.e. django-autocomplete, django-select2), but they seem to work with forms. I was thinking of getting the form fields id, by listening on the trigger 'formAdded' and working from there. However, this seems not to be fired (see: django-formset-js-improved not firing 'formAdded' event). Any idea on how to solve this?