Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I restrict the list of objects in API view once an object has been added to a relationship?
I am working in django-rest-framework and I have three models: Event, Performer, and Link. I have many-to-many relationships established on the Event and Performer models as 'links' pointing to the Link model. In the API view, when I am creating or updating an event or performer, I am given a list of all links. I would like them to be removed as options once they've been associated with another object, but I can't seem to figure out how to. Below is my code: class Link(models.Model): created = models.DateTimeField(auto_now_add=True) address = models.URLField() def __str__(self): return f"{self.address}" class Meta: ordering = ['created'] class Performer(models.Model): created = models.DateTimeField(auto_now_add=True) first_name = models.CharField(max_length=20) last_name = models.CharField(max_length=20) links = models.ManyToManyField(Link) def __str__(self): return f"{self.first_name} {self.last_name}" class Meta: ordering = ['created'] class Event(models.Model): created = models.DateTimeField(auto_now_add=True) sale_date = models.DateTimeField() event_date = models.DateTimeField() performer = models.ForeignKey(Performer, on_delete=models.CASCADE) links = models.ManyToManyField(Link) class Meta: ordering = ['event_date'] and I'm using this for serializers: class LinkSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Link fields = ['url', 'address'] class PerformerSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Performer fields = ['url', 'first_name', 'last_name', 'links'] class EventSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Event fields = ['url', 'performer', 'sale_date', 'event_date', 'links'] I thought about using ManyToManyField.limit_choices_to but I don't know … -
When "select_related" is needed?
In my project , Each candidate can takepart in some assessments,each assessment havs some tests, each test has some questions in it and candidates should answer the questions al last the scores is saved in question_score and test_score table I need to get some values of field and use them I write a method for question_result table, to get them but i dont know if it is needed to use select_related or not if it is needed how can i use it ? Assessment: class Assessment(BaseModel): company = models.ForeignKey( 'company.Company', on_delete=models.CASCADE, related_name='assessments', ) title = models.CharField(max_length=255) job_role = models.ForeignKey( JobRole, on_delete=models.PROTECT, related_name='assessments', blank=True, null=True, ) tests = models.ManyToManyField( 'exam.Test', related_name='assessments', blank=True, through='TestOfAssessment', ) candidates = models.ManyToManyField( 'user.User', related_name='taken_assessments', blank=True, through='candidate.Candidate' ) def __str__(self): return self.title Test: class Test(BaseModel): class DifficultyLevel(models.IntegerChoices): EASY = 1 MEDIUM = 2 HARD = 3 company = models.ForeignKey( 'company.Company', on_delete=models.PROTECT, related_name='tests', null=True, blank=True, ) questions = models.ManyToManyField( 'question.Question', related_name='tests', blank=True, help_text='Standard tests could have multiple questions.', ) level = models.IntegerField(default=1, choices=DifficultyLevel.choices) title = models.CharField(max_length=255) summary = models.TextField() def __str__(self): return self.title Question : class Question(BaseModel): company = models.ForeignKey( 'company.Company', on_delete=models.SET_NULL, null=True, blank=True, related_name='company_questions', ) question_text = models.TextField() def __str__(self): return truncatewords(self.question_text, 7) TestResult: class TestResult(BaseModel): candidate … -
How to check user is authorised or not in urls.py?
I'm using a library for creating several calls in the front end but I have a problem. The library does not have authenticated user control, which is a severe problem, and also I cannot change the library for some reason. Is there a way to control the user login in urls.py? urls.py from drf_auto_endpoint.router import router ... path('api/v1/', include(router.urls)), -
Django : Only display model items that match with for each category
Here are the models I've created class Jeu(models.Model): nom = models.CharField('Nom du jeu', max_length=100) logo = models.ImageField(blank=True) class Course(models.Model): jeu = models.ForeignKey(Jeu, verbose_name='Nom du jeu', on_delete=models.CASCADE) ligue = models.ForeignKey(Ligue, on_delete=models.CASCADE) circuit = models.ForeignKey(Circuit, on_delete=models.CASCADE) date_evenement = models.DateTimeField("Date de la course") Here is the view : def home(request): courses_a_venir = Course.objects.filter(date_evenement__gte = datetime.today()).order_by('date_evenement') courses_passees = Course.objects.filter(date_evenement__lt = datetime.today()).order_by('-date_evenement')[:3] jeux = Jeu.objects.all() return render(request, 'base_site/home.html', context={'title': 'Accueil', 'courses_a_venir': courses_a_venir, 'jeux': jeux, 'courses_passees': courses_passees}) And then here is the HTML code : {% for jeu in jeux %} <h3>{{ jeu.nom }}</h3><br> <div class="row row-cols-1 row-cols-md-3 g-4"> {% for course in courses_a_venir %} <div class="col"> <div class="card"> <!--<img src="..." class="card-img-top" alt="...">--> <div class="card-body"> <h5 class="card-title">{{ course.jeu }}</h5> <p class="card-text">This is a longer card with supporting text below as a natural lead-in to additional content. This content is a little bit longer.</p> </div> <div class="card-footer"> <small class="text-muted">{{ course.date_evenement }}</small> </div> </div> </div> {% endfor %} </div><br> {% endfor %} <br><br> What I'd like to do, is to display only the "Course" items that match with the name of the "Jeu". I know that I have to insert an if statement in the HTML code, and I tried different things, such as : {% for jeu … -
Bulk delete with many-to-many field django ORM
Hii i have 1 model named College and in the model i have document_files field which is Many2ManyField now when i delete College objects i have to delete document_files also Below is my code and Model, college_datas = College.objects.filter(id__in=[1,2]) if college_datas.exists(): for college in college_datas: college.document_files.all().delete() college.delete() class College(models.Model): name = models.CharField(null=True, blank=True) document_files = models.ManyToManyField(CollegeDocuments, through='CollegeDocumentsThrough') class Meta: verbose_name_plural = "College" Here i am using for loop which i think its time consuming so i am finding efficent way to bulk delete the college queryset and also removes the associated Many2ManyField data also. -
Pass request.session after function is executed
I have app, with authentication and when user logs out, I want a notification message to be displayed. My logout view looks like: def logout_view(request): logout(request) message = 'Logout successfull' request.session['message'] = message return redirect('index') And my index(the one i'm redirecting to) view looks like: def index(request): context = {} if request.session: message = request.session['message'] context['message'] = message return render(request, 'index.html', context) My index.html: {{ message }} Now logged in or out when i go to my index view I see message. When I click on button which logs me out I still see message. I want users only to be able to see messages if they logged out. I don't know if this is possible and if it isn't then you may tell me another way to pass context with redirect function. Thanks for help! -
Django accessing values returned in Array with POST
I'm trying to return form data as an array, my html looks like this : {% for f in factures %} <tbody> <td>{{ f.numero }}</td> <td>{{ f.date}}</td> <td>{{ f.sommeRestante }}</td> <td><input type="number" name="valeur[]" value=0></td> </tbody> {% endfor %} in my view when i execute print(request.POST) i get : <QueryDict: {'csrfmiddlewaretoken':[...], 'valeur[]': ['100', '0']}> how can i access the values '100' and '0'? i tried request.POST['valeur[]'][0] but it returns 0 (it's returning the default value set inside html) -
Inherited apollo entities resolving to null
I faced a problem with Apollo federation, which in the end I couldn't resolve. I dug through the documentation and issues, which I was able to google out here on stackoverflow and github. Let me introduce you to a context a little bit. I am using django, together with graphene and graphene-federation. For the sake of this example (and to simplify it as much as I can) let's say I have two graphql APIs combined together using Apollo federation. Let's call them car-service and race-service. These APIs expose two schemas, each has it's own URL. One is /internal/graphql/ and another one is /external/graphql/. For that reason I have separate graphene types for internal and external schemas. The purpose may not be clearly visible in my examples, but imagine I am resolving additional fields here and there and want them to be internal only. Let's assume for that The problem I faced is that my internal entities are not resolved by graphene at all. In urls.py (both APIs): urlpatterns = [ path( "internal/graphql/", csrf_exempt( GraphQLView.as_view( graphiql=True, schema=internal_schema, ) ), ), path( "external/graphql/", csrf_exempt( GraphQLView.as_view( graphiql=True, schema=external_schema, ) ), ), ] In external_schema.py of car-service: @key(fields="uuid") class CarTypeExternal(django_filters.DjangoObjectType): class Meta: model = … -
The included URLconf does not appear to have any patterns in it. Error in Django
The included URLconf '<module 'myapp.urls' from 'C:\\Users\\Hp\\Desktop\\Python\\Django Projects\\myproject\\myapp\\urls.py'>' does not appear to have any patterns in it. If you see the 'urlpatterns' variable with valid patterns in the file then the issue is probably caused by a circular import. This is the error that I am getting while building my django app. Here is urls.py from myapp - from django.urls import path from . import views urlpatterns=[ path('', views.index, name='index') ] Here is views.py - from django.shortcuts import render from django import HttpResponse # Create your views here. def index(request): return HttpResponse('<h1>Hey, Welcome</h1>') this is from urls.py from myproject- """myproject URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/4.1/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('myapp.urls')), ] -
Django links, url parameters overwriting
I've got django template with table/list with sorting action: <a href="?order_by=name">Name</a> and later I've got paging: <a href="?page=1">first</a> What I want to achieve is a link: http://localhost:8000/list/?page=3&order_by=name while - clicking a link, I can get either page or order_by. How to solve it? (for 2 and more parameters). -
Include Stripe in angular project
I am working on a website which uses angular for client and django for backend and I want to include stripe for payments. To configure stripe on the backend I have a microservice which runs on docker and accepts the following requests: one for creating a stripe customer another one for creating a payment I configured stripe on the client using the provided form as follows: export class PaymentComponent implements OnInit { paymentHandler:any = null; constructor(private checkoutService: CheckoutService) { } ngOnInit() { this.invokeStripe(); } initializePayment(amount: number) { const paymentHandler = (<any>window).StripeCheckout.configure({ key: 'pk_test_51MKU1wDo0NxQ0glB5HRAxUsR9MsY24POw3YHwIXnoMyFRyJ3cAV6FaErUeuEiWkGuWgAOoB3ILWXTgHA1CE9LTFr00WOT5U5vJ', locale: 'auto', token: function (stripeToken: any) { console.log(stripeToken); alert('Stripe token generated!'); paymentStripe(stripeToken); } }); const paymentStripe = (stripeTocken: any) => { this.checkoutService.makePayment(stripeTocken).subscribe((data:any) => { console.log(data) }) } paymentHandler.open({ name: 'Card Details', description: 'Introduce the information from your card', amount: amount * 100 }); } invokeStripe() { if(!window.document.getElementById('stripe-script')) { const script = window.document.createElement("script"); script.id = "stripe-script"; script.type = "text/javascript"; script.src = "https://checkout.stripe.com/checkout.js"; script.onload = () => { this.paymentHandler = (<any>window).StripeCheckout.configure({ key: 'pk_test_51MKU1wDo0NxQ0glB5HRAxUsR9MsY24POw3YHwIXnoMyFRyJ3cAV6FaErUeuEiWkGuWgAOoB3ILWXTgHA1CE9LTFr00WOT5U5vJ', locale: 'auto', token: function (stripeToken: any) { console.log(stripeToken) alert('Payment has been successfull!'); } }); } window.document.body.appendChild(script); } } } The makePayment method makes a request to the django server sending the stripe tocken. From the server … -
Convert case sensitives
i want to convert any new enter user name to lowercase and check if the user is exist or now and use iexact to login in capital or small where should determine the login uses small or capital forms.py class AddCompanyForm(forms.ModelForm): """ Add company model form """ name = forms.CharField(required=True) password = forms.CharField(widget=forms.PasswordInput()) logo = forms.ImageField(required=False) phone_number = forms.CharField(widget=forms.NumberInput()) label = forms.CharField(max_length=20) country = forms.ModelChoiceField(queryset=Country.objects.all()) city = forms.ModelChoiceField(queryset=City.objects.all()) area = forms.ModelChoiceField(queryset=Area.objects.all()) latitude = forms.CharField(max_length=50, required=False) longitude = forms.CharField(max_length=50, required=False) water_source = forms.ModelChoiceField(queryset=WaterSource.objects.all()) class Meta: model = User fields = ['name', 'username', 'email', 'password'] def __init__(self, *args, **kwargs): super(AddCompanyForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_tag = False self.layout = Layout(Row(Column('name', css_class='form-group col-md-6 mb-0'), Column('username', css_class='form-group col-md-6 mb-0'), css_class='form-row'), Row(Column('email', css_class='form-group col-md-6 mb-0'), Column('password', css_class='form-group col-md-6 mb-0'), css_class='form-row'), Row(Column('phone_number', css_class='form-group col-md-6 mb-0'), Column('logo', css_class='form-group col-md-6 mb-0'), css_class='form-row'), Row(Column('label', css_class='form-group col'), css_class='form-row'), Row(Column('country', css_class='form-group col'), Column('city', css_class='form-group col'), Column('area', css_class='form-group col'), css_class='form-row'), Row(Column('latitude', css_class='form-group col'), Column('longitude', css_class='form-group col'), css_class='form-row'), Row(Column('water_source', css_class='form-group col'), css_class='form-row')) self.helper.layout = self.layout views.py class Companies(LoginRequiredMixin, UserPassesTestMixin, FormView, ListView): """ Company add edit delete view search paginator """ model = Company template_name = 'company/index.html' form_class = AddCompanyForm success_url = reverse_lazy('companies:index') object_list = Company.objects.all() def form_valid(self, form): user, created = User.objects.get_or_create(username=form.cleaned_data['username'], … -
How to set 0, instead of null?
I have 'average_rating' field that takes values from field 'rates' and calculate average value. But when 'rates' field is empty, its shows null. views.py: class BooksView(viewsets.ModelViewSet): serializer_class = BooksSerializer queryset = BooksModel.objects.all() filter_backends = [filters.DjangoFilterBackend, filtersrest.SearchFilter, filtersrest.OrderingFilter,] filterset_class = Myfilter filterset_fields = ('genres','date',) search_fields = ['title'] def get_queryset(self): return BooksModel.objects.all().annotate(average_rating=models.ExpressionWrapper(Round(Avg('rates__rate'), 2), output_field=models.FloatField()), _sum_users_cart=Count('users__user')) In the output i have this: "id": 18, "authors": [ { "author": "Андрей курпатов" } ], "age": [], "tags": [], "users": [], "genres": [], "rates": [], "average_rating": null, "sum_users_cart": 0, "title": "Мозг и бизнес", "desc": "123", "url_photo": "https://s1.livelib.ru/boocover/1007572198/o/fde7/Andrej_Kurpatov__Mozg_i_biznes.jpeg", "is_published": true, "date": "Декабрь 29, 2022", "time": "20:20:02" And i need something like this: "id": 18, "authors": [ { "author": "Андрей курпатов" } ], "age": [], "tags": [], "users": [], "genres": [], "rates": [], "average_rating": 0, "sum_users_cart": 0, "title": "Мозг и бизнес", "desc": "123", "url_photo": "https://s1.livelib.ru/boocover/1007572198/o/fde7/Andrej_Kurpatov__Mozg_i_biznes.jpeg", "is_published": true, "date": "Декабрь 29, 2022", "time": "20:20:02" -
django model form is not saving
When i fill the form and save it, does not save but stays on the same form page. views.py def locker_form(request): form = LockerForm() if request.method == 'POST': form = LockerForm(request.POST) if form.is_valid(): form.save() messages.success(request, 'You have successfully added to your locker.') return redirect('user-page') print(form.errors) context = {'form': form} return render(request, 'pwdbank/locker_form.html', context) template {% extends 'pwdbank/base/main.html' %} {% load static %} {% block title %}User Account{% endblock %} <!-- content --> {% block content %} <h2 class="mt-5 user-page">YOUR LOCKER</h2> <div class="d-grid gap-2 d-md-flex justify-content-md-end mt-5"> <a class="btn btn-dark btn-sm" href="{% url 'locker-form' %}" role="button" >add to locker</a > </div> <hr /> <div class="row gx-4 row-gap-4 mb-5"> {% for info in saved_info %} <div class="col-lg-4"> <div id="saved-details"> <h4>Site Name - {{ info.site_name }}</h4> <p> Site Url - <a href="{{ info.site_url }}" target="_blank">{{ info.site_url }}</a> </p> <p>Created Date - {{ info.created_date }}</p> <hr /> <a class="btn btn-primary" href="{% url 'selected-savings' info.id %}" role="button" >View All</a > </div> </div> {% endfor %} </div> {% endblock %} forms.py class LockerForm(ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['site_name'].widget.attrs.update({ 'class': 'form-control', 'placeholder': 'site name', }) self.fields['site_url'].widget.attrs.update({ 'class': 'form-control', 'placeholder': 'site url', }) self.fields['username'].widget.attrs.update({ 'class': 'form-control', 'placeholder': 'username', }) self.fields['email'].widget.attrs.update({ 'class': 'form-control', 'placeholder': 'email', }) self.fields['password'].widget.attrs.update({ … -
Idle connections after update to django 4
We were using Django 3.2 and before the update everything was fine, but now, after the update to 4.0 we have a problem with too many open database connections. We getting errors like this: FATAL: remaining connection slots are reserved for non-replication superuser connections. We using CONN_MAX_AGE=60, but connections are sometimes not closed at all. Django 4.0.8 Daphne 4.0.0 channels & channels-redis 4.0.0 DB: postgresql 11/14 CONN_MAX_AGE=0 works well, but it is probably not the best option for efficient production. I also set the environment variable ASGI_THREADS=1, but nothing changed, we still have dozens of idle connections. I was also trying to replace Daphne with Gunicorn + Uvicorn and remove Django channels from the codebase, but nothing helped. I know that we can extend the number of available connections, but if old connections are not closing, then soon or later we will hit each limit. -
Creating a field thats connected with another in Django
The thing is that I'd like to create a field with a title that shows available titles depending on the artist's choice in the field above. For example, if a user selects "Drake" in the artist field, only the titles for that artist will be displayed in the title field. I'm completely stuck. Could you give me a hint how to solve the problem? I was wandering if I have to change my models.py by adding some kind of One-To-Many relationship or is there diffrent method? Webpage: enter image description here My models.py file: from django.db import models class SpotifyData(models.Model): title = models.CharField(max_length=60) rank = models.IntegerField() date = models.DateField() artist = models.CharField(max_length=60) region = models.CharField(max_length=20) chart = models.CharField(max_length=8) streams = models.IntegerField() class Meta: indexes = [ models.Index(fields=['title']), models.Index(fields=['rank']), models.Index(fields=['date']), models.Index(fields=['artist']), models.Index(fields=['region']), models.Index(fields=['chart']), ] My view.py file: import plotly.express as px import plotly.graph_objects as go from django.shortcuts import render from spotify_data.models import SpotifyData from spotify_data.charts import (make_song_rank_changes_chart, ) from typing import Any, Dict from django.views.generic import TemplateView from django.views.generic.list import ListView class HomeView(ListView): model = SpotifyData context_object_name = "record" def get_context_data(self, **kwargs: Any) -> Dict[str, Any]: context = super().get_context_data(**kwargs) context["records_all"] = SpotifyData.objects.all().count() return context class SongRankChangesChart(TemplateView): model = SpotifyData context_object_name = … -
Is it possible with Django to have a global view that is called on every page?
I was wondering if it is possible with Django to have a "global view" that is called on every page before all the initial views, for example to display additional information other than the user's information. All of this to avoid having to call a model on all of my views. To allow me to call it only once. -
`pytest-django` tables are emptied when used with `live_server`
I need prevent the tables from being emptied after each test, which is the default behavior when the tests are defined as below. Note: I populate the User table before running the tests, that's why the below works. class TestViews: @staticmethod def test1(django_user_model): assert django_user_model.objects.count() > 0 @staticmethod def test2(django_user_model): assert django_user_model.objects.count() > 0 result: ============================= test session starts ============================== collecting ... collected 2 items test_live_server.py::TestViews::test1 test_live_server.py::TestViews::test2 ============================== 2 passed in 7.86s =============================== Process finished with exit code 0 However, when live_server fixture is included: class TestViews: @staticmethod def test1(django_user_model, live_server): assert django_user_model.objects.count() > 0 @staticmethod def test2(django_user_model, live_server): assert django_user_model.objects.count() > 0 all model tables are emptied after each test. ============================= test session starts ============================== collecting ... collected 2 items test_live_server.py::TestViews::test1 test_live_server.py::TestViews::test2 PASSED [ 50%] FAILED [100%] tests/test_live_server.py:5 (TestViews.test2) 0 != 0 Expected :0 Actual :0 <Click to see difference> django_user_model = <class 'django.contrib.auth.models.User'> live_server = <LiveServer listening at http://localhost:61926> @staticmethod def test2(django_user_model, live_server): > assert django_user_model.objects.count() > 0 E AssertionError: assert 0 > 0 E + where 0 = <bound method BaseManager._get_queryset_methods.<locals>.create_method.<locals>.manager_method of <django.contrib.auth.models.UserManager object at 0x10d83fc90>>() E + where <bound method BaseManager._get_queryset_methods.<locals>.create_method.<locals>.manager_method of <django.contrib.auth.models.UserManager object at 0x10d83fc90>> = <django.contrib.auth.models.UserManager object at 0x10d83fc90>.count E + where <django.contrib.auth.models.UserManager object … -
Django AttributeError: module 'lib' has no attribute 'OpenSSL_add_all_algorithms'
The problem just appeared now. When I try to ./docker-compose.sh development up my django application, and after the ./manage.py collectstatic I see the error: => ERROR [6/6] RUN EXTRA_SETTINGS_URLS=/usr/src/app/dummy_external_settings.yml ./manage.py coll 3.2s ------ > [6/6] RUN EXTRA_SETTINGS_URLS=/usr/src/app/dummy_external_settings.yml ./manage.py collectstatic: #0 2.996 Traceback (most recent call last): #0 2.996 File "/usr/src/app/./manage.py", line 15, in <module> #0 2.997 execute_from_command_line(sys.argv) #0 2.998 File "/usr/local/lib/python3.9/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line #0 2.998 utility.execute() #0 2.998 File "/usr/local/lib/python3.9/site-packages/django/core/management/__init__.py", line 395, in execute #0 2.999 django.setup() #0 2.999 File "/usr/local/lib/python3.9/site-packages/django/__init__.py", line 24, in setup #0 3.000 apps.populate(settings.INSTALLED_APPS) #0 3.000 File "/usr/local/lib/python3.9/site-packages/django/apps/registry.py", line 91, in populate #0 3.000 app_config = AppConfig.create(entry) #0 3.000 File "/usr/local/lib/python3.9/site-packages/django/apps/config.py", line 224, in create #0 3.000 import_module(entry) #0 3.000 File "/usr/local/lib/python3.9/importlib/__init__.py", line 127, in import_module #0 3.001 return _bootstrap._gcd_import(name[level:], package, level) #0 3.001 File "<frozen importlib._bootstrap>", line 1030, in _gcd_import #0 3.002 File "<frozen importlib._bootstrap>", line 1007, in _find_and_load #0 3.002 File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked #0 3.002 File "<frozen importlib._bootstrap>", line 680, in _load_unlocked #0 3.003 File "<frozen importlib._bootstrap_external>", line 850, in exec_module #0 3.003 File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed #0 3.003 File "/usr/local/lib/python3.9/site-packages/ucamwebauth/__init__.py", line 7, in <module> #0 3.004 from OpenSSL.crypto import FILETYPE_PEM, load_certificate, verify #0 3.004 … -
"python manage.py makemigrations" command is not executing in a production environment
i have a live database and i have committed my models.py file in live server using git push. after login into the live server by using ssh (1) when i run python3 manage.py makemigrations i get this error: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 16, in main ) from exc ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? (2) when i run python manage.py makemigrations i get this error: File "manage.py", line 16 ) from exc ^ SyntaxError: invalid syntax How to run migrations in a production environment? Any help will be more valuable for me i have committed my models.py file using git push, then i have tried to run python manage.py makemigrations. i want my changes to be applied in production environment. -
Django How to use drf-yasg in class-base view which is parent of all other views to generate swagger docs?
I'm trying to add swagger to my project so drf-yasg was the option with @swagger_auto_schema, but I'm using a baseView view which is parent class view for all other views, thus all HTTP methods are written in baseView, so that children views doesn't need to implement these methods. the problem is that when I added @swagger_auto_schema to baseView methods it didn't see the child attributes but the baseView's attributes. The baseView: class BaseView(APIView): model = models.Model serializer_class = serializers.Serializer description = '' id = openapi.Parameter('id', in_=openapi.IN_QUERY, type=openapi.FORMAT_UUID) @swagger_auto_schema(manual_parameters=[id] ,responses={200: serializer_class},operation_description=description) def get(self, request, id=None, **kwargs): .... @swagger_auto_schema(request_body=serializer_class) def post(self, request, **kwargs): .... Then let's say I have this child view: class TestApi(BaseView): model = test description = 'This is test api' serializer_class = TestSerializer In this approach Swagger are show empty values for description and serializer_class because it doesn't see child values how to solve this without have to configure each view with HTTP methods and @swagger_auto_schema. thank you in advance. -
How to integrate VISA, MASTERCARD payment in my Django website project [closed]
I want to add this payment option to my website, how do i integrate the VISA, mastercard API to my website ,,, a step to step guide will be helpfulenter image description here -
How to create a form with fields for all instances of another model in Django?
I'm new to Django and I'm currently trying to create a form which should contain input fields for all existing objects of another model. Let's say that I would like to manage my supplies at home and make sure that I have enough of various products at diffect storage locations. For example, I would like to make sure that the storage locations bathroom and basement should always have plenty of the supply toilet paper. I don't need toilet paper in the location kitchen. The storage locations are pre-defined and available through a model. I couldn't find any way to create a form for Supply which dynamically generates form fields for MinimumQuantity objects based on all available StorageLocation objects. My form should look like this when creating the supply "toilet paper": supply name: <input example: "toilet paper"> minimum supply quantities bathroom - amount: <input example: 6> kitchen - amount: <input example: 0> basement - amount: <input example: 3> I'm a bit lost here and any hints would be much appreciated. This is my current code (shortened): models.py: class Supply(models.Model): name = models.CharField(max_length=50) class StorageLocation(models.Model): name = models.CharField(max_length=50) class MinimumQuantity(MinimumQuantity): storage_location = models.ForeignKey(StorageLocation, on_delete=models.PROTECT) supply = models.ForeignKey(Supply, on_delete=models.PROTECT) amount = models.IntegerField() views.py: … -
How to transfer date from form to django code (datepicker form to value (htmx))?
Good good evening! I have a standard datepicker form. I'm trying to figure out how to take the start and end date values. At least one date value from the form to use in various Python calculations. I have a data table where the data is sorted by date. And I need to take only certain rows from the given table. Having values in code. I need to somehow capture the date value and send this value to the code. Maybe there are some modern methods for taking data from an html or htmx form? I have been thinking for a long time how and what can be done in order to take data from a form and put it into code for some kind of calculation processing. I would be very grateful for any hints, help. models.py from django.db import models class Offer(models.Model): expiration_date = models.DateField(null=True) forms.py from django import forms from django.forms import ModelForm from .models import Offer class DateInput(forms.DateInput): input_type = 'date' class OfferForm(forms.ModelForm): class Meta: model = Offer fields = fields = '__all__' widgets = { 'expiration_date': DateInput(), } template <form action="" enctype="multipart/form-data" method="POST"> {% csrf_token %} {{ form|crispy }} <input type="submit" name="submit" value="Submit"> </form> -
Openedx Sometimes throws Internal Server error while calling “api/courseware/sequence” api
we have installed openedx with tutor and we are making one edu-tech platform where it is using openedx apis and maintaining its own database at the same time on another django-project in docker. our edu-tech django-project docker is communicating with openedx apis, and sometimes openedx returns 500 Internal Error while i calling /api/courseware/sequence/{{block_key}} api. then i traced the exception from tutor local lms logs, this is exception made by openedx-lms. NOTE: It happens only sometimes lms_1 | 2023-01-02 18:32:42,511 ERROR 19 [django.request] [user 42] [ip 172.18.0.14] log.py:224 - Internal Server Error: /api/courseware/sequence/block-v1:SOS+CSE-10+2022_r1+type@sequential+block@b9aad4acdd1f48259c3dfd92fdc216c2 lms_1 | Traceback (most recent call last): lms_1 | File "/openedx/venv/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner lms_1 | response = get_response(request) lms_1 | File "/openedx/venv/lib/python3.8/site-packages/django/core/handlers/base.py", line 181, in _get_response lms_1 | response = wrapped_callback(request, *callback_args, **callback_kwargs) lms_1 | File "/opt/pyenv/versions/3.8.12/lib/python3.8/contextlib.py", line 75, in inner lms_1 | return func(*args, **kwds) lms_1 | File "/openedx/venv/lib/python3.8/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view lms_1 | return view_func(*args, **kwargs) lms_1 | File "/openedx/venv/lib/python3.8/site-packages/django/views/generic/base.py", line 70, in view lms_1 | return self.dispatch(request, *args, **kwargs) lms_1 | File "/openedx/venv/lib/python3.8/site-packages/rest_framework/views.py", line 509, in dispatch lms_1 | response = self.handle_exception(exc) lms_1 | File "/openedx/venv/lib/python3.8/site-packages/rest_framework/views.py", line 506, in dispatch lms_1 | response = handler(request, *args, **kwargs) lms_1 | File "/openedx/edx-platform/./openedx/core/djangoapps/courseware_api/views.py", line …