Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Automatic monthly updation of data in django
I have been designing a daily expense website where user can enter the data and it displays it along with the total expense of the user. I want to change the total expense to monthly expense so that it shows zero at the starting of each month. Here is my html file for displaying that part: <h3 class='center'>Expenditure of this month: <span style="color:green;">{{ budget|floatformat:"-2" }}</span> dollars</h3> I have tried datetime library of python in views to change it: def app_view(request): bal_qs = [int(obj.cost) for obj in BudgetInfo.objects.filter(user=request.user)] now = [i.lstrip("0") for i in datetime.now().strftime("%d")] budget=0 if now[0]!='1': for obj in range(len(bal_qs)): budget=budget+bal_qs[obj] uzer_qs = BudgetInfo.objects.filter(user=request.user).order_by('-date_added') return render(request,'tasks_notes/index.html',{'budget':budget,'uzer':uzer_qs[0:5]}) But it's not changing the budget value monthly. How can I achieve it? -
How to register using subdomain field in django?
I want to register company details using subdomain so that the user can login using subdomain. I created models.forms and views but i am facing problem with rendering the form models.py class Company(models.Model): name = models.CharField(max_length=100) address = models.CharField(max_length=2000) sub_domain = models.CharField(max_length=30) user_limit = models.IntegerField(default=5) country = models.CharField(max_length=3, choices=COUNTRIES, blank=True, null=True) forms.py class RegistrationForm(forms.ModelForm): class Meta: model = Company fields = ['name', 'address', 'sub_domain', 'country'] def __init__(self, *args, **kwargs): self.request_user = kwargs.pop('request_user', None) super(RegistrationForm, self).__init__(*args, **kwargs) views.py class RegistrationView(AdminRequiredMixin, CreateView): model = Company form_class = RegistrationForm template_name = "company_register.html" def is_valid(self, form): company = Company.objects.create_company(form.cleaned_data['name'], form.cleaned_data['address'], form.cleaned_data['sub_domain'], form.cleaned_data['country']) company.save() return super(RegistrationView, self).form_valid(form) urls path('register/', RegistrationView.as_view(), name='register'), reg.html {% extends 'base.html' %} {% block content %} <h1>Registration</h1> <form method="POST" class="user-form"> {{ form.as_p }} <button class="btn btn-primary" type="submit">Submit</button> </form> {% endblock %} Where i have done mistake as i am a newbie can someone help me?Thanks -
How to tell django where to look for css fies?
I;m trying to build a website for an online store and when I ran my html files, I found that my css files are having no effect on my pages. How do I inform django where to look for it? Can anyone help me? -
Django, tried to add a field to exsting model raises error
I Have a Django rest framework API which contained the following model: class Points(models.Model): mission_name = models.CharField(name='MissionName', unique=True, max_length=255, blank=False, help_text="Enter the mission's name" ) latitude = models.FloatField(name="GDT1Latitude", unique=False, max_length=255, blank=False, help_text="Enter the location's Latitude, first when extracting from Google Maps.", default=DEFAULT_VALUE) longitude = models.FloatField(name="GDT1Longitude", unique=False, max_length=255, blank=False, help_text="Enter the location's Longitude, second when extracting from Google Maps.", default=DEFAULT_VALUE) Iv'e added a User field, When trying to makemigrations and migrate it I get the following error: django.db.utils.ProgrammingError: column find_second_gdt_points.user does not exist LINE 1: SELECT "find_second_gdt_points"."id", "find_second_gdt_point... Which I don't get, of course, this column does not exist. This is what migartions are for, no? -
django charField accepting only numbers
I have this django charField and i want it to accept only numbers .How can we achieve this in django ? class Xyz(models.Model): total_employees = models.CharField(max_length=100) I want total_employees to accept only numbers and not strings from my client .I want to put a check on api end too . -
has_add_permission function throwing 403 Forbidden in Django admin
@admin.register(Book) class BookAdmin(NestedModelAdmin): list_per_page = 50 list_display = ('name', 'author', 'course_name', 'created_at', 'updated_at') inlines = [BookSectionInline] def has_add_permission(self, request): return False -
How can i share session between a java and a python-django app?
I have two web apps(one in java and one in python(django)), I want to share session between these two apps. Is it possible? If yes, how can i do that. Please share. Problem Statement: I am displaying some information related to a machine learning problem on java app page and upon clicking that info i am redirecting to the django-python webapp apge. I want my login in the java webapp to persist throught the django webapp page, so that i do not have to login again in the django app. This may sound like an overcomplicated situation to some but unfortunately that's how the client wants it. Any help is appreciated. Thanks in Advance. -
How do I use request.user in template
I am trying display different text to user on an empty tag. I was able to implement this correctly in other template, but I do not clearly understand why it is not displaying correctly in another template. For example, if user A login, I want only user A to see 'Find people to follow' , while other users to see 'No users'. def following_view(request, username): p = FriendRequest.objects.filter(from_user__username=username) all_profile_user=[] button_status_list=[] for user_obj in p: u = user_obj.to_user all_profile_user.append(u) friend = Profile.objects.filter(user=request.user, friends__id=user_obj.id).exists() button_status = 'none' if not friends: button_status = 'not_friend' if len(FriendRequest.objects.filter(from_user=request.user).filter(to_user=u)) == 1: button_status = 'cancel_request_sent' button_status_list.append(button_status) context={'profile_and_button_status':zip(p, button_status_list), 'u':all_profile_user, 'following':p,} {% for data in profile_and_button_status %} #Button codes here {% empty %} #why this doesn't display {% for data.user != request.user %} No users {% endfor %} {% for data.user == request.user %} Find people to follow {% endfor %} {% endfor %} -
Django - Using TimeField() as a foreign key
I have a Meeting model which has meeting_hour getting its value from MeetingHour model. But I'm getting an error as follows after submitting form: Cannot assign "datetime.time(14, 0)": "Meeting.meeting_hour" must be a "MeetingHour" instance. I know its because of I'm not using MeetingHour as a foreign key correctly, but don't know how can I fix it. Here are my codes: models.py class MeetingHour(models.Model): hour = models.TimeField() def __str__(self): return self.hour class Meeting(models.Model): participant_name = models.CharField(max_length=50) participant_email = models.EmailField(max_length=50) meeting_date = models.DateField() meeting_hour = models.ForeignKey(MeetingHour, on_delete = models.CASCADE) is_scheduled = models.BooleanField(default=False) def __str__(self): return self.participant_name views.py def index(request): context = { 'schedules': Meeting.objects.all() } if request.method == "POST": participant_name = request.POST.get('name') participant_email = request.POST.get('email') meeting_date = str(request.POST.get('date')) meeting_hour = str(request.POST.get('hour')) converted_meeting_date = datetime.strptime(request.POST.get('date'), "%Y-%m-%d").date() if meeting_date else None converted_meeting_hour = datetime.strptime(request.POST.get('hour'), "%H:%M").time() if meeting_hour else None subject = 'Meeting' message = f'Hi, {participant_name} ! \nYour meeting date: {meeting_date}, hour: {meeting_hour}' from_email = settings.SERVER_EMAIL recipient_list = [participant_email] send_mail(subject, message, from_email, recipient_list) if request.POST.get('email'): Meeting.objects.create( participant_name = request.POST.get('name'), participant_email = request.POST.get('email'), meeting_date = converted_meeting_date, meeting_hour = converted_meeting_hour, is_scheduled = True ) return render(request, 'index.html', context) -
What Server provider is best for a Django-MySQL back end?
I just finished my 4 month project to create a mobile app. I built my own backend API (only returns JSON) in Django to fetch data from my MySQL database and I have completed the front end user interface in Swift. Up to this point, both my Django API and my database have been running locally on my Mac. I am ready to deploy my mobile app and I understand this requires pushing my backend API/database onto a server. Which server provider is best for my needs? Thank you. -
TypeError at /items/ join() argument must be str, bytes, or os.PathLike object, not 'dict'
Please help, I tried tracing back my code by removing some part of it and putting it back in to see which one raised the error and this one was the one that raised the above error. context = { 'items': 'Item.objects.all()' } This is from my django-views from django.shortcuts import render from .models import Item def vendors(request): return render(request, 'pages/vendors.html', {'title': 'Vendors'}) def items(request): context = { 'items': Item.objects.all() } return render(request, context, 'pages/items.html', {'title': 'Items'}) def request(request): return render(request, 'pages/request.html', {'title': 'Request'}) This is the items page I was trying to access. {% extends "pages/base.html" %} {% load humanize %} {% block content %} {% for item in items %} <article class="media content-section"> <div class="media-body"> <div class="article-metadata"> <a class="mr-2" href="#">{{ item.requester }}</a> <small class="text-muted">{{ item.date_requesteded|naturaltime }}</small> </div> <h2><a class="article-title" href="#">{{ item.name }}</a></h2> <p class="article-content">{{ item.description }}</p> </div> </article> {% endfor %} {% endblock content %} The other html page worked fine. -
Python - How do i make this code look good
Is there simpler way to write this code and Refactor the code and write some very simple sanity checks to show that the refactored version is equivalent to the ugly version? for i in range(len(colours)-1,-1,-1): print(colours[i]) -
How to use Javascript function on input elements in a for loop. Django
I'm working on a Django form that can calculate values in real time. I would like the javascript function to work for all rows which consists of 3 input fields each. I tried assigning each input field with an id followed by a forloop counter. I also looped through the function hoping that it will work for all the ids, a1,a2,a3... b1,b2,b3... c1,c2,c3... However, the function only worked for the last row. Here's the javascript I used: <script type="text/javascript"> for (i = 0; i < {{ total_rows|safe }}; i++) { $('input').keyup(function(){ var firstValue = Number($('#a'+i).val()); var secondValue = Number($('#b'+i).val()); document.getElementById('c'+i).value = firstValue * secondValue; }); } </script> Here's my template: <form> {% csrf_token %} <table> <thead> <tr> <th>Quantity</th> <th>Unit Price</th> <th>Amount</th> </tr> </thead> <tbody> {% for item, amount in loop_list %} <tr> <td> <input id="a{{ forloop.counter }}" type="text" class="form-control" placeholder="" name="quantity1" value="{{ item.quantity }}"> </td> <td> <input id="b{{ forloop.counter }}" type="text" class="form-control" placeholder="" name="unit_price1" value="{{ item.product.unit_price }}"> </td> <td> <input id="c{{ forloop.counter }}" type="text" class="form-control" placeholder="{{ amount }}" readonly> </td> </tr> {% endfor %} </tbody> </table> </form> -
Django does not load static files after opening a new window with JS
I have a Django app, and seems like I did something wrong with static files. My static files works as needed across all project, except one moment. I have following js function: function sendForm() { let xhr = new XMLHttpRequest(); xhr.onreadystatechange = function () { if (this.readyState === 4 && this.status === 200) { window.open('/url/to/open/' + xhr.responseText); } }; let info = document.querySelector("#parameters"); let data = new FormData(info); xhr.open("POST", "/url/to/open/", true); xhr.setRequestHeader("X-CSRFToken", document.getElementsByName("csrfmiddlewaretoken")[0].value); xhr.send(data) } This code works, and new tab loads all the static files it has. But if I do Ctrl + F5 on any page I will see [01/Apr/2020 05:53:42] "GET /static/images/logo.png HTTP/1.1" 404 1669 [01/Apr/2020 05:53:42] "GET /static/js/scripts.js HTTP/1.1" 404 1663 [01/Apr/2020 05:53:42] "GET /static/icons/cat.png HTTP/1.1" 404 1669 [01/Apr/2020 05:53:42] "GET /static/css/style.css HTTP/1.1" 404 1663 [01/Apr/2020 05:53:42] "GET /static/icons/dog.png HTTP/1.1" 404 1675 [01/Apr/2020 05:53:42] "GET /static/icons/butterfly.png HTTP/1.1" 404 1678 [01/Apr/2020 05:53:43] "GET /static/css/style.css HTTP/1.1" 404 1663 [01/Apr/2020 05:53:43] "GET /static/js/scripts.js HTTP/1.1" 404 1663 [01/Apr/2020 05:53:43] "GET /static/favicon.ico HTTP/1.1" 404 1657 which means Django lost somewhere my static files. Since this moment static files will always return 404. Can you explain what does this happen and how to fix it? Template with sendForm() caller. This template does … -
ValueError at /shop/checkout/ Incorrect AES key length (22 bytes)
This code give invalid AES key length error in server side. How can I correct it? Server gets created after that when a msg is sent from client side server gets error. Server code: File "/home/saurabh/.local/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/saurabh/.local/lib/python3.6/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/saurabh/.local/lib/python3.6/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/saurabh/project/myshop/shopingsite/shop/views.py", line 126, in checkout param_dict['CHECKSUMHASH'] = Checksum.generate_checksum(param_dict, MERCHANT_KEY) File "/home/saurabh/project/myshop/shopingsite/PayTm/Checksum.py", line 24, in generate_checksum return encode(hash_string, IV, merchant_key) File "/home/saurabh/project/myshop/shopingsite/PayTm/Checksum.py", line 103, in encode c = AES.new(key.encode('utf-8'), AES.MODE_CBC, iv.encode('utf-8')) File "/home/saurabh/.local/lib/python3.6/site-packages/Crypto/Cipher/AES.py", line 232, in new return _create_cipher(sys.modules[name], key, mode, *args, **kwargs) File "/home/saurabh/.local/lib/python3.6/site-packages/Crypto/Cipher/init.py", line 79, in _create_cipher return modes[mode](factory, **kwargs) File "/home/saurabh/.local/lib/python3.6/site-packages/Crypto/Cipher/_mode_cbc.py", line 274, in _create_cbc_cipher cipher_state = factory._create_base_cipher(kwargs) File "/home/saurabh/.local/lib/python3.6/site-packages/Crypto/Cipher/AES.py", line 93, in _create_base_cipher raise ValueError("Incorrect AES key length (%d bytes)" % len(key)) ValueError: Incorrect AES key length (22 bytes) [01/Apr/2020 06:33:08] "POST /shop/checkout/ HTTP/1.1" 500 101430 -
Python Django get variable problem using in django-tables2
In this project, I need to take the pk in views and use them in tables.py. What should I do to use the variables of views in tables.py? I want to get the var1.pk using in modelB.objects.get(id=3) at tables.py Can anyone help ? and sorry for my poor English views.py def create_page(request, pk): var1 = get_object_or_404(modelB, pk=pk) form = CreateForm(request.POST or None) profile_id_list = [] success_id_list = [] fail_id_list = [] if request.method == 'POST': if form.is_valid(): profile_id = request.POST['profile_id'].split(',') profile_id_list = profile_id for num in profile_id: if modelA.objects.get(id=num).check_function(modelB.objects.get(id=var1.pk)): modelC.objects.create( A=modelA.objects.get(id=num), B=modelB.objects.get(id=royalty.pk), ) success_id_list.append(num) else: fail_id_list.append(num) form = RoyaltyAuthorizerCreateForm() table_success = TableA(modelA.objects.filter(id__in=success_id_list)) table_fail = TableB(modelB.objects.filter(id__in=fail_id_list)) context = {Skip} return render(request, template_path, context) tables.py from django.utils.html import format_html from django.utils.translation import ugettext_lazy as _ from svapps.dps.models import UserProfile, IncomeProject from svapps.pa.tables.base import BaseTable import django_tables2 as tables class RoyaltyAuthorizerCreateFailListTable(BaseTable): A = tables.Column() B = tables.Column() C = tables.Column() fail_reason = tables.Column(, empty_values=(), orderable=False) operation = tables.TemplateColumn(template_name='path', orderable=False) def render_fail_reason(self, record): html_str = '' field_names = ['A','B', 'C'......] for field_name in field_names: if getattr(`modelB.objects.get(id=3)`, field_name): if not getattr(record, field_name): html = format_html('<span class="badge badge-pill badge-light mr-1 mb-1">{}</span>', IncomeProject._meta.get_field(field_name).verbose_name) else: html = '' html_str = format_html('{} {}', html_str, html) return html_str class Meta(BaseTable.Meta): … -
Django ORM Inheritance: You are trying to add a non-nullable field 'dish_ptr' to [...] without a default
I am working on a restaurant app (and new to Django/Python). I want to have a parent class Dish that will contain some counter or ID that increments for every instance of a child class of Dish. The instances are dishes like Pizza, Pasta, etc with different characteristics and relations. I'm trying to make Dish concrete, because in that case I reckon I just access Dish's PK and that will give each menu-item a Dish-ID. However, I don't know how to correctly fix the errors I come across: You are trying to add a non-nullable field 'pasta_ptr'. Here are the relevant code snippets: class Dish(models.Model): pass # should automatically generate PK, right? class Pasta(Dish): name = models.CharField(max_length=64, primary_key=True) price = models.DecimalField(max_digits=6, decimal_places=2) def __str__(self): return f"{self.name}, price: ${self.price}" class Pizza(Dish): sizestyle = models.CharField(max_length=4, choices=SIZESTYLE_CHOICES, default=SMALL_REGULAR) topping_count = models.IntegerField(default=0, validators=[MaxValueValidator(5), MinValueValidator(0)]) price = models.DecimalField(max_digits=6, decimal_places=2) def __str__(self): return f"Price for {self.sizestyle} pizza with {self.topping_count} toppings: ${self.price}" class Sub(Dish): name = models.CharField(max_length=64, primary_key=True) price_category = models.ForeignKey(SubPrice, on_delete=models.DO_NOTHING, related_name="sub_price_category") def __str__(self): return f"{self.name}, Price Category: {self.price_category}" class Platter(Dish): name = models.CharField(max_length=64, primary_key=True) price_large = models.DecimalField(max_digits=6, decimal_places=2, default=0) price_small = models.DecimalField(max_digits=6, decimal_places=2, default=0) def __str__(self): return f"{self.name} price: Large ${self.price_large}, Small ${self.price_small}" -
how to take sum of each ObjectList, DJANGO
thanks for your time: i am trying to get the sum of all Pets separeted by People: models.py: class People(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='person') birthday = models.DateField() cpf = models.CharField(max_length=11, validators=[RegexValidator(r'^\d{1,10}$')]) def __str__(self): return '%s' % (self.user) class Pets(models.Model): pessoa = models.ForeignKey(People, on_delete=models.CASCADE, related_name='peop') nome = models.CharField(max_length=150) custo = models.DecimalField(max_digits=7, decimal_places=2) tipo = models.SmallIntegerField() def __str__(self): return '%s - %s' % (self.pessoa, self.nome) views.py q7 = People.objects.all() for p in q7: q8 = Pets.objects.filter(pessoa=p) l=[] for pet in q8: custa = pet.custo l.append(custa) custo_total2 = sum(l) its returning me just the sum of the last People.Pets query i guess i'm not understanding the logic -
I can not Dockerize MySQL and Django App using docker-compose
I am trying to Dockerize mysql and Django app but facing a lot of issues can you help me with it. settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'trying', 'USER': 'root', 'PASSWORD': '159753', 'HOST': 'db', 'PORT': '3306', } } Dockerfile FROM python:3.6 ENV PYTHONUNBUFFERED 1 RUN mkdir /my_app_dir WORKDIR /my_app_dir ADD requirements.txt /my_app_dir/ RUN pip install -r requirements.txt ADD . /my_app_dir/ docker-compose.yml version: '3' services: db: image: mysql:5.7 ports: - '3305:3306' environment: MYSQL_DATABASE: 'trying' MYSQL_USER: 'root' MYSQL_PASSWORD: '159753' MYSQL_ROOT_PASSWORD: '159753' web: build: . command: "python trying/manage.py runserver 0.0.0.0:8000" volumes: - .:/my_app_dir ports: - "8000:8000" depends_on: - db I was running docker-compose run web trying\manage.py migrate but getting a lot of errors error is I was running the command and getting this error I want my container to connect with my MySQL server and work perfectly but I am facing issues please help Traceback (most recent call last): File ".\trying\manage.py", line 21, in <module> main() File ".\trying\manage.py", line 17, in main execute_from_command_line(sys.argv) File "/usr/local/lib/python3.6/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.6/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python3.6/site-packages/django/core/management/base.py", line 341, in run_from_argv connections.close_all() File "/usr/local/lib/python3.6/site-packages/django/db/utils.py", line 225, in close_all for alias in self: File "/usr/local/lib/python3.6/site-packages/django/db/utils.py", line 219, in __iter__ … -
Getting 'No module named 'XYZ' error' while running Django application
I just moved from Django 1.8 to 3.0, and also upgraded python 2.7 to 3.7 simultaneously for my project. Upon python manage.py runserver, I am getting the response File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 965, in _find_and_load_unlocked No module named "XYZ" where XYZ is a connection mentioned in my Database configuration. Any clue how to resolve this error? -
React & DRF - no cookies being saved
I'm trying to implement session based authentication the first time. I'm using React and Django Rest Framework, but there's some weird thing I don't understand. I have a pretty standart Login view, so I send POST request from React with username and password, I got response with status 200, I can see cookies in the response with Chrome developer tools. But these cookies aren't being saved. If I do the same POST request with Rest plugin for Chrome - it saves them. Maybe I'm missing something here since it's my first time? Or should I save it manually somehow? So that's my request with axios, maybe I need to add something here: const sendLogin = () => { if (login && password) { axios.post(SERVER_ADDRESS + 'login/', {username: login, password: password}) .then((response) => { if (response.status !== 200) { handleClick(); } else { history.push('/'); } }) } } -
jCarousel (connected carousels) with django
I'm trying to make a dynamic jCarousel pulling images from DB, but I don't know how to get it to work, because the thumbnails are not displaying nor the next images on the carousel, the thumbnails were not working before I added the "if" statements <!--jCarousel--> <div class="wrapper"> <div class="connected-carousels"> <div class="stage"> <div class="carousel carousel-stage" data-jcarousel="true"> <ul> <li><img src="{{ property.main_photo.url }}" width="600" height="400" alt=""> </li> {% if property.photo_1 %} <li><img src="{{ property.photo_1.url }}" width="600" height="400" alt=""> </li> {% endif %} {% if property.photo_2 %} <li><img src="{{ property.photo_2.url }}" width="600" height="400" alt=""> </li> {% endif %} {% if property.photo_3 %} <li><img src="{{ property.photo_3.url }}" width="600" height="400" alt=""> </li> {% endif %} {% if property.photo_4 %} <li><img src="{{ property.photo_4.url }}" width="600" height="400" alt=""> </li> {% endif %} {% if property.photo_5 %} <li><img src="{{ property.photo_5.url }}" width="600" height="400" alt=""> </li> {% endif %} </ul> </div> <p class="photo-credits"> <a href="#">credits</a> </p> <a href="#" class="prev prev-stage inactive" data-jcarouselcontrol="true"> <span>&lsaquo;</span></a> <a href="#" class="next next-stage" data-jcarouselcontrol="true"><span>&rsaquo; </span></a> </div> <div class="navigation"> <a href="#" class="prev prev-navigation inactive" data- jcarouselcontrol="true">&lsaquo;</a> <a href="#" class="next next-navigation" data-jcarouselcontrol="true">&rsaquo;</a> <div class="carousel carousel-navigation" data-jcarousel="true"> <ul> <li data-jcarouselcontrol="true" class="active"><img src="{{ property.main_photo.url }}" width="50" height="50" alt=""></li> {% if property.photo_1 %} <li data-jcarouselcontrol="true" class="active"><img src="{{ property.photo_1.url }}" width="50" … -
postfix with django send mail
I have vps on ovh and installed postfix and it's work but i can't send mail with django using postfix and this id django mail settings EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'localhost' EMAIL_PORT = 25 EMAIL_HOST_USER = '' EMAIL_HOST_PASSWORD = '' EMAIL_USE_TLS = False and this is how i try to send mail from radio import settings from django.core.mail import EmailMultiAlternatives, send_mail def home(request): if 'requestSong' in request.POST: form = RequestSongForm(request.POST) if form.is_valid(): form.save() send_mail( 'Thank you', 'Hello, thank you for contacting radio-active we hope That you\'ve liked our radio,please send us your feedback and suggestions for the radio and wait for our reply ☺️.', 'root@radio-active.co', ['ahmed.rabea.smaha@gmail.com'], fail_silently=True ) -
writing tests and doc at the same time django rest framework
There is something called Spring Rest Docs in java where you can write api tests and generate doc at the same time Is there such a test driven document generation framework for django rest framework? -
Django modify FileField input button and label in Django form
I am trying to get rid of the regular file upload view by default in a Django formset, my approach is right now to hide the input file and then use a label and make that label clickable to upload file, however, right now after clicking on my label can be uploaded, I am using pure CSS for this current my html template is: HTML FORM <form method="POST" data-url="{% url 'home:post-create' %}" class="post-create-form"> {% csrf_token %} <div class="modal-header"> <h5 class="modal-title" >Create a Post</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body" style="overflow-y: auto;"> {{ form|crispy }} <button type="button" id="show-image-upload-inputs" class="btn btn-sm mr-auto btn-primary pb-1"> <span><i class="fas fa-camera"></i></span> </button> <div id="image-upload-div" class="mt-1 mx-1" style="display: none;"> <div class="d-flex justify-content-center"> {% for a_form in formset %} <div class="pl-1"> <label for="file"><i class="mt-2 fas fa-plus fa-5x"></i></label> {{ a_form }} </div> {% endfor %} </div> </div> </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> <button type="submit" class="btn btn-primary">Post</button> </div> </form> <style> input[type='file'] { display: none; } label[for='file'] { padding-left: 2px; cursor: pointer; background-color: rgb(212, 231, 238); border: 1em; border-radius: 10px; width: 6em; height: 6em; text-align: center; opacity: 0.5; color:lightblue; } </style> Django View @login_required def post_create(request): data = dict() ImageFormset = modelformset_factory(Images,form=ImageForm,extra=4) …