Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django 403 error for static files on shared hosting using passenger_wsgi
I'm trying to get my Django app running on a shared hosting site using passenger_wsgi (following the instruction of the hosting provider). Since the app is for the main domain I installed it using this folder layout: public_html django static css js images SMC_website templates In settings.py I have: STATIC_URL = 'static/' STATICFILES_DIRS = [ '/home/xxxxxx/public_html/django/static/', '/home/xxxxxx/public_html/django/static/css', '/home/xxxxxx/public_html/django/static/js', '/home/xxxxxx/public_html/django/static/images', ] In urls.py I have: urlpatterns = [ path('admin/', admin.site.urls), re_path(r"^$", views.index, name="Home Page"), ] urlpatterns += static(settings.STATIC_URL, document_root=os.path.join(settings.BASE_DIR, 'static')) When I try out the "static(settings.STATIC_URL,document_root=os.path.join(settings.BASE_DIR, 'static'))" in the django manage.py shell I get a an empty list ([]). Not sure why, or if this is the cause of my problem. The app runs, pulls data from the database, but generates a 403 error for any content accessed from the static folders (css, js, or images). I have these folder permisisons: drwxr-x--- 2 xxxxxx xxxxxx 4096 Dec 17 18:30 css drwxr-x--- 8 xxxxxx xxxxxx 4096 Dec 17 18:30 images drwxr-x--- 3 xxxxxx xxxxxx 4096 Dec 17 18:30 js drwxr-xr-x 5 xxxxxx xxxxxx 4096 Dec 11 14:24 SMC_website drwxr-xr-x 3 xxxxxx xxxxxx 4096 Dec 11 14:24 logs -rw-r--r-- 1 xxxxxx xxxxxx 689 Dec 11 14:24 manage.py -rw-r--r-- 1 xxxxxx xxxxxx 1442 Dec … -
Django admin: reverse select foreign keys
I want to add pre-existing foreignkey items from the parent's admin. I have a "Bundle" model to hold "Product" items; many-to-one/foreignkey: models.py class Bundle(models.Model): title = models.CharField(max_length=300) class Product(models.Model): title = models.CharField(max_length=300) bundle = models.ForeignKey( 'Bundle', on_delete=models.CASCADE, null=True, blank=True, ) Below, I used StackedInline but this is for creating new products with a form: admin.py class ProductInline(admin.StackedInline): model = Product @admin.register(Bundle) class BundleAdmin(admin.ModelAdmin): inlines = [ ProductInline, ] Instead, I want to repeatedly add existing products from a dropdown/search in the Bundle section of admin. So, I make a Bundle and then add a series of Products from a dropdown / with a search. Thanks in advance. -
How to make query for some fields of the models?
I am makine business directory and i stucked in city and districts pages of business directory. I made a simple business directory. All i want three queries; Forexample category name: Manufacturing First: I want one page like this: abc.com/directory/category/slug:slug(this slug means category name)/ ( I did, i have no problem with this page. Second: City url like this abc.com/directory/category/slug:slug/(city name with slug style)/. forexample abc.com/category/manufacturing/london/ Third: District url like this abc.com/directory/category/slug:slug/(city name with slug style)/. forexample abc.com/category/manufacturing/london/southwark(district names) I only did first one and second and third made me crazy... I tried lots of things but failed... Here are my codes: models.py from django.db import models from django.urls import reverse from tinymce import models as tinymce_models # Create your models here. class City(models.Model): city = models.CharField(max_length=50) slug = models.SlugField() def __str__(self): return str(self.city) class District(models.Model): district = models.CharField(max_length=50) slug = models.SlugField() city = models.ForeignKey(City, on_delete=models.CASCADE) def __str__(self): return str(self.district) class FirmaCategory(models.Model): title = models.CharField(max_length=255) slug = models.SlugField() class Meta: verbose_name_plural = 'Firma Kategorileri' def __str__(self): return str(self.title) class Firma(models.Model): category = models.ForeignKey(FirmaCategory, related_name="Firma", on_delete=models.CASCADE) title = models.CharField(max_length=255) slug = models.SlugField() adres = tinymce_models.HTMLField() tel = tinymce_models.HTMLField() website = tinymce_models.HTMLField() email = tinymce_models.HTMLField() intro = tinymce_models.HTMLField() body = tinymce_models.HTMLField() city = … -
Rendering data from a dictionary inside json after saving data into JSONField in Django
I am working on a django project whereby I am using JSONField to save data into the database of the model. Everything works fine but I am having issues when trying to render the data into the html template. The data saved into the database is as shown below. {'degree': ['BSc','MSc'], 'designition': [ 'content writer', 'data scientist', 'systems administrator', ], 'email': 'maunarokguy@gmail.com', 'name': 'Brian Njoroge', 'phone': '+918511593595', 'skills': [ 'Python', ' C++', 'Power BI', 'Tensorflow', 'Keras', 'Pytorch', 'Scikit-Learn', 'Pandas', 'NLTK', 'OpenCv', 'Numpy', 'Matplotlib', 'Seaborn', 'Django', 'Linux', 'Docker'], 'total_exp': 3, 'university': ['gujarat university', 'wuhan university', 'egerton university']} I am looking for a way to render them such that in the html, I will have something that displays the dictionary data inside skills and university as a list. Here is the template for loop {% for skill in user.profile.json_data %} {{skill}} {% endfor %} And here is the models class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) avatar = models.ImageField(default='default.jpg', upload_to='profile_images') bio = models.TextField() resume = models.FileField('Upload Resumes', upload_to='resumes/', null=True, blank=True,default='resume.docx') json_data = models.JSONField(null=True, blank=True) Here is the views @login_required def myprofile(request, user_id): profile = Profile.objects.get(id=user_id) context = {'profile':profile} return render(request, 'user/profile.html', context) -
can not createsuperuser becuase one column (foreignkey) can not be null in django
I have started a django project with extending User model from AbstractUser to my CustomUser model which have foreign key relation with other model. When I try to create superuser with manage.py it does not create a superuser. It shows an error --> django.db.utils.IntegrityError: (1048, "Column 'cid_id' cannot be null"). Any help will be appreciated blog/models.py from django.db import models from django.utils import timezone from django.contrib.auth import get_user_model from ckeditor.fields import RichTextField # Create your models here. class Category(models.Model): cid = models.AutoField(primary_key=True) category_name = models.CharField(max_length=100) def __str__(self): return self.category_name class Post(models.Model): aid = models.AutoField(primary_key=True) image = models.ImageField(default='blog-default.png', upload_to='images/') title = models.CharField(max_length=200) # content = models.TextField() content = RichTextField() created = models.DateTimeField(default=timezone.now) author = models.ForeignKey(get_user_model(), on_delete=models.CASCADE) cid = models.ForeignKey(Category, on_delete=models.CASCADE, verbose_name='specialization') approved = models.BooleanField('Approved', default=False) like = models.ManyToManyField(get_user_model(), related_name='likes') def __str__(self): return self.title users/model.py from django.db import models from blog.models import Category from django.contrib.auth.models import AbstractUser # Create your models here. class CustomUser(AbstractUser): cid = models.ForeignKey(Category, on_delete=models.CASCADE) profile_pic = models.ImageField(default='default_person.jpg', upload_to='profile_pics') cid in the Category model is the foreign key in the Post and CustomUser model. But when I try to createsuperuser it shows the error I mentioned above. cid can not be null for the user because when a user … -
Are there other cases which "select_for_update()" doesn't work in Django?
When using select_for_update() with update() as shown below: # "store/views.py" from django.db import transaction from .models import Person from django.http import HttpResponse @transaction.atomic def test(request): # Here # Here print(Person.objects.select_for_update().all().update(name="Tom")) # Here # Here print(Person.objects.select_for_update().filter(id=1).update(name="Tom")) return HttpResponse("Test") Only UPDATE query is run without SELECT FOR UPDATE query as shown below. *I use PostgreSQL and these logs below are the queries of PostgreSQL and you can check On PostgreSQL, how to log queries with transaction queries such as "BEGIN" and "COMMIT": While when using select_for_update() with save() as shown below: # "store/views.py" from django.db import transaction from .models import Person from django.http import HttpResponse @transaction.atomic def test(request): # Here person1 = Person.objects.select_for_update().all().first() person1.name = "Tom" person1.save() # Here # Here person2 = Person.objects.select_for_update().filter(id=1).first() person2.name = "Tom" person2.save() # Here # Here person3 = Person.objects.select_for_update().get(id=1) person3.name = "Tom" person3.save() # Here return HttpResponse("Test") SELECT FOR UPDATE query and UPDATE query are run as shown below: And, when using select_for_update() with count() as shown below: # "store/views.py" from django.db import transaction from .models import Person from django.http import HttpResponse @transaction.atomic def test(request): # Here # Here print(Person.objects.select_for_update().all().count()) # Here # Here print(Person.objects.select_for_update().filter(id=1).count()) return HttpResponse("Test") SELECT query is run instead of SELECT FOR UPDATE … -
Problem when download Python package and then install from .whl files
I want to download Python package pipy.org and move them to another machine and finally install that packages with downloaded .whl files in that machine This is requirements.txt file: amqp==5.1.1 anytree==2.8.0 asgiref==3.5.2 async-timeout==4.0.2 attrs==22.1.0 autobahn==22.7.1 Automat==22.10.0 beautifulsoup4==4.11.1 billiard==3.6.4.0 celery==5.2.7 certifi==2022.9.24 cffi==1.15.1 channels==4.0.0 channels-redis==4.0.0 charset-normalizer==2.1.1 click==8.1.3 click-didyoumean==0.3.0 click-plugins==1.1.1 click-repl==0.2.0 constantly==15.1.0 coreapi==2.3.3 coreschema==0.0.4 cryptography==38.0.3 daphne==4.0.0 Deprecated==1.2.13 Django==4.0.8 django-celery-beat==2.3.0 django-celery-results==2.4.0 django-filter==22.1 django-jalali==6.0.0 django-timezone-field==5.0 djangorestframework==3.14.0 djangorestframework-simplejwt==5.2.2 drf-yasg==1.21.4 et-xmlfile==1.1.0 gunicorn==20.1.0 h2==4.1.0 hpack==4.0.0 hyperframe==6.0.1 hyperlink==21.0.0 idna==3.4 incremental==22.10.0 inflection==0.5.1 itypes==1.2.0 jdatetime==4.1.0 Jinja2==3.1.2 kombu==5.2.4 lxml==4.9.1 MarkupSafe==2.1.1 msgpack==1.0.4 multitasking==0.0.11 numpy==1.23.3 openpyxl==3.0.10 packaging==21.3 pandas==1.5.0 pandas-datareader==0.10.0 Pillow==9.2.0 priority==1.3.0 prompt-toolkit==3.0.31 psutil==5.9.2 psycopg2==2.9.4 pyasn1==0.4.8 pyasn1-modules==0.2.8 pycparser==2.21 PyJWT==2.6.0 pyOpenSSL==22.1.0 pyparsing==3.0.9 python-crontab==2.6.0 python-dateutil==2.8.2 python-dotenv==0.21.0 pytz==2022.4 redis==4.3.4 requests==2.28.1 ruamel.yaml==0.17.21 ruamel.yaml.clib==0.2.7 service-identity==21.1.0 simplejson==3.17.6 six==1.16.0 soupsieve==2.3.2.post1 sqlparse==0.4.3 Twisted==22.10.0 txaio==22.2.1 typing_extensions==4.4.0 tzdata==2022.5 Unidecode==1.3.6 uritemplate==4.1.1 urllib3==1.26.12 vine==5.0.0 wcwidth==0.2.5 wrapt==1.14.1 yfinance==0.1.74 zope.interface==5.5.1 I did download packages with: pip download -r requirements.txt and after copy all `.whl files to traget computer, I did run this code: pip install --no-index --find-links ~/LocalPythonPackage -r requirements.txt But I got this error: ERROR: Could not find a version that satisfies the requirement MarkupSafe==2.1.1 (from versions: none) ERROR: No matching distribution found for MarkupSafe==2.1.1 I use python3.11 and Ubuntu 20.04.5 LTS in both computers. I think that, this problem is for dependencies or different in OS. Can … -
clean method not called in modelform
As written in the title, the form gets validated whatever happens, I don't understand why are my clean and clean_ methods are not called. Used forms for quite some time but here I am puzzled on what I am forgetting. Thanks simplified forms.py class ProfileForm(forms.ModelForm): class Meta: model = Profile fields = ["workcity", "post_address", "billing_address", "country", "phone"] def clean(self): #not called cleaned_data = super().clean() billing_address = cleaned_data.get('billing_address') post_address= cleaned_data.get('post_adress') if not billing_address == post_address: do some raising validation error def clean_workcity(self, *args, **kwargs): #not called workcity= self.cleaned_data.get("workcity") if xxx: do some raising validation error return workcity simplified views.py def profileform(request): if request.method =='POST': form = ProfileForm(request.POST) if form.is_valid(): form.instance.user = request.user form.save() messages.success(request, 'Profile created successfully') return redirect('profile') else : handle errors else: form = ProfileForm() return render(request, "CORE/home.html", {"form": form}) -
model form not rendering in django template
My models.py and this is my model for photos. # home photo page class Photos(models.Model): photo_title = models.CharField(max_length=50, blank=False) photo_description = models.CharField(max_length=50, blank=False) photo_date = models.DateField(blank=False) photo_location = models.CharField(max_length=50, blank=False) photo_file = models.FileField(upload_to='photos', blank=False) def __str__(self): return self.photo_title My forms.py this is the model form I made to render it as a form. class UploadPhotosForm(forms.Form): class Meta: model = Photos fields = '__all__' my views.py these are my relavent imports and section I coded in view file. from .forms import CampForm, ProjectForm, HikeForm, UploadPostsForm, UploadPhotosForm posts = UploadPostsForm() photo = UploadPhotosForm() print(photo.as_p()) context = { 'title': 'manage_wall', 'posts': posts, 'photo': photo, } return render(request, 'manager/manage_wall.html', context) My template {% block content %} <div class="container"> <div class="row"> <div class="col"> <form action="" method="post"> {% csrf_token %} {{photo.as_p}} <input type="submit" value="Add"> </form> </div> <div class="col"> <form action="" method="post"> {% csrf_token %} {{posts.as_p}} <input type="submit" value=" Add"> </form> </div> </div> </div> {%endblock %} As you can see here my photoForm is not rendering in the frontend can someone point out the mistake I have made not to render that form only while other forms are successfully rendering in the frontend. My Question is all other model forms rendered successfully why this is not displaying … -
404 Not Found Nginx Error After SFTP Changes via FireZilla
I just updated my site's (Django; deployed via AWS Lightsail) files via FileZilla but my website won't load now, giving me a 404 error. I've done some research and they're telling me it is an error with Nginx's conf file, but I'm not sure how I should change it to resolve the issue. Here is the conf file: GNU nano 3.2 nginx.conf user www-data; worker_processes auto; pid /run/nginx.pid; include /etc/nginx/modules-enabled/*.conf; events { worker_connections 768; # multi_accept on; } http { ## # Basic Settings ## sendfile on; tcp_nopush on; tcp_nodelay on; keepalive_timeout 65; types_hash_max_size 2048; # server_tokens off; # server_names_hash_bucket_size 64; # server_name_in_redirect off; include /etc/nginx/mime.types; default_type application/octet-stream; I've attempted to return to a previous snapshot (that used to function) by creating a new instance, but when I try to load the backup via its public IP it seems to still give me a 404. -
Django / ListView / Use get_context_data to count all keys in a json variable
I would like to return in my Link.html the number of links contain in allLinks variable (json) So far I guess I misunderstand the use of get_context_data and how to pass to context['CountLink'] the total count of links. With the current code , I got : Liste des recherches terre : <QuerySet [<Post: terre>, <Post: océan>]> Links océan : <QuerySet [<Post: terre>, <Post: océan>]> Links Models.py class Post(models.Model): title = models.CharField(max_length=255) url = models.URLField(max_length=255) allLinks = models.JSONField() def __str__(self): return self.title views.py class LinkView(ListView): model = Post template_name = 'link.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['CountLink'] = Post.objects.all() return context Link.html {% for post in object_list %} <li> <a href="{% url 'DetailLink' post.pk %}">{{ post.title }}</a> : {{CountLink}} Links </li> {% endfor %} -
Trouble with importing Django import-export library
I've tried to import Django's import-export library as specified in the documentation. It seems that it has been installed correctly in my venv: asgiref==3.5.2 defusedxml==0.7.1 diff-match-patch==20200713 Django==4.1.4 django-import-export==3.0.2 et-xmlfile==1.1.0 import-export==0.3.1 MarkupPy==1.14 numpy==1.23.5 odfpy==1.4.1 openpyxl==3.0.10 pandas==1.5.2 python-dateutil==2.8.2 pytz==2022.7 PyYAML==6.0 six==1.16.0 sqlparse==0.4.3 tablib==3.3.0 tzdata==2022.7 xlrd==2.0.1 xlwt==1.3.0 I've also added it to my installed apps in settings.py: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'app.apps.AppConfig', 'django.conf' 'import_export', ] But still, when I'm trying to import it in my app's admin.py file, it doesn't work: What else could go wrong? The project itself as for now doesn't really include almost any code. I've tried re-installing the library in my venv, double checked it if it's there, but that didn't solve the problem I'm struggling to find any solutions I could apply, since almost all of the tutorials and answers only include the two setup steps I've mentioned and done -
Django: accessing the related_name on a Model returns None
models.py from django.contrib.auth.models import AbstractUser from django.db import models class User(AbstractUser): pass class Likes(models.Model): pass class Unlikes(models.Model): pass class Post(models.Model): post_text = models.TextField(max_length=1000) user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='posts') created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) likes = models.ManyToManyField(User, null=True, related_name="liked_posts") unlikes = models.ManyToManyField(User, null=True, related_name="unliked_posts") def __str__(self): return f'{self.user} at {self.created_at}: {self.post_text[0:20]}...' views.py def profile(request, username): print(User.objects.get(username=username).posts) print(Post.objects.filter(user = User.objects.get(username=username))) return render(request, 'network/profile.html', { 'user': request.user, 'profile': User.objects.get(username=username) }) My models.py file defines the relationship between User and post as follows: user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='posts') Running: print(User.objects.get(username=username).posts) print(Post.objects.filter(user = User.objects.get(username=username))) returns: network.Post.None <QuerySet [<Post: Joe at 2022-12-18 10:48:18.941880+00:00: test1...>, <Post: Joe at 2022-12-18 10:53:27.407349+00:00: test1...>, <Post: Joe at 2022-12-18 10:53:34.167508+00:00: test2...>]> My question: How can the first print statement return no rows, when the second statement returns the expected value (3 rows)? As far as I understand, the two statements should achieve the same thing? -
Docker Gulp based on Django Cookiecutter - node path errors
I have installed a Docker project based on Django Cookiecutter using Gulp. Runs perfectly. First thing I try to do is install my NPM package. They install and I can see them in the docker local_node. But I will get path error when running Docker Up. Cookiecutter comes installed Bootstrap. So I use that as an example. This Gulp code and my added NPM works fine in a normal Django project - so I know the address paths are fine for the node_modules. But in a Docker Up I get a bad path error. [12:14:12] Error: File not found with singular glob: /app/node_modules/tooltipster/dist/js/tooltipster.bundle.js (if this was purposeful, use `allowEmpty` option) prelim_local_node | at Glob.<anonymous> (/app/node_modules/glob-stream/readable.js:84:17) prelim_local_node | at Object.onceWrapper (node:events:628:26) prelim_local_node | at Glob.emit (node:events:513:28) prelim_local_node | at Glob.emit (node:domain:489:12) prelim_local_node | at Glob._finish (/app/node_modules/glob/glob.js:194:8) prelim_local_node | at done (/app/node_modules/glob/glob.js:179:14) Why do the preinstalled bootstrap npm packages work and my installed packaged create issues? Is there some special way to add a path for a Docker image? Docker will still run - just not with my packages. The gulpfile. tooltipster and parsleyjs do not work. The code will stop processing after the first error. // Relative paths function function pathsConfig(appName) … -
django pipeline FileNotFoundError when the path is right
I'm trying to add pipeline to my django project. But it's throwing me winerror 2 (FileNotFoundError) when I'm trying to execute collectstatic settings.py STATIC_URL = 'static/' STATICFILES_STORAGE = 'pipeline.storage.PipelineStorage' STATIC_ROOT = 'static' STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', 'pipeline.finders.PipelineFinder', ) PIPELINE = { 'PIPELINE_ENABLED': True, 'STYLE': { 'base': { 'source_filenames': ( 'css\\core\\header.css', 'css\\core\\reset.css', 'css\\core\\style.css' ), 'output_filename': 'css\\core\\base.css' }, } } ├───css │ ├───BRS │ │ journal.css │ │ journal.css.map │ │ journal.scss │ │ │ ├───core │ │ form.css │ │ header.css │ │ images.css │ │ intro.css │ │ reset.css │ │ start.css │ │ style.css │ │ table.css │ │ │ ├───Portfolio │ └───user │ user.css │ user.css.map │ user.scss I even changed the subprocess module to output the executable variable and I get None Tried to change the STATIC_ROOT variable to BASE_DIR / "static" but that didn't help Expected static files to be compressed -
Django logger not logging error in log file
Hi all I am facing issues with logging in django. It is not logging error in my django.log file. Following is the code I am using in views.py :- import logging logger = logging.getLogger(__name__) class SomeView(CreateAPIView): serializer_class = some_class queryset = models.model_name.objects def create(self, request, *args, **kwargs): try: some_code try: some_more_code except Exception as e: logger.error(e, exc_info=True) print(e) except: pass return 1 This works and inner block print error. Then in settings.py import logging LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'verbose': { 'format': '%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s' }, }, 'handlers': { 'file': { 'level': 'ERROR', 'class': 'logging.FileHandler', 'filename': 'django.log', 'formatter': 'verbose' }, 'console': { 'level': 'ERROR', 'class': 'logging.StreamHandler', 'formatter': 'verbose' }, }, 'loggers': { 'django': { 'handlers': ['file', 'console'], 'level': 'ERROR', 'propagate': True, }, }, } this creates a django.log file but I dont see errors in django.log files when i trigger error. Can anyone please guide me. I am using pycharm which shows log format not recognized i f that is of any help -
Django Jinja2 - AttributeError: 'Environment' object has no attribute 'get_source'
I have the following two lines of code. Both are using jinja2 to replace the template variables: subject = Environment(loader=BaseLoader).from_string(template.email_subject).render(context) body = Environment(loader=BaseLoader).from_string(template.email_template).render(bodyContext) The first line works just fine, while the second line throws the Error: AttributeError: 'Environment' object has no attribute 'get_source' The context dictionary includes all necessary template variables and the jinja2 syntax should be correct as well. Just to be sure, here are the templates as well: template.email_template: Hallo {{name}}, {%- include invoiceType+'/email_body.tpl' -%} Viele Grüße {{emailFooter}} invoiceType/email_body.tpl: im Anhang findest du/findet ihr den Entwurf für die kommende Rechnung über alle angefallenen Kosten bis zum {{invoiceDate -}}. template.email_subject: Rechnung {{currentYear}}{{invoiceID}} -
How to show content with zip in view with django?
I hava a django applicaiton. And I try to show the content values from the backend in the template. There is a method: show_extracted_data_from_file where I combine three methods: class FilterText: def total_cost_fruit(self): return [3588.20, 5018.75, 3488.16, 444] def total_cost_fruit2(self): return [3588.20, 5018.75, 3488.99] def total_cost_fruit3(self): return [3588.20, 5018.75, 44.99] def show_extracted_data_from_file(self): regexes = [ self.total_cost_fruit(), self.total_cost_fruit2(), self.total_cost_fruit3, ] matches = [(regex) for regex in regexes] return zip(matches) and I have the view: def test(request): content_pdf = "" filter_text = FilterText() content_pdf = filter_text.show_extracted_data_from_file() context = {"content_pdf": content_pdf} return render(request, "main/test.html", context) and html: <div class="wishlist"> <table> <tr> <th>Method 1</th> <th>Method 2</th> <th>Method 3</th> </tr> {% for value in content_pdf %} <tr> <td>{{value.0}}</td> <td>{{value.1}}</td> <td>{{value.2}}</td> </tr> {% endfor %} </table> </div> But it looks now: Method 1 Method 2 Method 3 [3588.2, 5018.75, 3488.16, 444] [3588.2, 5018.75, 3488.99] [3588.2, 5018.75, 44.99] But I want it of course under each other: Method 1 Method 2 Method 3 3588.2 3588.2 3588.2 5018.75, 44.99 3488.99 5018.75, 5018.75 3488.16 444 -
Django Using Default Form & File Submission with Drag and Drop functionality
I have a django application that allow user to upload their image and then another dialog opens to collect user data related to them. After the dialog form has been submitted, I have added the javascript eventlistener to submit successfully submit the form with data and it redirects to the form's action attribute. I wanna implement the same functionality, if user drop their image in the browser then dialog opens to collect user data, then do the same as above and redirect to the form's action attribute. How can I achieve it? Here is my code #--urls.py from django.urls import path from . import views from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('', views.index, name='index'), path('success/', views.success_function, name='success page'), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) #--views.py def index(request): form = userForm() return render(request, 'polls/hello_world.html', {'form': form}) def success_function(request): if request.method == 'POST': form = userForm(request.POST, request.FILES) user_files = request.FILES.getlist('django_image_field') if form.is_valid(): images_data = [] for eachfile in user_files: #handle_uploaded_file(eachfile) file_path = file_upload(eachfile) img_details = {'file_path': file_path, 'file_name': eachfile.name} images_data.append(img_details) return render(request, 'polls/success.html', {'data': images_data}) else: print(form.errors) return HttpResponse("Not valid form") else: return HttpResponse("Not a valid method") --under forms.py class NameForm(forms.Form): your_name = forms.CharField(required=False, label='Your name', max_length=100) django_image_field = … -
assign a reserved word of sql as a variable in a sql query
I would like to know how to put a reserved word of sql as a variable in a sql query def requeteDB(sql_request): with connection.cursor() as cursor: cursor.execute(*sql_request) row = cursor.fetchall() return row def query1(choice, limit): return(''' SELECT col1, SUM(col2) as nb as ORDER BY nb %s LIMIT %s ''', [choice, limit]) requeteDB(query1(choice="DESC", limit="5")) > *** django.db.utils.ProgrammingError: ERROR: Type 'nb' does not exist LINE 10: ORDER BY nb 'DESC' ------------------^ -
Django DRF - nested serializer (level>2) does not show up in the response
We have the follwing structure (library->books->pages) the first serializer class Library(serializers.ModelSerializer): books = BookSerializer(many=True) class Meta: model = Library fields = '__all__' @transaction.atomic def create(self, validated_data): # create logic here the second serializer class BookSerializer(serializers.ModelSerializer): results = PageSerializer(many=True, required=False) class Meta: model = Book fields = '__all__' we have an endpoint library/, where we post the payload of the following format { "ref": "43a0c953-1380-43dd-a844-bbb97a325586", "books": [ { "name": "The Jungle Book", "author": "Rudyard Kipling", "pages": [ { "content": "...", "pagenumber": 22 } ] } ] } all the objects are created in the database, but the response does not contain pages key. It looks like this { "id": 27, "ref": "43a0c953-1380-43dd-a844-bbb97a325586", "books": [ { "id": 34, "name": "The Jungle Book", "author": "Rudyard Kipling" } ] } depth attribute does not seem to work. What do I have to do to make pages appear in the responce? -
How to delete UserFollowing based on user_id and following_user_id using Django Rest Framework
Here's the link to the answer of how the following relationship was created in the first place. https://stackoverflow.com/a/58799650/18498343 -
Is there a way that fully managed device under android management api stays enrolled after factory reset?
I enroll the device using qrCode and have not disabled factory reset. But once I factory reset the device, the device no longer stays enrolled and becomes a simple personal phone. Is there a way, the device stays enrolled after factory reset or any soft reset functionality? -
How to return empty queryset from django_filters.FilterSet in API view if querystring hasn't any valid key
I use django-filter package with djangorestframework package for filter objects that return from API view. There are my files: # models.py class Symbol(models.Model): title = models.CharField(max_length=30, verbose_name='title') # serializers.py class SymbolSerializer(serializers.ModelSerializer): class Meta: model = Symbol fields = ('title',) # filters.py class SymbolFilter(django_filters.FilterSet): st = django_filters.CharFilter(method='get_st', label='search') def get_st(self, queryset, field_name, value): return queryset.filter(title__icontains=value) class Meta: model = Symbol # views.py @api_view(['GET']) def symbol_list(request): queryset = Symbol.objects.all() view_filter = APIFilters.APISymbolFilter(request.GET, queryset=queryset) if (view_filter.is_valid() is False) or (not view_filter.qs): return Response(None, status=status.HTTP_404_NOT_FOUND) ser = SymbolSerializer(view_filter.qs, many=True) return Response(ser.data, status=status.HTTP_200_OK) # urls.py from .views import * urlpatterns = [ path('symbol/list/', symbol_list, name='symbol_list'), ] So, If I sent get request to localhost:8000/symbol/list/?st=sometitle all things are good and I will got Symbol objects that have sometitle in there title field. But when I remove st from querystring, django-filter will return all objects in Symbol model. My question is: How Can I return empty queryset if st key isn't in querystring or if filter(title__icontains=value) was empty? -
HeidiSQL is not showing any data even when table size is more than 0B
I have Postgresql Database in production and i'm trying to insert data from my localhost using psycopg2 library. i'm seeing my database through HeidiSQL. But after i finished inserting the data, my HeidiSQL shows that table size increased but when i try to see the data, it shows 0 rows. I have tried to drop all tables and re-migrate and re-insert the data, but still it shows 0 rows even when the table size is not 0 B. I have tried to insert table one by one from the program by comment the other insert and it works. But i still can't understand why i can't see any data when i'm inserting simultaneously