Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
UI video play Issue but works perfectly on Postman
I am not able to play video on UI received from the django backend. I am using normal javascript on UI and Django on the backend. Please find the backend code snippet: file = FileWrapper(open(path, 'rb')) response = HttpResponse(file, content_type=content_type) response['Content-Disposition'] = 'attachment; filename=my_video.mp4' return response The video plays perfectly on Postman but cant play on the UI screen. The UI code is below: function getUploadedImageAndVideo(combined_item_id){ request = {} request["combined_item_id"] = combined_item_id; var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { vdata = this.responseText; var src1 = document.getElementById('src1'); src1.setAttribute("src", "data:video/mp4;base64,"+vdata); //myVid.setAttribute("src", vdata); //doesnt work either var src2 = document.getElementById('src2'); src2.setAttribute("src", "data:video/mp4;base64,"+vdata); //myVid.setAttribute("src", vdata); //doesnt work either return } } xhttp.open("POST", port + host + "/inventory_apis/getUploadedImageAndVideo", true); xhttp.setRequestHeader("Accept", "video/mp4"); xhttp.setRequestHeader("Content-type", "application/json"); xhttp.setRequestHeader("X-CSRFToken", getToken()); xhttp.send( JSON.stringify(request) ); } on html side: <video controls=""> <source type="video/webm" src="" id="src1"> <source type="video/mp4" src="" id="src2"> </video> Network Response of function call: "ftypmp42 ... isommp42 ... mdat ... ó! ... °}b ... $¥Ð" I am not able to play video on the UI Side. Please Help. -
Django web frame work client server chat communication project
So basically this is a client server communication application which is been written in python and been successfully executed.For the same code i need to built a client separate and a server separately. My client Server program communicate on an self written algorithm which is included separately in the code already.. So i just need a help on how to add client and server separately in a project or should i create a separate project for client and server. Please help me out . I have tried different some method but that do not work. Thank you for advance for the help -
Django Microsoft Graph Authentication
I'd like users to be able to login to my Django app using their Microsoft personal, work or school account. I have no interest in any profile or other data from the user's account. I just want authentication. I've been playing with django-allauth and and Azure portal and have successfully set things up so I can log in with my personal outlook.com account. I've set the AD tenants up to allow for personal and institutional accounts. I've successfully served the .wellknown json and was able to verify the app in Azure. I run into trouble when I try to log in with a Microsoft 365 work or school account. The consent form shows the app as "unverified" and indicates that the app wants profile information and to store data. I ended up in a rabbit hole of Microsoft AD documentation about MPN IDs and such. Before I go further I want to know if I what I want to do is even possible. Keeping in mind that I'm not interested in profile information, can I achieve authentication in Django with a users Microsoft Work or School account? If so, what do I have to do? -
Django : Define url with the pk value in the middle and add it to the template
After the login, the user is redirected to a page where he has to select a contract value. The value selected redirects him to the specific home page. It is the home page concerning the contract where there are several apps. The structure of the URLS is : urlpatterns = [ path('selectcontrat', views.selectcontrat, name='selectcontrat'), path('home/<int:id_contrat>/', views.home, name="home"), path('home/<int:id_contrat>/upload', views.upload, name="upload"), ] The views : @authenticated_user def selectcontrat(request) : context = initialize_context(request) form_client = SelectClient(request.POST, user=request.user) if form_client.is_valid(): id_contrat = request.POST.get("ID_Customer") return redirect(reverse('home', args=(id_contrat,))) context['form_client'] = form_client return render(request, 'base/selectcontrat.html', context) @authenticated_user @check_user_rights() def home(request, id_contrat=None): context = initialize_context(request) context["id_contrat"] = id_contrat return render(request, 'home.html', context) @authenticated_user def upload(request, id_contrat=None): bla_bla_bla return render(request, 'base/upload.html', context) How do I add the urls/links in the template for the app "Upload Files" with the id_contrat value in the middle ? This is not working : <li><a href="{% url 'upload' %}">Upload Files</a></li> -
Django get results from multiple tables based on date range
Like said in the title. I have multiple tables in Postgres, where each of them have date range column. I want to pass a date range query to Django and get results from all of those different tables together ordered by date. What is the best and most efficient approach to this issue ? -
Python/Django - How to pass value from html to view via {% url %}?
I have a Django application that contains a form where the user can select "choice1" or "choice2" . So what I'm trying to do is that when an user gives an input via the radiobutton in the html and clicks "Update", it sends the new values (view.choice1 and view.valuechoice2 which are Boolean values) of to my a view, and prints the new values in my console. What I have is the following: choiceMenu.html <form class="card" action="" method="POST" enctype="multipart/form-data"> <input type="radio" name="update_choice" value="choice1"> Choice1 </input> <input type="radio" name="update_choice" value="choice2"> Choice2 </input> <div class="form-group"> <a href="{% url 'core:choicemenu:choices' view.choice1 %}" class="btn btn-secondary btn-sm">Update</a> </div> </form> model.py class ChoiceModel(models.Model): choice1 = models.BooleanField(default=False) choice2 = models.BooleanField(default=True) views.py class ChoiceMenu(generic.TemplateView): template_name = 'core/choiceMenu.html' context_object_name = 'choicemenu' current_model_set = ChoiceModel.objects.get(id=1) choice1 = int(current_model_set.choice1 == True) choice2 = int(current_model_set.choice2 == True) class ChoiceSetting(generic.TemplateView): extra_context = {"choices_page": "active"} context_object_name = 'choices' template_name = 'core/choices/choiceindex.html' def get(self, queryset=None, **kwargs): choice1 = self.kwargs.get("choice1") logger.info(choice1) ### <<-- I want to get this printed in my console return redirect(reverse("core:choicemenu")) urls.py app_name = 'core' urlpatterns = [ path('choicemenu', login_required(views.ChoiceMenu.as_view()), name='choicemenu'), path('choicemenu/choices/<int:choice1>/', login_required(views.ChoiceSetting.as_view()), name='choices') ] So, what I want is that when the user selects choice1 and pushes the button Update, it prints 1 … -
Cross-Origin-Opener-Policy header error when making GET request in Django
I'm making a stock app which displays live market data via Alpaca API. The error is The Cross-Origin-Opener-Policy header has been ignored, because the URL's origin was untrustworthy. It was defined either in the final response or a redirect. Please deliver the response using the HTTPS protocol. You can also use the 'localhost' origin instead. Here's how I'm making the request: symbol = 'AAPL' url = f'https://data.alpaca.markets/v2/stocks/{symbol}/trades/latest' requests.get(url, headers={ 'APCA-API-KEY-ID': API-KEY-ID, 'APCA-API-SECRET-KEY': API-SECRET-KEY, }) My request works when market is closed, but not open. However, if I run the code in a console during open hours, it still works so the API endpoint should be correct. In Django settings, I have: ALLOWED_HOSTS = ['market-master.herokuapp.com'] CSRF_TRUSTED_ORIGINS = ['https://market-master.herokuapp.com'] My site is https, is there an additional header I'm missing? I'm not sure how to "deliver the response using HTTPS protocol". -
Fail to Add Google pay into a django project
I want to add payment subscription in my Django project using Google pay but I don't know how to made that happen. I want a user to pay $5 dollars a months in my website. The stripe is not working in my country. I don't want to use PayPal also, I just want to use Google pay or any other payment processing in to Django website. Is any body who can help me do that please. I'm beginner in payment processing. -
How to get a list of all custom Django commands in a project?
I want to find a custom command in a project with many apps, how to get a list of all commands from all apps? -
Can I convert my Django app in an IOS app?
I'm currently creating a Django app, and I need to turn it into an IOS app. However, after looking online, I'm seeing conflicting statements on if it's possible to do so or not. Is it possible to convert my Django app (both front and backend) into an IOS app, or can it only be done for the backend? -
IntegrityError at /accounts/signup/ NOT NULL constraint failed: users_user.birth_date in Django allauth form
I get the following error when I try to signup using Django allauth form with custom user model. IntegrityError at /accounts/signup/ NOT NULL constraint failed: users_user.birth_date This is the custom user model and its manager I use: from django.contrib.auth.models import AbstractUser, BaseUserManager ## A new class is imported. ## from django.db import models from datetime import datetime class UserManager(BaseUserManager): """Model manager for User model with no username field.""" use_in_migrations = True def _create_user(self, email, password, **extra_fields): """Make and save a User with the given email and password.""" if not email: raise ValueError('The given email must be set') email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, password=None, **extra_fields): """Make and save a regular User with the given email and password.""" extra_fields.setdefault('is_staff', False) extra_fields.setdefault('is_superuser', False) return self._create_user(email, password, **extra_fields) def create_superuser(self, email, password, **extra_fields): """Make and save a SuperUser with the given email and password.""" extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) if extra_fields.get('is_staff') is not True: raise ValueError('Superuser must have is_staff=True.') if extra_fields.get('is_superuser') is not True: raise ValueError('Superuser must have is_superuser=True.') return self._create_user(email, password, **extra_fields) # User model class User(AbstractUser): """User model.""" username = None email = models.EmailField(verbose_name='email address', unique=True) first_name = models.CharField(max_length=128, blank=False) last_name = models.CharField(max_length=128, blank=False) … -
Form Create View and 3 hierarchical models - Limit Choices for ForeignKey
I am trying to create an 'Expense Tracker'. I have query regarding create view and Models with 3 hierarchical levels. For eg:- class ExpenseYear(models.Model): year = models.PositiveIntegerField() class ExpenseMonth(models.Model): month = models.CharField(max_length = 14,blank = False) month_year = models.ForeignKey(ExpenseYear,related_name = 'month',on_delete=models.CASCADE) class Expenses(models.Model): expense = models.PositiveIntegerField() expense_month = models.ForeignKey(ExpenseMonth,related_name = 'expense', on_delete=models.CASCADE) Now, while creating CreateView for 'Expenses' model, i am facing an issue. I want to display only the months in that particular year (in 'expense_month' foreignkey), but all months of all the years are being displayed in the 'expense_month' foreignkey. This is what i am getting - CreateView I searched stackoverflow about limiting foreignkey choices and ended up finally with another code, but now no months are displayed in the foreign key Forms.py #forms.py class ExpensesForm(forms.ModelForm): class Meta(): model = Expenses fields = ('expenses','expense_month') def __init__(self, *args, **kwargs): month_year_id = kwargs.pop('month_year_id') super(ExpensesForm, self).__init__(*args, **kwargs) self.fields['expense_month'].queryset = ExpenseMonth.objects.filter(month_year_id=month_year_id) Views.py #views.py class ExpensesCreateView(CreateView): model = models.Expenses form_class = ExpensesForm def get_form_kwargs(self): kwargs = super(ExpensesCreateView, self).get_form_kwargs() kwargs.update({'month_year_id': self.kwargs.get('month_year_id')}) return kwargs However, as i said no months are displayed if i write this code. This is what i am getting if i write the above code - CreateView How to limit foreignkey … -
I am getting error on downloading django-core using pip
I am trying to download django-core module but it always shows error.I have tried finding any information on internet but till now i am not able to find anything. pip install --trusted-host pypi.org --trusted-host files.pythonhosted.org django-core Collecting django-core Using cached django-core-1.4.1.tar.gz (37 kB) Preparing metadata (setup.py) ... error error: subprocess-exited-with-error × python setup.py egg_info did not run successfully. exit code: 1 D:\project\backend-develop\retail\lib\site-packages\setuptools\dist.py:757: UserWarning: Usage of dash-separated 'description-file' will not be supported in future versions. Please use the underscore name 'description_file' instead warnings.warn( D:\project\backend-develop\retail\lib\site-packages\setuptools\installer.py:27: SetuptoolsDeprecationWarning: setuptools.installer is deprecated. Requirements should be satisfied by a PEP 517 installer. I have added the error which is shown. I have upgraded pip and setuptools to latest version also. But this error is not removed. If anyone has any knowledge regarding it, it will be most helpful to me. -
Validationerror: "choose a valid option" on related field in ModelForm
I have a Model Inserzione related to a Model Servizio: class Inserzione(models.Model): servizio = models.OneToOneField( 'hub.Servizio', on_delete=models.CASCADE, null=True, default=None, related_name='+' ) In my InserzioneModelForm I want to restrict the choices of Servizio, I don't want all Servizio instances to be included. So in my InserzioneModelForm __init__ method: query = self.fields['servizio'].queryset self.fields['servizio'].queryset = query.filter(# my condition) This works correctly, when the user is submitting a form only the Servizio instances I want are available in the form field. The problem is that the form_valid() method returns False. It return a ValidationError {'servizio': [ValidationError(["Choose a valid option. The selected option is not between the available ones"])]} But it's actually an existing and valid Servizio instance. Here the incriminated form field in my template: <div class="controls "> <select name="servizio" class="select form-control" required="" id="id_servizio"> <option value="" selected="">---------</option> <option value="1">Corso Sicurezza sul Lavoro</option> <!--other options--> </select> </div> Any help is really aprreciated, thanks. -
Getting the error: This field is required when update user
I'm trying to update a user profile using two forms the problem is that when I click to update I get the following error: “<ul class="errorlist"> <li>username<ul class="errorlist"><li>This field is required.</li> </ul> ” My model module is the following: # user.models from django.contrib.auth.models import AbstractUser from django.db import models from model_utils.models import TimeStampedModel from localflavor.br.models import BRPostalCodeField, BRStateField, BRCNPJField, BRCPFField class User(AbstractUser): class Roles(models.IntegerChoices): SUPER = 0 COMPANY = 1 UNITY = 2 STAFF = 3 picture = models.ImageField(blank=True, null=True) role = models.IntegerField(choices=Roles.choices, default=Roles.STAFF) class Staff(TimeStampedModel): user: User = models.OneToOneField(User, null=True, on_delete=models.CASCADE) unity = models.ForeignKey(Unity, related_name="staff", on_delete=models.CASCADE) cpf = BRCPFField("CPF") class Meta: verbose_name: str = 'Staff' verbose_name_plural: str = 'Staff' ordering = ("-created",) def __str__(self): if f"{self.user.first_name} {self.user.last_name}".strip(): return f"{self.user.first_name} {self.user.last_name}" return str(self.user.username) And my user forms looks like: #user.forms class UserModelForm(forms.ModelForm): class Meta: model = User fields = ['username', 'first_name', 'last_name', 'email', 'is_active'] class StaffModelForm(forms.ModelForm): class Meta: model = Staff fields = ['cpf', 'unity'] widget = { 'cpf': forms.TextInput(attrs={'class': "form-control", 'placeholder': 'Primeiro Nome', }), 'unity': forms.EmailInput(attrs={'class': "form-control", 'placeholder': 'meu@email.com', }), } with the following view: #views … def update_staff(request: HttpRequest, pk: int) -> HttpResponse: instance: Staff = get_object_or_404(Staff, pk=pk) # get staff instance template_name = 'pages/staff_update_form.html' # use this … -
Date label in JavaScript chart doesn't display properly
I'm doing a Django project. In my chart.html file, I created a javascript bar chart. The data and the label of the chart have been defined in my views.py file. This is my JavaScript bar chart: (I'm drawing this chart to display the order numbers in the most recent 7 days) var ctx = document.getElementById("BarChart7d"); var BarChart7d = new Chart(ctx, { type: 'bar', data: { labels: [{{date7}}, {{date6}}, {{date5}}, {{date4}}, {{date3}}, {{date2}}, {{date1}}], datasets: [{ label: "orders: ", backgroundColor: ['#4e73df', '#1cc88a', '#36b9cc', "#e74a3b", "#f6c23e", "#9B59B6", "#D68910"], hoverBackgroundColor: ['#353F8C ', '#17a673', '#2c9faf', "#9C4545", "#9C8545", "#4A235A", "#784212"], borderColor: "#4e73df", data: {{value7day}}, }], }, options: { maintainAspectRatio: false, layout: { padding: { left: 10, right: 25, top: 25, bottom: 0 } }, scales: { xAxes: [{ gridLines: { display: false, drawBorder: false }, ticks: { maxTicksLimit: 6 }, maxBarThickness: 80, }], yAxes: [{ ticks: { callback: function(value, index, values) { return number_format(value); } }, gridLines: { color: "rgb(234, 236, 244)", zeroLineColor: "rgb(234, 236, 244)", drawBorder: false, borderDash: [2], zeroLineBorderDash: [2] } }], }, legend: { display: false }, tooltips: { titleMarginBottom: 10, titleFontColor: '#6e707e', titleFontSize: 14, backgroundColor: "rgb(255,255,255)", bodyFontColor: "#858796", borderColor: '#dddfeb', borderWidth: 1, xPadding: 15, yPadding: 15, displayColors: false, caretPadding: 10, callbacks: … -
TypeError: background() got an unexpected keyword argument 'repeat' [closed]
I have the below Django background tasks code that I want to run after 60 seconds. However, I am getting the above error @background(repeat=60) def checkAccountBalances(): print(" working on it") -
Free realtime stockprice data and how to add charts like a real trading app chart
I currently planning for build a stock trading app using react for study purpose. Is there is any api that can give realtime stock price data and if you can please suggest a good charting package for my peoject. -
How to add custom Post Form in Django Admin below Model Records
I need some guidance! How to Create Custom Form in this Area? I will be thankful for Help. Thanks enter image description here -
How to do reverse URL with keyword argument in Jinja2?
In a view function we can do the following: from django.http import HttpResponseRedirect from django.urls import reverse def SomeView(request): return HttpResponseRedirect( reverse('blog:specific-topic', kwargs={'topic':'python'}) ) In a template, without keyword argument, we can do this: <a href="{{ url('home-page') }}">Home Page</a> But how to do reverse URL in Jinja2 with keyword arguments? I am developing a programming blog, so I need to organize articles into topics including Python, Dajngo, Jinja2, Designing Relational Databases, and so forth. I wrote the following: <a href="{{ url('blog:specific-topic', topic.slug) }}" class="topic">{{ topic.name }}</a> But it did not work. -
Django. How to not repeat yourself using class based views?
I'm new to Django. I wonder if it is considered 'repeating yourself' when I use generic views such as CreateView, ListView and etc. in different apps and they differ in values for attributes like 'model', 'fields' or 'template_name' only? Do I repeat myself in this case or I shouldn't be worried? -
Django - Group by and do ArrayAgg
I have a model: class Deviation(models.Model): deviation_number = models.SmallIntegerField() day_of_calculation = models.SmallIntegerField() And I'd like to group records of the model by day_of_calculation and get list of deviation_numbers: deviations = Deviation.objects \ .values('day_of_calculation') \ .annotate(deviation_numbers=ArrayAgg('deviation_number')) But Django incorrectly creates sql: SELECT "deviation"."day_of_calculation", ARRAY_AGG("deviation"."deviation_number" ) AS "deviation_numbers" FROM "deviation" GROUP BY "deviation"."day_of_calculation", "deviation"."deviation_number" Grouping by deviation_number should not happen. What do I do wrong? -
Unwanted fields appear on the template (Django)
I give the products to the page with the loop in the template, but there is a problem. There is a gap on the page and I can't find the reason. Most likely because of HTML codes. I will be glad if you help. This gap in the middle products.html <!-- STORE --> <div id="store"> <!-- row --> <div class="row"> <!-- Product Single --> {% for product in products %} {% if product.available %} <div class="col-md-4 col-sm-6 col-xs-6"> <div class="product product-single"> <div class="product-thumb"> <div class="product-label"> <span>New</span> {% if product.sale %} <span class="sale">-{{product.sale}}%</span> {% endif %} </div> <button class="main-btn quick-view"><i class="fa fa-search-plus"></i> Göz At</button> <img src="{{product.main_image.url}}" alt=""> </div> <div class="product-body"> {% if product.sale %} <h3 class="product-price">{{product.discount}} AZN <del class="product-old-price">{{product.price}} AZN</del></h3> {% else %} <h3 class="product-price">{{product.price}} AZN</h3> {% endif %} <div class="product-rating"> <i class="fa fa-star"></i> <i class="fa fa-star"></i> <i class="fa fa-star"></i> <i class="fa fa-star"></i> <i class="fa fa-star-o empty"></i> </div> <h2 class="product-name"><a href="#">{{product.name}}</a></h2> <div class="product-btns"> <button class="main-btn icon-btn"><i class="fa fa-heart"></i></button> <button class="main-btn icon-btn"><i class="fa fa-exchange"></i></button> <button class="primary-btn add-to-cart"><i class="fa fa-shopping-cart"></i> Səbətə At</button> </div> </div> </div> </div> {% endif %} {% endfor %} <!-- /Product Single --> </div> <!-- /row --> </div> <!-- /STORE --> -
I have a problem with override title in admin when use TabularInline
I have a problem with title in admin, when i use TabularInline, the name of the fields is overwritten. This happens precisely with ManiToMany. How can i change it? Field name in admin "AdditionalCourseModel_course object (1)" block name in admin "ADDITIONALCOURSEMODEL" models.py class CoursesDescriptionModel(models.Model): ... class Meta: verbose_name = 'Курс' verbose_name_plural = 'Курсы' def __str__(self): return f'{self.name_courses}' class CourseDetailModel(models.Model): course = models.ForeignKey(CoursesDescriptionModel, on_delete=models.CASCADE, related_name='course') ... class Meta: verbose_name = "Что изучает курс" verbose_name_plural = "Что изучает курс" def __str__(self): return f'{self.detail}' class AdditionalCourseModel(models.Model): course = models.ManyToManyField(CoursesDescriptionModel, related_name='add_course', verbose_name='qwerty') name_course = models.CharField(max_length=100, verbose_name='название допа') ... class Meta: verbose_name = 'Доп к курсу' verbose_name_plural = 'Допы к курсу' def __str__(self): return f'{self.name_course}' admin.py class CoursesDescriptionInline(admin.TabularInline): model = CourseDetailModel fk_name = 'course' extra = 1 max_num = 10 class AdditionalCourseModelInline(admin.TabularInline): model = AdditionalCourseModel.course.through extra = 1 max_num = 1 verbose_name = 'допы к курсу' verbose_name_plural = 'Доп к курсу' @admin.register(CoursesDescriptionModel) class CourseAdmin(admin.ModelAdmin): fields = (...) list_display = (...) inlines = [CoursesDescriptionInline, AdditionalCourseModelInline] enter image description here -
django 4.0 Invalid path type: PurePosixPath but working on django 3.1
i tried to migrate from django 3 to django 4 my project based on wemake-django-template i have 2 virtual env, django 3.1 and django 4.0 the project working fine on venv django 3.1 but have this error on django 4.0 raise TypeError("Invalid path type: %s" % type(value).__name__) TypeError: Invalid path type: PurePosixPath ` from pathlib import PurePath from decouple import AutoConfig BASE_DIR = PurePath(file).parent.parent.parent.parent config = AutoConfig(search_path=BASE_DIR.joinpath('config')) ` the project still empty, i just wanna my default setting are working properly on django 4.0