Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Trouble Building OpenShift from Private Git Repository
I'm using OpenShift 4.10.20 to host/build a Django project (v4) I'm running into trouble building the application. These are the errors that I get when I build: Error: ErrImagePull Failed to pull image "visibility-testing-application:latest": rpc error: code = Unknown desc = reading manifest latest in docker.io/library/visibility-testing-application: errors: denied: requested access to the resource is denied unauthorized: authentication required Error starting build: an image stream cannot be used as build output because the integrated container image registry is not configured I'm using a source secret to pull the code from my private git repository to my image. I used the 'Import from Git' wizard for this. Import from git How I can fix this? -
How to filter based on a field in the custom through model using rest serializer?
I have two models with many to many relation. The many2many table is created and linked to the parent tables by the 'through' attribute. ModelA(modles.Model): name = charfield() ModelB(models.Model): subject = charfield(default=1, choices = [1,2,3]) people = ManyToManyField(ModelA, through="MOdelAB") ModelAB(models.Model): status = integerfield() modela_id = foreignkey() modelb_id = foreignkey() ModelB_Serializer(serializers.Serializer): modela = ModelASerailizer(many=True) class Meta: model = ModelB exclude = ... fields = ... depth = 1 This returns all the A objects in the through table, but I want to filter only the ones with status=99. Is there a nice way to do that? -
Django: How to add a foreign key that references itself and also sets a field on the referenced object
Sorry for the terrible title. I'm not even sure what I'm looking for. Basically, I would like to create the following: Model comprised of Ethernet switch interfaces (ex. ge-0/0/1, po4096, etc.) Be able to connect Ethernet switch interfaces TOGETHER (so, a foreign key to its own model) This is what I currently have: class EthernetSwitchInterfaces(models.Model): """ Represents interfaces on switches (ex. ge-0/0/1, ae1001, po1001, xe-1/1/1, eth1/101, etc.) """ interface = models.CharField(max_length=32, blank=False, null=False, help_text='Interface name (ex. xe-1/1/1, eth1/101, po1001, etc.)') switch = models.ForeignKey(EthernetSwitches, to_field='id', on_delete=models.CASCADE, help_text='Switch') # Note the speed of that interface link_bandwidth_in_gbps = models.IntegerField(blank=False, null=False, help_text='Total interface bandwidth in Gbps') # Account for port channel interfaces is_port_channel = models.BooleanField(default=False, blank=False, null=False, help_text='Is this a port channel interface?') number_of_links = models.IntegerField(blank=False, null=False, default=1, help_text='Number of links (if port channel)') switch_to_switch = models.ForeignKey('self', blank=True, null=True, help_text='Switch-to-switch connection', on_delete=models.SET_NULL) def __str__(self): return "{} - {}".format(self.switch, self.interface) class Meta(object): unique_together = ('interface', 'switch',) This almost works. I create an interface, create a second interface, and set the second interface's switch_to_switch field to the original interface. This works great except the original interface has a blank switch_to_switch value. Any help would be greatly appreciated! I've been stuck on this for a week now … -
Ariadne graphql displaying Django choices in query
I have a django model with Integer Choice fields class issue_status(models.IntegerChoices): '''Status''' Open = 1 Pending = 2 Completed = 3 class Issue(models.Model): person = models.ForeignKey('Person', on_delete=models.CASCADE, blank=False, null=False) name = models.CharField(max_length=100, null=True, blank=True) status = models.IntegerField(choices=issue_status.choices, blank=True, null=True) def __str__(self): return self.name I have my graphql types and resolver defined like this from ariadne import gql type_defs = gql(""" enum Status { Open Pending Completed } type Issue { id: ID person: Person! name: String status: Status } input IssueInput { id: ID person: PersonInput! name: String status: Status } input IssueUpdate { id: ID! person: PersonInput name: String status: Status } type Query { Issues(id: ID, name:String, ): [Issue] } """) query = QueryType() @query.field("Issue") def resolve_Issue(*_, name=None, id=None,): if name: filter = Q(name__icontains=name) return Issue.objects.filter(filter) if id: filter = Q(id__exact=id) return Issue.objects.filter(filter) return Issue.objects.all() When I do a gql query I get null values in the status field: { "data": { "Issues": [ { "person": { "name": "Test1" }, "id": "1", "name": "Things", "status": null }, { "person": { "name": "Test1" }, "id": "2", "name": "Clown and clown", "status": null } ] }, "errors": [ { "message": "Enum 'Status' cannot represent value: 1", "locations": [ { "line": … -
Django Models. User - Marks
Good afternoon! I'm trying to figure out the models on the example of a training site in Django. Question: Is it possible to make a "filter" in the model so that users from the Members table with the role of "teacher" come to T_Member? Or is it not possible to do this at the model level? second question: did i define the fields correctly? :) Thanks to There is a class "Users" student = 'ST' parent = 'PA' teacher = 'TE' SCHOOL_CHOICES = [ (student, 'Student'), (parent, 'Parent'), (teacher, 'Teacher'), ] user_id = models.AutoField(verbose_name='User ID', auto_created=True, primary_key=True) username = models.CharField(verbose_name='username', max_length=255, blank=True) dob = models.DateField(verbose_name='date of birthday', blank=False, default=date.today) role = models.CharField(max_length=2, choices=SCHOOL_CHOICES, default=student ) and class Marks: class Marks(models.Model): mark_id = models.AutoField(verbose_name='User ID', auto_created=True, primary_key=True) d_of_publ = models.DateField(verbose_name='Дата оценивания', blank=False, default=date.today) subject = models.ManyToManyField(Subject, verbose_name='Subjects') T_Member = models.ManyToManyField(Members, verbose_name='Teachers') S_Member = models.ManyToManyField(Members, verbose_name='Students') mark = models.IntegerField(verbose_name='Marks', blank=False, default=2) -
django template render pagination
I want to set dynamic pagination to my template but the problem is that when i change the page, the pagination will reset view is: def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['paginate'] = [1, 2, 4] context['CurrentPaginate'] = self.request.GET.get('paginate') return context template is : <select name="paginate" class="form-select form-select-sm" aria-label=".form-select-sm example" onchange="if(this.value != 0) { this.form.submit()};"> {% for option in paginate %} {% if option != currnetPaginate %} <option selected="selected" value={{ option }}> Pagination{{ option }} </option> {% elif option == currnetPaginate %} <option selected="selected" value={{ option }}>Pagination {{ option }} </option> {% endif %} {% endfor %} </select> the IF statement won't work correctly. -
how do i convert this function based view to a class based view?
i recently created a category system but the problem is that when ever i go to another page that isn't the home page, all the categories go away because i haven't referenced them. i found that by adding def get_context_data(self, *args, **kwargs): cat_menu = Category.objects.all() context = super(CategoryView, self).get_context_data(*args, **kwargs) context["cat_menu"] = cat_menu return context below each view then it would allow the categories in all my pages. but because for a few views i used function based views and since i can't for example do: def CategoryView(request, cats): category_posts = Post.objects.filter(category=cats) return render(request, 'blog/categories.html', {'cats':cats, ' category_posts':category_posts}) def get_context_data(self, *args, **kwargs): cat_menu = Category.objects.all() context = super(CategoryView, self).get_context_data(*args, **kwargs) context["cat_menu"] = cat_menu return context i need to convert def CategoryView(request, cats): category_posts = Post.objects.filter(category=cats) return render(request, 'blog/categories.html', {'cats':cats, ' category_posts':category_posts}) to a class based view. i first tried doing this: class CategoryView(ListView): template_name = 'blog/categories.html' model = Post context_object_name = "category_posts" def get_queryset(self): return super().get_queryset().filter(category=self.kwargs.get('cats')) def get_context_data(self, *args, **kwargs): cat_menu = Category.objects.all() context = super(CategoryView, self).get_context_data(*args, **kwargs) context["cat_menu"] = cat_menu return context but when i rendered out the template i lost the {{cats}} - categories any help would be appreciated -
How to use Django Simple Pagination?
Hello bros Im using Django Simple Pagination from github. Everything is quite simple but there are two issues. 1: Simple Pagination is not showing current links. 2: It is not using link's template (Which I want to be used to edit pagination). Module name: simple_pagination models.py #!/usr/bin/python # -*- coding: utf-8 -*- """Ephemeral models used to represent a page and a list of pages.""" from __future__ import unicode_literals from django.template import loader from django.utils.encoding import iri_to_uri from simple_pagination import settings from simple_pagination import utils # Page templates cache. _template_cache = {} class EndlessPage(utils.UnicodeMixin): """A page link representation. Interesting attributes: - *self.number*: the page number; - *self.label*: the label of the link (usually the page number as string); - *self.url*: the url of the page (strting with "?"); - *self.path*: the path of the page; - *self.is_current*: return True if page is the current page displayed; - *self.is_first*: return True if page is the first page; - *self.is_last*: return True if page is the last page. """ def __init__( self, request, number, current_number, *args, **kwargs ): total_number = kwargs.get('total_number') querystring_key = kwargs.get('querystring_key', 'page') label = kwargs.get('label', None) default_number = kwargs.get('default_number', 1) override_path = kwargs.get('override_path', None) self._request = request self.number = number … -
ConfingExeption while Sending a job signal to kubernetes inside django to activate a pod
I have made a C++ program and set it up with docker/kubernetes inside google cloud using Github actions. I have 3 active pods inside my cluster and my c++ program basically takes a json as an input from a django application and gives an output. My goal right now is to trigger a pod inside django. Right now i wrote some code using the official kubernetes django package but I'm getting an error: Here is what i wrote up until now: from kubernetes import client, config, utils import kubernetes.client from kubernetes.client.rest import ApiException # Set logging logging.basicConfig(stream=sys.stdout, level=logging.INFO) # Setup K8 configs # config.load_incluster_config("./kube-config.yaml") config.load_kube_config("./kube-config.yaml") configuration = kubernetes.client.Configuration() api_instance = kubernetes.client.BatchV1Api(kubernetes.client.ApiClient(configuration)) I don't know much about the kube-config.yaml file so i borrowed a code from the internet: apiVersion: batch/v1beta1 kind: CronJob metadata: name: test spec: schedule: "*/5 * * * *" jobTemplate: spec: template: spec: containers: - name: test image: test:v5 env: imagePullPolicy: IfNotPresent command: ['./CppProgram'] args: ['project.json'] restartPolicy: OnFailure But when i call this via a view i get this error on the console: kubernetes.config.config_exception.ConfigException: Invalid kube-config file. No configuration found. Is my load_kube_config call at fault or is my yaml file wrong? If so is there an example … -
django - BaseSerializer.save() takes 1 positional argument but 2 were given
The following error occurred while implementing signup.. When it is a get request, the value of the field appears well, but when i send a post request, the following error occurs. [ BaseSerializer.save() takes 1 positional argument but 2 were given ] What should I do? Help me please.. ㅠ_ㅠ <serializers.py> from .models import User from dj_rest_auth.registration.serializers import RegisterSerializer from rest_framework import serializers class SignUpSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['email', 'password', 'realname', 'nickname', 'address', 'phone', 'height', 'weight'] def save(self, request): user = super().save(request) realname = self.data.get('realname') nickname = self.data.get('nickname') address = self.data.get('nickname') phone = self.data.get('phone') height = self.data.get('height') weight = self.data.get('weight') if realname: user.realname = realname if nickname: user.nickname = nickname if address: user.address = address if phone: user.phone = phone if height: user.height = height if weight: user.weight = weight user.save() return user <models.py> class User(AbstractUser): username = None email = models.EmailField(max_length=255, unique=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = UserManager() realname = models.CharField(max_length=50, blank=True) nickname = models.CharField(max_length=50, blank=True) address = models.CharField(max_length=200, blank=True) phone = models.CharField(max_length=100, blank=True) height = models.DecimalField(max_digits=4, decimal_places=1, default=0) weight = models.DecimalField(max_digits=4, decimal_places=1, default=0) def __str__(self): return self.email <setting.py> REST_AUTH_REGISTER_SERIALIZERS = { 'REGISTER_SERIALIZER': 'accounts.serializers.SignUpSerializer' } -
Django : Adding pagination and searchbar to filter the listing of a FormView (ClassView)
I use a FormView from the ClassView available in Django to upload and display listing of files. In the FormView there is no get_queryset and pagination methods to list easily data. So I used the te get_context_data and the get method combined with a pagination method that I wrote to do my file table listing.This part works I want to add a searchbar to filter the results and change the pagination too. However I do not manage to add this fonctionnality to my code. I think that the code is not well structured between the "get_context_data", "get" and "pagination" and I do not see how to change it. I think the problem is more with how I use the "get_context_data" and "get". Can anyone help me ? There is no interest to look to the post method of the code, it is to upload the files. views.py class DocumentUpload(FormView) : model = Documents template_name = 'upload/upload.html' form_class = FilesForm def pagination(self, page_number, list_files): paginator = Paginator(list_files, 10) try: list_files_page = paginator.page(page_number) except PageNotAnInteger: list_files_page = paginator.page(1) except EmptyPage: list_files_page = paginator.page(paginator.num_pages) return list_files_page def get_context_data(self, *args, **kwargs): # Call the base implementation first to get a context context = super(DocumentUpload, … -
python manage.py runserver won't run after git cloning my repo
Please I am having issues running python manage.py runserver after git cloning my project repo, creating a virtual environment and installing all required requirements. Please response is needed urgently (.venv) PS C:\Users\ASUS\desktop\project\file-comp-107> python manage.py runserver Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\ASUS\desktop\project\file-comp-107.venv\lib\site-packages\django\db\backends\base\base.py", line 244, in ensure_connection self.connect() File "C:\Users\ASUS\desktop\project\file-comp-107.venv\lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) File "C:\Users\ASUS\desktop\project\file-comp-107.venv\lib\site-packages\django\db\backends\base\base.py", line 225, in connect self.connection = self.get_new_connection(conn_params) File "C:\Users\ASUS\desktop\project\file-comp-107.venv\lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) File "C:\Users\ASUS\desktop\project\file-comp-107.venv\lib\site-packages\django\db\backends\postgresql\base.py", line 203, in get_new_connection connection = Database.connect(**conn_params) File "C:\Users\ASUS\desktop\project\file-comp-107.venv\lib\site-packages\psycopg2_init_.py", line 122, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) psycopg2.OperationalError: connection to server at "localhost" (::1), port 5432 failed: fe_sendauth: no password supplied The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.1264.0_x64__qbz5n2kfra8p0\lib\threading.py", line 1009, in _bootstrap_inner self.run() File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.1264.0_x64__qbz5n2kfra8p0\lib\threading.py", line 946, in run self._target(*self._args, **self._kwargs) File "C:\Users\ASUS\desktop\project\file-comp-107.venv\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\ASUS\desktop\project\file-comp-107.venv\lib\site-packages\django\core\management\commands\runserver.py", line 137, in inner_run self.check_migrations() File "C:\Users\ASUS\desktop\project\file-comp-107.venv\lib\site-packages\django\core\management\base.py", line 576, in check_migrations executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS]) File "C:\Users\ASUS\desktop\project\file-comp-107.venv\lib\site-packages\django\db\migrations\executor.py", line 18, in init self.loader = MigrationLoader(self.connection) File "C:\Users\ASUS\desktop\project\file-comp-107.venv\lib\site-packages\django\db\migrations\loader.py", line 58, in init … -
Foreign key relationship with boolean values
I'm working on a feature. I've three different car types (Sedan, Hatchback, SUV): Category(models.Model): id- name- image- I've 6 features in total. Feature(models.Model): id- name- detail- image- Out of 6, 4 features are their in every car. The second car category has 5 and the third has all the 6 features. Here where I'm getting stuck: I've to send all the 6 features in all the categories to the frontend so that if someone clicks on the first category, they should be able to show them all 6 with 2 non-available feature strike down or disabled or something. So basically there should be some boolean value which shows that this feature in this category is True or False. How can I design the tables? -
How can I build a simple website where the user/visitor gives some input via drop down menus and based on that input something specific is displayed?
I want to build a simple web app that has at least a few drop down menus all populated with lists of items. The user selects all the according to his/her preferences and then based on that selection something specific is displayed. Each combination of selections will have to be mapped to a certain result that will be displayed to the user after submitting the selections. I tried googling, but I did not find what I was looking for. I would be grateful if the answer/solution came in Python/Django, but I would welcome it in any other language/framework as long as the end result is the web app I am looking for. Cheers. -
How Do I Make Python Django HTMLCalendar Clickable Based On The Date That Is Clicked?
I'm using a tutorial I found online...and it's working. I'm trying to enhance it so that if the user clicks on the cell of the calendar I pass it a URL to go to another view. Conceptually I get it, but I can't seem to work out the specifics.... Here's my utils.py class Calendar(HTMLCalendar): def __init__(self, year=None, month=None, dropdown=None): self.dropdown = dropdown self.year = year self.month = month super(Calendar, self).__init__() # formats a day as a td # filter events by day def formatday(self, day, requests): requests_per_day = requests.filter(Q(start_time__day=day,end_time__day=day) ).order_by('start_time').distinct() d = '' for request in requests_per_day: d += f'<li> {request.get_html_url} </li>' if day != 0: return f"<td><span class='date'>{day}</span><ul> {d} </ul></td>" return '<td></td>' # formats a week as a tr def formatweek(self, theweek, requests): week = '' for d, weekday in theweek: week += self.formatday(d, requests) return f'<tr> {week} </tr>' # formats a month as a table # filter events by year and month def formatmonth(self, withyear=True): requests = OncallRequest.objects.filter(Q(oncall_calendar=self.dropdown)).distinct() cal = f'<table border="0" cellpadding="0" cellspacing="0" class="calendar">\n' cal += f'{self.formatmonthname(self.year, self.month, withyear=withyear)}\n' cal += f'{self.formatweekheader()}\n' for week in self.monthdays2calendar(self.year, self.month): cal += f'{self.formatweek(week, requests)}\n' cal += f'</table>\n' cal += f'<h1 class="title107">Oncall Schedule For {self.formatmonthname(self.year, self.month, withyear=withyear)}</h1>\n' return cal Here's the … -
converting dynamic HTML file to PDF
i have question, i try resolve solution more then one week. Now in my project i have dynamic HTML file (receipt), and when client payd for service i send him email, and in this email i put this HTML file. service_email.send_email( RECEIPT, { "address": client_adddress, "nett": nett, "gross": gross, "tax": tax, "tax_rate": tax_rate, }, [client.email], ) And now i need add pdf file to email, and thats no problem, problem in putting data in HTML file and from this file generate PDF. I tryed to use fpdf, pyqt, jinja and other libary, but still noting. -
Django UpdateView - Prevent URL tampering
I have a Contact model. The url.py has: path('contact/update/<int:id>/', views.ContactUpdate.as_view(), name='contact-update'), The UpdateView looks like: class ContactUpdate(UpdateView): model = Contacts form_class = ContactForm template_name = 'contact_detail.html' success_url = reverse_lazy('test:contacts-list') The pk is not included in the fields of the form. class ContactForm(ModelForm): class Meta: model = Contacts fields = ['name', 'company', 'addr1', 'addr2', 'city', 'state', 'zip'] But the pk is sent in the url. The form works in the template and contacts are stored and edited with the above view without issue. However, if a malicious (logged in user) changes the post url to reflect a different pk, Django will happily edit the hacked record. ORIGINAL GET URL: http://test.com/test/contact/update/2/ HACKED POST URL: http://test.com/test/contact/update/3/ Django will update the record with a pk of 3. The session and csrf tokens are all valid, so nothing flags as an error. Is there a way to prevent this besides using a session variable with a uuid that is sent into the form and used on return to get the original pk? Thanks for any advice. -
Django on Google App Engine connection to Cloud SQL, cannot connect
I have a Django app deployed on App Engine. Inside the same project, I've set up a MySQL instance set up with a Private IP. Side Note: I've been using this DB to do local development, and can connect to it via my laptop as I whitelisted the IP address, so I know I can at least connect to it. Per the instructions on the instruction guide found here: https://cloud.google.com/sql/docs/mysql/connect-app-engine-standard I have done the following: Set up my Cloud SQL Instance with a Private IP Set up a Serverless VPC Access connector (this is where I think I'm going wrong) with IP Address Range 10.8.0.0/20 Set my DATABASES dictionary in settings.py to try to connect to each of the following IP addresses with all failing: The private IP (x.x.x.x) listed on the SQL server page, on port 3306. 127.0.0.1 as per the instructions on the google web page. I tried 10.174.0.0 because that's listed as the "Internal IP Range" in the VPC networks area. And finally, out of desperation, 10.8.0.0, because that's the example given as the textbox hint. In the Cloud SQL GUI, I set the "Network" to Default. All failed, but in different ways. The Private IP at … -
Django generic DetailView I want to create and display multiple objects, but what should I do?
model.py class Kcal(models.Model): height = models.PositiveIntegerField(default='', null=False , verbose_name='height') weight = models.PositiveIntegerField(default='', null=False, verbose_name='weight') age = models.PositiveIntegerField(default='', null=False, verbose_name='age') sex = models.CharField(max_length=200, choices=SEX_CHOICE, null=False, verbose_name='sex') view.py class KcalDetailView(DetailView): model = User context_object_name = 'target_kcal' template_name = 'kcalculatorapp/detail.html' def get_context_data(self, **kwargs): try: kcl = self.request.user.kcal men_kcal = round((66 + (13.8 * kcl.weight + (5 * kcl.height)) - (6.8 * kcl.age)) * (kcl.actv)) women_kcal = round((655 + (9.6 * kcl.weight + (1.8 * kcl.height)) - (4.7 * kcl.age)) * (kcl.actv)) if kcl.goal == 'diet': if kcl.sex == 'male': bmr = men_kcal - 500 else: bmr = women_kcal - 500 return bmr else: if kcl.sex == 'male': bmr = men_kcal + 500 else: bmr = women_kcal + 500 return bmr if kcl: context = super().get_context_data(**kwargs) context['bmr'] = bmr context['carb_kcal'] = bmr * (2/3) context['prt_kcal'] = bmr * (1/6) context['fat_kcal'] = bmr - (carb_kcal + prt_kcal) return context except: HttpResponseRedirect(reverse('kcalculatorapp:create')) with the kcal model. Making body information an object. In generic view detail view I used def get_context_date() method. After importing the model object and processing it to templates {{ carb_kcal }} {{ prt_kcal }} I want to put it like this. What should I do? -
Accessing django database from another python script
I have a Django project, and I need to access the information inside that database(model). This is my directory hierarchy- I've seen a lot of questions on this subject, but everything I tried didn't work. For example- import models # gives me this error- django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. If I try to do this I get another error- import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "OrAvivi.OrAvivi.settings") import models # gives me this error- django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. and it just continues... I'm quite a newbie, spent most of my day on this so I would appreciate some help! -
Costum schema generator drf-yasg to support nested serializers
I built nested serializer where ModelSerializer include another serializer as field. Everything works well but in swagger docs in example body parameters I don't see openning_time field. What can I change to obtain openning_time field in docs? I tried with swagger_auto_schema but got error: drf_yasg.errors.SwaggerGenerationError: specify the body parameter as a Schema or Serializer in request_body serializers.py class WarehouseSerializer(serializers.ModelSerializer): openning_time = OpenningTimeSerializer(many=True, read_only=True) class Meta: model = Warehouse fields = ['pk', 'name', 'action_available', 'openning_time', 'workers'] views.py class WarehouseApi(mixins.RetrieveModelMixin, mixins.UpdateModelMixin, mixins.ListModelMixin, viewsets.GenericViewSet): queryset = Warehouse.objects.all() serializer_class = WarehouseSerializer permission_classes = [IsAuthenticated, ] warehouse_param_config = openapi.Parameter( 'openning_time', in_=openapi.IN_BODY, description='Description', type=openapi.TYPE_OBJECT) @swagger_auto_schema(manual_parameters=[warehouse_param_config]) def update(self, request, *args, **kwargs): return super().update(request, *args, **kwargs) There is screen from swagger docs and i wanted add information about openning_time which is represented as list of dictionaries as below: [ { "weekday": 4, "from_hour": "12:22:00", "to_hour": "13:13:00" }, { "weekday": 5, "from_hour": "16:00:00", "to_hour": "23:00:00" } ] -
what is the best way to use prefetch_related with multitable inheritance and multiple types of discounts for an ecommerce website
i have the following models: class Theme(models.Model): name = mode.charfield() class Category(mdoesl): name = models.charfield() class Product(models.Model): title = models.charfield() class Course(Product): .......... class LtProduct(Product): category = models.ForeignKey(Category) theme = models.ForeginKey(Theme) class CouponCode(models.Model): code = models.Charfield(unique = True) ......... class ProductDiscount(models.Model): product = models.ForeignKey(Product) codes = models.ManyToManyField(CouponCode) class CategoryDiscount(models.Model): category = models.ForeignKey(Category) class ThemeDiscount(models.Model): theme = models.ForeignKey(Theme) class UserCoupon(models.Model): user = models.OneToOneField(User) code = models.ForeignKey(CouonCode) is_used = models.BooleanField(default = False) what I want to do here is first to get the user code and check if that code can be applied to add this product to the user cart, and also fetch the category and theme related to this product and with their discounts and codes too, here's what I was trying to solve this product = Product.objects.prefetch_related('course', 'lvproduct__category__categorydiscount_set__codes', 'lvproduct__theme__theme_discount_set__codes','productdiscount_set__codes').get(id = product_id) and then I would fetch the user redeemed code by this: user_code = UserCoupon.objects.filter(user = user, is_used = False) and then I check by each type of discount to check if the codes belong to these discounts codes = product.productdiscount_set.codes.all() for code in codes: if code == user_code: #do the necessary calculation user_code.is_used = True if the code is not in the product discount codes then I will … -
Oscar Django many categories slow down the site
I've created a site ( Clothing Shop ) which has 426 categories . The site is really slow due to having many categories . ( Even when creating a child category it is saved in Category at the database as seen from shell (oscar category creation)) . I've tried many methods to optimize the queries that are made when a page is loading but still too slow . I've followed the django doc for optimized categories (https://docs.djangoproject.com/en/4.0/topics/db/optimization/) . I've also tried to cache some queries . Moreover the fact that I think the slowness comes from categories is because I've seen that the category queries take the most time through django toolbar .Any help would be great ! . -
django import-export plugin return only 1 row in excel
I have a formset in my DetailView where I am allowing a user to put a number of units in the form and after submission it returns an excel file with exported data. My problem is that I get only 1 row in my exported Excel file and I have no idea why. Could you please take a look at my code and let me know where is the issue? I believe that something is wrong with my loop in the form_valid method but I am not sure what it is. views.py class ProductDetailView(FormMixin, DetailView): template_name = 'hubble/ProductDetailView.html' model = Product form_class = CalculatorFormsetProduct def get_context_data(self, **kwargs): context = super(ProductDetailView, self).get_context_data(**kwargs) get_components = CostCalculator.objects.filter(related_product__slug=self.kwargs['slug']) form = CalculatorFormsetProduct(initial=[{ 'author': self.request.user.email, 'related_product': x.related_product, 'related_component': x.id, 'created': timezone.now, 'number_of_units': 0 } for x in get_components]) context['ce_form'] = form return context def get_success_url(self): return reverse('product', kwargs={'slug': self.kwargs['slug']}) def post(self, request, *args, **kwargs): form = self.get_form() self.object = self.get_object() if form.is_valid(): return self.form_valid(form) else: return self.form_invalid(form) def form_valid(self, form): for f in form: related_product = f.cleaned_data.get('related_product') created = f.cleaned_data.get('created') f.save() qs = CERequest.objects.filter(related_product__title=related_product, author=self.request.user, created=created) dataset = CERequestResource().export(qs) response = HttpResponse(dataset.xlsx, content_type="xlsx") response['Content-Disposition'] = 'attachment; filename=cost_estimation.xlsx' return response resources.py class CERequestResource(resources.ModelResource): related_component__service = Field(attribute='related_component__service', column_name='Service') … -
Django : transform a function download view into a class view
I am trying to rewrite a function view that download files into a classview. However I do not see how I can do it, since I have an argument from the url. Then I do not which on of the class view I should be using. Here is my function view that is working : def download(request, fileUUID): file = UploadFilesBlobStorage.objects.get(Uuid=fileUUID) filename = file.Filename file_type, _ = mimetypes.guess_type(filename) url = file.Url blob_name = url.split("/")[-1] blob_content = download_from_blob(blob_name) if blob_content: response = HttpResponse(blob_content.readall(), content_type=file_type) response['Content-Disposition'] = f'attachment; filename={filename}' messages.success(request, f"{filename} was successfully downloaded") return response return Http404