Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Are there any libraries for Python to implement Audit Trail in MySQL?
I want to implement audit trail for FastAPI and Django applications but cannot find any updated packages for such task I tried searching on the web and found a package called django-audittrail but its last update was in 2020 -
Django validate fileds on form
I can`t understand how to return error in template I making check on valid in my from FORMS.py class UserForm(forms.Form): first_name= forms.CharField(max_length=20, label='Name') last_name= forms.CharField(max_length=20, label='Last_name') password= forms.CharField(label='Password') repassword= forms.CharField(label='Confirm password') def clean(self): cleaned_data = super().clean() self.password = cleaned_data('password') self.repassword = cleaned_data('repassword') if self.password != self.repassword: raise ValidationError('Password dont match') VIEW.py def index(request): form = UserForm() if request.method == 'POST': form = UserForm(request.POST or None) if form.is_valid(): firstname= form.cleaned_data.get("first_name") lastname= form.cleaned_data.get("last_name") password = form.cleaned_data.get('password') re_password = form.cleaned_data.get('repassword') form = UserForm() context = {'form': form, } return render(request, 'create_users/index.html', context) return render(request, 'create_users/index.html', {'form': form} As result i see this when update my template dict' object is not callable -
The "pip install django" command gets an error, how do I solve it?
pip install django Collecting django WARNING: Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ReadTimeoutError("HTTPSConnectionPool(host='files.pythonhosted.org', port=443): Read timed out. (read timeout=15)")': /packages/2d/ac/9f013a51e6008ba94a282c15778a3ea51a0953f6711a77f9baa471fd1b1d/Django-4.1.5-py3-none-any.whl WARNING: Retrying (Retry(total=3, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ReadTimeoutError("HTTPSConnectionPool(host='files.pythonhosted.org', port=443): Read timed out. (read timeout=15)")': /packages/2d/ac/9f013a51e6008ba94a282c15778a3ea51a0953f6711a77f9baa471fd1b1d/Django-4.1.5-py3-none-any.whl WARNING: Retrying (Retry(total=2, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ReadTimeoutError("HTTPSConnectionPool(host='files.pythonhosted.org', port=443): Read timed out. (read timeout=15)")': /packages/2d/ac/9f013a51e6008ba94a282c15778a3ea51a0953f6711a77f9baa471fd1b1d/Django-4.1.5-py3-none-any.whl WARNING: Retrying (Retry(total=1, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ReadTimeoutError("HTTPSConnectionPool(host='files.pythonhosted.org', port=443): Read timed out. (read timeout=15)")': /packages/2d/ac/9f013a51e6008ba94a282c15778a3ea51a0953f6711a77f9baa471fd1b1d/Django-4.1.5-py3-none-any.whl WARNING: Retrying (Retry(total=0, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ReadTimeoutError("HTTPSConnectionPool(host='files.pythonhosted.org', port=443): Read timed out. (read timeout=15)")': /packages/2d/ac/9f013a51e6008ba94a282c15778a3ea51a0953f6711a77f9baa471fd1b1d/Django-4.1.5-py3-none-any.whl ERROR: Could not install packages due to an OSError: HTTPSConnectionPool(host='files.pythonhosted.org', port=443): Max retries exceeded with url: /packages/2d/ac/9f013a51e6008ba94a282c15778a3ea51a0953f6711a77f9baa471fd1b1d/Django-4.1.5-py3-none-any.whl (Caused by ReadTimeoutError("HTTPSConnectionPool(host='files.pythonhosted.org', port=443): Read timed out. (read timeout=15)")) I tried the following methods but it didn't work pip install --trusted-host=pypi.python.org --trusted-host=pypi.org --trusted-host=files.pythonhosted.org django pip install django --user (not working in venv) -
Using random generator in django
views.py class PostListView(ListView): model = Post template_name = 'feed/home.html' context_object_name = 'posts' ordering = ['-date_posted'] paginate_by = 10 def get_context_data(self, **kwargs): context = super(PostListView, self).get_context_data(**kwargs) if self.request.user.is_authenticated: liked = [i for i in Post.objects.all() if Like.objects.filter( user=self.request.user, post=i)] context['liked_post'] = liked return context home.html <div> {% for post in posts %} <div> <a href="{{ post.user_name.profile.get_absolute_url }}"> <img src="{{ post.user_name.profile.image.url }}" class="rounded-circle" width="30" height="30" alt=""></a> <a href="{{ post.user_name.profile.get_absolute_url }}"><b>{{ post.user_name }}</b></a> <br><small >Posted on {{ post.date_posted }}</small> <br><br> <p >{{ post.description }}</p> </div> {% end for %} </div> i want to add carousel in the above template for that i want random object (with 4 objects ) so how can i use random objects and where? Help me in using random object generator in django ? -
Problem with separating images using Django
hi I am loading images using Django but I want to sperate images which end with jpg and png , how do I do that ? thank you . -
how to updata all changes on database as one block
I have this code for i in range(100): table2.objects.create(id = i, some_extra_fields) how to upload all database changes one time in one query -
Aggregate in model property result in extra queries
My example: class Product(models.Model): name = models.CharField(max_length=50) category = models.ManyToManyField("wms.ProductCategory", blank=True) @property def quantity_in(self): return self.intodocumentproduct_set.aggregate(total=Sum('quantity_in', default=0))['total'] class IntoDocumentProduct(models.Model): product = models.ForeignKey("wms.Product", on_delete=models.CASCADE) quantity_in = models.FloatField(blank=True, null=True) class ProductListAPIView(ListAPIView): # queryset = Product.objects.prefetch_related('category').annotate(sum_quantity_in=Sum('intodocumentproduct__quantity_in', default=0)).all() queryset = Product.objects.prefetch_related('category').all() serializer_class = ProductModelSerializer Commented queryset results in 4 queries while other query (using property) results in 6 queries. Probably n+ problem. I have to use properties like: quantity_ordered, quantity_reserved, quantity_out, quantity_in, quantity_stock, quantity_available, quantity_pending_release and more in many places in web app. Calculating them in every view will be time comsuming and error susceptible. This solution is not very handy when property is used in many views with many properties. Is there any other solution to remove extra queries? -
is it possible to add db_index = True to a field that is not unique (django)
I have a model that has some fields like: current_datetime = models.TimeField(auto_now_add=True) new_datetime = models.DateTimeField(null=True, db_index=True) and data would be like : currun_date_time = 2023-01-22T09:42:00+0330 new_datetime =2023-01-22T09:00:00+0330 currun_date_time = 2023-01-22T09:52:00+0330 new_datetime =2023-01-22T09:00:00+0330 currun_date_time = 2023-01-22T10:02:00+0330 new_datetime =2023-01-22T10:00:00+0330 is it possible new_datetime to have db_index = True ? the reason i want this index is there are many rows (more than a 200,000 and keep adding every day) and there is a place that user can choose datetime range and see the results(it's a statistical website). i want to send a query with that filtered datetime range so it should be done fast. by the way i am using postgresql also if you have tips for handling data or sth. like that for such websites i would be glad too hear thanks. -
HELLO CAN ANYONE HELP ME OUT , I AM EXHAUSTED NOW, PLEASE HELP ME
[settings.py ' gaierror: [Errno 11003] getaddrinfo failed' i am getting this error. ](https:/ /i.stack.imgur.com/OTCj4.png) i am trying this way but not enter image description heregetting accurate output. -
psycopg2.errors.UndefinedFunction: function gen_random_uuid() does not exist
Error occurs when trying to run python manage.py migrate in a django application. complete code git clone https://github.com/saleor/saleor.git cd saleor python manage.py migrate psycopg2.errors.UndefinedFunction: function gen_random_uuid() does not exist LINE 1: UPDATE "account_user" SET "uuid" = GEN_RANDOM_UUID() it doesn't work when running but works in running postgres I created extention in postgres, commited that. postgres=# SELECT gen_random_uuid(); gen_random_uuid f36d69b7-5681-4b92-b37e-9b0217b7d829 (1 row) It works fine with docker. Any help will be appreciated. -
Encrpyt URL Id in django
I was trying to excrypt Update URL id to encrpyted format in the url. from my profile page of a user one edit button is there. that button contains url of the update view. #My profile page. code def profile(request): lst = request.user.id #This line is the problem l=[] for i in lst: i['encrypt_key']=encrypt(i['id']) i['id']=i['id'] l.append(i) return render(request, 'profile.html', {'lst':l}) #The update view code def update(request, id): id=decrypt(id) #Update code. return render(request, 'edit_profile.html', context) In the profile page for that edit button, since it is an iteratable for loop I coded like this is the Html template <li class="ctx-item"> <button class="ctx-menu-btn icon-box"> <span class="material-symbols-rounded icon" aria-hidden="true">edit</span> {% for x in lst %} <span class="ctx-menu-text"><a href="/update/{{x.encrypt_key}}">Edit</a></span> {% endfor %} </button> </li> Since three users are there in my database, three edit links are coming. To restrict it in the profile view I have to change the filteration while retriving the user in lst. If i put request.user.id, It is showing the following error. TypeError at /profile/ 'int' object is not iterable Please help me to correct this error. -
django_bootstrap5 not formatting anything
I'm trying to get basic bootstrap formatting working in a django app, and installed django_bootstrap5 to do so. No formatting, however, is getting applied to any of the pages. Here's the various pages: base.html: <!DOCTYPE html> {% load django_bootstrap5 %} <html lang="en"> <head> <meta charset="UTF-8"> <title> {% block title %} {% endblock %} </title> </head> <body> <div class="container"> {% block body %} {% endblock %} </div> </body> </html> I extend this in a simple index page: <!DOCTYPE html> {% extends 'base.html' %} {% load django_bootstrap5 %} {% block title %} Home {% endblock %} {% block body %} <h1>Hello World</h1> {% endblock %} Hello World, however, is not showing up in a container. This is also failing on a form page: <!DOCTYPE html> {% extends 'base.html' %} {% load django_bootstrap5 %} {% block body %} <div class="container"> <h1>Sign Up</h1> <form method="POST"> {% csrf_token %} {% bootstrap_form form %} <input type="submit" value="Sign Up" class="btn btn-default"> </form> </div> {% endblock %} The form is neither in a bootstrap container, nor does it have any styling at all. What am I missing here? Thank you. -
How can I skip pk in url while redirecting to another url with generic RedirectView in Django?
I am trying to delete a record after displaying it with DetailView and redirecting to the list page again. view.py ... class DailyRecordDeleteConformationView(RequiredBasicDetailsAndContextMixin, DetailView): model = DailyRecord obj_not_found_redirect = reverse_lazy('business:add_daily_records') template_name = 'business/daily_records_detail.html' context_object_name = 'record' def get_object(self): detail = self.model.custom_obj.get_single(self) return detail class DailyRecordDeleteView(RequiredBasicDetailsMixin, RedirectView): pattern_name = 'business:daily_records' def get_redirect_url(self, *args, **kwargs): # Delete the record return super().get_redirect_url(*args, **kwargs) ... urls.py ... path('daily-records/', DailyRecordView.as_view(), name='daily_records'), path('daily-records/<int:pk>/', DailyRecordDeleteConformationView.as_view(), name='daily_record_detail'), path('daily-records/<int:pk>/delete/', DailyRecordDeleteView.as_view(), name='daily_record_delete'), ... Here I am getting this below error when click on the delete button on detail view NoReverseMatch at /business/daily-records/7/delete/ Reverse for 'daily_records' with keyword arguments '{'pk': 7}' not found. 1 pattern(s) tried: ['business/daily\\-records/\\Z'] I am new to class based views, and still not able to figure out how to redirect to url that does not have the pk parameter. I tryed to find any variable for RedirectView or something that can skip the pk of current url while redirecting to another url. Thanks. -
how do python handle asynchronous task
I've strong background in a JS frameworks. Javascript is single threaded language and during the execution of code when it encounters any async task, the event loop plays the important role there. Now I've been into Python/Django and things are going good but I'm very curious about how python handle any asynchronous tasks whenever I need to make a database query in django, I simple use the queryset method like def func(id): do_somthing() user = User.objects.get(id=id) do_somthing_with_user() func() another_func() I've used the queryset method that fetch something from database and is a asynchronous function without await keyword. what will be the behaviour of python there, is it like block the execution below until the queryset response, is it continue the execution for the rest of code on another thread. Also whenever we need to make an external request from python, we uses requests library method without await keyword, r = request.get("https://api.jsonplaceholder.com/users") # will the below code executes when the response of the request arrive? do_somthing() . . . do_another_thing() does python block the execution of code until the response arrives? In JS the async task is handled by event loop while the rest of the code executes normally console.log("first") fetch("https://api.jsonplaceholder.com/users").then(() … -
Converting HEIC Images to JPEG in python works on local windows but not working in ubuntu aws gunicorn and nginx server
I'm saving heic images to aws s3 bucket and try to convert it to jpeg before displaying it in the html page using python library Pillow and pillow_heif here is the code for the convertion import boto3 from PIL import Image from io import BytesIO import pillow_heif response = s3.get_object(Bucket=settings.AWS_STORAGE_BUCKET_NAME, Key=self.media.name) image_bytes = response['Body'].read() pillow_heif.register_heif_opener() img = Image.open(BytesIO(image_bytes)) new_name = self.media.name.replace('.heic', '.jpg') # Convert image to JPEG # Create a BytesIO object to save the image img_bytes = BytesIO() img.save(img_bytes, format='JPEG') img_bytes.seek(0) # Upload the image to S3 s3.upload_fileobj(img_bytes, settings.AWS_STORAGE_BUCKET_NAME, new_name) self.converted_image_name = new_name self.save() # Get the object URL url = s3.generate_presigned_url( ClientMethod='get_object', Params={ 'Bucket': settings.AWS_STORAGE_BUCKET_NAME, 'Key': new_name }, ExpiresIn=60000 # URL expiration time in seconds ) when I run that code in my local machine (Windows) in django using python manage.py runserver command it works fine, but when I deploy the code to the aws instance which is running using gunicorn and nginx the url that that code runs in gives 502 Bad Gateway nginx/1.18.0 (Ubuntu) error. And when I tried to check what is the issue, there is no errors came up in the gunicorn logs and nginx logs also. Can anyone please help me with this … -
Unable to fetch Json file in javascript in Django
I have a json file that I would like to fetch in javascript and create divs for it in the webpage. My issue is that I am providing local path of the json file to the fetch method but it is adding it to the django webpage url. The code below tries to fetch the local path of json file: fetch('../../scrapers/jsonOutputs/linkedin_jobs.json') .then(response => response.json()) .then(data => { const jobListings = data.Jobs; jobListings.forEach(job => { const jobTitle = job["Job Title:"]; const employerName = job["Employer name: "]; const jobLocation = job["Job Location: "]; const jobDetails = job["Job Details: "]; const linkToJob = job["Link To Job: "]; const jobListingElement = document.createElement("div"); jobListingElement.classList.add("job-listing"); jobListingElement.innerHTML = ` <h2>${jobTitle}</h2> <p>${employerName}</p> <p>${jobLocation}</p> <div class="job-description-container"> <div class="job-description"> <p>${jobDetails}</p> <a href="${linkToJob}">View Job</a> </div> </div> `; const jobListContainer = document.getElementById("job-list-container"); jobListContainer.appendChild(jobListingElement); }); }); Now when I run the django webapp and inspect element the webpage, I get the following error [Error] Failed to load resource: the server responded with a status of 404 (Not Found) (linkedin_jobs.json, line 0) [Error] Unhandled Promise Rejection: SyntaxError: The string did not match the expected pattern. promiseEmptyOnRejected (jobsearch-func.js:4) promiseReactionJob The inspect element shows http://127.0.0.1:8000/scrapers/jsonOutputs/linkedin_jobs.json which is problematic since this is not the path to my … -
DRF, why my root api urls are got mixed (combined)?
These are my code snippets: # serializers.py from rest_framework import serializers from .models import User class UserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = User fields = '__all__' class UserActivitySerializer(serializers.HyperlinkedModelSerializer): class Meta: model = User fields = ( 'id', 'email', 'last_login', 'last_requested_at', ) # urls.py router = routers.DefaultRouter() router.register(r'users', UserViewSet) router.register(r'user-activity', UserActivityViewSet) urlpatterns = [ path('', include(router.urls)), ] This leads to combined Root API urls, like so: However this is not the expected behavior. I wanted 2 separate urls. First with all users (for example, localhost:8000/users with all users and localhost:8000/users/ for specific user). And second with user activity API. with those 4 fields. I don't have clue why my urls got combined when I added router.register(r'user-activity', UserActivityViewSet) to my urls.py. Please help with broad explanation, if possible. Thanks! -
ask jinja if a profile exists
How can I check if the object in profile model does not exist in the database, the crearprofile button appears and if it exists, profile appears? {% if user.profile.is_defined %} <a class="nav-link" href="{% url 'profile' user.id %}">Perfil</a> {% else %} <a class="nav-link" href="{% url 'crearprofile' %}">Crear perfil</a> {% endif %} enter image description here check if the object in profile model does not exist in the database, the crearprofile button appears and if it exists, profile appears? -
Django: cannot cast type integer to time without time zone
I've had some previous testing with models and their functionality integration. There were few fields that were using for time input. At first I thought maybe IntegerField will be enough, but as we continue with more new solutions things changed. So there was check_in_time, check_out_time and etc. Now we want to set it to TimeField, but as we are trying to apply the migrations those errors appear. I'm not an postgres guru so I'm scared of breaking things up, cuz migrations might be an pain in the ass. This is the new migration: class Migration(migrations.Migration): dependencies = [ ('property', '0084_rename_max_tenants_property_max_guests_allowed'), ] operations = [ migrations.AlterField( model_name='property', name='check_in_after_time', field=models.TimeField(null=True), ), migrations.AlterField( model_name='property', name='check_in_before_time', field=models.TimeField(null=True), ), migrations.AlterField( model_name='property', name='check_out_after_time', field=models.TimeField(null=True), ), migrations.AlterField( model_name='property', name='check_out_before_time', field=models.TimeField(null=True), ), ] This is our fields that we want to use it right now as TimeFields: check_in_before_time = models.TimeField(null=True) check_in_after_time = models.TimeField(null=True) notice_days_before_check_in = models.PositiveIntegerField(default=0) check_out_before_time = models.TimeField(null=True) check_out_after_time = models.TimeField(null=True) How can I fix it now and prevent it from happening again when migrating this on other servers? LOG: bin/django migrate property Operations to perform: Apply all migrations: property Running migrations: Applying property.0085_auto_20230122_0304...Traceback (most recent call last): File "/home/dziugas/werent/app/venv/lib/python3.9/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) … -
Slug returns Reverse for '' with arguments '('',)' not found. 1 pattern(s)
I am trying to make it so when I view a blog from any particular link on my website, the url displays www.example.com/view-blog/slug. I have got it working for my images and image title. But I cannot get it to work with blog titles. It keeps returning the error: Reverse for 'viewblog' with arguments '('',)' not found. 1 pattern(s) tried: ['view\-blog/(?P[-a-zA-Z0-9_]+)/\Z']. Models.py class BlogPost(models.Model): blog_title = models.CharField(max_length=100, null=False, blank=False, default="") slug = models.SlugField() blog_article = RichTextUploadingField(null=True, blank=True, default="ici") blog_image = models.ImageField(null=True, blank=True, upload_to="images", default="default.png") blog_date = models.DateField(auto_now_add=True) blog_published = models.BooleanField(default=False) blog_featured = models.BooleanField(default=False) def save(self, *args, **kwargs): self.slug = self.slug or slugify(self.blog_title) super().save(*args, **kwargs) def __str__(self): return self.blog_title Views.py def viewBlog(request, slug): try: blog = BlogPost.objects.get(slug=slug) except BlogPost.DoesNotExist: print("ViewBlog with this slug does not exist") blog = None return render(request, 'view-blog.html', {'blog': blog, 'slug': slug}) Urls.py urlpatterns = [ path('', views.galleryPage, name='gallery'), path('gallery/', views.galleryPage, name='gallery'), path('contact/', views.contactPage, name='contact'), path('blog/', views.blogPage, name='blog'), path('blogs/', views.blogsPage, name='blogs'), path('search-blogs/', views.searchBlogs, name='searchblogs'), path('view-image/<slug:slug>/', views.viewImage, name='viewimage'), path('view-blog/<slug:slug>/', views.viewBlog, name='viewblog'), path('thank-you/', views.thankyouPage, name='thankyou'), path('about-me/', views.aboutmePage, name='aboutme'), ] **One of my templates I wish to link to viewblog page from ** ( I have tried to replace .id on my urls with .slug but this is what gives … -
how test a value in try except block with pytest and coverage in django setting?
I would like to test a Try/Except block, but I try any method Coverage that says that part is not tested. My goal is to test the Error_Message from the user's django settings, and if the user did not define file_validator_error_message in his Django settings, I would like to consider a default value (file} is not valid). Now I want to test the ERROR_MESSAGE value in the area where I test the Attributeerror error but I don't know how? The point is that in line 10 Coverage says: line 10 didn't jump to line 11, because the exception caught by line 10 didn't happen code : try: # Get Error Message From Django Setting ERROR_MESSAGE = settings.FILE_VALIDATOR_ERROR_MESSAGE except AttributeError: ERROR_MESSAGE = "{file} is not valid" except ImproperlyConfigured: ERROR_MESSAGE = "{file} is not valid" I want to test the ERROR_MESSAGE value in the AttributeerRor error section -
How can I get Total Deposit of Customers
I am working on a Django project with 2 Models; Customer and Deposit and I want to display a list of Customers with their names, deposited dated, account number, and Total Deposited within the year so how do I do it the right way. See what I have tried but Couldn't get the Customers' name in my Django Templates. Models: class Customer(models.Model): surname = models.CharField(max_length=10, null=True) othernames = models.CharField(max_length=20, null=True) account_number = models.CharField(max_length=10, null=True) address = models.CharField(max_length=50, null=True) phone = models.CharField(max_length=11, null=True) date = models.DateTimeField(auto_now_add=True, null=True) #Get the url path of the view def get_absolute_url(self): return reverse('customer_create', args=[self.id]) #Making Sure Django Display the name of our Models as it is without Pluralizing class Meta: verbose_name_plural = 'Customer' # def __str__(self): return f'{self.surname} {self.othernames} - {self.account_number}' class Deposit(models.Model): customer = models.ForeignKey(Customer, on_delete=models.CASCADE, null=True) acct = models.CharField(max_length=6, null=True) staff = models.ForeignKey(User, on_delete=models.CASCADE, null=True) deposit_amount = models.PositiveIntegerField(null=True) date = models.DateTimeField(auto_now_add=True) def get_absolute_url(self): return reverse('create_account', args=[self.id]) def __str__(self): return f'{self.customer} Deposited {self.deposit_amount} by {self.staff.username}' here is my view code: def customer_list(request): #Get Current Date current_date = datetime.now().date() #Get Current Month Name from Calendar current_month_name = calendar.month_name[date.today().month] group_deposits = Deposit.objects.filter(date__year=current_date.year).order_by('acct') grouped_customer_deposit = group_deposits.values('acct').annotate(total `=Sum('deposit_amount')).order_by()` context = { 'customers':grouped_customer_deposit,} Here is how I tried to display … -
menu dissapear in django
I have a problem with menu in html in django the problem is in index page menu works perfectly fine, but in other apps such as projects or blog pages menu loads ok but when you scroll down and scroll up menu dissapears and i have to reload the page, i have added menu in database so i can add things in admin panel, here is my codes: views.py def proindex(request): setting = Setting.objects.all().get() menu = SettingMenu.objects.all().get() proj = Project.objects.all() context = {'setting': setting, 'menu': menu, 'proj': proj, 'navbar': 'projects'} return render(request, "projects.html", context) models.py class Setting(models.Model): Website_Title = models.CharField(max_length=200) Footer_Text = models.CharField(max_length=10000) Header_Text1 = models.CharField(max_length=200, default="Text") Header_Text2 = models.CharField(max_length=200, default="Text") Banner_Text1 = models.CharField(max_length=200, default="Text") Banner_Text2 = models.CharField(max_length=200, default="Text") Banner_Button = models.CharField(max_length=200, default="Text") def __str__(self): return "Website Settings" class SettingMenu(models.Model): Admin_Panel = models.CharField(max_length=200) Admin_Link = models.CharField(max_length=200) Menu_Item1 = models.CharField(max_length=200) Menu_Link1 = models.CharField(max_length=200) Menu_Item2 = models.CharField(max_length=200) Menu_Link2 = models.CharField(max_length=200) Menu_Item3 = models.CharField(max_length=200) Menu_Link3 = models.CharField(max_length=200) Menu_Item4 = models.CharField(max_length=200) Menu_Link4 = models.CharField(max_length=200) Menu_Item5 = models.CharField(max_length=200) Menu_Link5 = models.CharField(max_length=200) Menu_Item6 = models.CharField(max_length=200) Menu_Link6 = models.CharField(max_length=200) Menu_Item7 = models.CharField(max_length=200) Menu_Link7 = models.CharField(max_length=200) Menu_Item8 = models.CharField(max_length=200) Menu_Link8 = models.CharField(max_length=200) def __str__(self): return "Menu Settings" base.html <!-- ***** Header Area Start ***** --> <header class="header-area header-sticky"> … -
Django autocomplete prompts are not working on a search bar text field
I am looking to implement autocomplete on a search field which is in the header of each webpage (layout.html). The search bar searches on a model field named 'Title'. While the search itself is working, I cannot get autocomplete to work, any help is greatly appreciated. I will include the search code as well in case they are somehow in conflict in a way I have not identified. Views.py ################# Search ##################### # attempts to search for title, OR Number, OR Title And Number -> looks to replace the '#' before a number if someone enters it that way, it does not always work with # #It works with a partial name OR full name OR number OR Full Name and Number @login_required(login_url="/login/") def SearchPage(request): srh = request.GET.get('search') title = "" number = "" title_match = re.search(r'(.*)\b(#*\d+)', srh) if title_match: title = title_match.group(1) number = title_match.group(2) number = number.replace("#", "") else: title_number_match = re.search(r'(#*\d+)', srh) if title_number_match: number = title_number_match.group(1) number = number.replace("#", "") else: title = srh title = title.strip() number = number.strip() if title and number: comics = ComicInput.objects.filter(Title=title, Number=number,Category='Sell') elif title: comics = ComicInput.objects.filter(Title__icontains=title,Category='Sell') elif number: comics = ComicInput.objects.filter(Number__icontains=number,Category='Sell') else: comics = ComicInput.objects.filter(Category='Sell') params = {'comics': comics, … -
object has no attribute 'title'. Updating Many to many field
am trying to create a form where by a user can upload image. The image and the Item have different form i join them together. The challenge is that Image is related to Item with manaytomyfield. i want after a user saved this form, the items field in images table to be updated to the title field in Items table i try to get this from django document but i realize that the document explaination is static but in my case i want it to be dynamic. this is my view def itemupload(request): message = 'Invalid Form' # success = 'Success' user= request.user items = Items.objects.all() if request.method =='POST': imageform = ImageForm(request.POST, request.FILES) form =ItemsForm(request.POST, request.FILES) if form.is_valid() and imageform.is_valid: item =form.save(commit=False) item.user =request.user item.save() images=imageform.save(commit=False) **images.save() images.items.title.add(item)** return redirect('index') return message imageforms =ImageForm() itemsform = ItemsForm context = { 'imageforms': imageforms, 'itemsform':itemsform, } return render(request, 'jijiapp/itemform.html', context) this is the model class Items(models.Model): user = models.ForeignKey(User, on_delete = models.CASCADE, related_name='useritem') title = models.CharField(max_length=10, null=True, blank =True) price = models.CharField(max_length=20, null=True, blank=True) phone = models.CharField(max_length=20, null=True, blank=True) location =models.CharField(max_length=20, null=True, blank=True) post_date = models.DateTimeField(auto_now_add=True, null=True, blank=True) def __str__(self): return self.title class Meta: ordering =['title',] # verbos_name ='Items' class Images(models.Model): image …