Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Image uploaded but not saved in media and database Django
Am creating a settings page where the user should be able to chang there image and biodata. But only the biodata gets updated when I print the request.FILES.GET("profile_picture") it prints the name of the photo I uploaded. why is it not uploaded and saved to the database? Models.py from django.db import models from django.contrib.auth.models import AbstractUser class User(AbstractUser): profile_pic = models.ImageField(upload_to="images/", null=True ,blank=True) bio = models.TextField(max_length=100, blank=True) forms.py class ProfileForm(forms.Form): profile_picture = forms.ImageField(required=False ) bio = forms.CharField(label='Bio', max_length=100 ,widget=forms.Textarea()) views.py def settings(request): if request.user.is_authenticated: intial_data = { 'first_name': request.user.first_name, 'last_name': request.user.last_name, 'user_name': request.user.username, 'email':request.user.email, 'bio':request.user.bio } profile_form=ProfileForm(intial_data) if request.method == "POST": profile_form=ProfileForm(request.POST, request.FILES) if profile_form.is_valid(): user_name = profile_form.cleaned_data.get('user_name') profile_picture =request.FILES.get('profile_picture') bio = profile_form.cleaned_data.get('bio') user= User.objects.get(pk=request.user.id) if user is not None: user.profile_picture=profile_picture, user.bio=bio user.save() context ={ "profile_form":profile_form } return render(request, 'user/settings.html',context) return redirect('home') my_template.html <tr> <td>Bio</td> <td>{{profile_form.bio}}</td> </tr> <tr> <td>Update Profile Picture</td> <td>{{profile_form.profile_picture}}</td> </tr> -
Django and DataTables ignoring Read, Edit, Delete buttons after initial 10 results
I am using Django with DataTables and it is working fine, except for one part I have not been able to figure out what I am missing. I have a table that adds Actions to each row READ, UPDATE and DELETE buttons to perform CRUD actions on each row of data. The buttons depend on data-form-url being set to the url and id, like the below, which then pop up in a modal. <button type="button" id="read-file" class="inline-block bs-modal btn btn-sm btn-primary" data-form-url="{% url 'read_file' fileupload.id %}"> <span class="fa fa-eye"></span> </button> This only works for the first 10 entries initialized in the table. The buttons are dead for entries 11 and beyond, basically anything not initialized in the first view and paginated or hidden via the "show 10, 25, 50, 100 entries" dropdown. Can someone help me understand why the buttons are not working and how to activate them again for paginated or hidden rows? views.py class FileUploadListView(generic.ListView): model = FileUpload context_object_name = 'fileuploads' template_name = 'fileupload/file-list-view.html' #Filter view for current user def get_queryset(self): """Returns FileUploads that belong to the current user""" return FileUpload.objects.filter(my_user=self.request.user) html (for the file-table which is included into a base file) <table class="table table-striped table-sm table-bordered {% … -
Bootstrap 4, Card Style in HTML
I use bootstrap 4 cards to develop my blog which actually looks grate, however, when it is used on a mobile version, the picture of the posts shifts on the top and all the dimensions go random. I would like to have the box dimensioning but still be on the left. Basically avoiding the shift to the top in html. <div class="d-flex justify-content-center"> <div class="container"> <div class="row"> <div class="col-12"> {% for post in object_list %} <div class="card mb-3" style="max-width: 540px;"> <div class="row no-gutters"> {% if post.immagine %} <div class="col-md-4"> <img src="{{ post.immagine.url }}" class="card-img" width="200" height="260"> </div> {% else %} <div class="col-md-4"> </div> {% endif %} <div class="col-md-8"> <div class="card-body"> <h5 class="card-title">{{ post.nome }} {{ post.cognome }} - </div> </div> </div> {% endfor %} -
Django split string from db and use in requests
I have tag {{ post.tags }} in template which prints all post tags from database. I would like to separate tags by space and use them in search function. Search function: def search_posts(request): query = request.GET.get('p') object_list = Post.objects.filter(tags__icontains=query) liked = [i for i in object_list if Like.objects.filter(user = request.user, post=i)] context ={ 'posts': object_list, 'liked_post': liked } return render(request, "feed/search_posts.html", context) -
Uncaught ReferenceError: $ajax is not defined
$ajax({ type: "POST", url: "/Unread", data: { htable: t, csrfmiddlewaretoken: "XgHM9ZCPEj9KaXa8OUoL2GLIBcv9SKPB56tTm7gVubudHPwwbrWpSO8hVP7mvBCP", }, success: function () { alert("done"); }, }); When i click on the SaveTable ("#saveTable") - it throws below error. Uncaught ReferenceError: $ajax is not defined at HTMLButtonElement. ((index):575)`` at HTMLButtonElement.dispatch (jquery-3.5.1.js:5429) at HTMLButtonElement.elemData.handle (jquery-3.5.1.js:5233) -
How to import whole python file and not break F403 flake8 rule?
Imports like this: from .file import * are "anti-patterns". How can I import one python file into another, without breaking flake8 F430 rule? I have settings.py in the Django project that I want to "overwrite" in test_settings.py like this, from settings import * # make tests faster DATABASES['default'] = {'ENGINE': 'django.db.backends.sqlite3'} to test with in-memory database, and I cant figure out how to do it without breaking the rule. -
When doing runserver, keep getting new data loaded in my database
Every time I do a: python manage.py runserver And I load the site, python gets data and puts this in my database. Even when I already filled some info in the database. Enough to get a view of what I am working on. Now it is not loading the information I want and instead putting in new information to add to the database so it can work with some data. What is the reason my data in the database is not being processed? And how do I stop new data being loaded into the database. -
ImportError: cannot import name 'Celery'
I'm trying to learn Celery i'm using Django 2.0 and celery 5.0.2 and my os is Ubuntu. This is my structure My project structure is: celery/ manage.py celery/ __init__.py cerely_app.py settings.py urls.py wsgi.py apps/ main/ __init__.py admin.py apps.py models.py task.py views.py test.py My configuration for cerely_app, based on documentation: import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'celery.settings') app = Celery('celery') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print(f'Request: {self.request!r}') And my init.py: from .celery_app import app as celery_app __all__ = ('celery_app',) But when django give a error of import when i use command python3 manage.py runserver: $python3 manage.py runserver Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/home/brayan/Envs/celery/lib/python3.8/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line utility.execute() File "/home/brayan/Envs/celery/lib/python3.8/site-packages/django/core/management/__init__.py", line 317, in execute settings.INSTALLED_APPS File "/home/brayan/Envs/celery/lib/python3.8/site-packages/django/conf/__init__.py", line 56, in __getattr__ self._setup(name) File "/home/brayan/Envs/celery/lib/python3.8/site-packages/django/conf/__init__.py", line 43, in _setup self._wrapped = Settings(settings_module) File "/home/brayan/Envs/celery/lib/python3.8/site-packages/django/conf/__init__.py", line 106, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/usr/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 961, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in … -
RecursionError: maximum recursion depth exceeded in comparison in pylint
I have created many tests and all working fine on local and gihub CI but while check PyLint I'm getting this error RecursionError: maximum recursion depth exceeded in comparison. I would be great if you can help me. command running on server: DJANGO_SETTINGS_MODULE=projectname.settings.test_set pylint --generated-members=viridis --load-plugins pylint_django okko/apps/* --errors-only Error: File "/opt/hostedtoolcache/Python/3.8.6/x64/lib/python3.8/site-packages/astroid/decorators.py", line 96, in wrapped res = next(generator) File "/opt/hostedtoolcache/Python/3.8.6/x64/lib/python3.8/site-packages/astroid/bases.py", line 136, in _infer_stmts for inferred in stmt.infer(context=context): File "/opt/hostedtoolcache/Python/3.8.6/x64/lib/python3.8/site-packages/astroid/util.py", line 160, in limit_inference yield from islice(iterator, size) File "/opt/hostedtoolcache/Python/3.8.6/x64/lib/python3.8/site-packages/astroid/context.py", line 113, in cache_generator for result in generator: File "/opt/hostedtoolcache/Python/3.8.6/x64/lib/python3.8/site-packages/astroid/decorators.py", line 132, in raise_if_nothing_inferred yield next(generator) File "/opt/hostedtoolcache/Python/3.8.6/x64/lib/python3.8/site-packages/astroid/decorators.py", line 89, in wrapped if context.push(node): File "/opt/hostedtoolcache/Python/3.8.6/x64/lib/python3.8/site-packages/astroid/context.py", line 89, in push if (node, name) in self.path: RecursionError: maximum recursion depth exceeded in comparison """ -
Adding Css in Django templates
I have been trying to apply css in the main.css on the class of (custom-card) but its not working. Anyone can find what's the mistake i'm doing. custom-card class is in home.html Below is the base.html in Django\mysite\blogapp\templates\blog\base.html . {% load static %} <!DOCTYPE html> <html> <head> <title>Home Page</title> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- CSS link --> <link rel="stylesheet" type="text/css" href="{% static 'blog/main.css' %}"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> </head> <body> <!-- ================ HEADER NAVIGATION ========================= --> <section class="header"> <div class="container"> <nav class="navbar navbar-expand-lg "> <a class="navbar-brand" href="#"><span>e-</span>Blog</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation"> <i class="fa fa-bars"></i> </button> <div class="collapse navbar-collapse" id="navbarNav"> <ul class="navbar-nav ml-auto text-center"> <!--ml auto used to have nav on right side,text-center used to make text in center when using mobile view--> <li class="nav-item"> <a class="nav-link active-home" href="{% url 'blog-homepage' %}">Home</a> </li> <li class="nav-item"> <a class="nav-link" href="{% url 'blog-aboutpage' %}">About</a> </li> <li class="nav-item"> <a class="nav-link" href="#">Services</a> </li> <li class="nav-item"> <a class="nav-link" href="#">Our project</a> </li> <li class="nav-item"> <a class="nav-link" href="#">Blog</a> </li> <li class="nav-item"> <a class="nav-link" href="#">Contact</a> </li> </ul> </div> </nav> </div> </section> <!-- ================ HEADER NAVIGATION/ENDED ========================= --> <div class="container"> {%block homecontent%} {%endblock%} … -
Database Postgres in Docker with Django?
For example I Use defoult settings in Django DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'database', 'USER': 'postgres', 'PASSWORD': 'postgres', 'HOST': '127.0.0.1', 'PORT': '5432', } When dockerize my db with depends_on: - db Should I change change my 'HOST' parameter '127.0.0.1' for 'db' could you explain this process thank you in advance -
Django Rest - "serializer.data" is empty dict() even though "serializer" has data with details
I was trying to implement password change based on some recommendations on stackoverflow but something which is really weird for me. After troubleshooting I got idea data my view is not working. Changing serializer actions to print I see data "serializer.data" is result "{}" even though "print(serializer)" give result. serializers.py class ChangePasswordSerializer(serializers.Serializer): old_password = serializers.CharField(max_length=128, write_only=True, required=True) new_password1 = serializers.CharField( max_length=128, write_only=True, required=True ) new_password2 = serializers.CharField( max_length=128, write_only=True, required=True ) def validate_old_password(self, value): user = self.context["request"].user if not user.check_password(value): raise serializers.ValidationError( { "old_passowrd": _( "Your old password was entered incorrectly. Please enter it again." ) } ) return value def validate(self, data): if data["new_password1"] != data["new_password2"]: raise serializers.ValidationError( {"new_password2": _("The two password fields didn't match.")} ) validate_password(data["new_password1"], self.context["request"].user) return super().validate(data) views.py class ChangePassword(UpdateAPIView): serializer_class = ChangePasswordSerializer permission_classes = [IsAuthenticated] def get_object(self, queryset=None): return self.request.user def update(self, request, *args, **kwargs): self.object = self.get_object() serializer = self.get_serializer(data=request.data) if serializer.is_valid(raise_exception=True): # user.set_password(serializer.data.get("new_password1")) # user.save() print(serializer.data) return Response("Success", status=status.HTTP_204_NO_CONTENT) return Response(serializer.errors, status.HTTP_400_BAD_REQUEST) -
Stripe Checkout Webhook CSRF Error despite @csrf_exempt (Django)
I am using Stripe Checkout for my Django subscriptions. I tested webhooks via CLI locally - with success. Now I am moving the project to staging area and got a CSRF issue. The registered webhook throughs this message (my comments are already added): In general, this can occur when there is a genuine Cross Site Request Forgery, or when https://docs.djangoproject.com/en/2.2/ref/csrf/ Django's CSRF mechanism has not been used correctly. For POST forms, you need to ensure: Your browser is accepting cookies. -> Yes, all cookies are accepted. Tests with different browsers led to the same result. The view function passes a request to the template's https://docs.djangoproject.com/en/dev/topics/templates/#django.template.backends.base.Template.render “render” method. -> No template is being used, since Stripe Checkout provides the template. In the template, there is a “{% csrf_token %}” template tag inside each POST form that targets an internal URL. -> No, CSRF_TOKENS inside the html. No template is being used, since Stripe Checkout provides the template. If you are not using “CsrfViewMiddleware”, then you must use “csrf_protect” on any views that use the “csrf_token” template tag, as well as those that accept the POST data. -> I am using CsrfViewMiddleware. Funny fact: If I disable CsrfViewMiddleware, then webhooks are functioning. … -
Django uWSGI + Nginx failed (104: Connection reset by peer) while reading upstream, client:
I have an issue uploading files to media. The files size is about 500M to 1GB. Configuration is Django + uWSGI + NGINX. Upload is restarting and restarting and finally cancelled. Error message is: failed (104: Connection reset by peer) while reading upstream, client:... For File-Upload I am using: django-file-form 3.1.0. Does anybody can help? Thx. -
Reverse for url with arguments '('',)' not found, but only on a certain machine
I deployed using Gunicorn and Nginx, and am seeing this error in one machine that's using my app, but not in the rest, so I'm starting to think it is an issue on the machine the error is displaying but not in the app. When doing the exact same actions to replicate the error in other machines, the app works just fine. The template form that causes the error: <form action="{% url 'cart:cart_add' product.id %}" method="post"> {% csrf_token %} <div class="form-group"> <label for="id_quantity"></label> <input data-toggle="touchspin" type="number" value="1" required id="id_quantity" name="quantity" data-bts-button-down-class="btn btn-danger" data-bts-button-up-class="btn btn-primary"> <input type="hidden" name="override" value="False" id="id_override"> </div> <button type="submit" class="btn btn-secondary"> <i class="uil-plus-circle"></i> Add to order </button> </form> urls.py: from django.urls import path from . import views app_name = 'cart' urlpatterns = [ path('', views.cart_detail, name='cart_detail'), path('add/<int:product_id>', views.cart_add, name='cart_add'), path('remove/<int:product_id>', views.cart_remove, name='cart_remove'), path('clear/', views.cart_clear, name='cart_clear'), ] Again, in other machines it is working just fine. -
Filtering on related fields in Django
I have two models in my Django project: ModelA(models.Model): name = models.CharField(max_length=20) ModelB(models.Model): a = models.ForeignKey(A, on_delete=models.CASCADE) date = models.DateField() There is a one-to-many relationship between models A and B, with around 50 instances of model A and 100,000 entries for model B. In the problem that I'm having, I have a specific queryset of ModelB, and from this queryset I want to know, for each date, how are these ModelB's distributed among the different ModelA. The data structure that I require is as follows: [ { "date": date_1, "num": num_1, "bins": [ { "name_A": model_A_1, "num": num_A_1_1 }, { "name_A": model_A_2, "num": num_A_1_2 } ] }, { "date": date_2, "num": num_2, "bins": [ { "name_A": model_A_1, "num": num_A_2_1 }, { "name_A": model_A_2, "num": num_A_2_2 } ] } ] where date_1 is one of the existing dates in Table B, num_1 is the total number of ModelB with date date_1. bins contains the distribution of ModelB among the different ModelA's, e.g. num_A_1_1 corresponds to the number of ModelB with date date_1 and Foreign key model_A_1, etc. Here's what I have tried: date_bins = initial_modelB_queryset.values("date").order_by("date").distinct() output = [] for bin in date_bins: B_A_queryset = ModelA.objects.filter(modelB__in=initial_modelB_queryset, modelB__date=bin["date"]) B_num = B_A_queryset.count() bins = … -
How to do a translator?
I am currently coding my first website, which is a translator in an invented language. You input a random phrase and it should get translated in the invented language. Here's the code for the translation: class TranslatorView(View): template_name= 'main/translated.html' def get (self, request, phrase, *args, **kwargs): translation = "" for letter in phrase: if letter.lower() in "a": if letter.isupper(): translation = translation + "U" else: translation = translation + "u" elif letter.lower() in "t": if letter.isupper(): translation = translation + "A" else: translation = translation + "a" elif letter.lower() in "c": if letter.isupper(): translation = translation + "G" else: translation = translation + "g" elif letter.lower() in "g": if letter.isupper(): translation = translation + "C" else: translation = translation + "c" return render(request, 'main/translator.html', {'translation': translation}) def post (self, request, *args, **kwargs): phrase = request.POST.get('text', 'translation') translation = phrase context = { 'translation': translation } return render(request,self.template_name, context) Template where you input the phrase: {% extends "base.html"%} {% block content%} <form action="{% url 'translated' %}" method="post">{% csrf_token %} <div class="form-group"> <center><h2 class = "display-3">TRANSLATE YOUR DNA CHAIN</h2></center> <br> <br> <textarea class="form-control" name='text' id="exampleFormControlTextarea1" rows="6"></textarea> <br> <button type='Submit' class= "btn btn-primary btn-lg btn-block">Translate</button> </div> </form> {% endblock content %} Template where … -
Cannot connect to test database after upgrading to django 3.1
I am trying to migrate a django app from 3.0.11 to 3.1. I can run the app without any issues. But I cannot run tests anymore. The following error is thrown when running python manage.py test django.db.utils.ConnectionDoesNotExist: The connection e doesn't exist This is from my settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': config("DB_NAME", default='postgres'), 'USER': config('DB_USER', default='postgres'), 'PASSWORD': config('DB_PASSWORD', default='postgres'), 'HOST': config('DB_HOST', default='postgres'), } } Full stacktrace: Creating test database for alias 'default'... Destroying test database for alias 'default'... Traceback (most recent call last): File "/usr/local/Caskroom/miniconda/base/envs/mysite/lib/python3.8/site-packages/django/db/utils.py", line 172, in ensure_defaults conn = self.databases[alias] KeyError: 'e' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/usr/local/Caskroom/miniconda/base/envs/mysite/lib/python3.8/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/usr/local/Caskroom/miniconda/base/envs/mysite/lib/python3.8/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/Caskroom/miniconda/base/envs/mysite/lib/python3.8/site-packages/django/core/management/commands/test.py", line 23, in run_from_argv super().run_from_argv(argv) File "/usr/local/Caskroom/miniconda/base/envs/mysite/lib/python3.8/site-packages/django/core/management/base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/Caskroom/miniconda/base/envs/mysite/lib/python3.8/site-packages/django/core/management/base.py", line 371, in execute output = self.handle(*args, **options) File "/usr/local/Caskroom/miniconda/base/envs/mysite/lib/python3.8/site-packages/django/core/management/commands/test.py", line 53, in handle failures = test_runner.run_tests(test_labels) File "/usr/local/Caskroom/miniconda/base/envs/mysite/lib/python3.8/site-packages/django/test/runner.py", line 698, in run_tests self.run_checks(databases) File "/usr/local/Caskroom/miniconda/base/envs/mysite/lib/python3.8/site-packages/django/test/runner.py", line 636, in run_checks call_command('check', verbosity=self.verbosity, databases=databases) File "/usr/local/Caskroom/miniconda/base/envs/mysite/lib/python3.8/site-packages/django/core/management/__init__.py", line 168, in call_command return command.execute(*args, **defaults) File "/usr/local/Caskroom/miniconda/base/envs/mysite/lib/python3.8/site-packages/django/core/management/base.py", line 371, in execute output = … -
Previewing images using Django
I have a html,css and js app that I ported to Django and I want to preview an image before upload. A dropdown form allows users to select an option that will then display the image onto the screen before upload. I did this through javascript by setting img src = "" to empty and then when the user selected an option from the dropdown menu, javascript set the img src path i.e if user selected car from menu then js would set img src=images/car.png and display it. function displayImage(imgValue){ if (imgValue == 'car') { previewImage.setAttribute("src", "images/car.png"); previewDefaultText.style.display = "none"; previewImage.style.display = "block"; } else if (imgValue == 'location') { previewImage.setAttribute("src", "images/newyork.jpg"); previewDefaultText.style.display = "none"; previewImage.style.display = "block"; .... .... } The issue is that the JS isn't setting the path of the img src in Django. Can I do this through JS or will it require to rewrite in a more Django/pythonic way? Note: w/o the use of ajax. -
Convert multiple texts with python markdown in django views
I have a blog that uses markdown. I am trying to convert it to HTML in views.py with python markdown. For individual posts, this code works: def detail_view(request, slug): md = markdown.Markdown() post = get_object_or_404(Post, slug=slug) postcontent = md.convert(post.md_text) context = {...} return render(request, 'details.html', context) However, applying the same logic to a view meant to show multiple posts fails: def home_view(request): posts = Post.objects.order_by('-id') md = markdown.Markdown() for markdown in posts: postcontent = md.convert(posts.md_text) context = {...} return render(request, 'home.html', context) What would I need to change to convert the text_md field(s) of my Post model in this view? Thanks in advance! -
Saving form data in the database
Hello I am new in Django and I have created an available house posting form but I cannot store the entered data in the database. I used if form.is_valid and form.cleaned_data please I need help my code: views.py def public(request): form = PublicationForm() if request.method == 'POST': form = PublicationForm(request.POST, request.FILES) if form.is_valid(): first_name=form.cleaned_data['first_name'] last_name=form.cleaned_data['last_name'] agency_name=form.cleaned_data['agency_name'] city=form.cleaned_data['city'] categories=form.cleaned_data['categories'] status=form.cleaned_data['status'] phone_number_1=form.cleaned_data['phone_number_1'] phone_number_2=form.cleaned_data['phone_number_2'] description=form.cleaned_data['description'] image_one=form.cleaned_data['image_one'] pub = Publication.objects.create( first_name=first_name, last_name=last_name, agency_name=agency_name, city=city, categories=categories, status=status, phone_number_1=phone_number_1, phone_number_2=phone_number_2, description=description, image_one=image_one ) pub.save() return HttpResponse("Publication réussie") else: form = PublicationForm() return render(request, 'pub/public.html', {'form':form}) This is my template views I used the django-crispy-form module public.html <form method="POST" enctype="multipart/form-data " class="form-block "> {% csrf_token %} {{ form.non_field_errors }} <div class="form-row"> <div class="col-md-4 mb-3"> {{ form.first_name.errors }} <label for="{{ form.first_name.id_for_label }} "></label> {{ form.first_name|as_crispy_field }} </div> <div class="col-md-4 mb-3"> {{ form.last_name.errors }} <label for="{{ form.last_name.id_for_label }} "></label> {{ form.last_name|as_crispy_field }} </div> <div class="col-md-4 mb-3"> {{ form.agency_name.errors }} <label for="{{ form.agency_name.id_for_label }} "></label> {{ form.agency_name|as_crispy_field }} </div> <div class="col-md-4 mb-3"> {{ form.city.errors }} <label for="{{ form.city.id_for_label }} "></label> {{ form.city|as_crispy_field }} </div> <div class="col-md-4 mb-3"> {{ form.categories.errors }} <label for="{{ form.categories.id_for_label }} "></label> {{ form.categories|as_crispy_field }} </div> <div class="col-md-4 mb-3"> {{ form.status.errors }} <label for="{{ form.status.id_for_label }} "></label> … -
How Retrieving a full tree data in Django Self Foreign Key?
I insert 3 records Electronics Null Mobile 1 Iphone 2 class Category(models.Model): name = models.CharField(max_length=160) parent = models.ForeignKey('self', on_delete=models.CASCADE, null=True, blank=True) if i search Iphone how to get all related data Example: Category.object.filter(name='Iphone') Result want all parent data ex: Electronics Mobile Iphone -
Linking ParentalKey to Abstract class and all subclasses in Wagtail
I am setting up a website in Wagtail. I have Author snippets which include author information. Each page (BlogPage) can be related to multiple Authors (via an AuthorOrderable). I am now trying to add a new Page type, so I have created an abstract superclass for Authors to link to, however I get the following error: AttributeError: type object 'BlogPage' has no attribute 'author_orderable' class AbstractPage(Page): class Meta: abstract = True author_panels = [ InlinePanel('author_orderable', label="Authors"), ] class BlogPage(AbstractPage): #Some fields- authororderable is not listed here class AuthorOrderable(Orderable, models.Model): page = ParentalKey('AbstractPage', on_delete=models.CASCADE, related_name='author_orderable') author = models.ForeignKey('Author', on_delete=models.CASCADE, related_name='+') @register_snippet class Author(models.Model): #Some fields -
Django to Heroku error: ModuleNotFoundError
I keep getting this error when deploying a Django app to Heroku via the Heroku CLI gunicorn the_weather.wsgi Traceback (most recent call last): File "c:\users\martin kalax\appdata\local\programs\python\python38-32\lib\runpy.py", line 194, in _run_module_as_main return _run_code(code, main_globals, None, File "c:\users\martin kalax\appdata\local\programs\python\python38-32\lib\runpy.py", line 87, in run_code exec(code, run_globals) File "C:\Users\MARTIN KALAX\AppData\Local\Programs\Python\Python38-32\Scripts\gunicorn.exe_main.py", line 4, in File "c:\users\martin kalax\appdata\local\programs\python\python38-32\lib\site-packages\gunicorn\app\wsgiapp.py", line 9, in from gunicorn.app.base import Application File "c:\users\martin kalax\appdata\local\programs\python\python38-32\lib\site-packages\gunicorn\app\base.py", line 11, in from gunicorn import util File "c:\users\martin kalax\appdata\local\programs\python\python38-32\lib\site-packages\gunicorn\util.py", line 9, in import fcntl ModuleNotFoundError: No module named 'fcntl' -
Can you explain easily what is the function of misaka in django?
I'm a beginner at Django. I want to learn about the function of misaka in Django.