Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
request.user.is_authenticated cycling between True and False when logged in Django
I made a middleware that returns 403 Forbidden if the user is not authenticated but after logging in, each time I refresh the page I am logged in then logged out and so on. This is only happening in production on Ubuntu DigitalOcean droplet running Gunicorn and Nginx. middleware.py from django.shortcuts import render def IsAuthMiddleware(get_response): def middleware(request): if (request.path.startswith('/dashboard') or 'account' in request.path) and not request.user.is_authenticated(): context = { "title": "Not logged in", "message": "- You are not logged in." } return render(request, '403.html', context) response = get_response(request) if response.status_code == 403: res = render(request, '403.html', {'message': response.content.decode()}) res.status_code = 403 return res if response.status_code == 404: res = render(request, '404.html', {'message': response.content.decode()}) res.status_code = 404 return res return response return middleware views.py from django.shortcuts import render from .models import Message from dashboard.models import Subscriber, Newsletter, Unsubscription from django.core.exceptions import ObjectDoesNotExist, ValidationError from django.db.utils import IntegrityError from django.http import HttpResponseNotFound from django.core.validators import validate_email from django.views.decorators.csrf import csrf_exempt from django.utils import timezone # Create your views here. def index(request): context = { "title": "Home", } return render(request, 'main/index.html', context) def privacy(request): return render(request, 'main/privacy.html') def contact(request): if request.method == "POST": context = { "title": "Contact", "msg": True, "good": True, "msg_content": … -
Is there a way to register "Comments" model (filtered by post) inside "Posts/SomePost in Django administration?
I'm trying to to make each post (inside admin) have a "Comments" like field that are specific to that post instead of having "Comments" as a separate section from "Posts". Is this possible? -
Cannot Login to Django admin with my superuser account when it is on Deployment, showing CSRF error 403 forbidden
I am super newbie on DJango and Programming. I made a backend server with django and deployed successfully on "render.com". I can approach to admin login screen but cannot login to it with my superuser ID. [it worked in runserver perfect but does not work on deployment... showing error below :-( ] Forbidden (403) CSRF verification failed. Request aborted. You are seeing this message because this site requires a CSRF cookie when submitting forms. This cookie is required for security reasons, to ensure that your browser is not being hijacked by third parties. If you have configured your browser to disable cookies, please re-enable them, at least for this site, or for 'same-origin' requests. I googled some articles about it. and they told me that I have to add CSRF_TRUSTED_ORIGINS= ["mydomain"] on settings.py Here is the questions... Q1. Do I have to put my frontend domain or backend domain in "mydomain" ? Q2. Some articles said that I have to add CSRF_COOKIE_SECURE = False in my settings.py too?? -
How do I pass an IP address to Google geolocation api?
I have a Django web app that deploys on Heroku, so I'm trying to get the actual user's IP, not the heroku server. Everything works fine when I run the project locally. When I deploy it to Heroku, it gives me the Heroku server location, even though I get the correct IP from x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR'). Am I passing it incorrectly to google? def get_latitude_longitude(request): # Get the user's IP address x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR') if x_forwarded_for: ip_address = x_forwarded_for else: ip_address = request.META.get('REMOTE_ADDR') url = f"https://www.googleapis.com/geolocation/v1/geolocate?key={settings.GOOGLE_API_KEY}&considerIp=true&ipAddress={ip_address}" # Make the request response = requests.post(url) # Check the response status code if response.status_code != 200: print(response) # Parse the response data data = response.json() latitude = data['location']['lat'] longitude = data['location']['lng'] accuracy = data['accuracy'] return latitude, longitude, data, ip_address -
querying database to give specific need in Class Base View doesn't work
I created a school database to store student informations, as a school database that can be used in different schools, when user try to create Primary model, it shown every Album that is created by other schools, instead of showing an Album that is created by a particular school. I don't want others school to be able see all the Album that isn't their own. Here is how I did it, but doesn't work: Class CreatePrimary(CreateView): Model = Primary Fields = ['profilePicture', 'first_name', 'last_name', 'year_of_graduation'] template_name = 'create_primary.html' success_url = ('Home') #trying to use "filter", but it doesn't work def get_queryset(self): return Album.objects.filter(user=self.request.user) def form_valid(self, form): form.instance.user = self.request.user return super (CreatePrimary, self).form_valid(form) Class Album(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) name = models.charfield(max_length=20) Class Primary(models.Model): profilePicture = models.FilesField(upload_to='image') first_name = models.charfield(max_length=20) last_name = models.charfield(max_length=20) year_of_graduation = models.Foreignkey(Album, on_delete=models.CASCADE) '''' -
It's difficult to say exactly what might be causing the error
[28/Dec/2022 20:24:21] "GET /signup?csrfmiddlewaretoken=l9U4EZMDWweoh7ajcY9HpPrnURHlhdjQUSa0y70d3qaIqGPYwS17WcirJOpxVwEA&username=prashant_1rai&fname=PRA&lname=R&email=prash8%40gmail.com&pass1=1233&pass2=123 HTTP/1.1" 200 1482 it should have proceeded with return redirect('signin') -
Django Regroup with tables and boostrap collapsible menu
I am trying to mix regroup (within a table) with bootstrapp's collpasible menus. I have a long list of product with categories. I was hoping to list the categories and leave the option for the user to look at the product within them by simply clicking on the category title. Example: How the data looks Category 1 Prod1 Prod2 Prod3 Category 2 Prod1 Prod2 Prod3 How I want it to look on the front end Category 1 Prod1 Prod2 Prod3 Category 2 My logic I thought if I was to input data-target="#category" in the grouper(category - first row) and then wrap the list of products within the category in <div id="category" class="collapse">, this should do the trick. For some reason the table seem to impact the way how regroup works. Any advice on how to user django regroup in a table, using boostrap collapsible menus? (I did find an alternative using JQuery (Django roll-up (collapsible) menu), but ideally would like to find out why this is not working) template {% regroup categories by category_menu as category_menu_list %} {% for category_menu in category_menu_list %} <table class="table"> <tr> <th></th> <th> <a class="button-account btn-block mybtn tx-tfm" data-toggle="collapse" data-target="#category">{{category_menu.grouper}}</a> </th> </tr> <div id="category" class="collapse"> … -
Wagtail permission for different user pass
in my wagtail app, I have a model that I want to only allow certain types of users to view that model. In django I would just inherit UserPassesTestMixin. In wagtail, I will allow it based on a session data. If request.session.dados_usuarios.bu == 'Corporate KO', he will be able to view the page. I'm new to wagtail, is it possible to do this? In django I would do it like this class SomeView(UserPassesTestMixin, TemplateView): ... def test_func(self): return request.session.dados_usuario.bu == 'Corporate KO' My model in wagtail app class IframePage(Page): iframe_url = models.URLField() fabricantes_com_acesso = ParentalManyToManyField( Fabricante, blank=True, verbose_name="Fabricas com Acesso" ) content_panels = Page.content_panels + [ MultiFieldPanel([ FieldPanel('iframe_url'), FieldPanel('fabricantes_com_acesso'), ], heading="Informações Principais"), ] -
Why does the number of bytes in this buffer change from the original size when dealing with images?
So i'm looking at some image resizing code in our code base, and i've noticed that after passing an image through PIL the number of bytes of the image increases by just under 2x. I've gutted most of the code out for the purpose of this demonstration just so I could isolate the case: import io from PIL import Image from django.core.files.base import ContentFile def size_test(content_file: ContentFile): with content_file.open("rb") as file: file_bytes = file.read() print("original size of bytes: %s" % len(file_bytes)) image = Image.open(io.BytesIO(file_bytes), formats=["JPEG"]) with io.BytesIO() as buffer: image.save(buffer, format="JPEG") buffer_bytes = buffer.getvalue() print("new size of bytes: %s" % len(buffer_bytes)) Calling the above with the following code, loading in a JPEG file of known size: with open('10mb.jpg', 'rb') as file: cf = ContentFile(file.read()) utils.size_test(cf) Here is the output: original size of bytes: 10174706 new size of bytes: 19538695 Maybe i'm missing something glaringly obvious, but i'm not sure what makes this image's bytes increase by 9MB in memory, unless it's to do with JPEG compression? Maybe by loading the JPEG into memory we are uncompressing it? Just tried this with a 1.7MB PNG file (changing the relevant formats in the original function): def size_test(content_file: ContentFile): with content_file.open("rb") as file: … -
drf-spectacular: Automatic rendering of schema fields
Is there a setting that will automatically display field data? Used: Django==3.0.14 drf-spectacular==0.24.2 drf-spectacular-sidecar==2022.12.1 drf-spectacular settings SPECTACULAR_SETTINGS = { 'SERVE_INCLUDE_SCHEMA': False, # Permission 'SERVE_AUTHENTICATION': ['rest_framework.authentication.SessionAuthentication'], 'SERVE_PERMISSIONS': ['rest_framework.permissions.IsAuthenticated'], # UI settings 'SWAGGER_UI_DIST': 'SIDECAR', # shorthand to use the sidecar instead 'SWAGGER_UI_FAVICON_HREF': 'SIDECAR', 'REDOC_DIST': 'SIDECAR', 'SCHEMA_PATH_PREFIX_TRIM': True, } In the swagger, the data is reflected in this form: swagger UI Is it possible to automatically expand the information of these fields? Example like here: Correct answer -
(I am a newbie in django) can somebody tell me why is this happening
i have created a model in django :- from django.db import models # Create your models here. class items(models.Model): price = models.IntegerField(), name = models.TextField(max_length=100), category = models.CharField(max_length=100) and when i try to insert a data in admin page it is showing that only category field is created and i am only able to fill data in category how can i fix this also it is showing an extra s in table name items for no reason I am expecting that there should be 3 columns to fill data name, price and category but getting only one -
Use password hash created in GO on Django admin auth doesn't work
I'he created a func in GO to simulate the hash password construction in Django. But when i create the user and try to login in Django Admin, i receive invalid password message and the hash of password was changed in database. The function in go to recreate de pass hash builder is: func PasswordEncode(password string, salt string, iterations int) (string, error) { if strings.TrimSpace(salt) == "" { salt = CreateRandomString(12) } if strings.Contains(salt, "$") { return "", errors.New("salt contains dollar sign ($)") } if iterations <= 0 { iterations = 20000 } hash := pbkdf2.Key([]byte(password), []byte(salt), iterations, sha256.Size, sha256.New) b64Hash := base64.StdEncoding.EncodeToString(hash) return fmt.Sprintf("%s$%d$%s$%s", "pbkdf2_sha256", iterations, salt, b64Hash), nil } func CreateRandomString(len int) string { var container string var str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890" b := bytes.NewBufferString(str) length := b.Len() bigInt := big.NewInt(int64(length)) for i := 0; i < len; i++ { randomInt, _ := rand.Int(rand.Reader, bigInt) container += string(str[randomInt.Int64()]) } return container } So i have this hash to 'example' password : pbkdf2_sha256$20000$rkOZv4FYyskC$gIn13Rsr229e5AbhgYDTflBWOH9k+d6wEyKPmHryIjI= But when i try to login in Django admin, i receive the invalid password message and the application change de hash to: pbkdf2_sha256$390000$M3ntXZosTvxynIk193G107$40btNBSvVzDKXlS3pbrYfxpZV8lyjsTzG+fW/PL7wCY= Obs.: I'he already tryied to put 22 characteres on salt build func , and set … -
Django-Channels sending messages from external processes with auth
I'm using Django-channels 4 to build a simple chat website where users can join any random channel and start chatting. I have AuthMiddleWare in asgi.py application = ProtocolTypeRouter( { "http": django_asgi_app, "websocket": AllowedHostsOriginValidator( AuthMiddlewareStack(URLRouter(client.routing.websocket_urlpatterns)) ), } ) Now, only logged in users can establish WS connection since its using cookie. BUT now what if I want to send a message to any channel from outside of my django app?. Say that could be from a python script running in same machine using websockets lib. In this case i should have; A session within WS header of the external script which won't expire so the script can use it all day long and hence auth is handled smoothly Identify and allow this external script to send message to any channel. I have seen Channels Custom Authentication where we can add token via the WS header. But i really want to use the existing session auth comes out of the box BUT allowing my special client to connect to the WS with say some sort of special cookie which won't expire (if that method exists). Tried copying cookie from a logged in user's WS header and adding in my script does allow … -
Hot to add buttons (links) to Geonode Menu bar using geonode-project 4.1.x?
I just install Geonode-project 4.1.x and try to follow the official documentation (https://docs.geonode.org/en/4.x/devel/workshops/index.html#customize-the-look-and-feel) to customize the look and add some Links (buttons) to the navigarion bar. So far I have created the templatetags folder and create the "get_menu_json.py" file with the following content from django import template register = template.Library() @register.simple_tag(takes_context=True) def get_base_right_topbar_menu(context): #is_mobile = _is_mobile_device(context) #if is_mobile: # return [] return [ { "type": "link", "href": "/", "label": "Custom 3" }, { "type": "link", "href": "/", "label": "Custom 4" }, ] @register.simple_tag(takes_context=True) def get_base_left_topbar_menu(context): #is_mobile = _is_mobile_device(context) return [ { "type": "link", "href": "/", "label": "Custom 1" }, { "type": "link", "href": "/", "label": "Custom 2" }, ] I have also modified the settings.py to add the templatetags TEMPLATES[0]['OPTIONS']['libraries']={ 'my_template_tag_menu': 'templatetags.get_menu_json', } But this is not working. Geonode is still showing the same buttons (Dataset, Maps, etc). My intention is to add (I am saying add, not override) buttons to the Navigation Bar, so i can access the new views I have created for geonode project. I am using geonode-project 4.1.x. Documentations appears to be outdated. -
What is the best way to sort a Django queryset by group?
I have the following model for events: class EventStatus(models.TextChoices): Open = "Open" Closed = "Closed" Completed = "Completed" Archived = "Archived" class Marketplace(models.Model): Creator = models.ForeignKey(User, on_delete=models.CASCADE) Speaking_Event_Name = models.CharField(max_length=100) Location = models.CharField(max_length=500, null=True) Topic = models.CharField(max_length=40) date = models.DateTimeField(default=timezone.now) Status = models.CharField(max_length=9, choices=EventStatus.choices, default=EventStatus.Open) def __str__(self): return self.Speaking_Event_Name def status(self): return EventStatus.Completed if timezone.now() > self.date else self.Status and I also have the following view function to show the list of events: def view_events(request): event_list = Marketplace.objects.filter(Creator=current_user) content = {'events': event_list} return render(request, 'view_events.html', content) I would like to know how to sort the events list in order by Status, where all the "Open" events are listed first, then "Closed" second, "Completed" third and "Archived" listed last. -
sending data from a "form action" to a views function in django
How are you community, I'm a little confused between my newbies and lack of knowledge, I'm working on a small project in Django and I'm also trying to send data from a form action in the html to another view function but I'm not understanding it well How does this work and on top of that I have to send several data not just one and it confuses me even more, I have the following HTML: {% extends "base.html" %} {% block content %} <main class="container"> <div class="row"> <div class="col-md-10 offset-md-1 mt-5"> <form action="/interface/" method="POST" class="card card-body"> <h1>Interface</h1> <h4>{{ error }}</h4> <select name="dv"> <option selected disabled="True">Select Device</option> {% for device in devicess %} <option>{{ device.id }} - {{ device.name }}</option> {% endfor %} </select> <br> {% csrf_token %} <br> <button type="submit" class="btn btn-primary">Send</button> </form> <br> {% for interface in interfaces %} <section class="card card-body"> <h2>{{interface.Interface}}</h2> {% if interface.Description == "" %} <p class="text-secondary">none description</p> {% else %} <P class="text-secondary">{{interface.Description}}</P> {% endif %} <form action= "{% url 'send_description' %}"method="POST"> {% csrf_token %} <input type="text" name="command" class="form-control" placeholder="Change description"> <br> <button type="submit" class="btn btn-primary align-content-lg-center">Send change</button> </form> <br> {% if interface.Status == "up" %} <p class="text-secondary">Interface State: 🟢 Free</p> {% else %} … -
Rename and resize django images on save
I'm currently trying to resize and rename my images on save The problem is that I would like to resize my images in order to make them square without stretching the images, and then change the name of the image to a random number. Currently I'm doing that inside my model : user = models.OneToOneField(User, on_delete=models.CASCADE) bio = models.TextField(null=True, blank=True) image = models.ImageField(default='/profile_pics/default.jpg', null=True, blank=True, upload_to='profile_pics') def __str__(self): return f'{self.user.username} Profile' def save(self, **kwargs): super().save() new_name = random.randint(1, 236325984) img = Image.open(self.image.path) if img.height > 300 or img.width > 300: output_size = (200, 200) img.thumbnail(output_size) if img.height < 299 or img.width < 299: output_size = (200, 200) img.thumbnail(output_size) img.save(self.image.path) I also tried to put in my save function : new_name = random.randint(1, 236325984) name = f'{new_name}.{img.format.lower()}' os.rename(self.image.path, os.path.join(os.path.dirname(self.image.path), name)) But that's not working and giving me an error : [WinError 32] -
AttributeError when building a custom users app in django
I am making a web tool with few apps in django. one of the apps is called "users" for which I made a custom app. I tried to create a superuser using the following command: python manage.py createsuperuser I was expecting the program to ask me for username, password, email and phone number but I was asked only for: username, password but I got the following error: Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/john/PycharmProjects/digital_products/venv/lib/python3.6/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/home/john/PycharmProjects/digital_products/venv/lib/python3.6/site-packages/django/core/management/__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/john/PycharmProjects/digital_products/venv/lib/python3.6/site-packages/django/core/management/base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "/home/john/PycharmProjects/digital_products/venv/lib/python3.6/site-packages/django/contrib/auth/management/commands/createsuperuser.py", line 79, in execute return super().execute(*args, **options) File "/home/john/PycharmProjects/digital_products/venv/lib/python3.6/site-packages/django/core/management/base.py", line 398, in execute output = self.handle(*args, **options) File "/home/john/PycharmProjects/digital_products/venv/lib/python3.6/site-packages/django/contrib/auth/management/commands/createsuperuser.py", line 189, in handle self.UserModel._default_manager.db_manager(database).create_superuser(**user_data) AttributeError: 'UserManager' object has no attribute 'create_superuser' here is the models.py for the users app: import random from django.db import models from django.utils.translation import ugettext_lazy as _ from django.core import validators from django.utils import timezone from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, BaseUserManager, send_mail class UserManager(BaseUserManager): use_in_migrations = True def _create_user(self, username, phone_number, email, password, is_staff, is_superuser, **extra_fields): now = timezone.now() if not username: raise ValueError('The given username … -
ValueError at /signup/ Cannot assign "<User: prosenjit>": "Referral.parent" must be a "Referral" instance
After reading a lot of answers similar to this problem I got a specific error in every single case. In the following, I have attached my mandatory code. Models.py import uuid import enum from django.db import models from django.utils import timezone, translation from django.conf import settings from django.core.validators import MinValueValidator, MaxValueValidator from django.contrib.auth import get_user_model from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation from django_numerators.models import NumeratorMixin from mptt.models import MPTTModel, TreeForeignKey, TreeManager _ = translation.gettext_lazy from .utils import generate_ref_code class Referral(NumeratorMixin, MPTTModel, models.Model): class Meta: verbose_name = _('Referral') verbose_name_plural = _('Referral') unique_together = ('parent', 'account') limit = 3 parent = TreeForeignKey( 'self', null=True, blank=True, on_delete=models.SET_NULL, related_name='downlines', verbose_name=_('Up Line')) account = models.OneToOneField( get_user_model(), on_delete=models.CASCADE, verbose_name=_('account')) balance = models.DecimalField( default=0, max_digits=15, decimal_places=2, editable=False, verbose_name=_("Balance")) created_at = models.DateTimeField( default=timezone.now, editable=False) code = models.CharField(max_length=12, blank=True) def __str__(self): return ( self.account.username if self.account.get_full_name() in ['', None] else self.account.get_full_name() ) def update_balance(self, balance): self.balance = balance self.save() def get_referral_limit(self): return getattr(settings, 'REFERRAL_DOWNLINE_LIMIT', None) or self.limit def get_uplines(self): return self.get_ancestors(include_self=False, ascending=True)[:self.get_referral_limit()] def save(self, *args, **kwargs): if self.code == "": code = generate_ref_code() self.code = code super().save(*args, **kwargs) utils.py import uuid import json from django.core.serializers.json import DjangoJSONEncoder from uuid import UUID import random def generate_ref_code(): code … -
Creating new SQLAlchemy project with possible future migration to Django in mind
I want to create a database with SQLAlchemy ORM. At this moment, no web server is needed, so this solution is ideal. However, it is likely, that in future, we will want to add some web server functionality (using Django). Are there any recommendations that I should do (when creating SQLAlchemy project) so that the possible migration to Django will be as easy as possible? (for example some naming conventions, using of multi column primary keys, and so on) I know that we can use Django with existing database, but my question is rather what are the steps I can do at the start of SQLAlchemy project to make the future transition easiest it can be. -
Django model: OperationalError: no such column: home_atliktas_darbas.bendrija_id, help fix, Django version 3.2
I am creating a model that is related to other one, meaning the model I am trying to create can't exist if the model its related to does not exist. now I am new to django (just a few months), but I have created models with the same concept and had no issues before, this is the first time this has happened and I have no idea what could be the cause this is the model its related to class Bendrija(models.Model): class Meta: verbose_name_plural = 'Bendrijos' name = models.CharField(max_length=254) address = models.CharField(max_length=254, null=True, blank=True) def __str__(self): return self.name and this is the model I want to create class Atliktas_Darbas(models.Model): class Meta: verbose_name_plural = 'Atlikti Darbai' bendrija = models.ForeignKey(Bendrija, on_delete=models.CASCADE, related_name="atliktas_darbas") pavadinimas = models.CharField(max_length=254) aprasymas = models.CharField(max_length=254, null=True, blank=True) preliminari_kaina = models.CharField(max_length=254) galutine_kaina = models.CharField(max_length=254, null=True, blank=True) atlikti_iki = models.DateField() darbas_atlikas = models.DateField(null=True, blank=True) pastabos = models.CharField(max_length=254, null=True, blank=True) def __str__(self): return self.pavadinimas first I thought I forgot to add "bendrija' (the model field) to list_display in admin.py and I was correct thinking that fixed it I thought I was done, but I was wrong, after that I tried a bunch of stuff, but nothing worked -
Popup window displayed wrongly
[tag: Hi All, I have added modal popup in my page. Popup was not coming correctly and unable to edit the popup screen as well. Pls see the attached image for more info I have a button, when user clicks it, it will show the popup <div class="mb-2 mb-sm-0"> <button type ="button" data-toggle="modal" data-target="#loginModal" class="btn px-4 btn-red mb-1"><i class="fa fa-upload"></i></button> </div> Modal code <!-- Login modal --> <div class="modal fade" id="loginModal" tabindex="-1" role="dialog" aria-labelledby="loginModalLabel" aria-hidden="true"> <div class="modal-dialog modal-dialog-centered" role="document" style="max-width: 360px;"> <div class="modal-content shadow border-none radius-2 px-3"> <div class="modal-header mt-n1 border-0 justify-content-center pos-rel"> <h3 class="modal-title text-white mt-n5 text-115" id="loginModalLabel"> Login to continue </h3> <button type="button" class="close position-br mb-n4" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">×</span> </button> </div> <div class="modal-body text-center py-0"> <h2 class="text-grey-d1 text-160"> <i class="fa fa-leaf text-success-m2 text-120 mr-1"></i> Test App </h2> <form autocomplete="off" class="form-row mt-45"> <div class="form-group col-12 mb-3"> <div class="d-flex align-items-center input-floating-label text-blue-m1 brc-blue-m2"> <input type="text" class="form-control pr-4 shadow-none radius-1" id="id-login-username" /> <i class="fa fa-user text-grey-m2 ml-n4"></i> <label class="floating-label text-grey-l1 text-95 ml-n3" for="id-login-username">Username</label> </div> </div> <div class="form-group col-12"> <div class="d-flex align-items-center input-floating-label text-blue-m1 brc-blue-m2"> <input type="password" class="form-control pr-4 shadow-none radius-1" id="id-login-password" /> <i class="fa fa-key text-grey-m2 ml-n4"></i> <label class="floating-label text-grey-l1 text-95 ml-n3" for="id-login-password">Password</label> </div> </div> <div class="form-group col-12"> <button type="button" … -
How to create a zip with multiple files from one folder and send it to the browser in modern Django
I was struggling with sending the downloadable Django zip with many files to browser, because many tutorials in the web are obsolete, like the one which was my inspiration to come up with what I will share with you: Django - Create A Zip of Multiple Files and Make It Downloadable -
'QueryDict' object has no attribute 'method'
So Im building a real estate website fro school. Im working on my CRUD functionality on the front end. When i try to post a new listing i get the error. 'QueryDict' object has no attribute 'method' I don't really know what the problem is. Any tips and i will be forever grateful. Also im new to this whole stack overflow thing, so please let me know if you need any more info from me. models.py from django.db import models from datetime import datetime from realtors.models import Realtor class Listing(models.Model): realtor = models.ForeignKey(Realtor, on_delete=models.DO_NOTHING) title = models.CharField(max_length=200) address = models.CharField(max_length=200) city = models.CharField(max_length=100) state = models.CharField(max_length=100) zipcode = models.CharField(max_length=20) description = models.TextField(blank=True) price = models.IntegerField() bedrooms = models.IntegerField() bathrooms = models.DecimalField(max_digits=2, decimal_places=1) garage = models.IntegerField(default=0) sqft = models.IntegerField() photo_main = models.ImageField(upload_to='photos/%Y/%m/%d/') photo_1 = models.ImageField(upload_to='photos/%Y/%m/%d/', blank=True) photo_2 = models.ImageField(upload_to='photos/%Y/%m/%d/', blank=True) photo_3 = models.ImageField(upload_to='photos/%Y/%m/%d/', blank=True) photo_4 = models.ImageField(upload_to='photos/%Y/%m/%d/', blank=True) photo_5 = models.ImageField(upload_to='photos/%Y/%m/%d/', blank=True) photo_6 = models.ImageField(upload_to='photos/%Y/%m/%d/', blank=True) is_published = models.BooleanField(default=True) list_date = models.DateTimeField(default=datetime.now, blank=True) def __str__(self): return self.title forms.py from django.forms import ModelForm from listings.models import Listing class listingForm(ModelForm): class Meta: model = Listing fields = '__all__' views.py def createListing(request): form = listingForm() if request.method == 'POST': form = createListing(request.POST) if form.is_valid(): … -
User' object has no attribute 'make_password'
what is the error with set_password /base/backends.py in authenticate from django.contrib.auth import get_user_model from django.contrib.auth.backends import ModelBackend class CaseInsensitiveModelBackend(ModelBackend): def authenticate(self,request,username=None,password=None,**Kwargs): UserModel=get_user_model() if username is None: username=Kwargs.get(UserModel.USERNAME_FIELD) try: case_insensitive_username_field='{}__iexact'.format(UserModel.USERNAME_FIELD) user = UserModel._default_manager.get(**{case_insensitive_username_field:username}) except UserModel.DoesNotExist: UserModel().set_paassword(password) else: if user.check_password(password) and self.user_can_authenticate(user): return user i try to put make_password but not working