Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Field 'id' expected a number but got '(string)
I'm creating a T-shirt shop with variants/colors. In adding to cart, I get the error: Field 'id' expected a number but got 'woodstock'. Woodstock is the name of the shirt, but I'm passing the cartid to the function. cartid is actually being used in the remove_from_cart function, but I'm not sure why the error is thrown when I push add to cart. Here's the cart model: class Cart(models.Model): #user = models.ForeignKey(User, null=True, blank=True, on_delete=models.CASCADE) total = models.DecimalField(max_digits=100, decimal_places=2, default=0.00) timestamp = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) active = models.BooleanField(default=True) def __str__(self): return "Cart id: %s" %(self.id) class CartItem(models.Model): cart = models.ForeignKey(Cart, on_delete=models.CASCADE, null=True, blank=True) product = models.ForeignKey(Product,on_delete=models.CASCADE) variations = models.ManyToManyField(Variation, blank=True) quantity = models.IntegerField(default=1) line_total = models.DecimalField(default=10.99, max_digits=100, decimal_places=2) timestamp = models.DateTimeField(auto_now_add=True, auto_now=False) updated = models.DateTimeField(auto_now=True) def __str__(self): try: return str(self.cart.id) except: return self.product.name views.py def view(request): print("viewing cart") try: the_id = request.session['cart_id'] except: the_id = None if the_id: cart = Cart.objects.get(id=the_id) new_total = 0.00 for item in cart.cartitem_set.all(): line_total = float(item.product.price) * item.quantity new_total += line_total request.session['items_total'] = cart.cartitem_set.count() cart.total = new_total cart.save() context = {"cart":cart} else: empty_message = "Your cart is empty, please keep shopping" context = {"empty": True, "empty_message": empty_message} template = "cart/view.html" return render(request, template, context) def … -
Django Send_mail with PDF attachment
I already done sending email with HTML template, I want to add a attachment(PDF) in email but I got an error. AttributeError: 'int' object has no attribute 'attach'. Can you give me an Idea on how to add attach file in sending email via send_email in django?Thank you Tree ├── Folder │ ├── management │ ├── templates │ │ └── p.pdf My send_mail command are inside the management folder send email code subject = 'Management Automated Email- ' + (item.emp) html_message = render_to_string('email.html',data) plain_message = item.emp recipient_list = [item.email] from_email = <email@gmail.com>' toaddrs = recipient_list mail = send_mail(subject, plain_message, from_email, toaddrs, html_message=html_message, fail_silently=False) mail.attach('papers.pdf', 'pdf/plain') mail.send() -
How to increase password compelxity of default user model in Django?
I am required to increase the password complexity of user model in Django, How can i do that i researched about it but didnt get a answer that satisfy my requirements , so please suggest -
Display several locations stored in my database into a google map APi
well im starting to look into google maps APis, so far i managed to set the map in html with the Api key: <div id="map"></div> <script src="https://maps.googleapis.com/maps/api/js?key=<myAPiKey>&callback=initMap&libraries=&v=weekly" async ></script> and i have the js code to set the map in the user location, but i dont know where to start to do what i asked above, i already have my database where users can register store addresses so i can show them in my map, im working with Django and SQLite3, can someone help me, is the first time i work with Google maps API's and documentation is confusing. Thank you so much for your time! -
django.core.exceptions.ImproperlyConfigured: Application labels aren't unique, duplicates: staticfiles?
registry.py code for entry in installed_apps: if isinstance(entry, AppConfig): app_config = entry else: app_config = AppConfig.create(entry) if app_config.label in self.app_configs: raise ImproperlyConfigured( "Application labels aren't unique, " "duplicates: %s" % app_config.label) -
Restarting celery and celery beat schedule relationship in django
Will restarting celery cause all the periodic tasks(celery beat schedules) to get reset and start from the time celery is restarted or does it retain the schedule? For example assume I have a periodic task that gets executed at 12 pm everyday. Now I restart celery at 3 pm. Will the periodic task be reset to run at 3 pm everyday? -
how to test django views that use requests module get method?
I know how to write django test code. But I don't know how to test with views that inlcude requests.get code View code is like this. class CertificateAPIView(APIView): permission_classes = [IsAuthenticated, IsOwner] def put(self, request): imp = request.data.get("imp") response = requests.get('another server') uid = response.get('uid') if uid == None: return Response( {"detail": ValidationError(_("Certification is failed"))}, status=status.HTTP_400_BAD_REQUEST, ) ... more condition branch logics. return ... imp value is automatically created by 'another server' that I am not managing. This code is related with another server response and check condition branch with response. But before getting response with imp vlue, we can't check whether response is error. -
Problem in uploading image from form in django
I am trying to upload image from django form but it is not taking any image. It shows no file chosen. I have done all media setting in settings.py and urls.py. Still unable to upload image. settings.py MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR,'media/') urls.py urlpatterns+=static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Also, I tried by using FileField in models.py models.py class Shop(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE) name = models.CharField(max_length=255) image = models.ImageField(upload_to='profile/',default='/profile/my.jpg') phone = models.CharField(max_length=10) shop_code = models.CharField(max_length=10,null=True,blank=True) forms.py class ShopForm(forms.ModelForm): class Meta: model = Shop exclude = ['user'] fields = ['name','image','phone'] widgets = { 'name':forms.TextInput(attrs={'class':'form-control'}), 'image':forms.FileInput(attrs={'class':'form-control'}), 'phone':forms.TextInput(attrs={'class':'form-control'}), } views.py def create_shop(request): if request.method == "POST": form = ShopForm(request.POST or request.FILES) if form.is_valid(): shop = form.save(commit=False) shop.user = request.user shop.shop_code = get_random_string(8) shop.save() return redirect('shop_profile_info') else: form = ShopForm() context = { 'form':form } return render(request,'shop_create.html',context) shop_create.html <form method="POST" enctype="multipart/form-data"> {% csrf_token %} {{ form }} <input type="submit" value="Submit" class="btn btn-dark mt-4"> </form> -
Django session variable value not up to date in view
i have two views to deal with some step processes. step 1: show all items with checkboxes, use ajax send seleted item's pk to backend by click button. There is a function at backend to set those values into session. def selecteditems(request): if request.is_ajax and request.method == "POST": request.session['selected'] = request.POST.getlist('items[]') request.session.modified = True return HttpResponse(status=200) step 2: get those variables from session and put them into second view. def step2(request): if request.method == "GET": selectedList = request.session.get('selected') allItems = Items.objects.all() selectedItem = allItems.filter(id__in=selectedList) context = { "selectedItem": selectedItem, } return render(request, 'step2.html', context) The problem i got is that, the second view always got "delay" values, meanning i have to refresh my page to load the latest items that i just selected, otherwise it is the data that i select in last time. -
Django model many to many through not working
i have mysql database that are already made. so models.py is created by manage.py inspectdb and i add artists = models.ManyToManyField(Artist, related_name='songs', through = "ArtistSong") to Song table like this. class Artist(models.Model): artist_id = models.IntegerField(primary_key=True) artist_name = models.TextField(blank=True, null=True) artist_main_genre = models.TextField(blank=True, null=True) class Meta: managed = False db_table = 'artist' class Song(models.Model): song_id = models.IntegerField(primary_key=True) issue_date = models.TextField(blank=True, null=True) album_name = models.TextField(blank=True, null=True) album_id = models.IntegerField(blank=True, null=True) song_name = models.TextField(blank=True, null=True) added_cnt = models.IntegerField(blank=True, null=True) thumb_url = models.TextField(blank=True, null=True) artists = models.ManyToManyField(Artist, related_name='songs', through = "ArtistSong") class Meta: managed = False db_table = 'song' class ArtistSong(models.Model): song = models.ForeignKey(Song, models.DO_NOTHING, blank=True, null=True) artist = models.ForeignKey(Artist, models.DO_NOTHING, blank=True, null=True) class Meta: managed = False db_table = 'artist_song' i want get name and artist name of song. my views.py here. class Songs(APIView): def get(self, request, *args, **kwargs): song_list= request.GET.get('song_list') queryset = Song.objects.filter(song_id__in = song_list) rec_songs = [] for song in queryset.iterator(): #for checking print(song.song_name) print(song.artists.all()) data = { 'song_name' : song.song_name, 'artist_name': [a.artist_name for a in song.artists.all()], } rec_songs.append(data) return Response(json.dumps(rec_songs,ensure_ascii = False)) print(song.song_name) shows song_name as i intened. print(song.artists.all()) shows nothing but <QuerySet []> please help! -
Do we need to close session explicitly in django request?
Let's say, we have class class Pipe(object): def __init__(self, imp_url=IAMPORT_API_URL): requests_session = requests.Session() requests_adapters = requests.adapters.HTTPAdapter(max_retries=3) requests_session.mount('https://', requests_adapters) self.requests_session = requests_session def get(self, url, payload=None) return self.requests_session.get(url, headers=headers, params=payload) views.py class RequestAPIView(APIView): pipe = Pipe() pipe.get(...) pipe.get(...) .... After call RequestAPIView, Do we need to close self.session explicitly in pipe object? Or after RequestAPIView done, Does the self.session will be closed automatically? -
Doing inference using pytorch saved weights in .tar file using django
I am doing a machine learning project where I need to display the predictions on a webpage. The webpage is build using Django. I have predictions function and the weights of the model but how to integrate the predictions function, model, and weights in the Django code and do predictions. My prediction code def predicting(model, device, loader): model.eval() total_preds = torch.Tensor() total_labels = torch.Tensor() with torch.no_grad(): for solute_graphs, solvent_graphs, solute_lens, solvent_lens in loader: outputs, i_map = model( [solute_graphs.to(device), solvent_graphs.to(device), torch.tensor(solute_lens).to(device), torch.tensor(solvent_lens).to(device)]) print(outputs) total_preds = torch.cat((total_preds, outputs.cpu()), 0) return total_preds.numpy().flatten() I have saved the weights in .tar file so I need to run the model while loading the weights for prediction. I have no idea where to keep my PyTorch model and the weights to do inference using Django. please help. -
'dict' object has no attribute 'META' redirect error
sorry for typos, I'm using translation I want to integrate virtual pos for payment method, but the error I got is as follows Error; 'dict' object has no attribute 'META' views.py: @login_required(login_url="/user/login") def payment(request): options = { 'api_key': 'api_key', 'secret_key': 'secret_key', 'base_url': 'sandbox-api.iyzipay.com' } payment_card = { 'cardHolderName': 'John Doe', 'cardNumber': '5528790000000008', 'expireMonth': '12', 'expireYear': '2030', 'cvc': '123', 'registerCard': '0' } buyer = { 'id': 'BY789', 'name': 'John', 'surname': 'Doe', 'gsmNumber': '+905350000000', 'email': 'email@email.com', 'identityNumber': '74300864791', 'lastLoginDate': '2015-10-05 12:43:35', 'registrationDate': '2013-04-21 15:12:09', 'registrationAddress': 'Nidakule Göztepe, Merdivenköy Mah. Bora Sok. No:1', 'ip': '85.34.78.112', 'city': 'Istanbul', 'country': 'Turkey', 'zipCode': '34732' } address = { 'contactName': 'Jane Doe', 'city': 'Istanbul', 'country': 'Turkey', 'address': 'Nidakule Göztepe, Merdivenköy Mah. Bora Sok. No:1', 'zipCode': '34732' } basket_items = [ { 'id': 'BI101', 'name': 'Binocular', 'category1': 'Collectibles', 'category2': 'Accessories', 'itemType': 'PHYSICAL', 'price': '0.3' }, { 'id': 'BI102', 'name': 'Game code', 'category1': 'Game', 'category2': 'Online Game Items', 'itemType': 'VIRTUAL', 'price': '0.5' }, { 'id': 'BI103', 'name': 'Usb', 'category1': 'Electronics', 'category2': 'Usb / Cable', 'itemType': 'PHYSICAL', 'price': '0.2' } ] request = { 'locale': 'tr', 'conversationId': '123456789', 'price': '1', 'paidPrice': '1.2', 'currency': 'TRY', 'installment': '1', 'basketId': 'B67832', 'paymentChannel': 'WEB', 'paymentGroup': 'PRODUCT', 'paymentCard': payment_card, 'buyer': buyer, 'shippingAddress': address, 'billingAddress': address, … -
m2m_changed signal with many-to-many through - save
I have these two basic models, class Product(models.Model): title = models.CharField(max_length=40) description = models.TextField(blank=True) price = models.DecimalField(decimal_places=2, max_digits=7, default=0) ... and class Cart(models.Model): user = models.ForeignKey( User, null=True, blank=True, on_delete=models.CASCADE) products = models.ManyToManyField( Product, blank=True, through='CartItem') total = models.DecimalField(default=0.00, max_digits=7, decimal_places=2) def recalculate_and_save(self): print("recalculate_and_save running") total = 0 for ci in self.cartitem_set.all(): total += ci.product.price*ci.quantity self.total = total self.save() , and a helper model for many-to-many relation above, to account for quantity: class CartItem(models.Model): cart = models.ForeignKey(Cart, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) quantity = models.SmallIntegerField(default=1) What I want to achieve is automatic calculation of Cart's total every time an item is added or removed. So, @receiver(m2m_changed, sender=CartItem) def m2m_changed_cart_receiver(sender, instance, action, *args, **kwargs): print(f"m2m_changed received; action={action}, instance={instance}") instance.recalculate_and_save() Then I realized, seeing pre_save and post_save actions in logs, that I'm likely doing something wrong - calling save in the function which is called (twice) from parent's save, as per docs. The first question is, then - why doesn't it send me into an infinite loop? And the second (and probably more important) - why am I only seeing the receiver function executing on removing items from the cart, but not on adding them? Removing is done via cart.products.remove(product_obj) , but … -
Django cant figure out how to use foreign key
''' class Project_types(models.Model): project_type = models.CharField(max_length=200) def __str__(self): return self.project_type class Projects(models.Model): project_types = models.ForeignKey(Project_types, on_delete=models.CASCADE) project = models.CharField(max_length=200) def __str__(self): return self.project ''' When I try to run - Project_types(project_type='games').item_set.all() I get an error saying that there is no attribute item set. -
Django filter json object's list by comparing with another list
I have a model that has a field which is a JSON field. This json_field has a value which is a list. model: attr1: attr2: attr3: json_field: { jattr1: jattr2: array_field: [values ...] } I have a queryset obtained from some other filter operation: queryset I want to apply model.objects.filter() such that I obtain every instance where array_field values are present in the queryset. For example: consider 4 instances instance1: json_field: { array_field: [1, 2, 3, 4] } instance2: json_field: { array_field: [2, 4] } instance3: json_field: { array_field: [1, 4] } instance4: json_field: { array_field: [3] } and queryset is : queryset: [2, 3] I am expecting something like this: Model.objects.filter(json_field__array_field__in=queryset) # This should return instance1: json_field: { array_field: [1, 2, 3, 4] } instance2: json_field: { array_field: [2, 4] } instance4: json_field: { array_field: [3] } Thank you for your help. -
Django how to add html style in JavaScript for load more button
I successfully implement load more button but now I can't add my html style in JavaScript. This is my original style before implement load more button. see the screenshot: after implementing load more button. I have style like this. see the screenshot below: How to implement my first style for individually showing each blog. here is my JavaScript for showing html: postsBox.innerHTML += `<div class="card mb-4" style="max-width:700px";> ${post.title} <br> ${post.body} </div> ` my .html page: <div id="posts-box"></div> <div id="spinner-box" class="not-visible"> <div class="spinner-border text-primary" role="status"></div> </div> <div id="loading-box"> <button class="btn btn-primary" id="load-btn">Load more</button> </div> -
Django - Disable authenticator for Swagger
So I have a Django app with Swagger, but I also added a custom authenticator to every endpoint automatically with REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'cheers.utils.authenticator.CognitoAuthentication', ), } How do I turn this off for swagger? The reason I'm not sure is because Swagger is added to URLs it's not a view How do I disable automatic authentication for swagger? Also I guess a side question would be how to disable this URL when debug is False -
Django dict(request.POST.lists()) returns twice(normal, empty)
Views.py @login_required(login_url="/users/login") def tresults(request): ids = dict(request.POST.lists()) print(ids) data = ids['selected'] msg = data.pop(0) HTML <form id = "{{ msg }}" action="tresults" method="POST"> <input type="hidden" name="selected" value="{{ msg }}"> <div class="table-responsive"> <table class="table table-bordered" id="dataTable" width="100%" cellspacing="0"> <thead> <tr> <th>GuildName</th> <th>GuildID</th> <th>Check</th> </tr> </thead> <tbody> {% for guild in guilds %} <tr> <td>{{ guild.name }}</td> <td>{{ guild.id }}</td> <td> {% csrf_token %} <input type="checkbox" name="selected" value="{{ guild.id }}"/> </td> </tr> {% endfor %} </tbody> </table> </div> </form> <a class="dropdown-item" href="#" onclick="document.forms['{{ msg }}'].submit();">Send</a> and I getting from print(ids) {'selected': ['61660a3afe554cfd1b4fe98f', '880716169986859039'], 'dataTable_length': ['10'], 'csrfmiddlewaretoken': ['OE9lhwbkU1KlKrDHiip1G6Yd5i9oOPS1bA0s2DapHY6RDbXc7UHc4KPd5jOlCLNm']} [13/Oct/2021 07:55:57] "POST /posts/post/tresults HTTP/1.1" 302 0 {} Internal Server Error: /posts/post/tresults I tried with various way like request.POST.dict() <- returns with only one value request.POST.copy() and dict(ids.iterlists()) or dict(ids) <- not working I don't know why two dict printed and last one is empty. I want to fix this -
Celery - What pool should I use for windows heavy cpu process and redis backend for status tracking?
I am running python 3.9, Windows 10, celery 4.3, redis as the backend, and aws sqs as the broker (I wasn't intending on using the backend, but it became more and more apparent to me that due to the library's restrictions on windows that'd I'd be better off using it if I could get it to work, otherwise I would've just used redis as the broker and backend). To give you some context, I have a webpage that a user interacts with to allow them to do a resource intensive task. If the user has a task running and decides to resend the task, I need it to kill the task, and use the new information sent by the user to create the new task. The problem for me arrives after this line of thinking: Me: "Hmmm, the prefork pool is used for heavy cpu background tasks... I want to use that..." Me: Goes and configures settings.py, updates the celery library, sets the environment variable to allow windows to run prefork pool - os.environ.setdefault('FORKED_BY_MULTIPROCESSING', '1'), sets a few other configuration settings, etc, runs the worker and it works. Me: "Hey, hey. It works... Oh, I still can't revoke a task … -
How to do predictions in django using restframe work
I am doing a machine learning project where I need to display the predictions on a webpage. The webpage is build using Django. I have predictions function and the weights of the model but how to integrate the predictions function, model, and weights in the Django code and do predictions. -
Celery task name is different in two workers
I have the following directory structure for a celery project: my_app ├── __init__.py ├── my_tasks.py I run the worker with exactly the same command celery -A my_app.my_tasks.post_request worker -l DEBUG in 2 nodes but got two different task names, one is absolute path: [tasks] . celery.accumulate . celery.backend_cleanup . celery.xxx . ... . my_app.my_tasks.post_request The other one is more like a relative path: [tasks] . celery.accumulate . celery.backend_cleanup . celery.xxx . ... . post_request How does celery generate the name of the task? I have read the section names of the official documentation but am still not able to find why the names are different in the two workers. -
Django why getting this error unsupported operand type(s) for -: 'NoneType' and 'int'
I am trying to implement load more button so I am writing this view for load json data but I am not understanding why I am getting this error. unsupported operand type(s) for -: 'NoneType' and 'int' here is my view: class PostJsonListView(View): def get(self, *args, **kwargs): print(kwargs) upper = kwargs.get('num_posts') lower = upper - 3 posts = list(Blog.objects.values()[lower:upper]) posts_size = len(Blog.objects.all()) max_size = True if upper >= posts_size else False return JsonResponse({'data': posts, 'max': max_size}, safe=False) -
Factoryboy can not generate database-dependent field
I use django-cities-light to store the user locations. However I need to import a huge dataset of countries & cities to the database. How can I create a factory that would automatically populate these fields during the tests? When not testing, the factory works properly by Country.objects.all(). But when testing, the database is empty and can not find any countries: IndexError: Cannot choose from an empty sequence. What should be the right approach for such cases? If you have a better solution to the use of LazyAttributes below, let me know the better approach. class UserProfileFactory(DjangoModelFactory): class Meta: model = UserProfile # ... birth_country = FuzzyChoice(Country.objects.all()) or None birth_region = factory.LazyAttribute( lambda o: o.birth_country.region_set.order_by("?").first() ) birth_subregion = factory.LazyAttribute( lambda o: o.birth_region.subregion_set.order_by("?").first() ) birth_city = factory.LazyAttribute( lambda o: o.birth_region.city_set.order_by("?").first() ) -
Django - How to filter and return data by groups
I have a model which I want to return group by an attribute of the object itself. Let's suppose the model is the next one: class User(): username = models.CharField(max_length=50, unique=True) group = models.CharField(max_length=20) Later in the view, I would be getting by group all the users: group1 = User.objects.filter(group='1') group2 = User.objects.filter(group='2') group3 = User.objects.filter(group='3') But that would return for each group the next structure: [{"username":"user1", "group":"1"}] [{"username":"user2", "group":"2"}] [{"username":"user3", "group":"3"}] How can I obtain the next structure (where the group is the root) directly from the filter or how can I combine the groups to achieve that: [ "1": [{"username":"user1","group":"1"}], "2": [{"username":"user2","group":"2"}], "3": [{"username":"user3","group":"3"}] ]