Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django check if superuser in class-based view
I am converting my project from function-based view to class-based view. In a view function, I can check if a user is a superuser using request.user.is_superuser() function. I can check if a user is logged in by inheriting LoginRequiredMixin in a View class, I want to know if there is any similar way that can be used for checking if the user is a superuser in a View class. I want a Django app only accessible by the superusers of the site. -
Embeding videos in a a Django project?
Using Django-embed-video 1.4.0, we can easily embed YouTube videos into Django projects. However it doesn't seem to work if the video is from any source but YouTube. The embed video code is different for every website and whenever I enter a code from a site like TikTok, CNN, or Facebook, it says "URL could not be recognized." YouTube Video CNN Video Is there a way to modify the URL so that Django-embed-video recognizes the URL? Or is there another way to create a django website that can show embedded videos from a source other then youtube? models.py from django.db import models # Create your models here. from embed_video.fields import EmbedVideoField class Item(models.Model): video = EmbedVideoField() -
HTML checkbox prepended to textbox and their sizes
Here my HTML code <div class="input-group mb3"> <div class="input-group-prepend"> <div class="input-group-text"> {% if item.complete == True %} <input type="checkbox", value="clicked", name="c{{item.id}}" checked> {% else %} <input type="checkbox", value="clicked", name="c{{item.id}}"> {% endif %} </div> </div> <input type="text" value="{{item.text}}" class="form-control"> </div> I prepended checkboxes before the textboxes, yet their sizes is not same as you see. Do I have to change their height(maybe width) values in order to make them equal or do I miss something else? By the way I am using CSS(I am a newbie to HTML, do not be harsh please :D ). Could it be relevant with that or it' s sources? Thanks! -
RadioSelect field not proper shown
I put RadioSelect field to my form and in Chromium my choices are in the left side of form not like labels and other fields in center, how can I fix it? Please any sygesstions. In FF it's looks also different, it's positioned to the left side. template {% extends 'school/index.html' %} {% load crispy_forms_tags %} {% load crispy_forms_field %} {% block content %} <form method="post" align='center' autocomplete="off" novalidate> {% csrf_token %} {{ form|crispy }} <button type="submit" class="btnSubmit">submit</button> </form> {% endblock %} form.py from django import forms from django.contrib.auth.models import User from django.core.validators import MinLengthValidator from django.utils.translation import gettext_lazy as _ class UserSignUpForm(forms.ModelForm): who = forms.ChoiceField( choices=[('student', 'Student'), ('teacher', 'Teacher')], required=True, widget=forms.RadioSelect(attrs={'style':'max-width: 20em; margin:auto; padding:300;', 'autocomplete':'off'}) ) password = forms.CharField( label="Password", validators=[MinLengthValidator(8, message="Minimum 8 characters")], widget=forms.PasswordInput(attrs={'style':'max-width: 20em; margin:auto', 'autocomplete':'off'})) confirm_password = forms.CharField( label="Confirm password", validators=[MinLengthValidator(8, message="Minimum 8 characters"), ], widget=forms.PasswordInput(attrs={'style':'max-width: 20em; margin:auto', 'autocomplete':'off'})) class Meta: model = User fields = ('who', "username", 'first_name', 'last_name', "password", ) help_texts = {"username": None} widgets = { 'username': forms.TextInput(attrs={'style':'max-width: 20em; margin:auto'}), 'first_name': forms.TextInput(attrs={'style':'max-width: 20em; margin:auto'}), 'last_name': forms.TextInput(attrs={'style':'max-width: 20em; margin:auto'}), } def clean(self): cleaned_data = super(UserSignUpForm, self).clean() password = cleaned_data.get("password") confirm_password = cleaned_data.get("confirm_password") if password != confirm_password: msg = _(f'Password and confirm password does not … -
I can't seek videos with django channels
I have a website and I could seek the videos but after I set up Django channels the videos don't seek, and I tried to solve this problem so I figured out when the server run with Starting ASGI/Channels the videos didn't do that, I have just one question Is this problem will continue with production or not? My asgi.p import os import django from django.core.asgi import get_asgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'site.settings') django.setup() application = get_asgi_application() -
How to upload geojson file in django postgresql
I would like to import a geojson file (Edge) in my postgresql database. I have a form for uploading the file. My problem is how to handle foreigns keys network, target, source and roadtype. Source and target must be Node instance. the file will be download inside the network page(pk). models.py class Edge(models.Model): param1 = models.FloatField(null=True, blank=True) param2 = models.FloatField(null=True, blank=True) param3 = models.FloatField(null=True, blank=True) speed = models.FloatField(null=True) length = models.FloatField(null=False) lanes = models.SmallIntegerField(null=True) geometry = models.LineStringField(null=True) name = models.CharField('Edge Name', max_length=200, blank=False) road_type = models.ForeignKey(RoadType, related_name='edges_road_type', on_delete=models.CASCADE) target = models.ForeignKey(Node, related_name='edges_target',on_delete=models.CASCADE) source = models.ForeignKey(Node, related_name='edges_source',on_delete=models.CASCADE) network = models.ForeignKey(RoadNetWork, related_name='edges_network', on_delete=models.CASCADE) my geojson file is like that { "type": "FeatureCollection", "features": [{ "type": "Feature", "properties": { "id": 1, "name": "Out 1 - E", "lanes": 1, "length": 4.0, "speed": 50.0, "source": 1, "target": 2, "param1": 3000.0, "road_type": 2 }, I try this.It's too slow. Could you please help me def upload_edge(request, pk): template = "networks/edge.html" network = RoadNetWork.objects.get(id=pk) if request.method == 'POST': form = EdgeForm(request.POST, request.FILES) if form.is_valid(): datafile = request.FILES['my_file'] objects = json.load(datafile) for object in objects['features']: objet_type = object['geometry']['type'] if objet_type == 'LineString': properties = object['properties'] geometry = object['geometry'] point1 = geometry['coordinates'][0] point2 = geometry['coordinates'][1] location = GEOSGeometry( LineString(geometry['coordinates'])) … -
How to change default page in paginator?
I changed default page like this (For this example I hardcored the number 3 as logic which I have in this function does not affect paginator) def test(request): paginator = Paginator(objects, 2) num = 3 page = paginator.get_page(number=num) return render(request,'personal.html', {'page':page,'paginator':paginator}) But now I can't go on other pages, it always returns page number 3. Is it possible to correct? Here is paginator {% if page.has_other_pages %} <nav> <ul class="pagination"> {% if page.has_previous %} <li class="page-item"> <a class="page-link" href="?page={{ page.previous_page_number }}">&laquo; Previous</a> </li> {% else %} <li class="page-item disabled"> <span class="page-link">&laquo; Previous</span> </li> {% endif %} {% for i in page.paginator.page_range %} {% if page.number == i %} <li class="page-item active"> <span class="page-link">{{ i }} <span class="sr-only">(current)</span> </span> </li> {% else %} <li class="page-item"> <a class="page-link" href="?page={{ i }}">{{ i }}</a> </li> {% endif %} {% endfor %} {% if page.has_next %} <li class="page-item"> <a class="page-link" href="?page={{ page.next_page_number }}">Next &raquo;</a> </li> {% else %} <li class="page-item disabled"> <span class="page-link">Next &raquo;</span> </li> {% endif %} </ul> </nav> {% endif %} And in another html I call it ... {% include 'paginator.html' with items=page paginator=paginator%} ... -
Display images manually that user has uploaded yet Python
How I display all the images manually that user has uploaded yet in Django show that I can create a Profile gallery -
Gunicorn / Procfile - module.wsgi not found
I'm trying to deploy a django app to heroku. My directory structure is: 'root'/ Procfile backend/ django_app/ manage.py mainapp/ settings.py wsgi.py I tried to follow the indications given on some posts here on stackoverflow but to no avail. I have a Procfile in the root directory. The latest version has: web: gunicorn backend.django_app.mainapp.wsgi --log-file - But it still gives me a module not found error: 2021-05-01T20:20:33.556737+00:00 heroku[web.1]: State changed from crashed to starting 2021-05-01T20:20:58.799412+00:00 heroku[web.1]: Starting process with command `gunicorn backend.django_app.mainapp.wsgi --log-file -` 2021-05-01T20:21:01.738041+00:00 app[web.1]: [2021-05-01 20:21:01 +0000] [4] [INFO] Starting gunicorn 20.0.4 2021-05-01T20:21:01.739021+00:00 app[web.1]: [2021-05-01 20:21:01 +0000] [4] [INFO] Listening at: http://0.0.0.0:46010 (4) 2021-05-01T20:21:01.739198+00:00 app[web.1]: [2021-05-01 20:21:01 +0000] [4] [INFO] Using worker: sync 2021-05-01T20:21:01.744319+00:00 app[web.1]: [2021-05-01 20:21:01 +0000] [8] [INFO] Booting worker with pid: 8 2021-05-01T20:21:02.007630+00:00 app[web.1]: [2021-05-01 20:21:02 +0000] [8] [ERROR] Exception in worker process 2021-05-01T20:21:02.007644+00:00 app[web.1]: Traceback (most recent call last): 2021-05-01T20:21:02.007645+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/gunicorn/arbiter.py", line 583, in spawn_worker 2021-05-01T20:21:02.007645+00:00 app[web.1]: worker.init_process() 2021-05-01T20:21:02.007646+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/gunicorn/workers/base.py", line 119, in init_process 2021-05-01T20:21:02.007646+00:00 app[web.1]: self.load_wsgi() 2021-05-01T20:21:02.007647+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/gunicorn/workers/base.py", line 144, in load_wsgi 2021-05-01T20:21:02.007648+00:00 app[web.1]: self.wsgi = self.app.wsgi() 2021-05-01T20:21:02.007648+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/gunicorn/app/base.py", line 67, in wsgi 2021-05-01T20:21:02.007648+00:00 app[web.1]: self.callable = self.load() 2021-05-01T20:21:02.007649+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/gunicorn/app/wsgiapp.py", line 49, in load … -
Why do I have a TypeError (Object ... is not JSON serializable) when trying to set a session value in a view?
I have this strange TypeError raised : "Object of type Product is not JSON serializable" when I try to set a session value in a view (in basket app). The error occurs with request.session['Hello'] = 'foo'. However, this error does not occur elsewhere. For instance, in store app, in views.py, the following request.session['Hello World'] = 'Alloy' works very well. Why is that happening ? basket app / views.py from django.shortcuts import render, get_object_or_404 from django.http import JsonResponse from . basket import Basket from store.models import Product from discount.forms import UserDiscountForm def basket_summary(request): basket = Basket(request) context = {'basket':basket} request.session['Hello'] = 'foo' return render(request,"store/basket_summary.html",context) def basket_add(request): basket = Basket(request) if request.POST.get('action') == 'post': product_id = int(request.POST.get('productid')) product_qty = int(request.POST.get('productqty')) product = get_object_or_404(Product, id=product_id) basket.add(product=product, qty=product_qty) basketqty = basket.__len__() response = JsonResponse({'qty':basketqty}) return response def basket_add_new(request): basket = Basket(request) if request.POST.get('action') == 'post': product_id = int(request.POST.get('productid')) product = get_object_or_404(Product, id=product_id) basket.add_new(product=product) basketqty = basket.__len__() response = JsonResponse({'qty':basketqty}) return response def basket_delete(request): basket = Basket(request) if request.POST.get('action') == 'post': product_id = int(request.POST.get('productid')) basket.delete(product=product_id) basketqty = basket.__len__() baskettotal = basket.get_total_price() response = JsonResponse({'qty':basketqty, 'subtotal':baskettotal}) return response def basket_update(request): basket = Basket(request) if request.POST.get('action') == 'update-basket': product_id = int(request.POST.get('productid')) product_qty = int(request.POST.get('productqty')) basket.update(product=product_id, qty=product_qty) basketqty … -
Django database stored images showing only text descriptions
I am trying to store images on a database and then display them on a Django template. For some reason Django is only showing the alt (alternate - html attribute) instead of the actual image. This is the template {% extends "myapp/layout.html" %} {% load static %} {% block body %} <div class="sidenav"> <a href="{% url 'index' %}" id="active">Gallery</a> <a href="{% url 'about' %}">About</a> <a href="{% url 'contact' %}">Contact</a> </div> <div class="main"> <h2>Gallery</h2> {% for image in images %} <img class="gallery" src="{% static '{{image.image.url}}' %}" alt="{{image.description}}"> {% endfor %} </div> {% endblock %} This is my model from django.db import models # Create your models here. class Image(models.Model): image = models.ImageField(upload_to='images/') description = models.CharField(max_length=50) def __str__(self): return "Description of image: " + self.description This is what I'm seeing -
remove checkbox checked jquery
I show some checkbox to the user. When a user selects a checkbox, it is checked. If the user selects another checkbox after the first selection, the second checkbox will also be checked, but the first checkbox selected by the user will not be unchecked. I want to make sure that by selecting each check box, the previous check box is removed and several checkbox are not checked at the same time, that is, only one check box has the right to be selected. $(document).on('change','.filter-form',function(event){ event.preventDefault(); $.ajax({ type:'GET', url:'filter/', data : $(this).serialize(), dataType: 'json', success: function (data) { $('#product-main').html(data['form']); }, error: function (data) { alert("error" + data); } }); }); <form action="" class="filter-form"> <input type="checkbox" name="price" value="new"> <input type="checkbox" name="discount" value="discount"> <input type="checkbox" name="old" value="old"> </form> -
How to get options order from select in (Model)MultipleChoiceField?
I need to somehow get the order of options from (in my case) ModelMultipleChoiceField. By that I mean indexes of options which are obtainable through JavaScript easily. I guess that to do that I would need custom Field which I've already created. It uses custom widget which allows user to reorder options of the field's select. class DataTypeForm(forms.ModelForm): file = forms.FileField() headers = OrderedModelMultipleChoiceField(queryset=Header.objects.none()) class Meta: model = DataType fields = ("file", "headers") def __init__(self, *args, **kwargs): super(DataTypeForm, self).__init__(*args, **kwargs) self.fields["headers"].queryset = Header.objects.filter(data_type=self.instance) class OrderedModelMultipleChoiceField(forms.ModelMultipleChoiceField): widget = OrderableSelectMultiple class OrderableSelectMultiple(forms.SelectMultiple): template_name = "django/forms/widgets/orderable_select.html" class Media: css = { "all": ("orderable-select-multiple.css",), } js = ("orderable-select-multiple.js",) How can I get access to those properties? -
why django channels is not working on server?
i create a django websocket chat app with django-channel and that is working in localhost very well ,but when i run it on the server with daphne and nginx is not working . since i dont have any error in journalctl -u daphne and journalctl -u nginx i think my nginx config has a problem this is nginx config in sites-available and also linked in sites-enabled : server { listen 80; server_name {DOMAIN-OR-IP}; location /ws/ { proxy_pass http://0.0.0.0:9000; proxy_http_version 1.1; proxy_read_timeout 86400; proxy_redirect off; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Host $server_name; } location = /favicon.ico { access_log off; log_not_found off; } location /static_in_env/ { root /home/mhfd/newblog17/blog23; } location / { include proxy_params; proxy_pass http://unix:/home/mhfd/newblog17/blog23/blog23.sock; } } and this is config of daphne.service in systemd: [Unit] Description=daphne daemon After=network.target [Service] User={USER} Group=www-data WorkingDirectory={PROJECT-DIRECTORY} ExecStart={VIRTUAL-ENVIRONMENT-ADDRESS}/bin/daphne --bind 0.0.0.0 --port 9000 --verbosity 0 {PROJECT-NAME}.asgi:application [Install] WantedBy=multi-user.target i got no error but websocket chat (send and recieve) is not working? error image -
"ValueError: I/O operation on closed file" when reading CSV file from form data in Django
I want website users to be able to upload a CSV file to my webpage. The file is uploaded through a form with a FileField. I overrode the is_valid method of the FormField to check whether the file has a CSV extension or not. If the form is valid, I want to read the lines of the CSV and save them to a model. The is_valid method works well. But when I try to execute the code following the is_valid condition I run into "ValueError: I/O operation on closed file". Views.py def upload_file(request): if request.method == 'POST': form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): csv_processor(form.cleaned_data['csv_file']) #messages.success(request, 'Archivo recibido para procesamiento') return HttpResponseRedirect(reverse('home_page')) else: form = UploadFileForm() return render(request, 'products/csv_upload_page.html', {'form': form}) csv_processor function def csv_processor(csv_file): csv_object = TextIOWrapper(csv_file, encoding='utf-8-sig') reader = csv.reader(csv_object) # Code to read lines follows here forms.py class UploadFileForm(forms.Form): csv_file = forms.FileField(label = 'Adjunte archivo csv', validators= [csv_content_validator]) def csv_content_validator(csv_file): if not csv_file.name.endswith('.csv'): raise ValidationError('Archivo debe tener extension csv') return True csv_object = TextIOWrapper(csv_file, encoding='utf-8-sig') reader = csv.reader(csv_object) first_row = next(reader) headers = ['SKU','Price'] # Check if column names match desired names for header_index in range(len(headers)): # Check if first row of the CSV file contains correct names … -
django.db.utils.OperationalError: foreign key mismatch - "Entry_returncylinder" referencing "Entry_cylinderentry"
Getting following error even after I have cleared all migrations.All was working fine until I tried to primary_key to my Cylinderentry model later on I removed but still it displays "django.db.utils.OperationalError: foreign key mismatch - "Entry_returncylinder" referencing "Entry_cylinderentry" " when I run py manage.py makemigrations it displays: You are trying to add a non-nullable field 'id' to cylinderentry without a default; we can't do that (the database needs something to populate existing rows).splays following : or when I run py manage.py migrate it displays: django.db.utils.OperationalError: foreign key mismatch - "Entry_returncylinder" referencing "Entry_cylinderentry" here is all models: from django.db import models from django.utils import timezone from django.urls import reverse # Create your models here. class CylinderEntry(models.Model): stachoice=[ ('Fill','fill'), ('Empty','empty') ] substachoice=[ ('Available','availabe'), ] cylinderId=models.CharField(max_length=50,unique=True) gasName=models.CharField(max_length=200) cylinderSize=models.CharField(max_length=30) Status=models.CharField(max_length=40,choices=stachoice,default='fill') Availability=models.CharField(max_length=40,choices=substachoice,default="available") EntryDate=models.DateTimeField(default=timezone.now) def get_absolute_url(self): return reverse('cylinderDetail',args=[(self.id)]) def __str__(self): return self.cylinderId class IssueCylinder(models.Model): cylinder=models.OneToOneField('CylinderEntry',on_delete=models.CASCADE) userName=models.CharField(max_length=60) issueDate=models.DateTimeField(default=timezone.now) def save(self,*args,**kwargs): if not self.pk: CylinderEntry.objects.filter(cylinderId=self.cylinder.cylinderId).update(Availability=('issued')) super().save(*args,**kwargs) def __str__(self): return self.userName class ReturnCylinder(models.Model): rechoice=[ ('fill','Fill'), ('empty','Empty') ] reav=[ ('Yes','yes'), ('No','no') ] cylinder=models.ForeignKey('CylinderEntry',on_delete=models.CASCADE) user=models.ForeignKey('IssueCylinder',on_delete=models.CASCADE) status=models.CharField(max_length=20,choices=rechoice) returnDate=models.DateTimeField(default=timezone.now) Availability=models.CharField(max_length=5,choices=reav) def save(self,*args,**kwargs): if not self.pk: IssueCylinder.objects.get(userName=self.user.userName).delete() if self.status=='yes' or self.status=='Yes': CylinderEntry.objects.get(cylinderId=self.cylinder.cylinderId).update(Availability=('available')) else: CylinderEntry.objects.get(cylinderId=self.cylinder.cylinderId).delete() super().save(*args,**kwargs) def __str__(self): return self.cylinder I don't where I m missing. Help!! -
mobile number standardization
You are given mobile numbers. Sort them in ascending order then print them in the standard format shown below: +91 xxxxx xxxxx The given mobile numbers may have +91,91 or 0 written before the actual digit number. Alternatively, there may not be any prefix at all. -
Has decompyle3 started to provide support for Python 3.9?
I forgot to add .gitignore in my repository root of my Python Django Project and I committed the code to my github repository. Now the root folder contains __pycache__, where all the compiled python files are located. I tried looking at, how to decompile the files and found the required resource uncompyle6 on PyPI. However, it works for Python 2.4 - 3.8. In addition, there is a Python decompiler decompyle3 for Python 3.7 - 3.8 which is stripped down from uncompyle6. But the version of Python I have been using all along is Python 3.9. Is there a way I can get around this and be able to solve my problem of decompiling my .py files anyhow so I can get the earlier project structure that I require? -
how can i retrieve and save latitiude and longitude from django-mapbox-LocationField?
i careate a django models with mapbox-locationfield : from mapbox_location_field.models import LocationField class Profile(models.Model): user = models.OneToOneField(User,on_delete=models.SET_NULL ,blank=True,null=True) location = LocationField(null=True, blank=True) latitude = models.DecimalField(max_digits=20,decimal_places=18,null=True, blank=True) longitude = models.DecimalField(max_digits=20,decimal_places=18,null=True, blank=True) def __str__(self): return self.store_name def save(self,*args, **kwargs): if self.location: self.latitude = self.location.y self.longitude = self.location.x super(Profile,self).save(*args, **kwargs) i want to save latitude and longitude but i got this error: 'tuple' object has no attribute 'y' -
I cannot install django onto macos using pip
I'm new to python and I'm trying to install Django onto my MacBook. I am following the documentation on the site from https://docs.djangoproject.com/en/3.2/topics/install/#installing-official-release using $ python -m pip install Django but I get this error message. Traceback (most recent call last): File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/runpy.py", line 174, in _run_module_as_main "__main__", fname, loader, pkg_name) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/runpy.py", line 72, in _run_code exec code in run_globals File "/Library/Python/2.7/site-packages/pip-21.0.1-py2.7.egg/pip/__main__.py", line 21, in <module> from pip._internal.cli.main import main as _main File "/Library/Python/2.7/site-packages/pip-21.0.1-py2.7.egg/pip/_internal/cli/main.py", line 60 sys.stderr.write(f"ERROR: {exc}") ^ SyntaxError: invalid syntax I'm not sure what the issue is. I might have a bugged version of pip. I'm not sure. Like I said I'm fairly new to all this so help would really be appreciated. Thank you -
Security in django multi tenants and django.contrib.sessions
I'm working with django multi tenancy package, and i would like to know if are there any guidelines on using django-tenants in a secure manner? or ant good practices I can think of at least one issue by which using django-tenants could lead to a security vulnerability. By having 'django.contrib.sessions' in SHARED_APPS, can't a user in one sub-domain/tenant impersonate a user in some other sub-domain/tenant? While I am not sure if my guess is correct, can some one help because it's my first experience in multi tenancies -
how can i change the format of datetime that django is sending to frontend?
model.py class DateTest(models.Model): date_created = models.DateTimeField(auto_now_add=True) view.py def getdate(request): dates = DateTest.objects.filter(product=pid).values('date_created') da=list(dates) print(da) return JsonResponse({'reviews':da}) Expected output: [{ 'date_created': datetime.datetime(May 1, 2021, 5:37 p.m.)}] Actual output: [{'date_reviewed': datetime.datetime(2021, 5, 1, 13, 2, 12, 404779, tzinfo=<UTC>)}] -
Loading pre-existing data into Django project
I have a pre-existing db file 'sample.db' in sqlite3 format that I'm trying to import into my Django project. I've already added it to the settings.py file: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', }, 'sample': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'sample.db', } I was able to generate the model.py in my application folder using inspectdb. I have run makemigrations and migrate and everything seems to be fine. I try to get some data in my views.py: obj = table_name.objects.get(id=1) Then I start the server: python manage.py runserver, and try to load a page at http://127.0.0.1:8000/ It displays an error message saying: NameError at / Name table_name is not defined What did I miss? Thank you! -
should i keep my custom user model in shared apps?
I'm working with django multi tenancy package, and I have created my own custom user models called users. just i would like to know if i should keep my custom user model, with shared apps or with tenant apps? my second question is related the first one : should i let those apps bellow in tenant apps also or just in shared apps: i'm talking about those exactly : SHARED_APPS = [ 'django_tenants', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', # My custom user model # 'users', -
filter category Django
I want to make a button to filter product by category.. Example Salad or Meat. Without Model ProductAtribuut im able to do it, but now i added the model, so im real confused how i can get the data of a Foreign Key inside a Foreign Key ProductAtribuut -> Product(FK) -> Categorie(FK) Models.py class Categorie(models.Model): naam = models.CharField(max_length=150,db_index=True) slug = models.SlugField(unique=True) class MPTTMeta: order_insertion_by = ['naam'] class Meta: ordering=('-naam',) def __str__(self): return self.naam def get_absolute_url(self): return reverse('JavaKitchen:product_by_categorie', args=[self.slug]) @property def get_products(self): return Product.objects.filter(categorie__naam=self.naam) class Groente(models.Model): groente = models.CharField(max_length=100) def __str__(self): return self.groente class Vlees(models.Model): vlees = models.CharField(max_length=100) def __str__(self): return self.vlees class Product(models.Model): slug = models.SlugField(unique=True, primary_key=True) titel = models.CharField(max_length=200) beschrijving = models.TextField(blank=True, null=True) categorie = models.ForeignKey(Categorie, on_delete=models.CASCADE) class Meta: ordering=('-titel',) def __str__(self): return self.titel def get_title_uppercase(self): return self.titel.upper() def get_absolute_url(self): return reverse('JavaKitchen:product_detail',args=[self.id,]) class ProductAtribuut(models.Model): def groente(): return Groente.objects.filter(groente='geen').first() def vlees(): return Vlees.objects.filter(vlees='geen').first() product = models.ForeignKey(Product, on_delete=models.CASCADE, blank=False) groente = models.ForeignKey(Groente, on_delete=models.CASCADE, default=groente) vlees = models.ForeignKey(Vlees, on_delete=models.CASCADE, default=vlees) prijs = models.FloatField(default=0) afbeelding = models.ImageField(blank=True, upload_to='gerechten/') #later upgrade.. zichtbaar = models.BooleanField(default=True) def __str__(self): return self.product.titel def image_tag(self): return mark_safe('<img src="/media/%s" width="80" height="auto" />' % (self.afbeelding)) image_tag.short_description = 'Image' Views.py def product_list(request,categorie_slug=None): categorie = None javakitchen = JavaKitchen.objects.get(id=1) openings_tijden = Openings_tijden.objects.all() categories …