Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Nested select_related to get data from various models django ORM
i have 5 models below: class Products: product_name=models.CharField(max_length=300,blank=True) product_price=models.IntegerField(blank=True) class ProductImages(models.Model): image=models.ImageField(upload_to='product_images',null=True,blank=True) image_product=models.ForeignKey(Product,on_delete=models.CASCADE) class ProductModel(models.Model): model_product=models.ForeignKey(Product,null=True,on_delete=models.CASCADE) model_name=models.CharField(max_length=130,blank=True) class Colour(models.Model): colour_name=models.CharField(max_length=20,blank=True) colour_product=models.ForeignKey(Product,on_delete=models.CASCADE) class Sale: name=models.CharField(max_length=30,null=True,blank=True) class ProductSale: saleid=models.ForeignKey(Sale,on_delete=models.CASCADE) product=models.ForeignKey(Product,on_delete=models.CASCADE) I am filtering and getting products present in ProductSale on the basis of sale id prod=ProductSale.objects.filter(sale=sale.id).prefetch_related('product') Now i have product ids, but i want additional details also that is product images,colour,Model which is present in ProductImages model,Colour model,ProductModel model.How can i achieve this in most optimize way below is my try but its taking time and not optimized. prod=ProductSale.objects.filter(sale=sale.id).prefetch_related('product') for prod in prod: pm=ProductModel.objects.filter(model_product=prod.product_id).values() pc=Colour.objects.filter(colour_product=prod.product_id).values() images=prod.product.productimages_set.all().order_by('id')[:2].values() sale_product.append({"product_id":prod.product.id,"product_name":prod.product.product_name,"stock":prod.product.product_quantity,"product_price":prod.product.product_price, "sale_price":prod.product.sale_price,"saleprice_startdate":prod.product.saleprice_startdate, "saleprice_enddate":prod.product.saleprice_enddate,"product_category":prod.product.category_name,"product_reviews":review_product,"review_count":len(pr), "product_images":images,'product_colour':pc,'product_model':pm}) How can i optimize the query get the data in a format which i am using in a dictionary, Kindly help badly stuck in this. -
Queryset with annotate Subquery with OuterRef and Sum
I'm trying to return the sum of fields from another model inside a Subquery. My main queryset returns all users of type company. I have to return the total of credits used by taking the data from CreditOrder and Sum the credit_used field My CreditOrder model class CreditOrder(ClusterableModel): credit = ParentalKey( Credit, on_delete=models.CASCADE, related_name="credit_order" ) order = ParentalKey(Order, on_delete=models.CASCADE, related_name="credit_order") credit_used = models.DecimalField( max_digits=12, decimal_places=2, null=True, blank=True ) My queryset def get_queryset(self, request): qs = super().get_queryset(request) qs = qs.filter(user_type='company') credits_used_subquery = Subquery(CreditOrder.objects.filter(credit__font__company__id=OuterRef('id')).order_by() .values('credit_used').annotate(credit_used_sum=Sum('credit_used')) .values('credit_used_sum'), output_field=DecimalField()) qs = qs.annotate( _credits_used_sum=credits_used_subquery ) return qs But this error is returning me: django.db.utils.ProgrammingError: more than one row returned by a subquery used as an expression -
How to implement writing to the Python/Django database on the server side using the methods of the PyDriller library?
Good afternoon. Help me solve the problem. I'm trying to parse the commit data from github. The user enters the URL of the repository in the form on the "index" page, from there the string is read and written to the database. Next, on the server side, using the Pydriller library, I want to implement getting data about comets (the user does not enter them himself). The results page should display the results - the entered URL and the data itself. To get the comet data (not in the django project, but by creating a Platonic file separately and running it), I use the following code: for commit in Repository(url_text).traverse_commits(): commit_url = url_text + '/commit/' + commit.hash print('Hash: {}; ' .format(commit.hash)) if I execute the "commit.hash" method, I will get a string in the output. Now I want to implement this in my project. There is an implemented class and a model, for example models.py: class UrlRepository(models.Model): # full path to the repository url_text = models.CharField('URL адрес репозитория', max_length=255) def __str__(self): return self.url_text class Meta: verbose_name = 'URL адрес' verbose_name_plural = 'Список URL адресов' class Commit(models.Model): commit_hash = models.CharField('Hash', max_length=50, blank=True) forms.py: class UrlRepositoryForm(ModelForm): class Meta: model = UrlRepository fields … -
How do I individually render radio buttons and file field in django?
I need to individually render radio buttons and the filefield in django. How do I do that? models.py: class Complaint(models.Model): user = models.ForeignKey(User, on_delete= models.CASCADE, null = True, blank=True) title = models.CharField(max_length=300) description = models.TextField(null=True, blank= True) highpriority = models.CharField(max_length=200, blank=True) document = models.FileField(upload_to='static/documents', blank=True, null=True) def __str__(self): return self.title forms.py: PRIORITY_CHOICES= [ ('high', 'High'), ('low', 'Low'), ] class ComplaintForm(ModelForm): highpriority = forms.CharField(label='Priority', widget=forms.RadioSelect(choices=PRIORITY_CHOICES)) class Meta: model = Complaint fields = ['title', 'description'] #'highpriority', 'document'] def clean(self): cleaned_data = super(ComplaintForm, self).clean() title = cleaned_data.get('title') description = cleaned_data.get('description') if not title and not description: raise forms.ValidationError('You have to write something!') return cleaned_data views.py: def NewComplaint(request): user = request.user if request.method == 'POST': form = ComplaintForm(request.POST) print(form) if form.is_valid(): print("hello") cmp_obj = form.save(commit=False) cmp_obj.user = user cmp_obj.save() submitbutton= request.POST.get('submit') if submitbutton: messages.success(request, 'Submitted!') context = {'form': form} return render(request, 'new.html', context) else: form = ComplaintForm() context = {'form': form} return render(request,'new.html',context) template: <!-- Middle Container --> <div class="col-lg middle middle-complaint-con"> <i class="fas fa-folder-open fa-4x comp-folder-icon"></i> <h1 class="all-comp">New Complaint</h1> <form class="" action="" method="POST" enctype="multipart/form-data"> {% csrf_token %} <div class="form-control col-lg-10 comp-title-field" name="title">{{form.title}}</div> <p class="desc">Description</p> <button type="button" class="btn btn-secondary preview-btn">Preview</button> <div class="Descr " name="description">{{form.description}}</div> {{message}} <button type="file" name="myfile" class="btn btn-secondary attach-btn"><i class="fas fa-file-upload"></i> Attachment</button> … -
Filtering the specific data for response in DRF
I have following response data [ { "id": 7, "name": "Default Group", "permissions": [ 22, 24 ] }, { "id": 10, "name": "Another Group", "permissions": [ 1, 2, 22, 24 ] }, { "id": 11, "name": "New Group", "permissions": [ 10, 11, 12, 5, 6, 7, 8 ] }] But I want to remove the dictionary whose id = 10 from the response data ,how can I do that ? I have following lines of code.. class GetUserGroupList(APIView): def post(self, request, *args, **kwargs): groups = Group.objects.all() serializer = GroupSerializer(groups, many=True) return Response(serializer.data) In serializers.py class GroupSerializer(serializers.ModelSerializer): class Meta: model = Group fields = ('id', 'name', 'permissions',) Any help would be appreciated !! -
how to show related product in Django?
I have about 10 + models where I'm showing the 3 of them. Where the name is motors, drum, slide. Now in these three models, one field is the same which is the name code. Trying to explain: models.py class Motors(models.Model): . . code = models.CharField(max_length=10) . . . def __str__(self): return str(self.id) class Drum(models.Model): . . code = models.CharField(max_length=10) . . . def __str__(self): return str(self.id) class Sliders(models.Model): . . code = models.CharField(max_length=10) . . . def __str__(self): return str(self.id) Now in the above model, they have the same field as code. And in the code, they have the same name like for eg: in one model the code is DD1, DD2, DD3 and another model code is DD1, DD2, DD3. Now in the Above, the codes are matching. So, if the user selects one motor with Code DD1. Then show the related 2 models with code DD1 or if the user selects one drum with code DD1. Then show related two models items in Django I had used add to cart functionality the code goes here. views.py def addProductMotor(request): user = request.user motor_id = request.GET.get('motor_id') motor_cart = Motor.objects.get(id=motor_id) Cart(user=user, motor=motor_cart).save() return redirect('main:index') In the above, I add one … -
Test of creating new post with image not working. Django
I'm learning Django and created easy blog-like site, where user can create new post. When I try add new post with image on site all work fine, but when I try run test, he don't create new post with image and returning error. Why and how can I fix it? test_forms.py: class PostCreateFormTests(TestCase): @classmethod def setUpClass(cls): super().setUpClass() cls.author = User.objects.create_user(username='author') settings.MEDIA_ROOT = tempfile.mkdtemp(dir=settings.BASE_DIR) cls.small_gif = ( b'\x47\x49\x46\x38\x39\x61\x02\x00' b'\x01\x00\x80\x00\x00\x00\x00\x00' b'\xFF\xFF\xFF\x21\xF9\x04\x00\x00' b'\x00\x00\x00\x2C\x00\x00\x00\x00' b'\x02\x00\x01\x00\x00\x02\x02\x0C' b'\x0A\x00\x3B' ) cls.uploaded = SimpleUploadedFile( name='big.gif', content=cls.small_gif, content_type='image/gif' ) cls.group = Group.objects.create( title='test group', slug='test-test', description='super-mega-test-group', ) cls.post = Post.objects.create( text='Тестовый текст', author=cls.author, group=cls.group, image=cls.uploaded, ) @classmethod def tearDownClass(self): shutil.rmtree(settings.MEDIA_ROOT, ignore_errors=True) super().tearDownClass() def setUp(self): self.guest_client = Client() self.authorized_client = Client() self.authorized_client.force_login(self.author) def test_create_post(self): """Form create new post.""" posts_count = Post.objects.count() form_data = { 'text': 'Test text', 'group': self.group.id, 'image': self.uploaded, # If I comment this line test will work fine. } response = self.authorized_client.post( reverse('new_post'), data=form_data, follow=True ) self.assertEqual(response.status_code, HTTPStatus.OK) self.assertEqual(Post.objects.count(), posts_count + 1) post_get = Post.objects.get(pk=2) self.assertEqual(post_get.text, form_data['text']) self.assertEqual(post_get.group, self.group) self.assertEqual(post_get.author, form_data['author']) self.assertEqual(post_get.image, 'posts/big.gif') # and this views.py: @login_required def new_post(request): form = PostForm(request.POST or None, files=request.FILES or None) if form.is_valid(): post = form.save(commit=False) post.author = request.user post.save() return redirect('index') return render(request, 'new.html', {'form': form}) ) The error … -
Show liked post by ManyToMany Users
I am building a small Blog app in Django. I am making a functionality in which user_x can add multiple users as favorite ( With the help of ManyToManyField ) and user_x will be able to see the liked posts of favorite users. BUT when i try to access posts which are liked by request.user's favorite users. Then it is nothing showing. models.py class BlogPost(models.Model): post_user = models.ForeignKey(User,on_delete=models.CASCADE) title = models.CharField(max_length=509) likes = models.ManyToManyField(User, related_name='likes_of_post', blank=True) class FavouriteUsers(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE) favourite_users = models.ManyToManyField(User, related_name='favourite_users', blank=True) views.py def favourite_users_page(request): users = FavouriteUsers.objects.filter(favourite_users=request.user) context = {'users':users} return render(request, 'favourite_users.html', context) favourite_users.html {% for use in users %} {% for pos in use.post_set.likes.all %} {{ pos.title }} {% endfor %} {% endfor %} I have also tried :- {% for pos in likes.all %} {{ pos }} {% endfor %} BUT it is showing all users which liked by post but i am trying to show only favorite users. Any help would be Much Appreciated. -
Import data from a CSV file without id as column
I would like to know if it's possible to import data but with a table that does not have a column named id My import are doing fine with every table that contained a column id but with the one that does not contained a column id it does not work. I got a row_error saying : Error: 'id' -
Including CSRF token in HTTP POST request to a Django server by using HttpUrlConnection class in Android
In my Django project, the view method to handle a HTTP POST request is as : def receive_message(request): if request.method == "POST": data = request.body print(str(data, 'UTF-8')) return HttpResponse(str(data, 'UTF-8'), content_type="application/json") And my code in Android project to make that HTTP POST request is as : HttpURLConnection connection=null; BufferedWriter writer=null; BufferedReader reader=null; if (strings==null){ uploadStatus=UploadStatus.IDLE; return null; } try{ uploadStatus=UploadStatus.PROCESSING; URL url = new URL(strings[0]); connection = (HttpURLConnection) url.openConnection(); CookieManager cookieManager = new CookieManager(); CookieHandler.setDefault(cookieManager); cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL); if (cookieManager.getCookieStore().getCookies().size() > 0) { List<HttpCookie> cookies = cookieManager.getCookieStore().getCookies(); if (cookies != null) { for (HttpCookie cookie : cookies) { connection.setRequestProperty("Cookie", cookie.getName() + "=" + cookie.getValue()); } } } Log.d(TAG, "doInBackground: connecting"); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/json"); connection.setRequestProperty("Accept", "application/json"); Log.d(TAG, "doInBackground: connected"); Log.d(TAG, "doInBackground: connecting input stream"); Log.d(TAG, "doInBackground: response code is : "+connection.getResponseCode()); Log.d(TAG, "doInBackground: response message is "+connection.getResponseMessage()); StringBuilder result = new StringBuilder(); reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); // String line; // while(null != (line = reader.readLine())) { for(String line = reader.readLine(); line != null; line = reader.readLine()) { result.append(line).append("\n"); } Log.d(TAG, "doInBackground: input stream connected"); uploadStatus=UploadStatus.OK; return result.toString(); } catch(MalformedURLException e) { Log.e(TAG, "doInBackground: Invalid URL " + e.getMessage() ); } catch(IOException e) { Log.e(TAG, "doInBackground: IO Exception writing data: " + e.getMessage()); … -
What are the server requirements on Amazon EC2 to run Django for about 1000 users?
To tell you the truth, I'm actually a beginner and not so good at English. Database aside (already on another server), let's suppose there are 1000 users surfing simultaneously on the website. They can retrieve a restaurant menu, do some groceries, pantries, takeouts and search for them (there are multiple restaurants). I'll need the minimal requirements for these tasks. If you some tools to do it, I'll take it too. But, I need it to be free (no online account due to country constraints). -
CurrentDate variable not display as Value in input box
I was wondering what's wrong with the form I made. It's a Date Input text box where it automatically populates the current date. Could someone point out what's wrong? from datetime import date today = date.today() currentDate = today.strftime("%m/%d/%Y") class DateInput(forms.DateInput): input_type = 'date' class salesForm(forms.Form): entryDateField = forms.DateField(label="Entry Date", widget=DateInput(attrs={'value': currentDate, 'readonly': 'readonly', 'class':'col-sm-8'})) -
Django: Quantity matching query does not exist
I am trying to build a food ordering web app for a restaurant. I want the customer to be able to select the quantity of items that he/she orders, but I don't know exactly how do I do it. Being the site admin, I want to see what items a customer has ordered along with their quantity. Here is my code snippet: views.py class Order(View): def get(self, request, *args, **kwargs): sandwiches = MenuItem.objects.filter(category__name__contains='Sandwich') pizzas = MenuItem.objects.filter(category__name__contains='Pizza') drinks = MenuItem.objects.filter(category__name__contains='Drink') # pass into context context = { 'sandwiches': sandwiches, 'pizzas': pizzas, 'drinks': drinks, } # render the template return render(request, 'customer/order.html', context) def post(self, request, *args, **kwargs): name = request.POST.get('name') email = request.POST.get('email') order_items = { 'items': [] } items = request.POST.getlist('items[]') for item in items: menu_item = MenuItem.objects.get(pk=int(item)) item_quantity = Quantity.objects.get(pk=int(item)) item_data = { 'id': menu_item.pk, 'name': menu_item.name, 'price': menu_item.price, 'count': item_quantity.count } order_items['items'].append(item_data) price = 0 item_ids = [] for item in order_items['items']: price += item['price']*item['count'] item_ids.append(item['id']) order = OrderModel.objects.create( price=price, name=name, email=email ) order.items.add(*item_ids) context = { 'items': order_items['items'], 'price': price } return render(request, 'customer/order_confirmation.html', context) models.py from django.db import models class MenuItem(models.Model): name = models.CharField(max_length=100) description = models.TextField() image = models.ImageField(upload_to='menu_images/') price = models.DecimalField(max_digits=5, decimal_places=2) category = … -
form not getting validated in django
Can someone please tell me what is wrong with my form? My form is not getting validated and I do not know why. forms.py: class ComplaintForm(ModelForm): highpriority = forms.CharField(label='Priority', widget=forms.RadioSelect(choices=PRIORITY_CHOICES)) class Meta: model = Complaint fields = ['title', 'description', 'highpriority', 'document'] def clean(self): cleaned_data = super(ComplaintForm, self).clean() title = cleaned_data.get('title') description = cleaned_data.get('description') if not title and not description: raise forms.ValidationError('You have to write something!') this is the views.py:(I added print(form) and print("Hello") in the code to see if the form is getting validated or not but the print("Hello") statement is not getting printed. THe form does get printed though) def NewComplaint(request): user = request.user if request.method == 'POST': form = ComplaintForm(request.POST) print(form) if form.is_valid(): print("hello") cmp_obj = form.save(commit=False) cmp_obj.user = user cmp_obj.save() submitbutton= request.POST.get('submit') if submitbutton: messages.success(request, 'Submitted!') context = {'form': form} return render(request, 'new.html', context) else: form = ComplaintForm() context = {'form': form} return render(request,'new.html',context) This is my template: <div class="col-lg middle middle-complaint-con"> <i class="fas fa-folder-open fa-4x comp-folder-icon"></i> <h1 class="all-comp">New Complaint</h1> <form class="" action="" method="POST" enctype="multipart/form-data"> {% csrf_token %} <div class="form-control col-lg-10 comp-title-field" name="title">{{form.title}}</div> <p class="desc">Description</p> <button type="button" class="btn btn-secondary preview-btn">Preview</button> <div class="Descr " name="description">{{form.description}}</div> {{message}} <button type="file" name="myfile" class="btn btn-secondary attach-btn"><i class="fas fa-file-upload"></i> Attachment</button> <button type="submit" name="submit" … -
How to add progress bar while uploading using django
I'am working on Django project and I need to add progress bar while uploading file.I have tried celery. -
how can i resolve the issue in displaying the ajax search results in django?
Problem The results are being retrieved by the ajax search function but when I display the data retrieved in the selector using $(selector).htm(data) it loads whole the page with a page with correct search results. The code is attached below with the screenshot of what I'm getting from this code for a better understanding. JS $('#searchsubmit').on('click', function(e){ e.preventDefault(); q = $('#search').val(); console.log(q); updateContentBySearch(q); }); function updateContentBySearch(q) { var data = {}; data['search_by'] = q // data["csrfmiddlewaretoken"] = $('#searchform [name="csrfmiddlewaretoken"]').val(); $.ajax({ method: 'POST', url: "{% url 'main:Search' %}", data: { 'search_by': q, 'csrfmiddlewaretoken' : $("input[name=csrfmiddlewaretoken]").val() }, success: function (data) { searchSuccess(data) } }); } function searchSuccess(data, textStatus,jqXHR) { $('#search-results').html(data); } HTML <div class="row"> <div class="row justify-content-center" style="text-align:center"> <form class="d-flex col-md-6" id="searchform" method="POST"> {% csrf_token %} <div class="input-group mb-3" style="text-align:center"> <input name="q" type="text" class="form-control" placeholder="Search" id="search"> <button class="btn btn-primary shadow px-5 py-2" type="submit" id="searchsubmit">Search</button> </div> </form> </div> <hr style="border-top: 1px solid #ccc; background: transparent;"> <div class="row" id="search-results"> {% regroup transaction by productID as ProductList %} {% for productID in ProductList %} ///some code </div> {% endfor %} </div> VIEWS @csrf_exempt def search(request): q = request.POST.get('search_by') print(q) product = Products.objects.all() cart_product_form = CartAddProductForm() transaction = transactions.objects.filter(productID__name__icontains=q,status='Enable').order_by('productID') print(transaction) context={ 'products':product, 'transaction': transaction, 'cart_product_form':cart_product_form } … -
Django HTML template not rendering content
I am building an notifcation system. I am almost complete the notifcation system. Now my problem is notifcation content not rendering my html template. I am not understanding where I am doing mistake.here is my code: notifications models.py: class Notifications(models.Model): blog = models.ForeignKey('blog.Blog',on_delete=models.CASCADE) NOTIFICATION_TYPES = (('New Comment','New Comment'),('Comment Approved','Comment Approved'), ('Comment Rejected','Comment Rejected')) sender = models.ForeignKey(User, on_delete=models.CASCADE, related_name="noti_from_user") user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="noti_to_user") notification_type = models.CharField(choices=NOTIFICATION_TYPES,max_length=250) text_preview = models.CharField(max_length=500, blank=True) date = models.DateTimeField(auto_now_add=True) is_seen = models.BooleanField(default=False) views.py def ShowNOtifications(request): user = request.user notifications = Notifications.objects.filter(user=user).order_by('-date') Notifications.objects.filter(user=user, is_seen=False).update(is_seen=True) template_name ='blog/notifications.html' context = { 'notify': notifications, } return render(request,template_name,context) #html {% for notification in notifications %} {% if notification.notification_type == "New Comment" %} @{{ notification.sender.username }}You have received new commnet <p>{{ notification.text_preview }}</p> {%endif%} {%endfor%} why notification content not showing in my html template? where I am doing mistake? -
Why getting settings.DATABASES is improperly configured. Please supply the ENGINE value.?
I have not written so much line just created a new database in setting.py and routers file in django project. After this run following command in shell and every this goes well and a new file with name auth_db.db.sqlite3 create. python manage.py migrate --database=auth_db C:\Users\Admin\Desktop\project\assignment>python manage.py createsuperuser --database=auth_db Username (leave blank to use 'admin'): admin Email address: admin@gmail.com Password: Password (again): The password is too similar to the username. This password is too short. It must contain at least 8 characters. This password is too common. Bypass password validation and create user anyway? [y/N]: y Superuser created successfully. But when i tried to login in admin panel i get error as:- settings.DATABASES is improperly configured. Please supply the ENGINE value. Check settings documentation for more details. -
fetching data from database ajax with django based on click button
I'm trying to show some data as notification click on the button the view will appear class Post(models.Model): title = models.CharField(max_length=40) boolean = models.BooleanField(default=False) my views.py from django.core import serializers @login_required def alerts(request): if request.is_ajax(): lists = Post.objects.filter() list_serializer = serializers.serialize('json',lists) return JsonResponse(list_serializer,safe=False) return JsonResponse({'message':'bad request'}) $(document).ready(function(){ $('.myBtn').click(function(){ $.ajax({ url:'{% url 'booking:alerts' %}', type:'json', method:'GET', success:function(data){ var k; for(i=0; i<data.length; i++){ k = '<div class="p-2 mt-1 text-center bgpurple textpurple">' k+= '<p class="p-1 text-white border-2 bgpurple rounded-3xl">'+data[i]['title']+'</p>' k+='</div>'; } console.log(data) document.getElementById('notification').innerHTML = k; } }) }) }) <div class="fixed z-50 w-1/5 h-screen overflow-y-scroll shadow-xl header" id="notification"> <button class="px-4 py-1 m-2 bg-opacity-75 rounded-lg bgorange focus:outline-none myBtn" onclick="showNotifcation()"><i class="bi bi-x"></i></button> <!-- im trying to show the data here --> </div> <button class="relative px-6 py-1 rounded-full focus:outline-none textpurple" onclick="showNotifcation()" style="background-color: #ed9720;"> <span class="absolute top-0 w-4 h-4 text-xs rounded-full left-3 bgpurple" style="color: #ed9720;">display quantity of posts here</span> <i class="fas fa-bell "></i> </button> but it doesnt show anything except in the console return a dictionary is there something i have to change or add please ! -
Added prefix to django tables resulted in ProgrammingError. How can i solve it?
I have added prefix to all my tables in DB using package https://pypi.org/project/django-db-prefix/ I have made all migrations, and when I run the server its working fine. I am not able to open any page and is showing ProgrammingError File "/home/aryan/anaconda3/envs/shiraz/lib/python3.9/site-packages/django/db/backends/utils.py", line 98, in execute return super().execute(sql, params) File "/home/aryan/anaconda3/envs/shiraz/lib/python3.9/site-packages/django/db/backends/utils.py", line 66, in execute return self._execute_with_wrappers(sql, params, many=False, executor=self._execute) File "/home/aryan/anaconda3/envs/shiraz/lib/python3.9/site-packages/django/db/backends/utils.py", line 75, in _execute_with_wrappers return executor(sql, params, many, context) File "/home/aryan/anaconda3/envs/shiraz/lib/python3.9/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "/home/aryan/anaconda3/envs/shiraz/lib/python3.9/site-packages/django/db/utils.py", line 90, in __exit__ raise dj_exc_value.with_traceback(traceback) from exc_value File "/home/aryan/anaconda3/envs/shiraz/lib/python3.9/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) django.db.utils.ProgrammingError: relation "django_session" does not exist LINE 1: ...ession_data", "django_session"."expire_date" FROM "django_se... ^ [07/Jul/2021 05:53:37] "GET /sr_admin/signin/ HTTP/1.1" 500 181053 After migrations all the default tables like 'django_session', 'django_migrations', 'auth_group' etc. are also overridden, and I hope the error is because of that. What should I do to solve this? -
Linkage between pages not working but no error in powershell
I'm a beginner in python-django coding. Currently I am following this guide and doing the challenging part for the author page (https://developer.mozilla.org/en-US/docs/Learn/Server-side/Django/Generic_views) but I am facing a issue of the page im trying to set up is not loading. Page is catalog/authors. The catalog page is workable Below are the codes: urls.py: from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), path('books/', views.BookListView.as_view(), name='books'), path('book/<int:pk>', views.BookDetailView.as_view(), name='book-detail'), path('authors/', views.AuthorListView.as_view(), name ='authors'), path('authors/<int:pk>', views.AuthorDetailView.as_views(), name='author-detail'), ] views.py: from django.shortcuts import render # Create your views here. from .models import Book, Author, BookInstance, Genre def index(request): """View function for home page of site.""" # Generate counts of some of the main objects num_books = Book.objects.all().count() num_instances = BookInstance.objects.all().count() # Available books (status = 'a') num_instances_available = BookInstance.objects.filter(status__exact='a').count() # The 'all()' is implied by default. num_authors = Author.objects.count() context = { 'num_books': num_books, 'num_instances': num_instances, 'num_instances_available': num_instances_available, 'num_authors': num_authors, } # Render the HTML template index.html with the data in the context variable return render(request, 'index.html', context=context) from django.views import generic class BookListView(generic.ListView): model = Book paginate_by = 5 class BookDetailView(generic.DetailView): model = Book class AuthorListView(generic.ListView): model = Author paginate_by = 5 class AuthorDetailView(generic.DetailView): model = Author author-list.html … -
Django- allow both images and text to be uploaded at the same time?
I would like to have a field in my models.py and forms.py to have the option to upload either photos or text, or both at the same time. Currently, I use a WYSIWYG editor to do that. How would I modify my models so that I can have that option? Here is my code so far: models.py class Problem(models.Model): slug = models.SlugField(null = False, unique = True, max_length = 255) topic = models.ForeignKey(Topic, on_delete = models.CASCADE) free = models.CharField(max_length = 1, choices = Free) #problem when introducing UUID field traceID = models.UUIDField(default=uuid.uuid4, editable = True) #use meta tags to optimize SEO metaTags = models.TextField(default = "") questionToProblem = models.TextField() #migration with CKEDitor is 0023_alter_problem_solutiontoproblem.py solutionToProblem = RichTextUploadingField(blank = True, null = True) The field solutiontoProblem is where I have my text editor- I want to have the field so that it accepts both text and images. Similarily, here is my forms.py: forms.py class ProblemForm(forms.ModelForm): slug = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'link'})) topic = forms.ModelChoiceField(label = "Topic", queryset = Topic.objects.all()) metaTags = forms.CharField(label = "Meta Tags", widget=forms.Textarea(attrs={"rows" : 15, "cols" : 90})) questionToProblem = forms.CharField(label = "Question", widget = QuestionFormWithPreview(attrs={'id' : 'mathInputForQuestion', 'cols': 90, 'rows': 15, 'onkeyup':'PreviewQuestion.Update()'})) solutionToProblem = forms.CharField(widget = CKEditorUploadingWidget(), label = … -
django TypeError: 'coroutine' object is not iterable
Here is the code snippet. I am fetching data from fatabase asynchronusly. but, I am getting below error for contract in contracts: TypeError: 'coroutine' object is not iterable @sync_to_async def get_all_contract_objects(): return EthereumContract.objects.all() def compute_topics_to_eventabis() -> Dict: "Loop through all contracts in our DB and compute topics to ABI mapping" topics_to_event_abis = {} contracts = get_all_contract_objects() for contract in contracts: print(contract) return topics_to_event_abis This part only need to fix. so that i can loop over contracts and print it. -
Is the data type of bid getting changed while I submit the data in HTML form?
I am working on a django project. I want to bid for an item. But when I enter a specific amount of float data it converts the type of the float data. I have been trying to solve this error for a couple of days but I didn't found a solution anywhere. This is what my bids model look like: models.py class bids(models.Model): auction = models.ForeignKey(auction_listing,on_delete=CASCADE) user = models.ForeignKey(User,on_delete=CASCADE) bid = models.FloatField(validators=[MinValueValidator(0.01)]) def __str__(self): return f"{self.bid}" Here is the view function of my code. views.py if request.method == "POST": if request.user.is_authenticated: bform = bid_form(request.POST) author = request.user post = listing user = request.user if bform.is_valid(): bid = bform.save(commit=False) biddata = bids(user=user,auction=post,bid=bid) biddata.save() return HttpResponseRedirect(reverse("displaylistitem",kwargs={"list_id" : list_id})) template.html <form action="" method="POST" class="form-inline"> {% csrf_token %} <div> {{ bform.as_table }} <input type="submit" name="bform" value="Submit" class="btn btn-warning text-light"> </div> </form> This form will redirect the user to the current page itself. But whenever I submit the form it gives this kind of weird error: TypeError while inserting float data. -
Posts liked by favorite user is not showing
I am building a Blog App and I made a model of Favourite Users with ManyToManyField in which a user can add multiple users as favorite users. I am trying to access the posts created by favorite users of user_1. AND I have successfully accessed the posts created by favorite users BUT now i am trying to access the likes hit by favorite users ( which posts are liked by favorite users ) BUT when i access it then it is showing nothing. models.py class Favourite(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE,related_name='user') favourites = models.ManyToManyField(User, related_name='favourites', blank=True) class Post(models.Model): post_creater = models.ForeignKey(User,default='',null=True,on_delete = models.CASCADE) post_title = models.CharField(max_length=500,default='') likes = models.ManyToManyField(User, related_name='post_like', blank=True) views.py def ParenCont(request): obj = Favourite.objects.filter(user=request.user) context = {'obj':obj} return render(request, 'favourite_users.html', context) favourite_users.html {% for objects in obj %} {% for favours in objects.favourites.all %} {% for posts in favours.post_set.all %} <!-- It is successfully showing the posts that are created by favorite users --> {% for post_likes in posts.likes.all %} {{ post_likes }} <!-- It is showing nothing --> {% endfor %} {% endfor %} {% endfor %} {% endfor %} I can understand that there is so much for loop in template but i convert this in view, …