Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Getting "TypeError: Object of type IFDRational is not JSON serializable" while trying to json.dumps EXIF info
I'm trying to extract EXIF information from an image and store it as a JSONField. It works well for some image types but not for others. Below my code: image_open = Image.open(self.image) image_open.verify() image_getexif = image_open.getexif() if image_getexif: exif = { ExifTags.TAGS[k]: v for k, v in image_getexif.items() if k in ExifTags.TAGS and type(v) is not bytes] } print(json.dumps(exif, indent=4)) I'm getting TypeError: Object of type IFDRational is not JSON serializable when trying to json.dumps(). When dumping the exif dict I notice it is pretty standard so not sure what this is about. {'ResolutionUnit': 2, 'ExifOffset': 204, 'Make': 'Apple', 'Model': 'iPhone 13', 'Software': '15.3.1', 'Orientation': 1, 'DateTime': '2022:03:04 17:35:15', 'XResolution': 72.0, 'YResolution': 72.0, 'HostComputer': 'iPhone 13'} -
Django - Link search bar with autocomplete to item detail page as a result of the search
I have a search bar with autocomplete but I don't know how to link it to the search bar action. Once the user selects one of the items from the autocomplete list, I want to move to the detail.html of that item (using the slug). How do I nest the autocomplete function into the search function? Right now I have a search function which takes the term searched, creates a list of potential item candidates with their url and shows them in the following search_result.html. I want to avoid this step and go straight from the search bar with autocomplete to the detail page of the item. See below the functions. Any ideas on how to do this? Sorry if this is too basic :/ def search(request): if request.method == "POST": searched = request.POST['keyword'] search_vector = SearchVector("descr") search_query = SearchQuery(searched) item = Object.objects.annotate(search=search_vector, rank=SearchRank( search_vector, search_query)).filter(search=search_query).order_by("text_len","-rank") return render(request, 'search_result.html', {'searched':searched, 'item':item}) else: return render(request, 'home.html', {}) def autocomplete(request): if 'term' in request.GET: search_vector = SearchVector("descr") search_query = SearchQuery(request.GET['term']) qs = item = Object.objects.annotate(search=search_vector, rank=SearchRank( search_vector, search_query)).filter(search=search_query).order_by("text_len","-rank") titles = list() # source at the autocomplete in the JQuery expects an url with a list of potential items. for i in qs: … -
Problem converting LDAPS connection from ldap3 to django_auth_ldap in Python Django
Problem getting LDAPS user authentication in Django Works with ldap3 module When I run the code below, the response indicates that the LDAP server was able to connect and find a user with the common name "MyUser" in the "ou=grouping,dc=example,dc=ad" search base. import ldap3 #Set up LDAP connection and bind server = ldap3.Server('ldaps://ad.example.com', use_ssl=True) conn = ldap3.Connection(server, 'cn=crunchy-test,cn=users,dc=example,dc=ad', 'PASSWORD') conn.bind() #Check if bind was successful if conn.bound: print('Successfully bound to LDAP server') else: print('Failed to bind to LDAP server') #Specify search base and search filter search_base = 'ou=grouping,dc=example,dc=ad' search_filter = "(cn=MyUser)" #Perform search and specify search scope as subtree conn.search(search_base, search_filter, search_scope=ldap3.SUBTREE, attributes=['givenName', 'sn', 'mail']) #Iterate over search results for entry in conn.response: print(entry['dn'], entry['attributes']['givenName'], entry['attributes']['sn'], entry['attributes']['mail']) #Unbind from LDAP server conn.unbind() Output Successfully bound to LDAP server <br/> CN=MyUser,OU=userGroup,OU=Grouping,DC=example,DC=ad My User My.User@email.com Does not work with from django_auth_ldap , ldap module #Configuration for LDAP login authentication - https://django-auth-ldap.readthedocs.io/en/latest/authentication.html #Baseline configuration. AUTH_LDAP_SERVER_URI = "ldaps://ad.example.com" AUTHENTICATION_BACKENDS = ('django_auth_ldap.backend.LDAPBackend', 'django.contrib.auth.backends.ModelBackend', ) #--------test search bind------ AUTH_LDAP_BIND_DN = "cn=crunchy-test,cn=users,dc=example,dc=ad" AUTH_LDAP_BIND_PASSWORD = "PASSWORD" AUTH_LDAP_USER_SEARCH = LDAPSearch("ou=grouping,dc=example,dc=ad",ldap.SCOPE_SUBTREE,"(cn=%(user)s)") #---ldap user login config #A dictionary of options to pass to each connection to the LDAP server AUTH_LDAP_CONNECTION_OPTIONS = { ldap.OPT_REFERRALS: 0, ldap.OPT_PROTOCOL_VERSION: 3, } #A string template that … -
When I am filtering the product but when i run the project i don't get the images
When I am filtering the product but when i run the project i don't get the images if i changethe Product.objects.filter(slug=slug) to replce the Product.objects.get(slug=slug) the i am facing this type off error Django 'Product' object is not iterable Views.py """ def product_detail(request, slug): try: product = Product.objects.filter(slug=slug) context = { 'product': product, } return render(request, 'buyer/product_details.html', context) except Product.DoesNotExist: return render(request, 'buyer/product_details.html', {'error': 'No data found.'}) """ Urls.py """ path('product/<slug:slug>', views.product_detail, name="product_detail"), Models.py """ class Product(models.Model): total_quantity = models.IntegerField() availability = models.IntegerField() feature_image = models.ImageField(upload_to='media/Product_image') product_name = models.CharField(max_length=100) price = models.IntegerField() discount = models.IntegerField() product_information = RichTextField() model_name = models.CharField(max_length=100) categories = models.ForeignKey(MainCategory, on_delete=models.CASCADE) tags = models.CharField(max_length=100) description = RichTextField() section = models.ForeignKey(Section, on_delete=models.DO_NOTHING) slug = models.SlugField(default='', max_length=500, null=True, blank=True) def __str__(self): return self.product_name def get_absolute_url(self): from django.urls import reverse return reverse("product_detail", kwargs={'slug': self.slug}) class Meta: db_table = "buyer_Product" def create_slug(instance, new_slug=None): slug = slugify(instance.product_name) if new_slug is not None: slug = new_slug qs = Product.objects.filter(slug=slug).order_by('-id') exists = qs.exists() if exists: new_slug = "%s-%s" % (slug, qs.first().id) return create_slug(instance, new_slug=new_slug) return slug def pre_save_post_receiver(sender, instance, *args, **kwargs): if not instance.slug: instance.slug = create_slug(instance) pre_save.connect(pre_save_post_receiver, Product) class ProductImage(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) image_url = models.ImageField(upload_to='media/Product_image') def __str__(self): return self.product.product_name """ … -
Django abstract model not working as expected
I have an abstract django model and a basic model. I am expecting any instance of the basic model to have a value for the field created_at or updated_at. However, as of now, all my instances have None for both these fields. What am I doing wrong? from django.db import models class Trackable(models.Model): created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: abstract = True class Quotation(Trackable): reference = models.CharField(null=True, max_length=80) quotation = Quotation(id=1) print(quotation.created_at) >>> None -
How to combine AND and OR in DRF permission_classes decorator?
Before executing a view I would like to verify multiple permissions within the permission_classes decorator, by checking permissions with AND and OR operators. My problem is that IsUserInstance isn't checked in the example bellow, and when I replace & by and then both permission into the parenthesis are not checked. What is the best way to do that ? or, alternatively, how can I create a new permission that check IsIndividual and IsUserInstance ? views.py @permission_classes([IsSuperUser | IsManager | (IsIndividual & IsUserInstance)]) class IndividualDetailsView(RetrieveAPIView): serializer_class = IndividualSerializer lookup_url_kwarg = "pk" def get_object(self): pk = self.kwargs.get(self.lookup_url_kwarg) return Individual.objects.get(pk=pk) permissions.py class IsIndividual(permissions.BasePermission): def has_permission(self, request, view): return Individual.objects.filter(pk=request.user.pk).exists() class IsUserInstance(permissions.BasePermission): def has_object_permission(self, request, view, obj): return obj == request.user -
django.db.utils.OperationalError: no such table: App_useraccount
from django.db import models from django.db import models from django.contrib.auth.models import (AbstractBaseUser, BaseUserManager, PermissionsMixin ) class MyAccountManager(BaseUserManager): def create_user(self, first_name, last_name, email,username,password=None): if not email: raise ValueError('user must have an email address') if not username: raise ValueError('user must have an username') user = self.model( email = self.normalize_email(email), username = username, first_name = first_name, last_name = last_name, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, first_name, last_name,username, email, password): user = self.create_user( email = self.normalize_email(email), username = username, password = password, first_name = first_name, last_name = last_name ) user.is_admin = True user.is_active = True user.is_staff = True user.is_superadmin = True user.save(using=self._db) return user class UserAccount(AbstractBaseUser,PermissionsMixin): first_name = models.CharField(max_length=64) last_name = models.CharField(max_length=64) username = models.CharField(max_length=64, unique=True) email = models.EmailField(max_length=64, unique=True) state = models.CharField(max_length=30) city = models.CharField(max_length=30) phone_number = models.CharField(max_length=20) address = models.CharField(max_length=80) dob = models.CharField(max_length=50) gender = models.CharField(max_length=30) min_salary = models.IntegerField(null=True) max_salary = models.IntegerField(null=True) profile_pic = models.ImageField(upload_to='app/img/condidate') # required_fields date_joined = models.DateTimeField(auto_now_add=True) last_login = models.DateTimeField(auto_now_add=True) is_admin = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=False) is_superadmin = models.BooleanField(default=False) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username','first_name','last_name'] objects = MyAccountManager() def __str__(self): return self.email def has_perm(self, perm, obj=None): return self.is_admin def has_module_perms(self, add_label): return True class Company(models.Model): user_id = models.ForeignKey(UserAccount, on_delete=models.CASCADE) post_by = models.CharField(max_length=60) company_name = models.CharField(max_length=150) … -
Django 4 REST framework JSON POST request filter
I have this API where I need to filter some data. My user will pass a JSON containing several instances that I need to return to them if there existis or not on my database. But I don't know how I can make Django 4 make several POST requests within the same JSON (I guess since they would be only getting information this would be several "GET" requests, but I need to make them in a POST). Thoughts on how should I do it? I don't even know how to start. For example, the POST request could be: [ { "name": "media1" }, { "name": "media2" }, { "name": "media3" } ] And if I had medias 1 and 3 but not 2, the API would return the following: [ { "id": 0, "name": "media1" }, { None }, { "id": 1, "name": "media3" } ] This is my current viewset. I have implemented a filter that works only for one GET request at a time: class MediasViewSet(viewsets.ModelViewSet): queryset = Media.objects.all().order_by('name') serializer_class = MediaSerializer authentication_classes = [JWTAuthentication] permission_classes = [IsAuthenticated] def get_queryset(self, *args, **kwargs): print(self.request) queryset = super().get_queryset() if(self.request.data.__contains__("name")): query = self.request.data['name'] if query: queryset = Media.objects.filter(name=query) return queryset This … -
How i can show:{{ if citizen.nizo.name == category.name }}?
I'm new to django. My problem is that I can't use "i .nizo.name".if citizen.nizo..name == category.name should work. Please answer me for 1 day.I have a deadline( P.S Sorry my english so bad)**** my one_category.html {% for i in citizen %} {% if i.nizo == category.name %} <p>if</p> <a href="{% url 'citizen' i.slug %}"><h3> {{ i.name }} - haqida malumuot</h3> </a> <br> {% else %} <p>else</p> {% endif %} {% endfor %} my models.py class Citizen (models.Model) : name = models.CharField(max_length=255, verbose_name= "F.I.SH",blank=True,null=True) #widget=models.TextInput(attrs={'class':'form-input'}) tugilgan_sanasi = models.DateField(max_length=255, verbose_name= "Tug'ilgan sanasi",blank=True,null=True) slug = models.SlugField(max_length=255, unique=True,verbose_name= "Slug") yashash_manzili = models.CharField(max_length=240, verbose_name= "Yashah manzili",blank=True,null=True) content = models.TextField(verbose_name ="Текст статьи",blank=True) photo = models.ImageField(upload_to="photos/%Y/%m/%d/", verbose_name="Izoh",blank=True,null=True) is_published = models.BooleanField(verbose_name= "Organilgan/Organilmagan") time_create = models.DateTimeField(auto_now_add=True, verbose_name="Время создания",blank=True,null=True) time_update = models.DateTimeField(auto_now=True, verbose_name="Время изменения",blank=True,null=True) nizo_shaxs =models.CharField(max_length=240, verbose_name="Nizoloshyatgan Shaxs F.I.SH",blank=True,null=True) nizo = models.ForeignKey('Category',on_delete=models.PROTECT, null=True,blank=True, verbose_name ="Nizo не выбрана") mah = models.ForeignKey('Mahalla',on_delete=models.PROTECT,null=True,blank=True, verbose_name= "Mahalla не выбрана") def __str__(self): return self.name def get_absolute_url(self): return reverse('iib:citizen', kwargs={'citizen_slug': self.slug}) class Category(models.Model): name = models.CharField(max_length=100, db_index=True, verbose_name="Nizo") slug = models.SlugField(max_length=255, unique=True, db_index=True, verbose_name="URL") def __str__(self): return self.name def get_absolute_url(self): return reverse('iib:category', kwargs={'nizo_slug': self.pk}) class Meta: verbose_name = 'Nizo' verbose_name_plural = 'Nizo' my views.py def show_one_category(request,nizo_slug:str): citizen = Citizen.objects.all() category = get_object_or_404(Category, slug=nizo_slug) context = { 'category':category, … -
How to access user Input as GET request and output the responce in HTML page using Flask Python
sorry to asking questions like this I am new to flask and html not able to figure out error where I am getting. building small application where it calculates the cycle count of the time series curves when curve profile lower end value <13 and peak end of the curve >20 my script calculates the count how many time the curve goes up above >20 and billow 13 values this is i did for static data if user input the data below 4 and above 15 it has to show the count value so far i used this script for count calculation import numpy as np from flask import Flask, render_template, request app = Flask(__name__) x = np.array([0, 7, 18, 24, 26, 27, 26, 25, 26, 16, 20, 16, 23, 33, 27, 27, 22, 26, 27, 26, 25, 24, 25, 26, 23, 25, 26, 24, 23, 12, 22, 11, 15, 24, 11, 12, 11, 27, 19, 25, 26, 21, 23, 26, 13, 9, 22, 18, 23, 26, 26, 25, 10, 22, 27, 25, 19, 10, 15, 20, 21, 13, 16, 16, 15, 19, 17, 20, 24, 26, 20, 23, 23, 25, 19, 15, 16, 27, 26, 27, 28, 24, 23, … -
django.db.utils.IntegrityError: The row in table 'accountss_comments' with primary key '10' has an invalid foreign key
I'm trying to make the patient give a review and a rate but this error pop up when I run migrate the error is django.db.utils.IntegrityError: The row in table 'accountss_comments' with primary key '10' has an invalid foreign key: accountss_comments.doctore_id contains a value '1' that does not have a corresponding value in accountss_doctor.user_id. this my models class User(AbstractUser): is_doctor = models.BooleanField(default=False) is_patient = models.BooleanField(default=False) class Doctor(models.Model): user = models.OneToOneField( User, on_delete=models.CASCADE, primary_key=True) number_phone = models.CharField( _('االهاتف :'), max_length=50, blank=True, null=True) class Patient(models.Model): user = models.OneToOneField( User, on_delete=models.CASCADE, primary_key=True) name = models.CharField(max_length=50, verbose_name="الاسم ") class Comments(models.Model): created_by = models.ForeignKey( Patient, on_delete=models.CASCADE) doctore = models.ForeignKey( Doctor, on_delete=models.CASCADE, related_name='comments') # co_email = models.ForeignKey( # User, on_delete=models.CASCADE, related_name='comment') co_body = models.TextField(max_length=400, verbose_name='التعليق') rate = models.IntegerField(default=0) created_dt = models.DateTimeField(auto_now_add=True) active = models.BooleanField(default=True) please if there is any solution write below and explain it because I'm still new to Django I tried so hard to fix but with no result -
Adding extra content in django admin jazzmin index page
I want to add user's count and total post count in my built in django admin (html css cards). Iam using jazzmin for styling my dashboard. I prefer to use context processors to fetch counts. I can't override current admin index page my Django version is 4.1 This is my curent admin panel i want to add the count cards abouve app list -
Django queryset checking existence having unexpected behavior
I have a model like this class Student(models.Model): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) archived = models.BooleanField(default=False) class Meta: constraints = [ UniqueConstraint( fields=["first_name", "last_name"], condition=Q(archived=False), name="unique_user" ) ] and code like below d = {"first_name": "John", "last_name": "Doe"} students = Student.objects.filter(first_name=d.get("first_name"), last_name=d.get("last_name")) for student in students: """Doing some stuff here""" pass if not students: Student.objects.create(first_name=d.get("first_name"), last_name=d.get("last_name")) I am getting an integrity error from the last line where I call objects.create duplicate key value violates unique constraint "unique_user" DETAIL: Key (first_name, last_name) In the objects.filter() I have two fields that are part of the unique constraint, and I am using the same queryset before the objects.create is called, so this error should not happen unless something going wrong with the queryset. This code is working without issues most of the time. Only once this error was raised. Any idea what is going on ? One possibility is that between the filter query and the create query the object was created and the integrity error was raised from create query. But that was not the case. I checked the db, there was nothing created. Infact there was already data which was created hours before matching these conditions. So the filter query … -
Azure Database for PostgreSQL flexible server Slow with Django
Am using Django to connect to Azure Database for PostgreSQL flexible server but it's very slow, below are the specs of the server : https://i.stack.imgur.com/DnV2y.png As you can see above, the specs are high, but the performance isn't better, in postman when I was hitting to get data it took 34.5 seconds, this is way too much to wait. In my Django code, I tried my best to optimize the queries, and on Heroku, it was super fast, however here on Azure it's extremely slow, what could be done to improve the speed of the server? For more information on Django this is the view.py of the endpoint: @method_decorator(cache_page(60 * 60 * 4), name='get') @method_decorator(vary_on_cookie, name='get') class PostList(generics.ListCreateAPIView): """Blog post lists""" queryset = Post.objects.filter(status=APPROVED).select_related( "owner", "grade_level", "feedback").prefetch_related( "bookmarks", "likes", "comments", "tags", "tags__following").prefetch_related("address_views") serializer_class = serializers.PostSerializer authentication_classes = (JWTAuthentication,) permission_classes = (PostsProtectOrReadOnly, IsMentorOnly) def filter_queryset(self, queryset): ordering = self.request.GET.get("order_by", None) author = self.request.GET.get("author", None) search = self.request.GET.get("search", None) tag = self.request.GET.get("tag", None) # filter queryset with filter_backends 🖟 queryset = super().filter_queryset(queryset) if ordering == 'blog_views': queryset = queryset.annotate( address_views_count=Count('address_views')).order_by( '-address_views_count') if author: queryset = queryset.filter(owner__email=author).select_related( "owner", "grade_level", "feedback").prefetch_related( "bookmarks", "likes", "comments", "tags", "tags__following").prefetch_related("address_views") if tag: queryset = queryset.filter( tags__name__icontains=tag).select_related( "owner", "grade_level", … -
In Django, can I use a variable passed to a function in order to access and attribute of a model?
I'm trying to create a custom function where one of the variables passed is the name of an attribute of a model. I'm doing this to try to access the underlying value. def tabsums(entity_object, year_object, columntitle): curassetobject = BSAccountType.objects.get(name = "Current asset", company = entity_object) curassetsum = BSSum.objects.get(Q(company = entity_object) & Q(year = year_object) & Q(account_type = curassetobject)).columntitle Essentially, I want columntitle to be a string that matches the model field name so I'm trying to pass the variable as the attribute name to access the underlying value. It's not working as Django/python is looking for the attribute "columntitle" which does not exist, rather than looking to the underlying string. Is there a syntax I can use that will allow Django to utilize the underlying string value that is passed? Thank you very much. -
Pass list dict as params in axios react
I am building a react app. I am trying send list dict as params in axios. I am using Django rest framework as backend and It is showing [] or None every times I send request. App.js function App() { const [currentState, setCurrentState] = useState([{"name": "First", "id": 100}, {"name": "Second", "id": 200},]) const sendRequest = () => { axios.get("/api/", {params: {state: currentState}).then((res) => { console.log(res); }) } return ( <> <b onClick={sendRequest}>Send request</b> </> ) } I am trying to send the whole list dict to backend as params like. [{"name": "First", "id": 100}, {"name": "Second", "id": 200}] But it showing none. in backend I am accessing like views.py class Api(APIView): def get(self, request, *args, **kwargs): data = self.request.query_params.get("state") print(data) return Response({"good"}) I have also tried using paramsSerializer in axios for serialization like :- const sendRequest = () => { axios.get("/api/", { params: { state: currentState }, paramsSerializer: params => { return qs.stringify(params, {arrayFormat: "repeat"}) }, ).then((res) => { console.log(res); }) } but it is still not working. Tried also {arrayFormat: "brackets"}. Any help would be much Appreciated. Thank You -
Is Django db_index helpful in text search queries?
I've a similar model in a Django project: from django.db import models class Book(models.Model): title = models.CharField(verbose_name='Title', max_length=255, db_index=True) authors = models.CharField(verbose_name='Authors', max_length=255, db_index=True) date = models.DateField(verbose_name='Date', db_index=True) In the views I need to do a full text search query like the following: books = Book.objects.filter(Q(title__icontains=query) | Q(authors__icontains=query)) Is the db_index=True actually helping the performances of my query or not? -
Django problem updating date field when updating a record
I have a problem when I try to update a field named date_updated. My intention with the field is that every time a record is updated, the date_updated field of that record should be updated by the date the change is made. That field and one other field I have inside a Base class and then in each of the models I inherit that class to repeat the fields. class Base(models.Model): ... date_updated = models.DateTimeField(auto_now=True) def save(self, *args, **kwargs): self.date_updated = django.timezone.now() super(Base, self).save(*args, **kwargs) class Meta: abstract = True class OtherClass(Base): ... My intention is that when I update any record in the OtherClass, its date_updated field will be updated. I also tried adding the overwrite of the save method in the OtherClass, but the result is the same. The date is kept after I make the change. I am making the change with .update(**data_to_update) -
TypeError: TestViews.test_fails() missing 1 required positional argument: 'param'
I'm trying to run tests on a django app using selenium + pytest which according to the docs, the below should work import pytest from django.contrib.staticfiles.testing import StaticLiveServerTestCase from selenium.webdriver import Chrome class TestViews(StaticLiveServerTestCase): @classmethod def setUpClass(cls): super().setUpClass() cls.driver = Chrome() @classmethod def tearDownClass(cls): if hasattr(cls, 'driver'): cls.driver.quit() super().tearDownClass() @pytest.mark.parametrize('param', ['param1', 'param2']) def test_fails(self, param): pass However I get: Creating test database for alias 'default'... Found 1 test(s). System check identified no issues (0 silenced). Error TypeError: TestViews.test_fails() missing 1 required positional argument: 'param' Destroying test database for alias 'default'... more details more details more details more details more details more details more details more details -
Django file upload is not uploading the file?
I have created a file upload something like this: DataUpload is the view that handles template rendering and handle_uploaded_file is the function that reads the file. View.py def DataUpload(request): if request.method == 'POST': form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): print(request.FILES['file']) handle_uploaded_file(request.FILES['file']) return HttpResponseRedirect('/success/url/') else: form = UploadFileForm() return render(request, 'DataBase/upload.html', {'form': form}) def handle_uploaded_file(f): with open(os.getcwd()+f, 'wb+') as destination: for chunk in f.chunks(): destination.write(chunk) url url(r'DataUpload', views.DataUpload, name='DataUpload'), forms.py from django import forms class Rand_Frag_From(forms.Form): Seq = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control','placeholder':'Tropomyosin beta chain '}),required=False) Acc = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control','placeholder':'P02671 '}), required=True) class UploadFileForm(forms.Form): file = forms.FileField() template {% load static %} <link rel="stylesheet" href="{% static 'css/table/custom.css' %}"> <div class="main"> <div class="site-content"> <div class="mdl-grid site-max-width"> <div class="mdl-cell mdl-cell--12-col mdl-card mdl-shadow--4dp page-content"> <div class="mdl-grid"> <div class="mdl-cell mdl-cell--12-col"><div class="mdl-card__supporting-text"> <h2 class="mdl-card__title-text">Enter UNIPROT ID and/or description </h2> <form action="{%url 'DataUpload' %}" method="POST" class="form-contact"> {%csrf_token%} </div> <div class="mdl-textfield mdl-js-textfield mdl-textfield--floating-label"> {{form.file}} </div> <button class="mdl-button mdl-js-button mdl-button--raised mdl-js-ripple-effect mdl-button--accent" type="submit"> Submit </button> </form> </div></div> </div> </div> </div> </div> </div> console log after submitting the form Quit the server with CONTROL-C. [22/Dec/2022 15:14:19] "POST /DataUpload HTTP/1.1" 200 1317 I'm not getting any error anywhere, but it's not uploading the file. -
Django how to store data from checkbox into a database
I want to add data from checkbox to database. I watched some videos but didn't worked out. checkbox.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Checkbox</title> </head> <body> <form action="" method="post"> {%csrf_token%} <div class="form-check"> <h5>Checkbox_report</h5> <input type="checkbox" value="Executive_summary" id="Executive_summary" name="checkbox_data"> <label for="Executive_summary"> Executive summary &nbsp</label> <input type="checkbox" value="Scope" id="Scope" name="checkbox_data"> <label for="Scope"> Scope &nbsp</label> <input type="checkbox" value="ISMS" id="ISMS" name="checkbox_data"> <label for="ISMS"> ISMS &nbsp</label> <input type="checkbox" value="Methodology" id="Methodology" name="checkbox_data"> <label for="Methodology"> Methodology &nbsp</label> <input type="checkbox" value="Recommendation" id="Recommendation" name="checkbox_data"> <label for="Recommendation"> Recommendation &nbsp</label> </div> <button type="submit">submit</button> </form> </body> </html> views.py from collections import Counter from django.shortcuts import render # Create your views here. def home(request): return render(request, 'home.html', {"text": "hello home"}) def about(request): return render(request, 'about.html', {"text": "hello about"}) def checkbox(request): if request.method == 'POST': checkbox_data = request.POST.getlist('checkbox_data') for i in checkbox_data: print(i) return render(request, 'checkbox.html') I want to add 1 when user check any of the checkbox and the one which are not checked add 0 second:: what is forms.py?what is the main difference between forms.py and manage.py -
A server error occurred. Please contact the administrator
i have a project but it says A server error occurred. Please contact the administrator. i have tried many times but not worked -
Django Server KeyError - Unable to locate my environment variable
I am making a blog using Django and am trying to make it secure by using 2 settings files (prod.py and local.py which both "import *" from a base.py original settings file). I have two environment variables which are on my local computer and have confirmed they exist: myBlog and SECRET_KEY. myBlog=prod The error I am receiving is a KeyError: (venv) C:\Users\shark\Documents\Bootstrap Tutorial Website Files\38. Bootstrap 2020 Starter Files\DjangoBlog - Copy\myBlog>python manage.py runserver Traceback (most recent call last): File "C:\Users\shark\Documents\Bootstrap Tutorial Website Files\38. Bootstrap 2020 Starter Files\DjangoBlog - Copy\myBlog\manage.py", line 22, in <module> main() File "C:\Users\shark\Documents\Bootstrap Tutorial Website Files\38. Bootstrap 2020 Starter Files\DjangoBlog - Copy\myBlog\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\shark\Documents\Bootstrap Tutorial Website Files\38. Bootstrap 2020 Starter Files\DjangoBlog - Copy\venv\lib\site-packages\django\core\management\__init__.py", line 446, in execute_from_command_line utility.execute() File "C:\Users\shark\Documents\Bootstrap Tutorial Website Files\38. Bootstrap 2020 Starter Files\DjangoBlog - Copy\venv\lib\site-packages\django\core\management\__init__.py", line 386, in execute settings.INSTALLED_APPS File "C:\Users\shark\Documents\Bootstrap Tutorial Website Files\38. Bootstrap 2020 Starter Files\DjangoBlog - Copy\venv\lib\site-packages\django\conf\__init__.py", line 92, in __getattr__ self._setup(name) File "C:\Users\shark\Documents\Bootstrap Tutorial Website Files\38. Bootstrap 2020 Starter Files\DjangoBlog - Copy\venv\lib\site-packages\django\conf\__init__.py", line 79, in _setup self._wrapped = Settings(settings_module) File "C:\Users\shark\Documents\Bootstrap Tutorial Website Files\38. Bootstrap 2020 Starter Files\DjangoBlog - Copy\venv\lib\site-packages\django\conf\__init__.py", line 190, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "C:\Python310\lib\importlib\__init__.py", line 126, in import_module … -
Apache2 not loading Django settings.py file properly
I am currently facing an issue where making any changes in settings.py file is not reflecting properly in my project. I have tried deleting the .conf file, adding it again, enabling it and reloading the apache2 server. But somehow it still does not work. I have an issue with CORS in Django, I made changes to correct it by allowing certain origins to make cross-origin requests: CORS_ALLOWED_ORIGINS = ['www.test.domain',...] So I tested it by running the Django server manually using python runserver 0.0.0.0:8000 and it is working fine, not getting any CORS issues But when I reload the apache2 server or even in this case, make a completely new .conf file and run it via apache2 - it still somehow does not recognize the changes and keeps giving me CORS errors. I am confused as to what is making this happen - to not reflect any newly made changes. The problem is, now I am not able to reflect these changes with a new configuration as well. So there is no way for me to keep this webserver running without getting CORS errors. NOTE: Apache has all the required accesses to my Django project - it can access settings.py without … -
How to get child model having one to one relation with default User model of Django?
I created a model having one to one relation with default User model to extend it for providing some permission for tabs in my website. Now I want to not show the tab options to the users not having permissions to access them. user permission model: from django.contrib.auth.models import User class userpermissions(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) Checking whether the user has permission or not I created a function which is supposed to get the userpermission model instance of the logged in user. For which I used the following code -> def check(user): up = User.userpermissions_set.get(id=user.id) Now when user logs in the login function will call this check function and redirect to the tab that the user can access and also send the up variable containing all the permissions of the user so that the Navbar templet can hide those tabs which the user has no access to. Now the problem that I am facing is when I run the server it shows this error -> AttributeError at / type object 'User' has no attribute 'userpermissions_set' I saw on YouTube that to get the instance of child model (I don't know what to call it..) we need to use it's …