Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django.core.exceptions.ImproperlyConfigured: Cannot import 'apps.AppName' after upgrade to django 4
I have upgraded a django app which worked ok for years on django 3 to 4.1.4 and now it fails an error. I anonymized the names. In settings I have: INSTALLED_APPS = [ 'foldername' I've figured out that I needed to add Meta.app_label, can someone confirm? So in foldername/apps.py I have now this: class MyApp(AppConfig): name = 'apps.MyApp' class Meta: app_label = 'apps.MyApp' I'm not sure if the name needs to be apps.MyApp or just MyApp. I also have seen others posted to have foldername.apps.MyApp and have put the full name into INSTALLED_APP= (not just project/folder name). I wonder what's right. Well, when I run: python manage.py, I get the stack trace: ....bla bla... strack trace ends with... django.core.exceptions.ImproperlyConfigured: Cannot import 'apps.MyApp'. Check that 'foldername.apps.MyApp.name' is correct. Can anyone spot the problem? I have spent so much time and don't know what to try. I've tried so much and rolled back again. Any feedback will make me happy at this point! :-) David Tried various combinations of: foldername.apps.MyApp (short, medium, long version) in name= in app_label, in moduleName and in INSTALLED_APPS. Tried adding in models.ypy: class BaseModel(models.Model): class Meta: abstract = True # specify this model as an Abstract Model … -
html page working independently without views.py in django
I'm developing a project in django for the 1st time. I have created a html file 'templates/app/token.html' ` <form action="{% url 'token' %}" method="post" name="portalForm" onsubmit="return validatePortalForm();"> <h3>Generate a new token</h3> <table> <tr><td><b>Select Portal Name</b></td><br></tr> <td><select name="portal"> <option value=""> Please select Portal name </option> {% for option in portalname %} <option value={{option}} >{{option}}</option> {% endfor %} </select></td> <td><input type="submit" value="Generate token"></td> </table> </form> <script type="text/javascript"> function validatePortalForm() { let portal = document.portalForm.portal.value; if (portal === null || portal === "") { alert("Select a portal from the list"); return false; } } </script> and added a function in '**views.py**'def token: context = { 'portalnames':portalList} return render(request,'PIM/token.html',context) ` Here there is an ambiguity in data. I'm passing 'portalnames' in views function and trying to access 'portalname' in html page. But it is working and even after tried removing the token function, the html page is not affected and it is able to produce portalnames option in html successfully. Note: I'm using the same 'portalname' in other view and other html page. So will this html page got affected by that or how is it able to work even after removing the views function -
How to query in one-to-many relationship in Django
Let's assume I have the following models: class Team(models.Model): name = CharField(max_length=100) class Employee(models.Model): name = CharField(max_length=100) profession = CharField(max_length=100) team = models.ForeignKey(Team) I have one team in the database and four employees with the following professions: developer, tester, tester, tester. I need to filter for teams that have at least one employee with a given profession. E. g. the expected inputs and the corresponding outputs would be: tester -> [team1] developer -> [team1] devops -> [] My attempt based on the documentation is: queryset = Team.filter(employee__profession='given_proffesion') The input and output for my code are: tester -> [] developer -> [team1] devops -> [] Interestingly, when I set the first employee to be a tester, it finds the result only if the input is 'tester', so it checks only one related entry. What am I doing wrong? -
DRF getting unneccessary data while querying
I have Category model and am querying through this model to list all categories. Im using django-silk to see how many queries got executed. It shows, category and Accounts. Accounts model has no relation with Catgeory. Below are the results. It shows accounts on the list of queries Im not requesting any data from Accounts Model. #Views.py class ListCategory(generics.ListAPIView): queryset = Category.objects.all() serializer_class = CategorySerializer #Serializer.py class CategorySerializer(ModelSerializer): class Meta: model = Category fields = [ "category_name", "slug", "title", "description", "category_image", ] #Models.py class Category(models.Model): category_name = models.CharField(max_length=15, unique=True) slug = models.SlugField(max_length=100, unique=True) title = models.CharField(max_length=25) description = models.CharField(max_length=300) category_image = models.ImageField(upload_to="photos/category") class Meta: verbose_name_plural = "Category" def __str__(self): return self.category_name It's not only limited to this API, In all API it shows account. I have exactly no idea why this happens. -
'NoneType' object is not callable error when I submite a form Django
When I press the submite button of my form, an error is displayed : 'NoneType' object is not callable error. The form appears correctly, but when posting I get this error error Globally, I'm trying to have two forms in one (by using get_context_data) for an update page where I can modify bio, user names.... Template : {% extends 'main.html' %} {% load crispy_forms_tags %} {% block title %} Register {% endblock %} {% block body_content %} <h1>Update your profile</h1> <form method="POST" action="" enctype="multipart/form-data"> {% csrf_token %} <fieldset class=form-group"> {{ u_form|crispy }} {{ p_form|crispy }} </fieldset> <div class=form-group"> <button class="btn" type="submit">Update</button> </div> </form> {% endblock %} View : from django.contrib.auth.models import User from django.contrib.auth.mixins import LoginRequiredMixin from django.views.generic import FormView from django.urls import reverse from users.forms.forms import UserUpdateForm, ProfileUpdateForm from users.models.users import Profile from django.contrib import messages class UpdateUserView(LoginRequiredMixin, FormView): template_name = 'base/profile.html' model = User, Profile redirect_authenticated_user = True form_classes = {'u_form': UserUpdateForm, 'p_form': ProfileUpdateForm} def form_valid(self, form): if self.request.method == 'POST': u_form = UserUpdateForm(self.request.user, self.request.POST, self.request.FILES, instance=self.request.user) p_form = ProfileUpdateForm(self.request.user.profile, self.request.POST, self.request.FILES, instance=self.request.user.profile) if u_form is not None and p_form is not None and u_form.is_valid() and p_form.is_valid(): u_form.save() p_form.save() messages.success(self.request, f'Your account has been updated!') return super().form_valid(form) else: … -
Google Calendar API authentication in Python working on localhost but not working in Production
I have checked my redirect URI's, they are working perfectly in localhost but in production on button click instead of going to the authentication page it redirects to the same page without displaying any error. I tried to create a try except block to log any errors but even the log file was empty. def create_workshop(request): try: flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file( 'static//client_secret_xxxx.json', scopes=['https://www.googleapis.com/auth/calendar.readonly','https://www.googleapis.com/auth/calendar']) flow.redirect_uri = CALENDAR_REDIRECT_URI authorization_url, state = flow.authorization_url( access_type='offline', include_granted_scopes='true') return redirect(authorization_url) except Exception as e: logging.basicConfig(filename="testing.log", format='%(asctime)s %(message)s', filemode='w') logger = logging.getLogger() logger.setLevel(logging.DEBUG) logger.error(e) I have looked at all the solutions, and it displayed the same code as solution but I'm not sure why isn't it redirecting. -
Django: why is django form not submitting when trying to update a model?
I am trying to update some models in my code, there is Student model and a Marks model, the Marks have a Fkey to the Student and i am using inline formset to add more dynamic forms to the marks model, i have written the logic to create student and mark from one view, when trying to update the model, the page just refreshes and nothing happens. when i hit f5 on my keyboard to refresh the page, it shows this: and nothing gets updated in the model. def edit(request, id): student = Student.objects.get(id=id) marks = Marks.objects.filter(student=student) context = {} MarksFormset = modelformset_factory(Marks, form=MarksForm) form = StudentForm(request.POST or None, instance=student) formset = MarksFormset(request.POST or None, queryset= Marks.objects.filter(student=student), prefix='marks') if request.method == "POST": if form.is_valid() and formset.is_valid(): try: with transaction.atomic(): student = form.save(commit=False) student.save() for mark in formset: data = mark.save(commit=False) data.student = student data.save() except IntegrityError: print("Error Encountered") return redirect('multi_forms:list') context['formset'] = formset context['form'] = form return render(request, 'multi_forms/create.html', context) -
I'm a beginner and I didn't understand about get_absolute_url [closed]
I'm very new on django I was follow the guide on the link below https://www.geeksforgeeks.org/createview-class-based-views-django/ after submit button on page "geeksmodel_form.html", I get error get_absolute_url. I know this article guideline code isn't fully completed but I already try to solve by myself but I can't. Please help me to understand this. Thank you. -
createListing() missing 1 required positional argument: 'request'
so Im still learing to code and looking for some help. Im building realestate website and im working on my CRUD functionality. When im trying to render out the basic structure of the CRUD admin page im getting an error of " createListing() missing 1 required positional argument: 'request' " Its should take in two arguments to show the web page but i dont know what arguments those are. views.py def createListing(request): form = createListing() context = {'form': form} return render(request, 'accounts/create_listing.html') forms.py from django.forms import ModelForm from listings.models import Listing class listingForm(ModelForm): class Meta: model = Listing fields = '__all__' models.py from django.db import models from datetime import datetime from realtors.models import Realtor class Listing(models.Model): realtor = models.ForeignKey(Realtor, on_delete=models.DO_NOTHING) title = models.CharField(max_length=200) address = models.CharField(max_length=200) city = models.CharField(max_length=100) state = models.CharField(max_length=100) zipcode = models.CharField(max_length=20) description = models.TextField(blank=True) price = models.IntegerField() bedrooms = models.IntegerField() bathrooms = models.DecimalField(max_digits=2, decimal_places=1) garage = models.IntegerField(default=0) sqft = models.IntegerField() photo_main = models.ImageField(upload_to='photos/%Y/%m/%d/') photo_1 = models.ImageField(upload_to='photos/%Y/%m/%d/', blank=True) photo_2 = models.ImageField(upload_to='photos/%Y/%m/%d/', blank=True) photo_3 = models.ImageField(upload_to='photos/%Y/%m/%d/', blank=True) photo_4 = models.ImageField(upload_to='photos/%Y/%m/%d/', blank=True) photo_5 = models.ImageField(upload_to='photos/%Y/%m/%d/', blank=True) photo_6 = models.ImageField(upload_to='photos/%Y/%m/%d/', blank=True) is_published = models.BooleanField(default=True) list_date = models.DateTimeField(default=datetime.now, blank=True) def __str__(self): return self.title create_listing.html {% extends 'base.html' %} {% block content … -
Retrieving Stripe metadata and process it
I am sending cart data from the cookies to Stripe and retrieving it, but I am unable to find a solution to process it correctly. Please help! I am learning Django and wanted to save the cart items of non-logged users into the cookies and send it to Stripe, as Metadata. From there retrieve it and if the checkout is completed to process the order, but I am unsuccessful to process the data that is retrieved to be able to save the order. Stripe Checkout Session: @csrf_exempt def create_checkout_session(request): stripe.api_key = settings.STRIPE_SECRET_KEY domain_url = 'http://localhost:8000/checkout/' if request.user.is_authenticated: customer = request.user.customer else: data = json.loads(request.body) total = data['form']['total'].replace('.', '') email = data['form']['email'] first_name = data['form']['first_name'] last_name = data['form']['last_name'] customer, created = Customer.objects.get_or_create( email=email ) customer.first_name = first_name customer.last_name = last_name customer.save() cart_info = cart_details(request) cart_items = cart_info['cart_items'] order = cart_info['order'] items = cart_info['items'] print(items) if request.method == 'GET': checkout_session = stripe.checkout.Session.create( shipping_address_collection={ "allowed_countries": ["US", "CA", "NL", "GB"] }, client_reference_id=request.user.id, customer_email=request.user.email, success_url=domain_url + 'success?session_id={CHECKOUT_SESSION_ID}', cancel_url=domain_url + 'cancelled/', payment_method_types=['card'], mode='payment', line_items=[ { 'name': 'Kenpachi Katana Store', 'quantity': 1, 'currency': 'usd', 'amount': int(order.get_cart_total*100), } ] ) return JsonResponse({'sessionId': checkout_session['id']}) else: checkout_session = stripe.checkout.Session.create( shipping_address_collection={ "allowed_countries": ["US", "CA", "NL"] }, **metadata=[items]**, client_reference_id=customer.id, customer_email=email, success_url=domain_url + … -
console error output not showing the line with the error
Please I really need help, I do not know what could be going on in my program, initialy if there was an error it just simply point where an error is in my code e.g. Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\software_developer\AppData\Local\Programs\Python\Python38\lib\threading.py", line 932, in _bootstrap_inner self.run() File "C:\Users\software_developer\AppData\Local\Programs\Python\Python38\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "C:\python_files\venv\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\python_files\venv\lib\site-packages\channels\management\commands\runserver.py", line 75, in inner_run self.check(display_num_errors=True) File "C:\python_files\venv\lib\site-packages\django\core\management\base.py", line 392, in check all_issues = checks.run_checks( File "C:\python_files\venv\lib\site-packages\django\core\checks\registry.py", line 70, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "C:\python_files\venv\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config return check_resolver(resolver) File "C:\python_files\venv\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver return check_method() File "C:\python_files\venv\lib\site-packages\django\urls\resolvers.py", line 408, in check for pattern in self.url_patterns: File "C:\python_files\venv\lib\site-packages\django\utils\functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\python_files\venv\lib\site-packages\django\urls\resolvers.py", line 589, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "C:\python_files\venv\lib\site-packages\django\utils\functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\python_files\venv\lib\site-packages\django\urls\resolvers.py", line 582, in urlconf_module return import_module(self.urlconf_name) File "C:\Users\software_developer\AppData\Local\Programs\Python\Python38\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen … -
how to get data from choice field of form from html to views in django
i am not able to fetch or get data from html post request to form i want to give selection option to use to choose any single data and i want that data in my database my html file <div class="col-md-4"> <div class="form-group"> <label>Gender</label> <form action="{% url 'my_view' %}" method="POST"> {% csrf_token %} <select name="gender" class="selectpicker" data-title="Select Gender" data-style="btn-default btn-block" data-menu-style="dropdown-blue"> {% for x,y in form.fields.gender.choices %} <option value="{{ x }}"{% if form.fields.gender.value == x %} selected{% endif %}>{{ y }}</option> {% endfor %} </select> <button type="submit">submit</button> </form> </div> </div> my forms.py class UserForm(forms.ModelForm): def __init__(self, *args, **kargs): super(UserForm, self).__init__(*args, **kargs) class Meta: model = models.User fields = '__all__' my models.py gender = ( ('x', 'filled'), ('y', 'notfilled'), ) class User(models.Model): lat = models.DecimalField(('Latitude'), max_digits=10, decimal_places=8,null=True) lng = models.DecimalField(('Longitude'), max_digits=11, decimal_places=8,null=True) gender = models.CharField(max_length=60, blank=True, default='',choices=gender,verbose_name="gender") answer me what to write in views.py please my views.py def bins(request): form = UserForm() return render(request ,'bins.html',{'form': form}) def my_view(request): form = UserForm(request.POST or None) answer = form.cleaned_data.get('gender') if form.is_valid() else '' return redirect('/') -
ElastiCache Redis, Django celery, how to on EC2 instance AWS?
So I have set up redis with django celery on aws so that when I run the task manually eg: $ python manage.py shell from myapp.tasks import my_task it works fine. Now of course I want to run that on deploy and perhaps making sure they always run especially on deploy . But when I start the beat from ym ec2 the same way I do locally it starts but triggers are not happening . why exactly I would like to run those at deploy for example : command : /var/app/current/celery -A project worker -l info command : /var/app/current/celery -A project beat -l info -
Best way to grant access to users after they purchase something
I am building an e-learning platform using Django and as part of the platform one can buy online courses. For each course I have a manytomany field of users and every time a user purchases a course I add them to the field. Is this a good approach to give users access to the course? What would your approach be in this case? -
Distributing static package data as separate Python package?
My Python + Django application has quite a lot of CSS/JS dependencies, which change quite seldom. I was thinking about separating the two. My package with the dependencies takes 2x more space than without them (with deps 8.7 MB, without deps about 4.3 MB). Those dependencies are crucial to run the application and I would not exactly like the idea of building them on a production server, as it introduces another possible point of failure. Also, having a comfort of pip install or even pipx install is a valuable thing for an application, so I thought about making them a dependency of the "main" app package. Are there any official, sanctioned methods to build separate static data package for an app? Or, are there any other sensible ways of building such data? I was looking into building another, separate static-data package with Poetry, but it does not look like an easy task. I would also like to build that data-package from the same source tree, as Django already collects the static files for me. In my Django app I already use an approach similar to django-yarnpkg , which is I keep a list of yarn-installable packages and use a custom … -
Django queryset fuzzy search
I hope you can help me - I am not sure what to search to find the answer. I have a Django queryset returned to my HTML template. I want to have an autocomplete search based on that queryset. So if I have 'Banana', 'Apple' and 'Orange' as my query results, when someone types Or it should show Orange as an example. How would I even go about doing that? Can javascript interact with the queryset objects or is there a simple way to do it? Thanks for any advice -
django-filters form not showing(only the submit button does)
template <form method="get"> {{ filter.form.as_p }} <input type="submit" value="Press" /> </form> {% for obj in filter.qs %} {{ obj.WorkType }} - ${{ gender.price }}<br /> {% endfor %} views @login_required(login_url='login') def ListingsPage(request): review = Review.objects.all() filter = Profilefilter(request.GET, queryset=Profile.objects.all()) context = {"profile":profile,"review":review,"filter":filter} return render(request,"base/Listings.html",context) filters.py import django_filters from .models import Profile class Profilefilter(django_filters.FilterSet): name = django_filters.CharFilter(lookup_expr='iexact') class Meta: model = Profile fields = ['WorkType', 'gender'] It is supposed to be showing the filters but doesn't render anything, only the submit button shows up. I think it is something to do with passing the context, not sure tho -
Reverse for 'exam-detail' with arguments '(4,)' not found. 1 pattern(s) tried
When rendering a template django returns this error: NoReverseMatch at /user/admin/package/1/ Reverse for 'exam-detail' with arguments '(4,)' not found. 1 pattern(s) tried: ['user/(admin|staff)/exam/(?P<pk>[0-9]+)/$'] html file: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> {{object.name}} {{object.price}} {% for exam in object.exams.all %} <p><a href="{% url 'exam-detail' exam.pk %}">{{exam.name}}</a></p> {% endfor %} </body> </html> urls.py: re_path(r'^(admin|staff)/exam/(?P<pk>[0-9]+)/$',ExamDetail.as_view(),name='exam-detail'), When I change the path to the following the error is resolved: path('admin/exam/<int:pk>/',ExamDetail.as_view(),name="exam-detail"), -
data:image/png;base64 not work but I don't know what to replace it with
def get_image(): buffer=BytesIO() plt.savefig(buffer, format='png') buffer.seek(0) graph=base64.b64encode(buffer.getvalue()).decode() buffer.close() return graph def chart_select_views(request): graph=None error_message=None; df=None; if purpd.shape[0]>0: ... df['date']=df['date'].apply(lambda x:x.strftime('%d-%m-%Y')) df2=df.groupby('date' ,as_index=False)['total_price'].agg('sum') if chart_type!='': .. graph=get_simple_plot(chart_type,x=df2['date'],y=df2['total_price'],data=df) else: error_message='selecte date'; else: error_message='no data'; context={ 'error_message':error_message, 'graph': graph, } return render(request, 'Product/index.html',context) <img src="data:image/png;base64, {{graph|safe}}"> the image is not displayed I tried with another format. I want to display the data in png format of the data that comes from my database of course in this part I do not want to use js even if it is very easy -
Grey box rendered in place of icon on Google Maps
I'm using the Google Maps API in my Django project to display the current users location and this is my first time using maps. The map loads fine, but there's a grey box in place of where the map marker should be(Just over the Au in Australia): // Initialize and add the map function initMap() { // The location of Uluru const uluru = { lat: -25.344, lng: 131.031 }; // The map, centered at Uluru const map = new google.maps.Map(document.getElementById("map"), { zoom: 4, center: uluru, }); // The marker, positioned at Uluru const marker = new google.maps.Marker({ position: uluru, map: map, }); } window.initMap = initMap; I've customized the icon to display a different image and only the size of the grey box changed, there are no errors in the console. Any help would be appreciated! -
is there a way to provide custom names for my drf-yasg endpoints?
i am implementing an API using django-rest-framework and using drf-yasg to document and name my endpoints every post method ends with create i tried searching through the documentation and i cant find a way to do it -
How do I remove or change the 'Unknown' option from the dropdown of a BooleanField filter created using django_filters?
In my models.py, there's a BooleanField named cash: class Realization(models.Model): patient=models.ForeignKey(Patient, on_delete=CASCADE) patient_type=models.ForeignKey(PatientType, on_delete=CASCADE, default=None) cash=models.BooleanField(default=False) amount_received=models.DecimalField(max_digits=10, decimal_places=2, default=0) And I'm using this model as a ForeignKey in another model IPDReport: class IpdReport(models.Model): patient=models.ForeignKey(Patient, on_delete=CASCADE) package=models.ForeignKey(Package, on_delete=CASCADE, blank=True, null=True) approvedpackage=models.ForeignKey(ApprovedPackage, on_delete=CASCADE, blank=True, null=True) ctscan=models.ForeignKey(CTScan, on_delete=CASCADE, blank=True, null=True) radiations=models.ForeignKey(Radiations, on_delete=CASCADE, blank=True, null=True) discharge=models.ForeignKey(Discharge, on_delete=CASCADE, blank=True, null=True) realization=models.ForeignKey(Realization, on_delete=CASCADE, blank=True, null=True) lockdata=models.ForeignKey(LockData, on_delete=CASCADE, blank=True, null=True) I wanted to create a filter for the IPDReport data, including Realization's cash field, so I used this way: class IpdFilters(django_filters.FilterSet): patient__name=django_filters.CharFilter(widget=forms.TextInput(attrs={'class':'form-control'}), lookup_expr='icontains', label='Name') ctscan__rt_number=django_filters.CharFilter(widget=forms.TextInput(attrs={'class':'form-control'}), lookup_expr='icontains', label='RT Number') package__patient_type__patient_type=django_filters.CharFilter(widget=forms.TextInput(attrs={'class':'form-control'}), lookup_expr='icontains', label='Type of Patient') realization__amount_received__gt=django_filters.NumberFilter(widget=forms.NumberInput(attrs={'class':'form-control'}), field_name='realization__amount_received', lookup_expr='gt', label='Min. Amount Received') realization__amount_received__lt=django_filters.NumberFilter(widget=forms.NumberInput(attrs={'class':'form-control'}), field_name='realization__amount_received', lookup_expr='lt', label='Max. Amount Received') from_date=django_filters.DateFilter(widget=forms.DateInput(attrs={'id': 'from_doa', 'class':'form-control'}), field_name='package__date_of_admission', label='From - Date of Admission ', lookup_expr='gte') to_date=django_filters.DateFilter(widget=forms.DateInput(attrs={'id': 'to_doa', 'class':'form-control'}), field_name='package__date_of_admission', label='To - Date of Admission ', lookup_expr='lte') from_date_bill=django_filters.DateFilter(widget=forms.DateInput(attrs={'id': 'from_bd', 'class':'form-control'}), field_name='realization__billing_month', label='From - Date of Billing ', lookup_expr='gte') to_date_bill=django_filters.DateFilter(widget=forms.DateInput(attrs={'id': 'to_bd', 'class':'form-control'}), field_name='realization__billing_month', label='To - Date of Billing ', lookup_expr='lte') class Meta: model=IpdReport fields={ 'realization__cash':['exact'] } Now on the IPDReport page in my app, the field renders like below: In the dropdown, the default option shows as Unknown. Is there any way I can change or remove that completely? Also, how can I add an HTML class attribute … -
Integrity error thrown even when parent model has values
I am getting this integrity error ORA-02091: transaction rolled back ORA-02291: integrity constraint (SYSTEM.MAIN_PAIN_ARTIST_ID_4D007402_F) violated - parent key not found even when parent model contain the values passed to foreign keys in the child table here are my models class Artist(models.Model): id = models.PositiveSmallIntegerField(primary_key=True , unique = True) name = models.CharField(max_length=200) country = models.CharField(max_length=200) year_of_birth = models.PositiveSmallIntegerField() year_of_death = models.PositiveSmallIntegerField(null=True) def __str__(self) -> str: return self.name class Owner(models.Model): id = models.PositiveSmallIntegerField(primary_key=True , unique = True) name = models.CharField(max_length=200) address = models.CharField(max_length=200) city = models.CharField(max_length=10) def __str__(self) -> str: return self.name class Painting(models.Model): id = models.PositiveSmallIntegerField(primary_key=True , unique = True) title = models.CharField(max_length=200) theme = models.CharField(max_length=200) rent = models.FloatField() owner_id = models.ForeignKey(Owner , on_delete=models.CASCADE , null= False , blank = False) artist_id = models.ForeignKey(Artist , on_delete=models.CASCADE , null=False ,blank = False) def __str__(self) -> str: return self.title Here is my views.py file def create_painting(response): if response.method == "POST": painting_form = createNewPainting(response.POST) if painting_form.is_valid(): i = painting_form.cleaned_data["id"] ttl = painting_form.cleaned_data["title"] thm = painting_form.cleaned_data["theme"] rent = painting_form.cleaned_data["rent"] own_id= int(painting_form.cleaned_data["owner_id"]) art_id= int(painting_form.cleaned_data["artist_id"]) answers = Painting.objects.filter(id=i) if not answers: with connection.cursor() as cursor: try: r = cursor.execute( f"INSERT INTO main_painting VALUES ({i} ,'{ttl}' , '{thm}' , {rent} , {own_id} , {art_id});") return HttpResponseRedirect("paintings/%s" %i) except … -
How to update a global variable from a function in Python?
I want to update an empty string value which is declared globally. I want to update that variable from inside a function. Following id the code: import jwt import os from dotenv import load_dotenv load_dotenv() from rest_framework.exceptions import APIException jwtPrivateKey = (os.environ.get('SECRET_KEY')) # VARIABLE DECALRED HERE token_value = "" def authenticate(auth_header_value): try: if auth_header_value is not None: if len(auth_header_value.split(" ", 1)) == 2: authmeth, auth = auth_header_value.split( " ", 1) if authmeth.lower() != "bearer" and authmeth.lower() != "basic": return TokenNotBearer() # WANT TO UPDATE THE VALUE OF token_value HERE token_value= jwt.decode( jwt=auth, key=jwtPrivateKey, algorithms=['HS256', ]) return TokenVerified() else: return TokenNotBearer() else: return TokenNotProvided() except (TokenExpiredOrInvalid, jwt.DecodeError): return TokenExpiredOrInvalid() # when token is expired or invalid class TokenExpiredOrInvalid(APIException): status_code = 403 default_detail = "Invalid/Expired token" default_code = "forbidden" # when token is not provided class TokenNotProvided(APIException): status_code = 401 default_detail = "Access denied. Authorization token must be provided" default_code = "unauthorized" # when the token is not provided in the bearer class TokenNotBearer(APIException): status_code = 401 default_detail = "Access denied. Authorization token must be Bearer [token]" default_code = "token not bearer" # when the token is valid class TokenVerified(): status_code = 200 default_detail = "Token verified Successfully" default_code = "verified" # … -
Slow loading Django Admin change/add
The Loading time is too much for this particular model in admin panel.I know it is because I have too many values in Foreign Fields (field with 20k+ records each) which takes too much time to load on client side. Is there a way to optimise this? below is my code and screenshot of loadtime, Loading Time Models: class Alert(BaseModelCompleteUserTimestamps): type = models.ForeignKey(to=AlertType, on_delete=models.CASCADE, verbose_name="Type") device = models.ForeignKey(Device, on_delete=models.CASCADE, related_name="alert_device") device_event = models.ForeignKey("dm_detection.VIDSDetection", on_delete=models.CASCADE, null=True, blank=True, related_name="device_event") anpr_event = models.ForeignKey("dm_detection.VSDSDetection", on_delete=models.CASCADE, null=True, blank=True, related_name="anpr_event") ecb_event = models.ForeignKey("dm_detection.ECBDetection", on_delete=models.CASCADE, null=True, blank=True, related_name="ecb_event") hr_only = models.IntegerField(null=True, blank=True) # acknowledged is_acknowledged = models.BooleanField(default=False, verbose_name="Acknowledged") acknowledged_at = models.DateTimeField(blank=True, null=True) acknowledged_by = models.ForeignKey(to=User, on_delete=models.CASCADE, null=True, blank=True, related_name="alert_acknowledged_by") # resolved is_resolved = models.BooleanField(default=False, verbose_name="Resolved") resolved_at = models.DateTimeField(blank=True, null=True) resolved_by = models.ForeignKey(to=User, on_delete=models.CASCADE, null=True, blank=True, status = models.ForeignKey(to=TicketStatus, on_delete=models.DO_NOTHING, default=1) Admin.py @admin.register(Alert) class AlertModelAdmin(BaseModelCompleteUserTimestampsAdmin): form = AlertEditForm fields = ('type', 'device', 'device_event', 'status', 'hr_only', 'is_acknowledged', 'acknowledged_at', 'acknowledged_by', 'is_resolved', 'resolved_at', 'resolved_by', 'anpr_event', 'created_at', 'updated_at', 'OD_vehicle_number' ) Forms.py class AlertEditForm(forms.ModelForm): status = forms.ModelChoiceField(queryset=TicketStatus.objects.filter(is_for_alert=True)) device_event = forms.ModelChoiceField(queryset=VIDSDetection.objects.all()) anpr_event = forms.ModelChoiceField(queryset=VSDSDetection.objects.all()) acknowledged_by = forms.ModelChoiceField(queryset=User.objects.all()) resolved_by = forms.ModelChoiceField(queryset=User.objects.all()) class Meta: model = Alert fields = '__all__'