Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django m2m_changed post_clear get cleared objects
In Django docs about m2m_changed signal, it's said that pk_set argument to the signal handler is None for clear actions: pk_set ... For the pre_clear and post_clear actions, this is None. But on post_clear action, how can one know what relations are removed? (On pre_clear it can be achieved by simply querying the relation, since it's not cleared yet.) -
MakeMigration Error on Django - ImportError: cannot import name 'UserProfile'
I want to create a back-end server for an online video website with Django. There are user information and video information in the database. I want users to pay attention to each other and collect videos. Users can also upload videos. For this I registered two apps: user and video. And added to INSTALLED_APPS. After I writing models.py, I run python manage.py makemigrations and reported error: File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "D:\Code\PycharmProjects\djangoProject_dachuang\venv\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line utility.execute() File "D:\Code\PycharmProjects\djangoProject_dachuang\venv\lib\site-packages\django\core\management\__init__.py", line 395, in execute django.setup() File "D:\Code\PycharmProjects\djangoProject_dachuang\venv\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "D:\Code\PycharmProjects\djangoProject_dachuang\venv\lib\site-packages\django\apps\registry.py", line 114, in populate app_config.import_models() File "D:\Code\PycharmProjects\djangoProject_dachuang\venv\lib\site-packages\django\apps\config.py", line 301, in import_models self.models_module = import_module(models_module_name) File "D:\Program Files\Python36\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "D:\Code\PycharmProjects\djangoProject_dachuang\user\models.py", line 8, in <module> from video.models import Video File "D:\Code\PycharmProjects\djangoProject_dachuang\video\models.py", line 20, in <module> from user.models import UserProfile ImportError: cannot import name 'UserProfile' this is user->models.py: from django.db … -
Trying to create an advertisement-like system to distribute ads to my website and further monetize it using Django
I have created a Django App which takes Image and Video Advertisements to the database and then renders it to a template where we can view every Ads and perform CRUD operations. Every Unique User may create or delete his own Ads. He will not be able to perform any operation on Other User's Ads. However, I want these Ads get circulated over my website (at first randomly, later we can distribute along the weight and type-investment of the advertisements) and circulate as it may be any type of advertisements from any Advertisement Company. Also, How will I distribute it into my website so that in every frame or container right advertisements appear. Secondly, I also want to know how can I help monetize my website and also how can i monetize advertisements and the idea of earning through advertisements. I am using Python and Django Framework and studying different packages to learn it. Please give me some tips and working of how to achieve this. Thank you for your time . -
ImageField Overwrite with different file name in Django
HI i am making a project in django where upload image and render is there but i want to make the project like it replace the previous image which can be in different name Like if i upload a image first like san.png and second time if i upload sanju.png the previous one should delete automatically and in folder there should be only one image..... How can i make the logic?? MODELS.PY from django.db import models class Image(models.Model): image = models.FileField(upload_to='images', max_length=255) -
django.db.utils.OperationalError: no such column: ...?
I got the fowling error when i ran ./manage.py migrate in django sqlite DB django.db.utils.OperationalError: no such column: users_user.phone_number then when I deleted all migrations history and makemigrations it solved. But of course I back the to prevues commit because I don’t want to delete the migrations history. Any idea to solve that without deleting the migrations history? full error messsage File "/Users/apple/.local/share/virtualenvs/backend-_hch_eH3/lib/python3.7/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "/Users/apple/.local/share/virtualenvs/backend-_hch_eH3/lib/python3.7/site-packages/django/db/backends/sqlite3/base.py", line 383, in execute return Database.Cursor.execute(self, query, params) sqlite3.OperationalError: no such column: users_user.phone_number The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/Applications/PyCharm.app/Contents/plugins/python/helpers/pycharm/django_manage.py", line 52, in <module> run_command() File "/Applications/PyCharm.app/Contents/plugins/python/helpers/pycharm/django_manage.py", line 46, in run_command run_module(manage_file, None, '__main__', True) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/runpy.py", line 205, in run_module return _run_module_code(code, init_globals, run_name, mod_spec) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/runpy.py", line 96, in _run_module_code mod_name, mod_spec, pkg_name, script_name) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/runpy.py", line 85, in _run_code exec(code, run_globals) File "/Users/apple/Documents/GitHub/solitary-poetry-26574/backend/manage.py", line 21, in <module> main() File "/Users/apple/Documents/GitHub/solitary-poetry-26574/backend/manage.py", line 17, in main execute_from_command_line(sys.argv) File "/Users/apple/.local/share/virtualenvs/backend-_hch_eH3/lib/python3.7/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() -
Django regex on template?
I need to make menu active based when user visits a page ! And it should also work on sub pages, how to allow everything after a particular word ? {% with request.resolver_match.url_name as url_name %} <li class="menu-item {% if url_name in 'settings, settings-password' %}active{% endif %}"> <a href="{% url 'settings' %}" class="nk-menu-link"> <span class="menu-text">Settings</span> </a> </li> {% endwith %} In the above, am adding these settings, settings-password, how to allow everything after settings to make the menu active ? I have other pages who has many sub pages, so its not fare to add everything under if In loop, so if i can allow everything after a word, for ex: How to make menu active which contains "settings" in their view name ? Please suggest -
Not able to load template that has been extended in Django
The django 'extends' template is not loading the content. In this I am trying to extend index.html to homepage.html. Both the files are under the same templates directory. The code snippets are shown below: index.html <!DOCTYPE html> {% load static %} <html lang="en"> <head> <meta charset="UTF-8"> <title> Tashi eComm</title> <!-- adding title icon --> <link rel = "icon" href ="{% static 'images/TecommLogo.png' %}" type = "image/x-icon"> <!-- Bootstrap 5 link --> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-F3w7mX95PdgyTmZZMECAngseQB83DfGTowi0iMjiWaeVhAn4FJkqJByhZMI3AhiU" crossorigin="anonymous"> <!-- Bootstrap 5 popper and javascript link --> <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.9.3/dist/umd/popper.min.js" integrity="sha384-W8fXfP3gkOKtndU4JGtKDvXbO53Wy8SZCQHczT5FMiiqmQfUpWbYdTil/SxwZgAN" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.1/dist/js/bootstrap.min.js" integrity="sha384-skAcpIdS7UcVUC05LJ9Dxay8AXcDYfBJqt1CJ85S/CFujBsIzCIv+l9liuYLaMQ/" crossorigin="anonymous"></script> <!--Bootstrap icons--> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.5.0/font/bootstrap-icons.css"> <!-- stylesheet --> <link rel="stylesheet" type="text/css" href="{% static 'css/stylesheet.css' %}"/> </head> <body> <div class="wrapper"> <div class="panel panel-default"> <div class="panel-heading"> <div class="d-flex justify-content-end "> <div class="top-header m-2 "> <a href="#">Marketplace</a> </div> <div class="top-header m-2 ">|</div> <div class="top-header m-2"> <a href="#">Buyer Protection</a> </div> <div class="top-header m-2 ">|</div> <div class="top-header m-2"> <a href="#">Track Order</a> </div> <div class="top-header m-2 ">|</div> <div class="top-header m-2"> <div class="form-group"> <select id="demo_overview_minimal" class="select-picker" data-role="select-dropdown" data-profile="minimal"> <!-- options --> <option>BTN</option> <option>USD</option> <option>EUR</option> </select> </div> </div> </div> </div> <div class="panel-body"> <nav class="navbar navbar-expand-lg navbar-light bg-light"> <div class="container-fluid"> <a class="navbar-brand ms-5" href="#"><img src="{% static 'images/TecommLogo.png' %}" alt="Logo" height="60px" width="60px"></a> <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarTogglerDemo01" aria-controls="navbarTogglerDemo01" … -
How to iterate over a Form in Html, store the data in a variable in Json, send it back to Django Backend
I need to iterate over an Html Form and get the data as JSON obj and send it to the Django backend to get data as objects. all(). Is this possible? In this form I am iterating over a student detail list that I have rendered to the template using Django. my form <form method="POST " id="studentform"> {% csrf_token %} <table class="table table-striped"> <thead> <tr> <th scope="col">Admission No</th> <th scope="col">First Name</th> <th scope="col">Last Name</th> <th scope="col">Present Status</th> </tr> </thead> <tbody> {% for student in student_names %} <tr> <th scope="row"> <div class="form-group "> <select class="form-control st" style="appearance: none;" id="admission_number" name="admission_number"> <option>{{student.admission_number}}</option> </select> </div> </th> <td> <div class="form-group"> <select class="form-control st" style="appearance: none;" id="first_name" name="first_name"> <option>{{student.first_name}}</option> </select> </div> </td> <td> <div class="form-group"> <select class="form-control st" style="appearance: none;" id="last_name" name="last_name"> <option>{{student.last_name}}</option> </select> </div> </td> <td> <div class="form-group"> <select class="form-control st " style="text-align: center;" id="attendance" name="attendance"> <option>Yes</option> <option>No</option> </select> </div> </td> </tr> {% endfor %} </tbody> </table> </div> </div> <div class="row"> <div class="form-group col-md-4"> <label for="birthdaytime">Grade :</label> <select class="form-control" style="appearance: none; font-size: 18px; font-weight: 500;" id="grade" name="grade"> <option>{{user.studying_grade}}</option> </select> </div> <div class="form-group col-md-4"> <label for="birthdaytime">Subject :</label> <select class="form-control" style="appearance: none; font-size: 18px; font-weight: 500;" id="subject" name="subject"> <option>{{user.assigned_subject}}</option> </select> </div> <div class="form-group col-md-4"> </div> <button … -
Django render django-tag from html
Does anyone know if you can have a django tag, like {{ val }} render another tag within it? Something like: {{ val }} where val="{% static 'path/to/file' %}" and have that render the static file? The reason why i am asking is because i am trying to write easy pages with markdown and have a django app template render them for me with {{ val | markdown | safe }} now everything was fine locally because i was using relative paths for image links, however in production these all broke because they were not using {% static %}. So my goal is to try to swap the markdown links with the proper django static tags but i realize that django does not render a nested tag (or at least i was not able to find a way for it to do it). I am open to suggestions if there is an alternative better way as well since i've been at this for a few days! Thanks for the help in advance. -
Docker Postgresql Django Error - django.db.utils.OperationalError: could not translate host name "db" to address: Temporary failure in name resolution
I have been trying to deploy a docker django postgresql application. docker-compose.prod.yml ... services: web: build: context: . dockerfile: Dockerfile.prod restart: always container_name: web command: gunicorn django_app.wsgi:application --bind 0.0.0.0:80 volumes: - static_volume:/static - media_volume:/media expose: - 80 env_file: - ./.env.prod depends_on: - db db: image: postgres:13.4-alpine container_name: db volumes: - postgres_data:/var/lib/postgresql/data/ env_file: - ./.env.db ... .env.db POSTGRES_USER=user1 POSTGRES_PASSWORD=password1 POSTGRES_DB=prod_db .env.prod ... SQL_ENGINE=django.db.backends.postgresql SQL_DATABASE=prod_db SQL_USER=user1 SQL_PASSWORD=password1 SQL_HOST=db SQL_PORT=5432 DATABASE=postgres ... settings.py ... DATABASES = { 'default': { "ENGINE": os.environ.get("SQL_ENGINE", "django.db.backends.sqlite3"), "NAME": os.environ.get("SQL_DATABASE", os.path.join(BASE_DIR, "db.sqlite3")), "USER": os.environ.get("SQL_USER", "user"), "PASSWORD": os.environ.get("SQL_PASSWORD", "password"), "HOST": os.environ.get("SQL_HOST", "localhost"), "PORT": os.environ.get("SQL_PORT", "5432") } } ... Full error message web | File "/usr/local/lib/python3.8/site-packages/psycopg2/__init__.py", line 122, in connect web | conn = _connect(dsn, connection_factory=connection_factory, **kwasync) web | django.db.utils.OperationalError: could not translate host name "db" to address: Temporary failure in name resolution Resolution attempts: testing with different postgresql image versions. setting POSTGRES_HOST_AUTH_METHOD to password and trust without success. changing password and username many times changing db name adding 'restart: always' to 'web' in docker-compose Do you have any idea whats required to resolve this error? If you require further details on my docker codebase to resolve this please let me know. Thanks -
What are the best plugins for django-cms in 2020?
After following the tutorial and building some pages I noticed that it doesn't compare for example to Elementor in Wordpress. I don't want to use Wordpress or PHP and I want to stick to learning python. What good plugins do you guys recommend? These is what my settings installed apps looks like at the moment: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'cms', 'menus', 'treebeard', 'djangocms_admin_style', 'sekizai', 'filer', 'easy_thumbnails', 'mptt', 'djangocms_text_ckeditor', 'djangocms_link', 'djangocms_file', 'djangocms_picture', 'djangocms_video', 'djangocms_googlemap', 'djangocms_snippet', 'djangocms_style', ] -
Check if a field is left empty - Django
Is there a way in Django to detect if a field is empty, and by this I mean detect if a field is left empty for every entry of a model submitted? -
Automatic ID Field Returning 'None' in Django
Hi I'm a beginner in Django trying to create a program that will save a model with some input. (Eventually I'll be using a form for that input but the request.POST would contains things I want to send to multiple different places so I can't just use a ModelForm) This is the code for the model: class Bid(models.Model): bid_owner = models.ForeignKey(User, on_delete=models.CASCADE, related_name="owner") bid_value = models.DecimalField(max_digits=6, decimal_places=2) bid_no = models.IntegerField(default=0, null = True, blank=True) bid_open = models.BooleanField(default=True, null = True, blank=True) bid_winner = models.ForeignKey(User, blank=True, default="None", null=True, on_delete=models.CASCADE, related_name="winner") def __str__(self): return f"My ID is {self.id} and this is {self.bid_owner}'s listing" and this is the code I'm calling in views.py: def bar(request): foo = Bid(bid_owner = request.user, bid_value = 25) foo.save() But it keeps bringing up the error " Field 'id' expected a number but got None". From the documentation I've seen the contents of the id field should automatically generate during saving so I'm at a loss on how to solve this. In rendering an HttpResponse showing the contents of 'foo' everything seems to be working except for the id. -
Right way to create nested objects and custom create method
If I use create method redefinition, which type of create objects should I use? Model.objects.create(...) or super.create(...). Both works as expected. What is best practice? Sry for stupid wording of the question. def create(self, validated_data): nested_data = validated_data.pop('nesteds', None) # THIS ONE instance = MODEL.objects.create(**validated_data) # OR THIS instance = super().create(validated_data) -
Error Submitting a form in Django - django.db.utils.IntegrityError: NOT NULL constraint failed: account_deal.company_id
I'm working on a form that takes value from another model, and everything is loaded correctly, but when I submit the data the form is showing the following error: django.db.utils.IntegrityError: NOT NULL constraint failed: account_deal.company_id The consensus is that you have to add blank=True,null=True but that only prevents the error if the user doesn't type any data, in this case, I'm using an auto-generated date, so not sure why am I getting this error. views.py def close_lead(request): if request.method == 'POST': deal_form = DealForm(request.POST) if deal_form.is_valid(): deal_form.save() messages.success(request, 'You have successfully updated the status from open to Close') id = request.GET.get('project_id', '') obj = Leads.objects.get(project_id=id) obj.status = "Closed" obj.save(update_fields=['status']) return HttpResponseRedirect(reverse('dashboard')) else: messages.error(request, 'Error updating your Form') else: id = request.GET.get('project_id', '') obj = get_object_or_404(Leads, project_id=id) m = obj.__dict__ keys = Leads.objects.get(project_id=m['project_id']) form_dict = {'project_id':keys.project_id, 'agent':keys.agent, 'client':keys.point_of_contact, 'company':keys.company, 'service':keys.services } form = NewDealForm(request.POST or None,initial = form_dict) return render(request, "account/close_lead.html", {'form':form}) models.py from django.db import models from django.conf import settings from django_countries.fields import CountryField from phone_field import PhoneField from djmoney.models.fields import MoneyField from ckeditor.fields import RichTextField from django.utils import timezone class Profile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) email = models.EmailField(blank=True,null=True, unique=True) role = models.TextField(blank=True) location = models.TextField(blank=True) photo = models.ImageField(upload_to='users/%Y/%m/%d', blank=True) … -
How to handle three functions with celery in django?
I'm having a three function in my django site views but I can only run one. I have never used celery, can you help me to transform this into the celery tasks? As you can see, I want to save document which is uploaded by user, and then I want to do some pandas stuff with that file, and after that I want to show pandas stuff in html page. This is forms.py class DocumentForm(forms.Form): docfile = forms.FileField(label='Select a file') This is views.py def save_exls(request): if request.method == 'POST': form = DocumentForm(request.POST, request.FILES) if form.is_valid(): newdoc = Document(docfile=request.FILES['docfile']) newdoc.save() return redirect('html_exls') else: form = DocumentForm() documents = Document.objects.all() context = {'documents': documents, 'form': form,} return render(request, 'list.html', context) def pandas_exls(request): if request.method == "POST": form = DocumentForm(request.POST, request.FILES) if form.is_valid(): output = io.BytesIO() newdoc = request.FILES['docfile'] dfs = pd.read_excel(newdoc, sheet_name=None, index_col=[0]) writer = pd.ExcelWriter(output) for name, df in dfs.items(): #pandas stuff done.to_excel(writer, sheet_name=name) output.seek(0) response = HttpResponse( output, content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') response['Content-Disposition'] = 'attachment; filename=%s' % filename return response else: form = DocumentForm() return render(request, 'list.html', {'form': form}) def html_exls(request): if request.method == "POST": form = DocumentForm(request.POST, request.FILES) if form.is_valid(): output = io.BytesIO() newdoc = request.FILES['docfile'] dfs = pd.read_excel(newdoc, sheet_name=None, index_col=[0]) writer … -
I need it a proxy webserver
Good night, i'm sorry for my bad english, i'm from colombia, this happening is in my job i give a web server in python style PHProxy, i wait me understand, help me, please, is my code, for example, show the page google, how the page (https://www.proxysite.com/) and return a views in Django 3.2, i want a proxysite, Someone know i how to build?: from http.server import BaseHTTPRequestHandler, HTTPServer import time hostName = "localhost" serverPort = 8080 class MyServer(BaseHTTPRequestHandler): def do_GET(self): self.send_response(200) self.send_header("Content-type", "text/html") self.end_headers() self.wfile.write(bytes("<html><head><title>https://myorg.org</title></head>", "utf-8")) self.wfile.write(bytes("<p>Request: %s</p>" % self.path, "utf-8")) self.wfile.write(bytes("<body>", "utf-8")) self.wfile.write(bytes("<p>I need it return another pages.</p>", "utf-8")) self.wfile.write(bytes("</body></html>", "utf-8")) if __name__ == "__main__": webServer = HTTPServer((hostName, serverPort), MyServer) print("Server started http://%s:%s" % (hostName, serverPort)) try: webServer.serve_forever() except KeyboardInterrupt: pass webServer.server_close() print("Server stopped.") -
How Session App Public-Key-Based Auth Works? And How to Apply It on Django App?
I am looking to implement this method of authentication on Django application. How it's works? And how to implement it ? The commonly expected user experience of being able to recover an account using a username and password is not possible. Instead, users are prompted to write down their long-term private key (represented as a mnemonic seed, referred to within Session as a recovery phrase) upon account generation. A user can use this backup key to recover their account if their device is lost or destroyed, and the user’s contacts will be able to continue contacting that same user account, rather than having to re-initiate contact with a new key. https://getsession.org/faq -
How to set a proxy model for foreign key query set in Django?
I have two models Parent and Child: class Parent(models.Model): some_field = models.IntegerField() class Child(models.Model): objects = models.Manager() custom_objects = managers.CustomManager() parent = models.ForeignKey(Parent) And one proxy model for Child: class ProxyChild(Child): class Meta: proxy = True If i want to get children of parent using custom manager i can do this: children = parent.child_set(manager='custom_objects').all() How can i get children of parent using ProxyChild, i think about this but it's not working: children = parent.child_set(model=ProxyChild).all() I need to get the set exactly through parent.child_set because I need access to the parent fields through child without additional queries to the database. Using ProxyChild.objects.filter(parent=parent).select_related('parent') has two cons: It is heavier. If i want to use a proxy model for parent and then filter the children then Django set the original class of parent(not proxy), for example: class ProxyParent(Parent): class Meta: proxy = True parent = ProxyParent.objects.all().first() child = ProxyChild.objects.filter(parent=parent).select_related('parent').first() print(child.parent) child.parent will be instance of Parent class not ProxyParent -
Are there advantages to using IntegerChoices field in a Django model if it's not shown to users?
I'm using IntegerChoices in my Django (3.2) model. class AType(db.IntegerChoices): UNKNOWN = 0, 'Unknown' SOMETHING = 1, 'Something' ANOTHER_THING = 2, 'Another thing' A_THIRD_THING = 3, 'A third thing' class MyObject(models.Model): a_type = db.IntegerField(choices=AType.choices) (I've changed the choices to be more generic.) Every time I add a value to AType, it produces a DB migration, which I faithfully apply. a_type is strictly behind the scenes. Users never see it, so it's only in the admin UI, but I don't need it to be editable. So forms aren't really used. Is there any impact on the DB (e.g., constraints) of these migrations? Is there any other utility to having an IntegerChoices field, given that it's not displayed to a (non-staff) user, and not in a form? If there's no utility, I'm thinking of just changing MyObject.a_type to an IntegerField, and continuing to use AType everywhere, but not having all the migrations. -
How to upload multiple files in Django using Dropzone js?
Info: I want to upload multiple files using Dropzone js in Django project. I have two models. One for the Post and the other would be for the File. My files model would have a foreignkey to the Post model. About my Views.py when the user is filling out the form post he has to complete the Files form too for the post. Fine: When i submit the Ajax_file_uploads form instead of using Dropzone.js multiple selected files are attached with single Post instance. Problem: If i try to upload multiple files using Dropzone.js Multiple articles are created along with multiple files when I submit the form. Any help would be much appreciated! models.py class Post(models.Model): title = models.CharField(max_length=100, blank=True) content = models.TextField(blank=True) class FileAttach(models.Model): file = models.FileField(upload_to='uploads/') post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='file_attach', null=True) views.py def Ajax_file_uploads(request): if request.method == "POST": p_form = PostForm(request.POST or None) form = AttachForm(request.POST or None, request.FILES) if p_form.is_valid(): art = p_form.save(commit=False) art.user = request.user art.save() files = request.FILES.getlist('file') if form.is_valid(): for f in files: file_instance = FileAttach(file=f, post=art) file_instance.save() return JsonResponse({"error": False, "message": "Uploaded Successfully"}) else: return JsonResponse({"error": True, "errors": p_form.errors}) else: p_form = PostForm() form = AttachForm() return render(request, "upload/api.html", {"p_form": p_form, "form": form}) … -
How To Fix "127.0.0.1 redirected you too many times. ERR_TOO_MANY_REDIRECTS" Django Permission Issue
How To Fix Django 127.0.0.1 redirected you too many times. ERR_TOO_MANY_REDIRECTS in python Whenever I Login With Agent User. Where Agent Only Have Permissions to Access Leads Page and Agent Can't See Any other pages. But When I open /lead It Raise An Error 127.0.0.1 redirected you too many times. ERR_TOO_MANY_REDIRECTS. If I Login With An Organizer User. I Can Visit Leads Page. But If I Login With an Agent. There i can see on navbar leads page but if I click on It's Raise Error 127.0.0.1 redirected you too many times. ERR_TOO_MANY_REDIRECTS App Views.py Code: https://paste.pythondiscord.com/kifimifida.rb App Url.py Code: https://paste.pythondiscord.com/emewavafay.lua app models.py Code: https://paste.pythondiscord.com/upaloqaduh.py -
HTMX/Django: Why does hx-post="." post to the wrong endpoint?
I am trying to get a very basic CRUD example working via htmx and django by adding a simple note/comment to a bookmark. I do not know why my submit button is going to the wrong endpoint, and I am hoping you might share some light into this matter. I have attached some questions to the bottom of this question. Wrong: HTTP POST /notebook/ 405 [0.12, 127.0.0.1:50193] Wanted: HTTP POST /b/<int:pk>/add-note/ Urls: path('b/<int:pk>/add-note/', add_bookmark_note, name="add-bookmark-note") View: @login_required def add_bookmark_note(request, pk): if request.method == "POST": bookmark = get_object_or_404(Bookmark, pk) note = request.POST.get('bookmark_note') if note: old_note = Comment.objects.filter(user=request.user, bookmark=bookmark).first() if old_note: old_note.comment = note old_note.save() print("updated") else: Comment.objects.create(comment=note, user=request.user, bookmark_id=pk) print("created") return render(request, "bookmark/htmx/bookmark_form.html", context={ "form": CommentForm }) Form <div hx-target="this" hx-swap="outerHTML" class=""> <form method="POST"> {% csrf_token %} <textarea name="bookmark_note" class="form-control" id="floatingTextarea2" style="height: 100px">{% if bookmark.comment_set.all.0.comment %}{{ bookmark.comment_set.all.0.comment }}{% endif %}</textarea> <label class="form-text" for="floatingTextarea2">{% trans "Write some notes" %}</label> <button type="submit" hx-post=".">Submit</button> </form> </div> Template <div class="card"> <div class="card-body"> <div hx-target="this"> <p>{{ bookmark.comments|linebreaks }}</p> <button hx-get="{% url 'add-bookmark-note' bookmark.id %}" hx-swap="outerHTML">Add note</button> </div> </div> </div> Questions: Why is hx-post pointing to the wrong endpoint? Why am I getting a NoReverseMatch if I use the url name: <button type="submit" hx-post="{% url 'add-bookmark-note' bookmark.id … -
Is it possible to pass a celery task as parameter in a dango view?
I would like to know if it is possible to pass a celery task as a function in a django (function based) view? -
how to capture image from webcam - django
i'm trying to access webcam and take picture and redirect the picture to my image field (to save into database - postgresql) this is my views.py @login_required def add_new_image(request,id): obj = get_object_or_404(Booking,id=id) if request.method == 'POST': images = UploadDocumentFormSet(request.POST,request.FILES) if images.is_valid(): for img in images: if img.is_valid() and img.cleaned_data !={}: img_post = img.save(commit=False) img_post.booking = obj img_post.save() return redirect(reverse_lazy("booking:add_booking",kwargs={"room_no":obj.room_no.room_no})) else: messages.error(request,_('take a picture or choose an image')) images = UploadDocumentFormSet(queryset=Document.objects.none()) return render(request,'booking/add_img.html',{'obj':obj,'images':images}) my models.py class Document(models.Model): booking =models.ForeignKey(Booking,on_delete=models.PROTECT) docs = models.ImageField(upload_to=upload_docs) def __str__(self): return str(self.booking.id) my forms.py class UploadDocumentsForm(forms.ModelForm): class Meta: model = Document fields = ['docs'] and this is my html + js const player = document.getElementById('player'); const canvas = document.getElementById('canvas'); const context = canvas.getContext('2d'); const captureButton = document.getElementById('capture'); const constraints = { video: true, }; captureButton.addEventListener('click', () => { // Draw the video frame to the canvas. context.drawImage(player, 0, 0, canvas.width, canvas.height); }); // Attach the video stream to the video element and autoplay. navigator.mediaDevices.getUserMedia(constraints) .then((stream) => { player.srcObject = stream; }); <form action="" method="POST" enctype="multipart/form-data" dir="ltr">{% csrf_token %} {% for form in images.forms %} {{form.id}} {{form.errors}} <div id="main_form" class="text-lg"> </div> <hr> {{images.management_form}} <div class="form-group mt-3" id="images"> {{ form.docs | add_class:'form-control-file' }} </div> <video id="player" controls autoplay></video> <button …