Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: write view based on multi-tenant static and media file structure
I am pretty confused about working with 'Django-tenants' in the regard of passing files to a function within a view. Here is my process: A tenant uploads a csv files that gets stored in his own media file (from django-tenant MULTITENANT_RELATIVE_MEDIA_ROOT). Then this file must pass through a python script that modifies the data and uploads it to this tenant's schema. the structure looks like that: media folder: tenant1: csv_file tenant2: csv_file view.py def etl(request): pd.read_csv(either tenant1 or tenant2 csv_file) # this is the part that is depending on the tenant [....] return render(request) although this process is not difficult, i am having trouble wrapping my mind about writing a view that would be applying to any tenant and not one particular tenant, especially because pd. read_csv needs the specific path. I was wondering if anyone had any help on this because I am really stuck and I cannot move forward. -
How to pass request.user correctly to query in Django Template
So I am attempting to query and display messages between two users in an inbox. I am running into a problem where no messages are appearing for request.user. It's showing as empty when there are messages. However, when I go into an inbox for another user that my request.user has messaged while still logged in to request.user, I can see the messages from both parties there and displayed correctly. So basically my current user cannot access their own messages. I know I need to pass request.user somehow into the template to query the messages correctly, but I'm not sure how. messages.html {% for msg in messages %} {% if msg.receiver_id == user.id %} <li class="text-right list-group-item">{{ msg.message }}<br/>{{ msg.date }}<br/>{{ request.user.username }}</li> {% elif msg.sender_id == user.id %} <li class="text-left list-group-item">{{ msg.message }}<br/>{{ msg.date }}</li> {% endif %} {% empty %} {%endfor %} views.py/messages def messages(request, profile_id): messages = InstantMessage.objects.filter(Q(sender_id=request.user, receiver_id=profile_id,) | Q(sender_id=profile_id, receiver_id=request.user,) ).\ values('sender_id','receiver_id', 'message', 'date', ).\ order_by('date',) return render(request, 'dating_app/messages.html', {'messages': messages,}) urls.py/messages path('messages/<int:profile_id>/', views.messages, name='messages') base.html/messages url href <a class="nav-link" href="{% url 'dating_app:messages' user.id %}">Check Messages</a models.py/InstantMessage class InstantMessage(models.Model): sender = models.ForeignKey(settings.AUTH_USER_MODEL, related_name= 'senderr',on_delete=models.CASCADE ) receiver = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) message = models.TextField() date = models.DateTimeField(auto_now_add=True) def … -
Download youtube video to user machine on Django website
Pretty much what the question says. Right now I have this function using pytube: `def download(request, video_url): url='http://www.youtube.com/watch?v='+str(video_url) homedir = os.path.expanduser("~") dirs = homedir + '/Downloads' download = YouTube(url).streams.first().download(dirs) return redirect('../../')` But this downloads the video to a directory '/Downloads/' in pythonanywhere - the site that I have uploaded my project to. How do I download the video to the user's machine? The solution doesn't have to be using the pytube package, as I just want an answer. It will be great if you tell me how to download the file as an .mp3 file too. Thanks in advance. -
How to check is model fiel empty or not before save it to database
I have a model which is template for creating objects League(models.Model): league = models.IntegerField(primary_key=True) league_name =models.CharField(max_length=200) country_code = models.ForeignKey("Country",null=True, on_delete=models.SET_NULL) season = models.ForeignKey("Season", null=True,on_delete = models.SET_NULL, to_field = "season") season_start = models.DateField(null = True) season_end = models.DateField(null = True) league_logo = models.URLField(null = True) league_flag = models.URLField(null = True) standings = models.IntegerField(null=True) is_current = models.IntegerField(null=True) cover_standings = models.BooleanField(null=True) cover_fixtures_events = models.BooleanField(null=True) cover_fixtures_lineups = models.BooleanField(null=True) cover_fixtures_statistics = models.BooleanField(null=True) cover_fixtures_players_statistics = models.BooleanField(null=True) cover_players = models.BooleanField(null=True) cover_topScorers = models.BooleanField(null=True) cover_predictions = models.BooleanField(null=True) cover_odds = models.BooleanField(null=True) lastModified = models.DateTimeField(auto_now=True) Data for creating objects from League model coming from external API #get data response = requests.get(leagues_url, headers = header) #cutting it and paste into variables to create objects from them leagues_json = response.json() data_json = leagues_json["api"]["leagues"] for item in data_json: league_id = item["league_id"] league_name = item["name"] country_q =Country.objects.get(country =item["country"]) season = Season.objects.get(season = item["season"]) season_start = item["season_start"] season_end = item["season_end"] league_logo = item["logo"] league_flag = item["flag"] standings = item["standings"] is_current = item["is_current"] coverage_standings = item["coverage"]["standings"] coverage_fixtures_events = item["coverage"]["fixtures"]["events"] coverage_fixtures_lineups = item["coverage"]["fixtures"]["lineups"] coverage_fixtures_statistics = item["coverage"]["fixtures"]["statistics"] coverage_fixtures_players_statistics = item["coverage"]["fixtures"]["players_statistics"] coverage_players = item["coverage"]["players"] coverage_topScorers = item["coverage"]["topScorers"] coverage_predictions = item["coverage"]["predictions"] coverage_odds = item["coverage"]["odds"] #creating objects from variables b =League.objects.update_or_create(league = league_id,league_name = league_name,country_code = country_q,season = season,season_start = season_start, … -
function in form_valid not being called (django)
class ARecordCreateView(CreateView): model = Record form_class = ARecordModelFormSpecial template_name = 'engine/dns/dns_settings_a_create.html' def get_success_url(self): return reverse('dns_settings', kwargs={ 'domain_name': self.kwargs['domain_name'] }) def get_context_data(self, *args, **kwargs): context = super(ARecordCreateView, self).get_context_data(**kwargs) context['my_domains_dns_settings_user'] = Domain.objects.get(name=self.kwargs['domain_name']).created_by context['domain_name'] = self.kwargs['domain_name'] return context def form_valid(self, form): f = form.save(commit=False) f.domain = Domain.objects.get(name=self.kwargs['domain_name']) f.save() rectify_zone(self.kwargs['domain_name']) return super(ARecordCreateView, self).form_valid(form) def get_form_kwargs(self): kwargs = super(ARecordCreateView, self).get_form_kwargs() # update the kwargs for the form init method with yours kwargs.update(self.kwargs) # self.kwargs contains all url conf params return kwargs I import rectify_zone from this package: https://github.com/gnotaras/django-powerdns-manager/blob/master/src/powerdns_manager/utils.py django-powerdns-manager When I run rectify_zone in shell it runs fine, but for some reason is not being executed in form_valid. Can anyone help? Thanks in advance. -
I deployed one Django project on two Elastic Beanstalk servers. Why does one have no images/access to the static file?
I deployed the same application (I know it's the same because the directory structures are exactly the same and I checked every file with the diff command) on two Elastic Beanstalk environments. I checked the settings and they appear identical except for Security Groups and one is not synced with my key (so I currently can't get into it's EC2 instance). Do you have any advice as to why they are behaving differently. Both are Python 3.6 running on 64bit Amazon Linux/2.7.7 servers and I am running Django 1.1.1. Here is my config file: option_settings: "aws:elasticbeanstalk:application:environment": DJANGO_SETTING_MODULE: "ecs_site.settings" PYTHONPATH: "/opt/python/current/app/ecs_site:$PYTHONPATH" "aws:elasticbeanstalk:container:python": WSGIPath: "ecs_site/ecs_site/wsgi.py" It's located in the .ebextensions directory. I think it's a problem with my static directory. Here's the pertinent information from the settings.py file. STATIC_URL = '/static/' STATICFILES_DIRS = [os.path.join(BASE_DIR, 'ecs_site/static')] I'm sure you'll have environmental questions. I'm here. -
Cannot import function from mysite.views in Django
mysite is the app name i created in my django project. below is the hierarchy of my app. mysite --- views.py --- tasks.py --- urls.py --- __init__.py I have a normal function(there is no request parameter, hence no entry in urls.py as well) in views.py as shown below. def function1(param1,param2): return something I am trying to import this function1 in tasks.py by using from .views import function1 but its throwing an error saying ImportError: cannot import name 'function1' from 'mysite.views' Is there any way to get rid of this error. -
Django qsessions - __init__() got an unexpected keyword argument 'ip'
When I try to install django qsessions, I get this error: Traceback (most recent call last): File "/.../lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/.../lib/python3.8/site-packages/sentry_sdk/integrations/django/middleware.py", line 131, in __call__ return f(*args, **kwargs) File "/.../lib/python3.8/site-packages/sentry_sdk/integrations/django/middleware.py", line 92, in sentry_wrapped_method return old_method(*args, **kwargs) File "/.../lib/python3.8/site-packages/django/utils/deprecation.py", line 93, in __call__ response = self.process_request(request) File "/.../lib/python3.8/site-packages/qsessions/middleware.py", line 10, in process_request request.session = self.SessionStore( Exception Type: TypeError at /home/ Exception Value: __init__() got an unexpected keyword argument 'ip' Thank you for any suggestions -
Problem With Django POST Request in Google Cloud Endpoint
My iOS app sends POST requests to my Cloud Run service. I've implemented ESP for security. So here is the setup: Cloud Endpoints (ESPv2) (deployed on public Cloud Run instance) as a gateway for my private Cloud Run instance. I'm using firebase security definition. While sending POST requests to Cloud Endpoint I was getting 401. I thought the problem was with authentication. But I was wrong. Further testing in Postman: I disabled all security definitions in open api file. GET requests to Public ESP which calls Private Cloud Run Container work fine POST requests to Public ESP which calls Private Cloud Run Container result in 404 then I enabled all my previous security definitions: GET request with JWT to Public ESP which calls Private Cloud Run Container works fine POST request with JWT to Public ESP which calls Private Cloud Run Container result in 404 then I made my Private Cloud Run Container public (all_users) both POST and GET requests directly to Public Cloud Run work fine My Private Cloud Run Container runs on Django Rest Framework. Clearly the problem is in that EPS is not able to route POST requests to Private Cloud Run Container or Django is somehow … -
How to fetch data after selecting the item from dropdown, without reloading the page ,
I am trying to build the an invoice system,I have put all the models and views The problem that i am facing is when select the option from dropdown, I want it to fetch all field of that product from the database without reloading, and also I want this same step in next line with different product. [Views.py][1] [1]: https://i.stack.imgur.com/bVQhF.png Invoice.html <!DOCTYPE html> <html lang="en"> <head> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> <meta charset="UTF-8"> <title>Entry</title> </head> <body> <div class=""> <select name="" id="select_path" ONCHANGE="location = this.options[this.selectedIndex].value;"> {% for product in Products %} <option value="{% url 'book' product.id %}">{{ product.Name }} </option> {% endfor %} </select> {{productInfo.Name}} </div> </body> </html> Views.py from django.http import HttpResponse,Http404,HttpResponseRedirect from django.shortcuts import render from django.urls import reverse from .models import Product # Create your views here. def index(request): context={ 'Products':Product.objects.all(), } return render(request,'invoices/index.html', context) def query(request): context={ 'Products':Product.objects.all(), } return render(request,'invoices/invoice.html',context) def book(request,product_id): context={ 'Products':Product.objects.all(), 'productInfo':Product.objects.get(pk=product_id) } return render(request,'invoices/invoice.html',context) URL from django.urls import path from . import views urlpatterns =[ path('',views.index,name="invoice"), path('invoice/',views.query,name='detail'), path('<int:product_id>/book',views.book,name='book') ] Models from django.db import models # Create your models here. class Product(models.Model): id = models.AutoField(primary_key=True) Name=models.CharField(max_length=50) HSN_code= models.CharField(max_length=15,unique=True) Rate=models.DecimalField(max_digits=11,decimal_places=2) def __str__(self): return f" {self.id} {self.Name} {self.HSN_code} {self.Rate}" -
Django Storing Payment Method
I'm tasked with providing users the ability to store multiple payment methods (Credit Cards) within their profile. What's the best way to validate credit card entry and have it encrypted when saved to the database? This is a personal project and will only be used locally. -
How to play song from its object [closed]
Okay, so, I have two objects in django, two songs, and I want if I click on Frank Sinatra example, I want to play his song, if I click some other song, to play exactly that song, here is my code: Django models: class Song(models.Model): art_name = models.CharField(max_length=30) song_name = models.CharField(max_length=70) cover_image = models.ImageField(upload_to='images/') file = models.FileField(upload_to='musics/') Django views: def index(request): all_objects = Song.objects.all() json_data = serializers.serialize("json", Song.objects.all()) context = { 'json': json_data, 'all_objects': all_objects } return render(request, 'index.html', context) Javascript: var data = {{json|safe}} function playSong(){ console.log(data) } HTML: <div class="box"> <div class="arrowLeft">prev</div> <div class="arrowRight">next</div> <div class="img"><img src="{{ song.cover_image.url }}" alt="" onclick="playSong()"></div> <p class="title">{{ song.art_name }}</p> <p class="desc">{{ song.song_name }}</p> </div> -
How can i display my RadioSelect Widget in django
I have a model, form, view and i cannot seem to actually display the RadioSelect widget. it doesnt show anything, i think everything is fine except the views, however, i am unsure. I basically want someone to choose and option from the two radio buttons, submit to then be able to register as one of the two options but like i said i cant even get the buttons to show. views.py def registration(request): reg = Registration.objects.all() return render(request, 'HTML/Registration.html', {"reg":reg}) models.py class Registration(models.Model): OPTIONS = ( ('COUNS','Counsellor'), ('CLIENT','Client'), ) SELECT = models.CharField(max_length=15, choices=OPTIONS) forms.py class Registration(forms.ModelForm): class Meta: model = Registration fields = '__all__' widgets = {'SELECT': forms.RadioSelect} HTML <form method="POST"> {% csrf_token %} <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom"> <h1 class="h2">Registration</h1> </div> {% render_field reg.SELECT %} <div class="form-row"> <div class="col pt-md-2"> <input type="submit" value="Next" class="btn btn-primary" style="float: right;"> </div> </div> </form> -
Update several fields in model instance using select_for_update in Django
I have model class named DataObj and some copmlex method that fetches DataObj isntance in the beginning, performs some calculations and updates it's fields. For integrity in concurrent environment it utilizes optimistic locking using integer version field. In order not to wrap all calculations in @atomic, I have short and fast save_changes function: @transaction.atomic def save_changes(DataObj dataObj): db_instance = DataObj.objects.select_for_update().get(id=dataObj.id, version=dataObj.version) # copy all changes from dataObj to db_instance db_instance.save() and I call it from my complex method def long_update_func(dataobj_id): obj = DataObj.objects.get(id=dataobj_id) # perform several calculations, update fields obj.field1 = result_of_calc1() ... try: save_changes(obj) except: # whoops, version changed notify_data_changed_during_calculations() Question: copying fields is really annoying. Can I avoid copying fields in save_changes function? I have nice modified dataObj with exactly same id, that I use to lock database rows in select_for_update call. Can I simply rewrite like this (or similar): @transaction.atomic def save_changes(DataObj dataObj): db_instance = DataObj.objects.select_for_update().get(id=dataObj.id, version=dataObj.version) # save our instance, because it has same id as db_instance and therefore its row in db table is locked db_instance.save() ? -
Django dev server using old version of views.py
For some reason, the changes I make on the views.py file are not being reflected. I initially made a function inside view.py to return HttpResponse(request.POST.items()). Even after making changes to the function, it's still performing the same thing. I tried clearing the cache of the browser, restarted the server, and also tried deleting the pyc files. Nothing worked. Any guess on why this is happening? -
How to add a value for a ModelMultipleChoiceFilter to queryset?
I need to add a field 'All' to choices of ModelMultipleChoiceFilter. In MultipleChoiceFilter I just use: shops = Shop.objects.filter(is_active=True) SHOP_CHOICES = [('All', 'All')] for x in shops: SHOP_CHOICES.append((x.address, x)) SHOP_CHOICES = tuple(SHOP_CHOICES) but in ModelMultipleChoiceFilter I have queryset instead of tuple. My filter: def departments(request): if request is None: return Shop.objects.none() curr_user = request.user if curr_user.role == 'SV': return Shop.objects.filter(is_active=True) else: return Shop.objects.filter(is_active=True, custom_user=curr_user) class ShopFilter(django_filters.FilterSet): address = django_filters.ModelMultipleChoiceFilter(queryset=departments) -
Django Rest / Sum the response values of identical coins
from api, I get multiply records on one coin. How can I summarize and add them to the Wallet.objects() correctly? Now I have such a code and it just overwrites the old value with a coin zero. Example i have response {"coin":"BIP","value":"5"} {"coin":"ZERO","value":"4"} {"coin":"BIP","value":"15"} {"coin":"INSIDER","value":"24"} {"coin":"BIP","value":"41"} I want add in database from this response: "coin":"BIP","value":"61" "coin":"ZERO","value":"4" "coin":"INSIDER","value":"24" Its sum all BIP (5+15+41). And other coins. How? My Wallet.objects now cant sum this amount obj, created = Wallet.objects.update_or_create(user=user, coin_id_id=coin.id, defaults={'amount_d': amount_d, 'amount_w': 0, 'cap_w': 0, 'cap_d': capitalize_d},) obj.save() i have this code: views.py def load_user_balance(request, wallet_id, imei): try: user = User.objects.get(imei=imei) except ObjectDoesNotExist: create = User.objects.create(imei=imei, wallet_mx=wallet_id) create.save() url_wallet = f"https://explorer-api.minter.network/api/v1/addresses/Mx6884bf2637f4efe8dc061132b9cfed03622dfc30" url_delegated = f"https://explorer-api.minter.network/api/v1/addresses/Mx6884bf2637f4efe8dc061132b9cfed03622dfc30/delegations" response_wallet=requests.get(url_wallet).json()['data'] response_delegated=requests.get(url_delegated).json()['data'] for coin in response_wallet['balances']: coin_w = coin['coin'] amount_w = coin['amount'] coin = Coins.objects.get(symbol=coin_w) user = User.objects.get(imei=imei) obj, created = Wallet.objects.update_or_create(user=user, coin_id_id=coin.id, amount_d=0, cap_w=0, cap_d=0, defaults={'amount_w': amount_w},) obj.save() for coin in response_delegated: coin_d = coin['coin'] amount_d = coin['value'] capitalize_d = coin['bip_value'] coin = Coins.objects.get(symbol=coin_d) user = User.objects.get(imei=imei) if Wallet.objects.filter(coin_id=coin).exists(): obj = Wallet.objects.filter(coin_id=coin).update(amount_d=amount_d, cap_d=capitalize_d) else: obj, created = Wallet.objects.update_or_create(user=user, coin_id_id=coin.id, defaults={'amount_d': amount_d, 'amount_w': 0, 'cap_w': 0, 'cap_d': capitalize_d},) obj.save() models.py class Coins(models.Model): name = models.CharField(max_length=150) symbol = models.CharField(max_length=45) crr = models.CharField(max_length=3) class Wallet(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) … -
Django: automatically detect the tenant media folder when reading csv in Views.py
In my multi-tenant django app, the user needs to upload a file to the server. this file is then used in a view. my view uses pd.read_csv() to read the file uploaded, however I cannot find anywhere what to use inside of the brackets to automatically look inside of this particular tenant media folder. Thanks to django documentation, I was able to seperate my tenants within the media folder but I still don't how to write the path inside of the pandas.read_csv() Any help would be appreciated, thank you! -
Original exception text was: 'QuerySet' object has no attribute 'name' using django rest framework
I'm learning Django and i got to this error and I couldn't find the solution. Here are my models class Retailer(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=255) website = models.CharField(max_length=255) def __str__(self): return str(self.id) class Product(models.Model): id = models.AutoField(primary_key=True) price = models.IntegerField(default=None, null=True) name = models.CharField(max_length=255) retailer = models.ForeignKey(Retailer,on_delete=models.CASCADE,related_name='retailer_info') is_active = models.BooleanField(default=False) def __str__(self): return str(self.id) And here are my serializers class ProductSerializer(serializers.ModelSerializer): class Meta: model = Product fields = '__all__' class RetailerSerializer(serializers.ModelSerializer): products = ProductSerializer(many=True, read_only=True) class Meta: model = Retailer fields = ['name', 'website', 'products'] And here's my view class RetailerList(APIView): def get(self, request): retailer = Retailer.objects.all() serializer = RetailerSerializer(retailer) return Response(serializer.data) And here's my url path('retailer', views.RetailerList.as_view()), But when I submit a get request on 127.0.0.1:8000/retailer i get this error: AttributeError at /product Got AttributeError when attempting to get a value for field name on serializer RetailerSerializer. The serializer field might be named incorrectly and not match any attribute or key on the QuerySet instance. Original exception text was: 'QuerySet' object has no attribute 'name'. What's the problem? -
Django creating .row for every post
i first time writing in django. When i trying to post-template, this code create a new <div class="row"></div> for every post. How i fix that? <div class="container news-card"> {% for post in post_list %} <div class="row" stlye="max-width"> <div class="card" style="width: 300px; height: 440px; margin-top: 60px; margin-left: 20px;"> <div class="card-img-top m-fix"><img src="https://telgrafs.com/assets/src/news-col1-row1-card-image.png"></div> <div class="card-text news-category">Ekonomi</div> <div class="card-title news-ct">{{ post.title }}</div> <div class="ccard-text news-ctext up-fix">{{post.content|slice:":200" }}</div> <div class="card-img-bottom author-image"><img src="https://telgrafs.com/assets/src/profile-kaa.png"></div> <div class="card-author-name">{{ post.author }}</div> <div class="card-post-time">{{ post.created_on}} </div> <a href="{% url 'post_detail' post.slug %}" class="card-text pb-more">DEVAMINI OKU &rarr;</a> </div> </div> {% endfor %} </div> {%endblock%} -
How to get a selected object in a form.Models using ModelChoiceField object
from bootstrap_modal_forms.mixins import PopRequestMixin, CreateUpdateAjaxMixin from bootstrap_modal_forms.forms import BSModalForm from django.contrib.auth import get_user_model class CommentForm(BSModalForm, PopRequestMixin, CreateUpdateAjaxMixin,): created_by = forms.ModelChoiceField(label="", widget=forms.HiddenInput, queryset=get_user_model().objects.all(), disabled=True,) paragraph = forms.ModelChoiceField(label="", required=False, queryset=MeetingReportContent.objects.none(), to_field_name="pk", disabled=False,) def __init__(self, *args, **kwargs): super(CommentForm, self).__init__(*args, **kwargs) self.fields['paragraph'].queryset = MeetingReportContent.objects.filter(pk=PARAGRAPH_SELECTED_HERE) class Meta: model = MeetingReport_Comment fields = ['paragraph', 'created_by', 'content_comment', ] exclude = [ 'accepted', 'timestamp'] I'm trying to get only the paragraph selected for the queryset, but get many errors... -
How can I temporarily save selected data from one table to another without overwriting the previous data?
I have an html table where I need to transfer or copy a row of data from this table to another table of the same structure that I call cart in my database. To do this, I would like that when I click on the button (+) of a given row, to add the corresponding data in the cart table. This is my template <form type="post" action="" style="margin: 0" > <label for="code" class="nav-link">Référence </label> <div class="col-sm-9"> <input id="productCode" type="text" name="productCode" placeholder="Entez le code du produit ..." onkeyup="myFunction()"> </div> </form> <table class="table table-bordered" id="productsTable" width="400"> <thead> <tr> <th>ID</th> <th width="10%">Code</th> <!-- <th width="16%">Catégorie</th> --> <th width="50%">Libéllé</th> <!-- <th width="12%">Marque</th> --> <th width="11%">Date entrée </th> <th width="11%">Qté initiale </th> <!-- <th width="12%">Quantity </th> --> <!-- <th width="12%">Qtité finale </th> --> <th>PU</th> <!-- <th>Statut</th> --> <th style="align-self: center;">Actions</th> </tr> </thead> <tbody> {% if products|length < 1 %} <tr> <td colspan="20" class="text-center">Aucune donnée trouvée, veuillez ajouter quelques données!</td> </tr> {% else %} {% for product in products %} <tr> <td>{{ forloop.counter }}</td> <td>{{ product.code }}</td> <!-- <td>{{ product.category }}</td> --> <td>{{ product.name }}</td> <!-- <td>{{ product.brand }}</td> --> <td>{{ product.date_entry }}</td> <td>{{ product.quantity_entry }}</td> <!-- <td>{{ product.quantity }}</td> --> <!-- <td>{{ product.final_stock }}</td> --> … -
Adding filtering options in Django - does not work properly
I'm trying to flirt my queryset depending on what I have in the database. I created a function in which query is my all queryset and filters my object (conditions). query = Shop.objects.all() filters = get_object_or_404(Filters, id=1) def shop_filters(query, filters): if filters.category_car: query.filter(category=1) if filters.category_computer: query.filter(category=2) if filters.category_phone: query.filter(category=3) return query It seems my function is not working at all. Despite the conditions, none of them works. My queryset still remains the same length. It seems that my queryset that I let into the function comes out the same. How to solve this problem? -
Range of models ORM django
how can I add range base ORM of some models? from .models import UsersLog if request.method == 'POST': login = request.POST.get('flogin') response_data = {} response_data['result'] = 'Failed' lengthBase = UsersLog.objects.get() for i in lengthBase: // I got 3 users so I want lengthBase equal 3 -
intellisense python suggestion
hey everybody i'm just started learning django and have a problem with vs-code it's seems that vs-code dosent suggest me some of the modules which i called in the program enter image description here as you can see vs-code should start to suggesting me name of the lists that i wrote before in the modules but it wont do the job ps: my cousin doing same thing but his vs-code seems to do the job perfectly