Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Reverse for 'printReports' with arguments '('',)' not found. 1 pattern(s) tried
My app currently runs through settings that are saved to the database in-order to print financial documents. I am using the pk variable to fetch the correct forms etc. However now when I am trying to redirect to the pk for 'printReports' in my project. It returns the above error. I am trying to figure out where I have mapped this wrongly , but I can't seem to find any errors Please see the below code: Views.py: def printReports(request , reports_pk): pkForm = get_object_or_404(SettingsClass , pk=reports_pk) form= SettingsClass(instance=pkForm) ### Printing Trial Balance PDF response = HttpResponse(content_type= 'application/pdf') response['Content-Disposition']= 'attachment; filename=TrialBalance' + \ str(datetime.now()) + '.pdf' response['Content-Transfer-Encoding'] = 'binary' content = {"arr_trbYTD":arr_trbYTD , 'xCreditTotal':xCreditTotal , 'xDebitTotal':xDebitTotal , 'complexName':complexName , 'openingBalances': openingBalances ,'printZero':printZero} html_string=render_to_string('main/pdf-trialbalance.html' , content) html=HTML(string=html_string) result=html.write_pdf() with tempfile.NamedTemporaryFile(delete=True) as output: output.write(result) output.flush() output.seek(0) response.write(output.read()) return response else: printTrialBalance = False return render(request , 'main/printReports.html') URLS.PY: #Reports path('reportsHome' , views.reportsHome, name='reportsHome'), path('accConnect/printReports/<int:reports_pk>' , views.printReports , name='printReports') reportsHome.html: {% extends "main/base.html"%} {% block content%} <h1 style=" text-align: center">Reports</h1> <hr> <br> <div class="list-group"> <a href="#" class='list-group-item active'>Print Single Complex's</a> {% for x in model %} <a href="{% url 'printReports' reports.pk %}" class="list-group-item list-group-item-action" >{{ x.Complex }} Reports</a> {% endfor %} </div> {% endblock … -
Why isn't my .Dockerignore file not ignoring files?
When I build the container and I check the files that should have been ignored, most of them haven't been ignored. This is my folder structure. Root/ data/ project/ __pycache__/ media/ static/ app/ __pycache__/ migrations/ templates/ .dockerignore .gitignore .env docker-compose.yml Dockerfile requirements.txt manage.py Let's say i want to ignore the __pycache__ & data(data will be created with the docker-compose up command, when creating the container) folders and the .gitignore & .env files. I will ignore these with the next .dockerignore file .git .gitignore .docker */__pycache__/ **/__pycache__/ .env/ .venv/ venv/ data/ The final result is that only the git & .env files have been ignored. The data folder hasn't been ignored but it's not accesible from the container. And the __pycache__ folders haven't been ignored either. Here are the docker files. docker-compose.yml version: "3.8" services: app: build: . volumes: - .:/django-app ports: - 8000:8000 command: /bin/bash -c "sleep 7; python manage.py migrate; python manage.py runserver 0.0.0.0:8000" container_name: app-container depends_on: - db db: image: postgres volumes: - ./data:/var/lib/postgresql/data environment: - POSTGRES_DB=${DB_NAME} - POSTGRES_USER=${DB_USER} - POSTGRES_PASSWORD=${DB_PASSWORD} container_name: postgres_db_container Dockerfile FROM python:3.9-slim-buster ENV PYTHONUNBUFFERED=1 WORKDIR /django-app EXPOSE 8000 COPY requirements.txt requirements.txt RUN apt-get update \ && adduser --disabled-password --no-create-home userapp \ && apt-get -y … -
Serializers.validated_data fields got changed with source value in DRF
I am trying to create an api, where user can create programs and add rules to them. Rules has to be executed in order of priority. I am using Django rest framework to achieve this and I am trying to achieve this using Serializer without using ModelSerializer. Provide your solution using serializers.Serializer class One program can have many rules and one rule can be in many programs. So, I am using many_to_many relationship and also I want the user to change the order of rules in a program, to achieve this I am using a through table called Priority, where I keep track of relationship between a rule and a program using priority field models.py class Program(models.Model): name = models.CharField(max_length=32) description = models.TextField(blank=True) rules = models.ManyToManyField(Rule, through='Priority') class Rule(models.Model): name = models.CharField(max_length=20) description = models.TextField(blank=True) rule = models.CharField(max_length=256) class Priority(models.Model): program = models.ForeignKey(Program, on_delete=models.CASCADE) rule = models.ForeignKey(Rule, on_delete=models.CASCADE) priority = models.PositiveIntegerField() def save(self, *args, **kwargs): super(Priority, self).save(*args, **kwargs) serializers.py class RuleSerializer(serializers.Serializer): name = serializers.CharField(max_length=20) description = serializers.CharField(allow_blank=True) rule = serializers.CharField(max_length=256) def create(self, validated_data): return Rule.objects.create(**validated_data) def update(self, instance, validated_data): instance.name = validated_data.get('name', instance.name) instance.description = validated_data.get('description', instance.description) instance.rule = validated_data.get('rule', instance.rule) instance.save() return instance class PrioritySerializer(serializers.Serializer): rule_id = serializers.IntegerField(source='rule.id') rule_name … -
Django Model's DateTimeField is taking UTC even when timezone is Asia/Calcutta everywhere. I can't set USE_TZ = False
My Django Server is storing time in UTC format. I want them in IST. But the problem is I can't set USE_TZ = False. Otherwise, it throws more errors and warnings. Pls, help me!!! TIME_ZONE = 'Asia/Calcutta' USE_I18N = True USE_L10N = True USE_TZ = True -
How to remove results with same value with django ORM?
I have a query that returns data that will be displayed in the browser as a line chart. Depending on the period chosen, this can represent a rather huge number of results (~25K max). Most of the time these values do not change, on average on 25 000 results I have about 8000 different values. I think it would be a real optimization if I only return these 8000 values instead of the 25 0000. My Model: class TechnicalData(models.Model): name = models.CharField(_('Name'), max_length=80) value = models.CharField(_('Value'), max_length=80) value_type = models.CharField(_('Value type'), max_length=20) date_time = models.DateTimeField(_("timestamp")) machine = models.ForeignKey("machine.Machine", verbose_name = _("machine"), related_name="technical_data_machine", on_delete=models.CASCADE) class Meta: verbose_name = _("TechnicalData") verbose_name_plural = _("TechnicalDatas") ordering = ["-date_time"] def __str__(self): return self.name If the "value" field does not change during a given period (date_time), I would like to remove the "duplicate/same" values. Today I have this view: class TechnicalDataViewSet(viewsets.ViewSet): """ A simple ViewSet for listing or retrieving technical data. """ permission_classes = [permissions.IsAuthenticated] pagination_class = LargeResultsSetPagination def list(self, request): id_machine = self.request.query_params.get('id_machine') name = self.request.query_params.get('name') only_last = self.request.query_params.get('only_last') names = self.request.query_params.get('name__in') date_start = self.request.query_params.get('date_start') date_end = self.request.query_params.get('date_end') queryset = TechnicalData.objects.all() if id_machine: queryset = queryset.filter(machine__id=id_machine) if name: queryset = queryset.filter(name=name) if names: names = … -
In this how i want to multiply quantity and unit_price to show in total?
class orderdetails(models.Model): product = models.CharField(max_length=100,default='') quantity = models.IntegerField() unit_price = models.IntegerField() total= () -
How to disiable BIGGERkeysses into an authentication application builded in django?
I want only to create users with lowercases into an authentication app login page -
Save Form after successful stripe Payment
I have a model form that the user fills. This form contains a file field as well. After filling in the form once the user presses the submit button, the form is saved to the database using POST after getting verified. What I would like to do is once the user clicks the submit button, they should be taken to another page to make a payment. The payment page will be created using Stripe Payment Intent and not Stripe Checkout. Once they have successfully paid I would like to save the data that the user have filled in the form.I have created the Stripe Payment page and I can see payments being made on the Stripe dashboard but I would like to save the data that the user has filled in the form after successful payment. How do I go about doing this in Python3 , Django? -
Django sales campaign model with list of foreign keys that can only appear in one sales campaign?
I want to create a sales campaign which stores a list of books (Items). But the book should only be applied to one sales campaign — ie. it should not be able to appear in two campaigns. I have the following model: class Campaign(models.Model): campaign_name = models.CharField(max_length=50, null=False, blank=False, default='Special Offer') included_items = models.ManyToManyField(Item, blank=True) active = models.BooleanField(default=True) fixed_price = models.DecimalField(max_digits=6, blank=True, null=True, decimal_places=2) But I think the included_items field might be of the wrong field type. From reading other questions and the Django manual, I think I may be approaching this back to front. Perhaps I should be tackling this from the Item model instead? (Shown below for reference) class Item(models.Model): sku = models.CharField( max_length=10, null=True, blank=True, default=create_new_sku) title = models.CharField(max_length=254) genre = models.ManyToManyField('Genre', blank=True) author = models.ManyToManyField('Author', blank=True) description = models.TextField() age_range = models.ManyToManyField( 'Age_range') image_url = models.URLField(max_length=1024, null=True, blank=True) image = models.ImageField(null=True, blank=True) price = models.DecimalField(max_digits=6, decimal_places=2, default=0.00) discount = models.DecimalField(max_digits=2, decimal_places=0, default=0) set_sale_price = models.DecimalField(max_digits=6, decimal_places=2, default=0.00) original_sale_price = models.DecimalField(max_digits=6, decimal_places=2, null=True, blank=True) final_price = models.DecimalField(max_digits=6, decimal_places=2, null=True, blank=False, editable=False) -
Django how to pass arguments from views.py to websocket "on_open" function in another file
In my Django in tasks.py file I am using websocket connection - on_open_socket function: def on_open__socket(ws): print("Socket connected") My connection: ws.on_open = on_open_socket How can I pass additional arguments dynamically to "on_open_socket" from views.py, like following: def on_open__socket(ws, {new arguments -> name, date}): print("Socket connected") stream = { "name" = name "date" = date } I tried using partial, but I cannot figure out how to do this from views.py. -
Adding the first product in cart returns intergrity error
In the views.py logic, as you can see that i have printed three characters x, y and z for the outer else block which create a new order with the first product being added. However if the cart is empty and try to add a product , it throws an error saying: null value in column "order_id" of relation "onlineshopping_order" violates not-null constraint DETAIL: Failing row contains (2021-09-23 07:49:55.861471+00, 2021-09-23 07:49:55.861471+00, f, 2, null, null, null, null). views.py: @login_required def add_to_cart(request, slug): item = get_object_or_404(AffProduct, slug=slug) order_item, created = OrderItem.objects.get_or_create( item=item, user=request.user, ordered=False ) order = Order.objects.filter(user=request.user, ordered=False).first() if order: # check if the order item is in the order if order.items.filter(item__slug=item.slug).exists(): order_item.quantity += 1 order_item.save() messages.info(request, "This item quantity was updated.") else: order.items.add(order_item) messages.info(request, "This item was added to your cart.") else: # ordered_date = timezone.now() print('x') order = Order.objects.create(user=request.user) print('y') order.items.add(order_item) print('z') messages.info(request, "This item was added to your cart.") return render(request, 'cart.html', {'order_item': order_item, 'object': order}) -
Reverse for 'printReports' with arguments '('',)' not found. 1 pattern(s) tried
My app currently runs through settings that are saved to the database in-order to print financial documents. I am using the pk variable to fetch the correct forms etc. However now when I am trying to redirect to the pk for 'printReports' in my project. It returns the above error. I am trying to figure out where I have mapped this wrongly , but I can't seem to find any errors Please see the below code: Views.py: def printReports(request , reports_pk): pkForm = get_object_or_404(SettingsClass , pk=reports_pk) form= SettingsClass(instance=pkForm) complexName = form.Complex printTrialBalance = True includeOpeningBalance = '' useMainAccounts = 'len(Master_Sub_Account) < 5 ' printNullValues = '' # else it will print null values printDescription = '' # if false it wil remove the print description line printAccount = '' # if false it wil remove the print account line OrderByAccount = 'ORDER BY iAccountType ' #CHECKING TRIAL BALANCE SETTINGS if form.Trial_balance_Year_to_date == True: printTrialBalance = True baseTRBYear = 'Inner JOIN [?].[dbo].[Accounts] '\ 'on Accounts.AccountLink = genLedger.AccountLink '\ 'Inner JOIN [?].[dbo].[_etblGLAccountTypes] as AccountTypes '\ 'on Accounts.iAccountType = AccountTypes.idGLAccountType '\ 'WHERE genLedger.AccountLink not in (161,162,163,164,165,166,167,168,122) '\ 'AND genLedger.TxDate > ?'\ op1 = '' op2 = '' op3 = '' op4 = '' … -
Problem with dynamic media in django project when i deploy on server with docker and nginx
I have a problem with an image that I upload to django-admin. Photos are added to the media folder in the running container, but it seems that the photos are trying to be taken from local files where they are not present. All working on my own computer, but i have faced with this problem when tried to deploy on server That's how it's looking in site enter image description here nginx can't find it enter image description here i have tried something like this Django static files not served with Docker but its not work for me This is my files structure: booking2 assets media main-app booking2 docker nginx Dockerfile nginx.conf docker-compose.yml Dockerfile entrypoint.sh .env main Dockerfile FROM python:3.8-alpine ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 WORKDIR /app RUN apk --update add RUN apk add gcc gcc python3-dev libc-dev libffi-dev jpeg-dev zlib-dev libjpeg libxml2-dev libxml2 libxslt-dev gettext RUN apk add postgresql-dev RUN pip install --upgrade pip COPY ./requirements.txt . RUN pip install -r requirements.txt COPY . . RUN chmod +x entrypoint.sh ENTRYPOINT ["/app/entrypoint.sh"] docker-compose.yml version: "3.7" services: web: build: context: . dockerfile: Dockerfile ports: - "8000:8000" entrypoint: - ./entrypoint.sh depends_on: - postgresdb postgresdb: build: context: ./docker/postgres dockerfile: Dockerfile environment: - … -
Does not show the login page
I am totally new in django. I tried to make a login form .whenever i press submit button i get the login/login URL it doesn't exist. This is my method in View.py(where i think the problem happens hereenter image description here) (when i go to the login page it shows me the page correctly but button do something wrong) def login(req): if req.method=='post': username=req.POST['username'] password=req.POST['password'] print(username,password) user=auth.authenticate(username=username,password=password) if user is not None: auth.login(req,user) return redirect("/") else: return redirect("task:all") else: return render(req, "Login.html") this is in urls.py path("login/", views.login, name='login'), path("logout/", views.logout, name='logout'), and this is my HTML <form action="login" method="post"> {% csrf_token %} <label for="username"><b>Userame</b></label> <input type="text" placeholder="Enter Username" name="username" required> <label for="psw"><b>Password</b></label> <input type="password" placeholder="Enter Password" name="password" required> <div class="row justify-content-center "> <button type="submit" class="signupbtn btn btn-primary" name="btn">Login</button> </div> </form> -
Convert Django framework to Django rest framework
To make the curl post request work, I am converting my existing Django project to Django REST framework. I have installed djangorestframework==3.12.4. My settings.py INSTALLED_APPS = [ .... 'rest_framework', ] REST_FRAMEWORK = { # Use Django's standard `django.contrib.auth` permissions, # or allow read-only access for unauthenticated users. 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly' ] } My views.py from django.shortcuts import render from . import forms from . import student_details_module from django.http import HttpResponseRedirect def student_details(request): submitted = False print (request) if request.method == 'POST': form = forms.studentDetailsForm(request.POST) if form.is_valid(): cd = form.cleaned_data return_message,return_code = student_details_module.show_data(cd['name']) return HttpResponseRedirect('/student_details?submitted=True') else: form = forms.studentDetailsForm() if 'submitted' in request.GET: submitted = True return render(request, 'student_details.html', {'form': form, 'submitted': submitted} ) How do I convert my view so it works well with djangorestframework. Please suggest. -
How do you customize dropdown container of option in html/css? please help i'm a beginner
i would like to change the border radius and border of the thing that is pointed by an arrow Here's my code: HTML- I use django forms and defined the class there: <div class="container-form"> <h1>ADD ISSUE</h1> <form action="" method="POST"> {% csrf_token %} {% for form in forms %} {{ form|safe }} {% endfor %} <input type="submit" value="create" class="submit-form"> </form> </div> Django forms: class IssueForm(ModelForm): project_bug = forms.CharField(max_length=200, required=True, widget=forms.TextInput(attrs={'class':'bug_form_text', 'placeholder':'Write your issue here'})) status = forms.ChoiceField(choices=Issue.StatusType.choices, required=True, widget=forms.Select(attrs={'class':'bug_form_dropdown'})) difficulty = forms.ChoiceField(choices=Issue.DifficultyType.choices ,required=True, widget=forms.Select(attrs={'class':'bug_form_dropdown'})) Css: .bug_form_text{ margin-top: 1em; border: none; border-bottom: 2px solid black; padding-bottom: .5em; outline: none; font-size: 1rem; background-color: transparent; } .bug_form_dropdown{ margin-top: 1em; border: none; outline: none; height: 4vh; background-color: #262626; color: #f2f2f2; border-radius: 3px; width: 70%; overflow: hidden; transition: ease-in 1s; } .submit-form{ margin-top: 1em; border: none; border-radius: 3px; outline: none; padding: .7em 2em; background-color: #e50914; color: #f2f2f2; } Attempted: I tried .bug_form_dropdown option{} it didn't work please help -
How django-filter called inside class based view?
I am just trying to work with django-filters. Below are the details : filters.py import django_filters from .models import work_allocation class WorkFilter(django_filters.FilterSet): class Meta: model = work_allocation fields = '__all__' views.py from .filters import WorkFilter class get_task_list(ListView): model = work_allocation myFilter = WorkFilter() work.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h2>List of Tasks</h2> <form method="GET"> {{myFilter.form}} </form> </body> </html> But I do not see any changes on my web page. Is that the right way I am calling filter? Please suggest -
How do I run a functon right after posting a model DRF
I have an api that has two models Company (which requires company name) and Info (which i want to be filled automatically based on the Company name) So what I'm doing there is asking for a company name at "localhost:8000/company/" then I want to get this name, add it to the link then get the information from finance.yahoo.com with get request as csv, run through it and fill my Info model with the information. The problem is when I'm calling Company.objects.last() it gets me the information about previous company For example: I post ZUO, it gets me nothing, then i post PD and I get info about ZUO Here is my models.py class Company(models.Model): company = models.CharField(max_length=10) class Info(models.Model): Date = models.CharField(max_length=64) Open = models.CharField(max_length=64) High = models.CharField(max_length=64) Low = models.CharField(max_length=64) Close = models.CharField(max_length=64) AdjClose = models.CharField(max_length=64) Volume = models.CharField(max_length=64) Here is my view.py def get_download_url(): comp = Company.objects.last() downloadUrl = ('https://query1.finance.yahoo.com/v7/finance/download/' + comp.company.upper() + '?period1=0&period2=5000000000&interval=1d&events=history&includeAdjustedClose=true') return downloadUrl def get_information(): downloadUrl = get_download_url() headers = {'User-Agent': 'user-agent'} response = requests.get(downloadUrl, headers=headers) info = [string.split(',') for string in response.text.split('\n')[1::]] return info class CompanyViewSet(viewsets.ModelViewSet): serializer_class = CompanySerializer queryset = Company.objects.none() def create(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) Info.objects.all().delete() info = … -
AttributeError 'list' object has no attribute '_committed'
I have created a page where the staff will upload their image and description, but when i click on the submit button, I got this error: AttributeError 'list' object has no attribute '_committed' as shown in the picture below. How do I fix this error? What die I do wrong in my code? AttributeError 'list' object has no attribute '_committed' traceback: Environment: Request Method: POST Request URL: http://127.0.0.1:8000/add/ Django Version: 2.2.20 Python Version: 3.8.0 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'account.apps.AccountConfig', 'crispy_forms'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django_session_timeout.middleware.SessionTimeoutMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback: File "C:\Users\TAY\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\exception.py" in inner 34. response = get_response(request) File "C:\Users\TAY\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\base.py" in _get_response 115. response = self.process_exception_by_middleware(e, request) File "C:\Users\TAY\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\base.py" in _get_response 113. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\TAY\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\contrib\auth\decorators.py" in _wrapped_view 21. return view_func(request, *args, **kwargs) File "E:\Role_based_login_system-master\account\views.py" in addPhoto 422. photo = Photo.objects.create( File "C:\Users\TAY\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\manager.py" in manager_method 82. return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Users\TAY\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\query.py" in create 422. obj.save(force_insert=True, using=self.db) File "C:\Users\TAY\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\base.py" in save 743. self.save_base(using=using, force_insert=force_insert, File "C:\Users\TAY\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\base.py" in save_base 780. updated = self._save_table( File "C:\Users\TAY\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\base.py" in _save_table 873. result = self._do_insert(cls._base_manager, using, fields, update_pk, raw) File "C:\Users\TAY\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\base.py" in _do_insert 910. return manager._insert([self], fields=fields, return_id=update_pk, File "C:\Users\TAY\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\manager.py" in manager_method 82. return getattr(self.get_queryset(), name)(*args, **kwargs) … -
How to add values for checked rows
The code below prints the list of students in Django as a table. I would like to add the name of the currently logged in account to the teacher column in the checked row when the 'Add Teacher' button is clicked. And I want the added data to be reflected in the DB. <table id="student-list" class="maintable"> <thead> <tr> <th class="text-black text-center text-nowrap bg-secondary font-weight-bold sticky-top-custom">Name</th> <th class="text-black text-center text-nowrap bg-secondary font-weight-bold sticky-top-custom">Register Date</th> <th class="text-black text-center text-nowrap bg-secondary font-weight-bold sticky-top-custom">Age</th> <th class="text-black text-center text-nowrap bg-secondary font-weight-bold sticky-top-custom">Sex</th> <th class="text-black text-center text-nowrap bg-secondary font-weight-bold sticky-top-custom">Teacher</th> <th class="text-black text-center text-nowrap bg-secondary font-weight-bold sticky-top-custom">Select</th> </tr> </thead> <tbody> {% for student in students %} <tr> <td>{{ student.name }}</td> <td>{{ student.register_date|date:'Y-m-d' }}</td> <td>{{ student.age }}</td> <td>{{ student.sex }}</td> <td>{{ student.teacher}}</td> <td><input type="checkbox"></td> </tr> {% endfor %} </tbody> </table> <input type="button" value="Add Teacher" class="addteacher"> </table> <script> $(function() { $(document).on("click", ".addteacher", function() { var getselectedvalues=$(".maintable input:checked").appendTo($(".maintable tbody").add(getselectedvalues)); }) }); </script> -
Ger all form data as a list, iterate over it and dilplay them in a table on template
I am working on a simple school project where students and teachers are registered as users. class monitors get a student list of their class and monitors have to submit and send a report to class teacher that all the students in the class are present for a certain lesson. So I have created a student model where parent class is the admission number. Then I have filtered a certain class (ex: Grade-6) and render them in to a template (grade-6 dashboard) and gave access to grade 6 class monitor. So the monitor can see all the student with their admission number on monitor dashboard. Then I have insert a select option with each student to select yes or no to say he or she is present or not. Then submit. After submitting in my view.py I get all the data as request.POST. But after saving the form (form.save()) I get last student details only. But all the details are in request.POST but I cannot get them to render in to a template. I dont know how. So I tried getting them as a list or a dict but couldnt. Please help me on getting this done. My form in … -
Static files are not found (gunicors)
I know this question was already asked frequently. But the supposed solutions seem not to help me. Here is my Nginx definition for the static files location /static/ { alias /data/atsi_webapp/ATSi_WebApp/static; } Here my Django settings BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) I did run already python manage.py collectstatic However, I get Not Found: /static/js/xxxx.js -
using custom function inside ModelViewset in Django rest framework
I always used APIView for writing all the CRUD operations in a single api view as because APIView already recognises which actions to be performed on the basis of http methods that comes from the request from the frontend. Recently I came across some code that is written using ModelViewset. Here a custom function is defined instead of list, create, destroy. For example a function named **"get_all_students_questions"** . Here is the snippet below: class QandaApiViewSet(viewsets.ModelViewSet, PusherMixin): """ Viewset that returns the paginated Qanda Details. """ queryset = Qanda.objects.all().order_by("-created_at") serializer_class = QandaModelSerializers def get_pusher_settings(self): setting = Setting.objects.filter(slug="pusher").first() if setting: return setting.settings return None def create(self, request): """ The method that accepts the form data to save the data as Qanda instance. """ serializer = self.get_serializer(data=request.data) if serializer.is_valid(raise_exception=True): validated_data = serializer.validated_data image_content = validated_data.get("content") subject = validated_data.get("subject") """ cms_content contains the cms data in which base64 image are converted to aws url image and content_Writing contains the image_url to those aws url image. """ cms_content, content_writing = parse_image_from_editor(image_content) new_data = { "content": cms_content, "content_writing": content_writing, "subject": subject, "student": request.user, } qanda = Qanda(**new_data) qanda.save() data = {"data": cms_content, "response": "Submitted Successfully"} """ Sending notification to admin side """ try: # getting pusher … -
How to add extra fields outside the list of items in modelView ? (like count for pagination)
I'm looking for the best way to add additional fields to the get list return of a ModelView. I have the following model: class Sale(models.Model): total = models.FloatField(_("Total")) name = models.CharField(_("Name")) [...] When I do a get list on this model, I get the following json: { "count": 0, "next": "http://example.com", "previous": "http://example.com", "results": [ { "id": 0, "name": "example", "total": 0, [...] } ] } I would like to add 2 fields min_total and max_total to the result (at the same level as "count"). Example: { "count": 0, "next": "http://example.com", "previous": "http://example.com", "min_total": 0, "max_total": 100, "results": [ { "id": 0, "name": "example", "total": 100, [...] } ] } My View: class SaleViewSet(viewsets.ReadOnlyModelViewSet): """ A simple ViewSet for listing or retrieving sales. """ permission_classes = [permissions.IsAuthenticated] filter_backends = [DjangoFilterBackend, filters.OrderingFilter] filter_fields = ['client', 'machine', 'date_time', 'total'] ordering_fields = '__all__' def get_serializer_class(self): if hasattr(self, 'action') and self.action == 'list': return SaleListSerializer if hasattr(self, 'action') and self.action == 'retrieve': return SaleRetrieveSerializer return SaleSerializer def get_queryset(self): queryset = Sale.objects.all().select_related('client') user = self.request.user if user.is_staff: cache_key = 'list_sale_sales' else: queryset = queryset.filter(client=user.profil.client) cache_key = f'list_sale_sales_client_{user.profil.client.pk}' return cache.get_or_set(cache_key, queryset, 60) To get these 2 values I just have to make these 2 requests: Sale.objects.all().aggregate(min=Min("total")) … -
how to save images in to particular path when image is give from link or url, in python
I'm trying to save images that are given from link, such a way that, image save in the given path and image file_name is created with uuid like below: my profile model is: class Profile(DataTimeModel): first_name = models.CharField(max_length=100) middle_name = models.CharField(max_length=100, null=True, blank=True) last_name = models.CharField(max_length=100) email_address = models.CharField(max_length=100) phone_number = models.CharField(max_length=100) address = models.CharField(max_length = 255, null=True, blank=True) citizenship_no = models.CharField(max_length = 25, null=True, blank=True) created_by = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True) Now when the profile is enrolled I will send multiple image link or single, from these link I need to download the image and save to the file path like below: root_dir = MEDIA_ROOT+'/profile/' new_dir = str(profile.id) file_name = str(uuid.uuid4())+'.jpeg' path = os.path.join(root_dir, new_dir) os.makedirs(path) Now, I need to save the image that comes from the URL into the path folder with image name file_name with extension. How can I do that? I try by using urllib.request.urlretrieve(url, file_name) this but it saves into base directory but I need to save in given path. Image link is given from this interface: