Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django, How to display 2 models on a Listview
I am working with my first Django project **model.py** class product(models.Model): product_code = models.CharField(max_length=15, unique=True) product_name = models.CharField(max_length=100) class stock_product(models.Model): product_code = models.CharField(max_length=15) branch_code = models.CharField(max_length=5) quantity = models.IntegerField(default=0) price = models.DecimalField(default=0) **views.py** class productList(ListView): model = product template_name = 'product/product_list.html' def get_queryset(self): queryset = super(productList, self).get_queryset() self.filterset = productFilter(self.request.GET, queryset=queryset) return self.filterset.qs def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['filter'] = self.filterset return context **product_list.html** {% for alist in product_list %} <tr> <td>{{ alist.product_code }}</td> <td>{{ alist.product_name }}</td> <td>{{ alist.price }}</td> <td>{{ alist.quantity }}</td> </tr> {% endfor %} Sample Data in tables **product** ['11111','paper' '22222','Wood'] **stock_product** ['11111','BR1',150, 10 '11111','BR2',120, 10 '11111','BR3',100, 15 '22222','BR1',50, 200 '22222','BR2',70, 200 '22222','BR3',40, 250] I want to get price and quantity from stock_product model, we can change branch_code by user how can we do Plese help. -
Docker: Move LibXMLSec settings / dependencies into executable directory
So. I'm trying to get my Dockerfile to run. Dockerfile is complicated, and doing things somewhat wrong for Python. The important part, though, is that it was working before I added XMLSec to the dependencies. (via the onelogin [https://github.com/onelogin/python-saml] package) On our non-Dockerized systems, we run: apt install -y libxml2-dev libxmlsec1-dev libxmlsec1-openssl pkg-config and it installs the dependencies. My containerized attempts, however, run into this issue: Running setup.py install for xmlsec: started Running setup.py install for xmlsec: finished with status 'error' Complete output from command /usr/local/bin/python3.6 -u -c "import setuptools, tokenize;__file__='/tmp/pip-install-wd6h548m/xmlsec/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record /tmp/pip-record-ufxw9hor/install-record.txt --single-version-externally-managed --compile: running install running build running build_py package init file 'src/xmlsec/__init__.py' not found (or not a regular file) creating build creating build/lib.linux-x86_64-3.6 creating build/lib.linux-x86_64-3.6/xmlsec copying src/xmlsec/py.typed -> build/lib.linux-x86_64-3.6/xmlsec copying src/xmlsec/constants.pyi -> build/lib.linux-x86_64-3.6/xmlsec copying src/xmlsec/template.pyi -> build/lib.linux-x86_64-3.6/xmlsec copying src/xmlsec/__init__.pyi -> build/lib.linux-x86_64-3.6/xmlsec copying src/xmlsec/tree.pyi -> build/lib.linux-x86_64-3.6/xmlsec running build_ext error: Unable to invoke pkg-config. The solution seems to be to use the XMLSec library as a compiled Wheel. (Per something I read in the XMLSec github) I can't find any documentation on how to add this compiled wheel into an executable location within the container via the Dockerfile. I've done quite a bit … -
Passing logged in user to form
I am trying to pass logged in user to form that i would like to save. forms.py class SpotForm(ModelForm): def __init__(self, *args, **kwargs): super(SpotForm, self).__init__(*args, **kwargs) self.fields['gross_weight'].widget = forms.NumberInput(attrs={'min':0}) self.fields['volume'].widget = forms.NumberInput(attrs={'min': 0}) class Meta: model = Spot fields = [ 'gross_weight','volume','origin_country','origin_port', 'dest_country','dest_port','ship_week','requestor' ] models.py class Stakeholder(models.Model): user = models.OneToOneField(User,null=True,blank=True,on_delete=models.CASCADE) company_name = models.CharField(max_length=15) mail = models.CharField(max_length=40) def __str__(self): return self.mail class Spot(models.Model): STATUSES = ( ('Open','Open'), ('Closed','Closed') ) gross_weight = models.FloatField(null=False,default=0,validators=[MinValueValidator(0)]) volume = models.FloatField(null=False,default=0,validators=[MinValueValidator(0)]) origin_country = models.CharField( validators=[RegexValidator(regex='[A-Z]{2}', message='Country code is two letters')], max_length=2,null=True) origin_port = models.CharField( validators=[RegexValidator(regex='[A-Z]{3}', message='Port code is three letters')], max_length=3,null=True) dest_country = models.CharField( validators=[RegexValidator(regex='[A-Z]{2}', message='Country code is two letters')], max_length=2,null=True) dest_port = models.CharField( validators=[RegexValidator(regex='[A-Z]{3}', message='Port code is three letters')], max_length=3,null=True) time_registered = models.DateField(default=timezone.now) spot_status = models.CharField(max_length=6,default='Open', choices=STATUSES) ship_week = models.CharField(max_length=2,null=True) requestor = models.ForeignKey(Stakeholder,null = True,on_delete=models.CASCADE) def __str__(self): return self.origin_country + self.origin_port + '-' + self.dest_country +self.dest_port + '-' + self.ship_week views.py def register_spot(request): my_user = Stakeholder.objects.get(user=request.user) form = SpotForm() if request.method =='POST': print("print",request.POST) form = SpotForm(request.POST) if form.is_valid(): form.save() return redirect('/') else: print(form.errors) context = {'form': form} return render(request, 'spotrequesting/register_spot.html', context) When i submit the form i am getting an error in command prompt stating "This field is required" for "requestor". After that - dropdown list … -
how can i solve AttributeError 'NoneType' object has no attribute 'write'
python manage.py migrate File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Users\hp\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\hp\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\management\__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\hp\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\management\base.py", line 328, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\hp\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\management\base.py", line 369, in execute output = self.handle(*args, **options) File "C:\Users\hp\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\management\base.py", line 83, in wrapped res = handle_func(*args, **kwargs) File "C:\Users\hp\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\management\commands\migrate.py", line 162, in handle self.stdout.write(self.style.MIGRATE_HEADING("Operations to perform:")) File "C:\Users\hp\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\management\base.py", line 145, in write self._out.write(style_func(msg)) AttributeError: 'NoneType' object has no attribute 'write' please can anyone help out with this error. it popup anytime i try to use manage.py. anyone please -
Django don't load static and media files in production
i really don't know why. You can see there my urls.py and my settings.py. Server NGINX, gunicorn urls.py from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('', include("appCms.urls")) ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) settings.py STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] STATIC_ROOT = os.path.join(BASE_DIR, 'static_cdn/') MEDIA_URL ='/mediafiles/' MEDIA_ROOT = os.path.join(BASE_DIR, 'mediafiles_cdn/') THANK YOUUU! -
same API call on different URL's python/django
I'm trying to get all orders of multiple webshops with the same api call but im not sure whats the fastest/best way to accomplish this. Every shop has its own KEY, SECRET & HOST and i'm trying to figure out how to loop over the different shops and get the results in the "order" -json dictionary in the get_all_orders(). As you can see below i tried to loop through the API model which contains all API_KEY, API_Secret and API_Hosts. The API_prefix has to stay the same. Any tips or suggestions ? Thanks in advance! Here is a small example: # API_Key = "<KEY>" # API_Secret = "<SECRET>" # API_Host = "<HOST>" API_Prefix = "/api/rest/v1/" def headers(method, uri, data): for x in Api.objects.all(): upper_method = str.upper(method) hash_string = x.API_Key + "|" + upper_method + "|" + uri + "|" + data hash = hash_string headers = { "x-hash": hash, "x-public": x.API_Key, } return headers def get(path, data): for x in Api.objects.all(): uri = API_Prefix + path url = x.API_Host + uri headers = headers("GET", uri, data) results = requests.get(url, data=data, headers=headers) return results def get_all_orders(request): res = get("/orders", "") print(res.status_code) if res.status_code == 200: orders = json.loads(res.text) return render(request, "orders.html", {'orders': … -
Getting a column instead of an object when relating with PrimaryKeyRelatedField in Django-Rest-Framework
I have a model for applications, which among many attributes have a category. This category is in fact a key to another model that has the category ID, its name, and so on. class Application(models.Model): title = models.CharField(max_length=50) vendor = models.CharField(max_length=50, default="Unknown", null=False) . . . category = models.ForeignKey('ApplicationCategory', related_name='applications', null=False, default=1, on_delete=models.SET_DEFAULT) class ApplicationCategory(models.Model): name = models.CharField(max_length=20, null=False) description = models.CharField(max_length=200, null=False) Then, on the Django REST serializers side I have the serializer for the applications: class SoftwareSerializer(serializers.ModelSerializer): category = serializers.PrimaryKeyRelatedField(queryset=ApplicationCategory.objects.all()) class Meta: model = Application fields = ['id', 'title', ... 'category'] Which is generating the expected API view, with a dropdown for the categories, but showing them as the ApplicationCategory objects and not giving me their name. API showing Category dropdown with objects instead of names Is there a way to access attributes of those objects to show the name in the dropdown, for usability sake? I have also tried creating a CategorySerializer object (class CategorySerializer(serializers.ModelSerializer)) and then using it as category = CategorySerializer(many=False) but instead of dropdowns, I get open text fields for the attributes of the category. Am I trying to do something that is not expected to work? -
How to take an audio file from React and serve it to django server?
I am trying to make a web app using react as front end and django as backend. I am trying to send the audio file from the front end to backend. But anyhow I am not able to properly understand how to do it. -
Cant send file using socket(python)
I wwant to send file to my computer using django site. I want to send file from one machine to other machine through my site. I have [Errno 111] Connection refused code of client: class Server: def __init__(self): self.connect_client() self.input_blend_file = open('data/proba.blend', 'wb') self.buffer = memoryview(bytearray(1024 * 1024 * 10)) self.num_bytes = 1 self.receive_file() self.close_connection(self.server_socket) def receive_file(self): while self.num_bytes: self.toread = 1024 * 1024 * 10 self.view = self.buffer[:] while self.toread: self.num_bytes = self.conn.recv_into(self.view, self.toread) self.view = self.view[self.num_bytes:] self.toread -= self.num_bytes if self.num_bytes == 0: self.buffer = self.buffer[:-self.toread] break self.input_blend_file.write(self.buffer) self.input_blend_file.close() def connect_client(self): self.server_socket = socket.socket() self.server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.server_socket.bind(('', 80)) self.server_socket.listen(1) self.conn, self.address = self.server_socket.accept() def close_connection(self, choosed_socket): choosed_socket.close() Code of site: class FileReceiver: def __init__(self, file, ip_client): self.infile_name = file self.ip_client = ip_client self.send_file_server() def connect_server(self): self.client_socket = socket.socket() self.client_socket.connect((self.ip_client, 80)) def send_file_server(self): self.connect_server() self.sf = self.client_socket.fileno() self.lf = open(self.infile_name, 'rb') self.client_socket.sendfile(self.lf) self.close_connection(self.client_socket) def close_connection(self, choosed_socket): choosed_socket.close() My problem is on this line: self.client_socket.connect((self.ip_client, 80)) I opend port on machine but it doesnt work. -
Django: How to send username across all the pages once the user is logged in
Here is the login method in the view: def login(request): if request.method == 'POST': username = request.POST['username'] password = request.POST['password'] user = auth.authenticate(username=username, password=password) if user is not None: auth.login(request, user) return redirect('forum') else: messages.info(request, 'Username or password is wrong!') return render(request, 'login.html') return render(request, 'login.html') Here is how I wrote my codes: In the views module: I've register method and login method which both work properly. However, I've other methods who required login in order to access them, since I redirect only a page at a time, I can't get the same username across the pages that required login before to access them. Now the problem is, how to create another page who treats data came from the forum by conserving the same username from the loggin. PS: In the forum, I can get the username but how to maintain the same username, is the problem Thanks :) -
Uploading file with selenium Virustotal
I'm trying to upload my file to upload in VirusTotal with selenium,But it keeps getting me this Error Message: Unable to locate element: [id="fileSelector"] This is my code: driver = webdriver.Firefox(executable_path='my_path') driver.get('https://www.virustotal.com/gui/home/upload') driver.find_element_by_xpath('/html/body/vt-virustotal-app//div[2]/vt-auth-checker/home-view//div/div[1]/vt-ui-selector/div[1]/vt-ui-main-upload-form//div/vt-ui-button[1]').click() I also tried: driver.find_element_by_id('fileSelector').click() and: driver.find_element_by_xpath('//*[@id="fileSelector"main"]').click() I have to mention that first I want to make sure that I can locate the parameter so I used click(). -
Only check one checkbox at a time for each loop
I want to check only one checkbox at a time but the problem is I'm using loop to display my checkbox data. So for the whole loop it can only check one when using code below. The thing is that I want it to be able to check one for each loop. {% for i in income %} <tr> <td>Salary</td> <td>{{ i.description}}</td> <td>${{ i.amount }}</td> <td><input type="checkbox" class="salary" value='{{ i.amount}}' name="formA" checked="checked" /></td> <td><input type="checkbox" class="salary" value='{{ i.amount}}' name="formB" /></td> </tr> {% endfor %} <script type="text/javascript"> $('input.salary').on('change', function() { $('input.salary').not(this).prop('checked', false); }); </script> How my code looks like: How I want it to be: Really appreciate if you guys could help me on this. -
Connection reset when connecting Azure Web App to Azure SQL?
I'm trying to set up my Azure Webapp with my Azure SQL database, but I keep running into this problem. (2013, 'Lost connection to MySQL server at 'reading initial communication packet', system error: 104 "Connection reset by peer"') Any ideas on how to fix it? Thanks! -
Translate date string returned by a django templatetag
How do I make sure time and date are properly translated if im using a custom templatetag to format the datetime to the user's local time? Here's a code snippet of the code I'm using to join the start and end date into a string def format_date_local(start_time, end_time, time_zone_str): start_date_local = get_local_time(start_time, time_zone_str).date() end_date_local = get_local_time(end_time, time_zone_str).date() return start_date_local.strftime("%-d %B") + ' - ' + end_date_local.strftime("%-d %B") Question is how do I translate the result within the template? Plus I'm also using words like 'and', 'in', 'midnight', 'noon' for other datetime formats, do I need to translate these manually within the templatetag? -
Uncaught TypeError: Cannot read property 'options' of null at HTMLButtonElement.<anonymous>
I am getting the above error while working on my django project.This is my HtMl file: {% if product.id in list_cart %} <div class="btn-group"> <button>Hi</button> </div> {% else %} <div class="btn-group"> <select class="selection-2 border" name="size" required id="sizebox"> {% for t in product.size.all %} <option value="{{t}}" id="{{t}}">{{t}}</option> {% endfor %} </select> </div> {% endif %} This is my javascript file for it: var updateBtns = document.getElementsByClassName('update-cart') for (i=0;i<updateBtns.length;i++){ updateBtns[i].addEventListener('click',function(){ var productId=this.dataset.product var action=this.dataset.action var sizebox = document.getElementById("sizebox"); if(typeof(sizebox) == undefined && sizebox==null){ var size='S'; updateUserOrder(productId, action, size) } else{ var size = sizebox.options[sizebox.selectedIndex].value; updateUserOrder(productId, action, size) } }) } function updateUserOrder(productId,action,size){ console.log('User is logged In , sending data....') var url = "/update_single/" fetch(url, { method:'POST', headers:{ 'Content-Type':'application/json', 'X-CSRFToken':csrftoken, }, body:JSON.stringify({'productId':productId,'action':action,'size':size}) }) .then((response) =>{ return response.json() }) .then((data) =>{ console.log('data:',data) location.reload() }) } The error is coming in this line:var size = sizebox.options[sizebox.selectedIndex].value; My concern is that in my html template when a product is already in cart then instead of showing the selectbox (for size) I want to show a simple button instead. Also there is a remove button in my template which removes the product from the cart and is meant to show the selectbox again instead of the button … -
Django ORM to Store the OneToOneField
Previously, I have a models.MataKuliah where it has related to models.MataKuliahDosenKompetensi, where the relation of dosen in MataKuliahDosenKompetensi was designed as OneToOneField, and the MataKuliah as ManyToManyField. class MataKuliah(TimeStampedModel): id = models.BigAutoField(primary_key=True) kode_mk = models.CharField(_('Kode MK'), max_length=10, unique=True) nama_mk = models.CharField(_('Nama MK'), max_length=256) .... # and more field (without any `DosenKaryawan` field or other relations). def __str__(self): return self.nama_mk class MataKuliahDosenKompetensi(TimeStampedModel): id = models.BigAutoField(primary_key=True) dosen = models.OneToOneField(DosenKaryawan, on_delete=models.CASCADE) mata_kuliah_set = models.ManyToManyField(MataKuliah) def __str__(self): return '%s' % self.dosen How can I get the DosenKaryawan list for each MataKuliah, like stored in ORM? (without templatetags). It's look like; MataKuliah.objects.published()\ .annotate(dosen_list=....) So, in my template I just put that dosen_list to each MataKuliah items, like: {% for mata_kuliah in mata_kuliah_list %} {{ mata_kuliah.kode_mk }} {{ mata_kuliah.nama_mk }} {{ mata_kuliah.dosen_list }} <!-- something like this --> {% endfor %} -
Django: View for autogenerated urls from model
I have a models.py: import ... class Article(models.Model): # name of the article title = models.CharField("Titel", max_length=150) # .html file containing the article article_file = models.FileField(upload_to='articles/') slug = models.SlugField(null=True) ... def get_absolute_url(self): return reverse('article_detail', kwargs={'slug': self.slug}) And a articles.html page with links to my articles: ... {% for article in all_articles %} <a class="box--thirty" href="{{ article.get_absolute_url }}"> <div class="img... ></div> ... </a> {% endfor %} ... and this urls.py: urlpatterns = [ ... path('articles/', views.Articles, name='articles'), path('<slug:slug>', views.ArticleDetailView.as_view(), name='article_detail'), ] So the idea is that the site admin can add Articles to the database with a .html side, which then automatically appears under the url mySite/articles/ - E.g. mySite/articles/foo. How do I write the ArticleDetailView (this is a dummy name) to automatically display the right html file from the model or autogenerate a view for each Article in the model? When I enter a slug right now in an Article object, the url generated by the SlugField is mySite/foo instead of mySite/articles/foo. How do I change that? Articles are right now uploaded to MEDIA_URL/articles. However, Django searches for the .html sites in the templates directory. Is it a no-go to put the MEDIA_URL into the templates directory? If so, how … -
How can I execute Scrapy in Django?
I have a task that I have to scrape some websites with Scrapy. I also have to delete and edit some URLs with Django. I want to use Django 3.1 and Scrapy 2.3.0. I already try Django-dynamic-scraper and Djangoitem. Because of some version problems, I couldn't use them. There was a class to execute Django command's called call_command call_command('Scrapy crawl ../first_bot/first_bot/spider.py', stdout=out) But it is just for the Django command. Is there any way to execute scrapy module when I click on a button on Django? -
Problem with Python Django Category Form creator
I'm working to make a Category Form on Django, the category is also a ForeignKey of Article Model. The FrontEnd work fine, but the form is not adding the category to the database and I can't use it on my principal Article Form; this is my code, thanks for your answers : Model.Py class Category(models.Model): name = models.CharField('Titolo', max_length = 250) slug = models.SlugField(max_length = 250, unique = True) desc = models.TextField('Descrizione', max_length=10000, blank=True,) def __str__(self): return self.name # Articles class Article(models.Model): title = models.CharField('Titolo', max_length=100) author = models.ForeignKey(User, on_delete=models.CASCADE, blank=False) category = models.ForeignKey (Category, on_delete=models.CASCADE, blank=False) desc = models.CharField('Descrizione', max_length=10000, blank=True, ) text = RichTextUploadingField( blank=True, null=True) image = models.ImageField('Foto', blank=True, upload_to="img") data = models.DateTimeField('Data di pubblicazione', blank=True) slug = models.SlugField(max_length = 250, null = True, blank = True, unique=True) def get_absolute_url(self): return reverse("EditHome") # Da cambiare class Meta: # Order post by date ordering = ['-data',] def __str__(self): return self.title def save(self, *args, **kwargs): # Auto Slug Field self.slug = slugify(self.title) super(Article, self).save(*args, **kwargs) Views.py class CreateCategoryView(CreateView): model = Category form_class = CategoryForm template_name = 'blog/category/AddCategory.html' Urls.py path('category/add-category/', CreateCategoryView.as_view(), name='AddCategory'), # Add Category Forms.py class CategoryForm(forms.ModelForm): class Meta(object): model = Category fields = ('name', 'slug', 'desc') widgets = … -
How do CRUD for native fields of the User object through the Account API?
I have a problem of CRUD in the Django REST API data of the User object through the API of the Account. When I add, it does not save the first_name, second_name and other fields of the User object. It saves only username and password and get obl. How to make a full CRUD? models.py def user_directory_path(instance, fileName): fileName = FileUtils.getTranslitedName(fileName) return 'user/{0}/{1}'.format(instance.user.username, fileName) class Account(models.Model): user=models.OneToOneField(User,on_delete=models.CASCADE, related_name="profile") description=models.TextField(blank=True) date_joined=models.DateTimeField(auto_now_add=True) updated_on=models.DateTimeField(auto_now=True) is_creator=models.BooleanField(default=False) user_pic = models.ImageField(upload_to=user_directory_path, default='user_pic_male.png', blank=True) phone = models.CharField(max_length=15, blank=True) status = models.CharField(max_length=50, blank=True) role = models.CharField(max_length=10, blank=True) def __str__(self): return self.user.username views.py class AccountSerializer(serializers.ModelSerializer): user=serializers.StringRelatedField(read_only=False) class Meta: model=Account fields='__all__' class AccountListCreateView(ListCreateAPIView): queryset=Account.objects.all().order_by('id').reverse() serializer_class=AccountSerializer #permission_classes=[IsAuthenticated] filter_backends = (SearchFilter, OrderingFilter, DjangoFilterBackend) parser_classes = (FileUploadParser, FormParser, MultiPartParser) ordering_fields = '__all__' search_fields = '__all__' #('user', 'first_name', 'second_name') #filter_class = AccountFilter def perform_create(self, serializer): user=self.request.user serializer.save(user=user) class AccountDetailView(RetrieveUpdateDestroyAPIView): queryset=Account.objects.all() serializer_class=AccountSerializer #permission_classes=[IsOwnerProfileOrReadOnly,IsAuthenticated] filter_backends = (SearchFilter, OrderingFilter, DjangoFilterBackend) parser_classes = (FileUploadParser, FormParser, MultiPartParser) -
Django model choice field exclude value
this is a example a model choice: class Student(models.Model): FRESHMAN = 'FR' SOPHOMORE = 'SO' JUNIOR = 'JR' SENIOR = 'SR' GRADUATE = 'GR' YEAR_IN_SCHOOL_CHOICES = [ (FRESHMAN, 'Freshman'), (SOPHOMORE, 'Sophomore'), (JUNIOR, 'Junior'), (SENIOR, 'Senior'), (GRADUATE, 'Graduate'), ] year_in_school = models.CharField( max_length=2, choices=YEAR_IN_SCHOOL_CHOICES, ) how can filter the choices for example exclude 'Freshman' from the list on the forms.py? -
Re-rending / Refresh of loop in Django template doubles list value displayed
Issue: Every page refresh the loop values duplicates and increases e.g. [{1:'aa', 2:'bb'}] when rendered through {% for x in list %} loads fine the first time and then every page refresh the list doubles. The effect is 'reset' when I make a change in the view.py file, reload/refresh and the correct values are shown on first load, then every refresh the list doubles in size...? I am new to python/Django and it's likely something I've borrowed from other languages and am doing incorrectly. Python 3.8.5, Django 3.1 NOTE: that I have created my own class (not DB model class) in models.py which takes ORM results list and loops on this to populate the custom object. Logic is: Loop through database resultset and format into 'Category' => 'Item' so that one can simply loop over the data in HTML and easily separate out (or group) each entry into a category. The Model code is class UserListDisplay(): categories = dict() def processResultset(self, charts): self.categories.clear() for chart in charts: cat = chart.entry.category if cat.id not in self.categories: category = CategoryList() category.setId(cat.id) category.setLabel(cat.label) self.categories[cat.id] = category self.categories[cat.id].addItem(chart.entry) And the template is <ul> {% for cat in catList %} <li> <div style="border: dotted 1px">{{cat.label}} … -
Django POST foreign key field?
How post 2 or more model table fields in one form action? my model: class User(model.Model): name = models.CharField(max_length=200, null=True, blank=True) surname = models.CharField(max_length=200, null=True, blank=True) class Instructor(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=200, null=True, blank=True) forms.py: class BasicInstructorForm(forms.ModelForm): class Meta: model = Instructor fields = '__all__' views.py def save_basic_instructor(request,id): instance = Instructor.objects.get(id=id) if request.method == "POST": form = BasicInstructorForm(request.POST, instance=instance) if form.is_valid(): form.save() return redirect("instructor") return render(request,"instructor/instructor.html",{'form': form}) in html tags I can not show input fields of name surname title and post same input fields in one request.POST -
Django in multiple admin site - allow access to only specific users [closed]
I have three applications like a computer, electrical and civil. I have developed these applications under a single project with multiple databases and multiple sites. I am managing database switching with routers. I created one auth module for authentication. my question: how to restrict the user to a particular application. thanks -
Is it possible to user translations on crispy form attributes?
I'm working on some crispy forms and defining some fields like: name = self.fields['name'] name.label = _('First name') name.widget.attrs = { 'class': 'common-field', 'data-altlabel': 'Alternative label', } Is there a way to define the data-altlabel also as _('Alternative label') or something similar to that?