Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django save image in zip
Client upload zip. Picture after decompression. I want to save the picture to the specified location. But my code cannot be saved to the specified location How to do? models.py def get_upload_path(instance, filename): return f'register/{instance.owner.job_number}/{filename}' class UserRegister(models.Model): owner = models.ForeignKey(UserProfile, on_delete=models.CASCADE) image = models.ImageField(upload_to=get_upload_path) class Meta: db_table = 'UserRegister' views class AddsUser(View): def get(self, request): data = { 'title': 'AddsUser' } return render(request, './User/adds_user.html', data) def post(self, request): zip_file = request.FILES.get('zip') date = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') dir_name = uuid.uuid4().hex zip_dir_path = f'./temp_zip/{dir_name}' with open(f'{zip_dir_path}.zip', 'wb') as files: for i in zip_file.chunks(): files.write(i) files.flush() os.mkdir(zip_dir_path) os.system(f'unzip {zip_dir_path}.zip -d {zip_dir_path}') for image_name in os.listdir(zip_dir_path): image_path = f"{zip_dir_path}/{image_name}" user_profile = UserProfile.objects.create(date=date) user_register = UserRegister.objects.create(owner_id=user_profile.id, image=image_path) return redirect(reverse('admin:adds_user')) This method will not store the picture in the location I specified. -
python-social-auth: Unable to keep logged in newly registered user after setting password
I am certain the problem derives from this statement: user.set_password(local_password) because when I omit it the pipeline ends with the user logged in as expected. Now, as others have pointed out, after using the set_password method django automatically finishes the session so to avoid that we may use update_session_auth_hash (request, user). The problem is that this does not work in the pipeline. I've also tried adding instead: user = authenticate(username=user, password=local_password) login(request, user) This also does not work. I also checked via print statements whether the user is authenticated, it happens to be in all 3 steps that I checked. Lastly, I also tried creating a new pipeline method and calling it afterwards. This one also did not work. @partial def login_users(strategy, request, user, *args, **kwargs): user = authenticate(username=user, password=strategy.session_get('local_password', None)) print(user.is_authenticated) request = strategy.request login(request, user) messages.success(request, "Welcome, you have successfully signed up") return In summary, and to avoid overflowing with data here, everything works as expected, but as soon as I save the password via user.set_password(local_password), the user is logged out and needs to click again on Linkedin to sign in. Otherwise, the behavior would be as expected, i.e. the data collected is saved and the home page … -
Search bar for Django MultipleChoiceField form
First of all sorry if my question is very simple, but i am a beginner in Django. I have a MultipleChoiceField form, containing many cities of US. I just want to add a search bar sto i can type some letter of the city and filter my results instead of scrolling.I also have another form in the same logic but with multiselct including categories. This is my form: from django import forms class CityForm(forms.Form): def __init__(self, *args, **kwargs): cities = kwargs.pop("City") super(CityForm, self).__init__(*args, **kwargs) self.fields["City"] = forms.ChoiceField(choices=cities, label='City name ', widget=forms.Select(attrs={'onchange': 'submit();'})) class CategoryForm(forms.Form): def __init__(self, *args, **kwargs): categories = kwargs.pop("Category") super(CategoryForm, self).__init__(*args, **kwargs) self.fields["Category"] = forms.MultipleChoiceField(choices=categories, label='Categories') I don't want to use modelChoice as i am begginger and it seems very complex This is my html template. <!DOCTYPE html> <html> <head> <title>Page Title</title> <style> body { background-color: white; text-align: center; color: black; font-family: Arial, Helvetica, sans-serif; } </style> </head> <body> <form action="" method="POST"> {% csrf_token %} {{ form.as_p }} </form> <p>Now select one or more categories you are interested in</p> <form action="" method="POST"> {% csrf_token %} {{ form2.as_p }} <input type="submit" value="Submit Category"> </form> </body> </html> Is there any simple way to add a seach bar? -
'EncryptedCharField' error while doing django/python upgrade
I am trying to upgrade my old django application (django 1.1, python 2.7) to latest django3.1 and python3. So created new virtual environment to do this and started installing related packages one by one, and then i encountered this issue: AttributeError: 'EncryptedCharField' object has no attribute 'keydir'. I have installed most of the packages including the crypto ones like cryptography, pycryptodome, encrypted_fields, python3_keyczar, but no luck. Any suggestions! -
how to show thumbnail images from a local url stored in session system in Django?
Django 3 + sorl-thumbnail 12.7.0 Hello! I'm using the session system to store various items like this: request.session['cart'][1] request.session['cart'][2] ... request.session['cart'][n] In every session unit i want to store a product.image.url and other fields of the product: request.session.setdefault('cart', {})[str(request.session['counter'])] = { 'producto': p.pk, 'talla': talla, 'cantidad': cantidad, 'producto_abstracto': p.producto_abstracto.pk, 'imagen': p.imagen_1.url, 'nombre': p.producto_abstracto.nombre_producto, 'marca': p.producto_abstracto.marca.marca, 'precio_venta':p.producto_abstracto.precio_venta, 'nombre_color':p.color_principal_id.nombre, 'color': p.color_principal_id.codigo, } (I can't use pickleserializer to store in session the complete object Product for security concerns). Then I want to show in a view the product.image as a thumbnail but here is the problem. It seems that sorl-thumbnail just work with image Objects but i just have the url. Then in template i try this: {% load thumbnail %} {% thumbnail '{{item.imagen}}' '300x300' as im %} <img class="im" style="width:100%;" src='{{ im.url }}'></img> {% endthumbnail %} As a result i have a 404 not found image with a route in cache like this: media/cache/31/a0/31a02cc7b19899a208a972a08e17fe12.jpg to a file that was not created. As a comment when i use thumnail with classic django objects and images stored it works so i think it is not a problem about media and static routes or memcached. What can i do to solve this problem and show … -
TypeError at /index/ expected str, bytes or os.PathLike object, not tuple
I have no idea about my template format. and this is my index method to do a render ''' def index(request): # return HttpResponse('hello') template = loader.get_template('index.html') context = { } return HttpResponse(template.render(context, request)) This is the trace back Environment: Request Method: GET Request URL: http://127.0.0.1:8000/index/ Django Version: 3.1.3 Python Version: 3.8.6 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'firstWEB'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "C:\Users\74007\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\74007\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\django\core\handlers\base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\74007\PycharmProjects\pythonProject1\firstWEB\views.py", line 11, in index template = loader.get_template('index.html') File "C:\Users\74007\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\django\template\loader.py", line 15, in get_template return engine.get_template(template_name) File "C:\Users\74007\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\django\template\backends\django.py", line 34, in get_template return Template(self.engine.get_template(template_name), self) File "C:\Users\74007\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\django\template\engine.py", line 143, in get_template template, origin = self.find_template(template_name) File "C:\Users\74007\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\django\template\engine.py", line 125, in find_template template = loader.get_template(name, skip=skip) File "C:\Users\74007\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\django\template\loaders\base.py", line 18, in get_template for origin in self.get_template_sources(template_name): File "C:\Users\74007\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\django\template\loaders\filesystem.py", line 36, in get_template_sources name = safe_join(template_dir, template_name) File "C:\Users\74007\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\django\utils_os.py", line 17, in safe_join final_path = abspath(join(base, *paths)) File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.8_3.8.1776.0_x64__qbz5n2kfra8p0\lib\ntpath.py", line 78, in join path = os.fspath(path) Exception Type: TypeError at /index/ Exception Value: expected str, bytes or os.PathLike object, not tuple And in the final … -
Django admin GenericForeignKey object_id lookup
I'm looking for great way of selecting object of selected content_type (component_type). Django serves the raw id field where the user can input an integer. Is there a way to make it look more like the django grappelli solution? Like an 3rd part app to install which modifies admin template and adds ONLY this one feature instead of full django admin template? Or there is a good-looking template which has this option (because grappelli looks so bad). Thanks in advance -
Django EditForm Unexpectedly Concatenating Fields
I have a weird scenario where my modal edit form is showing up odd.. The last two fields of mine are showing up concatenated to each other rather than on their respective lines... I feel like this could just be an issue with commas or seperators somewhere but maybe there's more to it. I guess maybe I've been staring at this too long. Any thoughts on what would cause this? views.py class UpdateCrudUser(View): def get(self, request): id1 = request.GET.get('id', None) employee1 = request.GET.get('employee', None) description1 = request.GET.get('description', None) stakeholder_group1 = request.GET.get('stakeholder_group', None) stakeholder_quadrant1 = request.GET.get('stakeholder_quadrant', None) obj = Stakeholder.objects.get(id=id1) obj.employee = employee1 obj.description = description1 obj.stakeholder_group = stakeholder_group1 obj.stakeholder_quadrant = stakeholder_quadrant1 obj.save() user = {'id':obj.id,'employee':obj.employee,'description':obj.description,'stakeholder_group':obj.stakeholder_group,'stakeholder_quadrant':obj.stakeholder_quadrant} data = { 'user': user } return JsonResponse(data) html: // Create Django Ajax Call $("form#updateUser").submit(function() { var idInput = $('input[name="formId"]').val().trim(); var employeeInput = $('input[name="formemployee"]').val().trim(); var descriptionInput = $('input[name="formdescription"]').val().trim(); var stakeholder_groupInput = $('input[name="formstakeholder_group"]').val().trim(); var stakeholder_quadrantInput = $('input[name="formstakeholder_quadrant"]').val().trim(); if (employeeInput && descriptionInput && stakeholder_groupInput && stakeholder_quadrantInput) { // Create Ajax Call $.ajax({ url: '{% url "polls:crud_ajax_update" %}', data: { 'id': idInput, 'employee': employeeInput, 'description': descriptionInput, 'stakeholder_group': stakeholder_groupInput, 'stakeholder_quandrant': stakeholder_quadrantInput }, dataType: 'json', success: function (data) { if (data.user) { updateToUserTabel(data.user); } } }); } else { alert("All … -
What is the role of using two dashes here __year in the example below ? im new in learning django
Get the question that was published this year. >>> from django.utils import timezone >>> current_year = timezone.now().year >>> Question.objects.get(pub_date__year=current_year) <Question: What's up?> -
django, class based views, DeleteView, redirect
massive noob here (worse than that, actually, I went to a bootcamp). About two days in now and I officially don't even know the terms I'm looking to google for. I have a collection of documents about a house. I'd like to organize them with aw django project. The categories for the documents are 'purchase', 'inspection' and 'rooms'. The category is selected with a dropdown on a form generated by the django CreateView (I uh, suspect that's what creates it?). If I delete a document, I want to be redirected to whatever URL I clicked the 'delete' button from. If the document was a 'room,' redirect me to the URL named 'rooms' (that's where I had to delete it from), same for the others. When the views have 'fields' it's straightforward as if/else. However, with DeleteView, there are no 'fields' and so I do not know (or, understand) what I'm looking to use to get the proper URL. How would one achieve said behavior? urls.py path('', index, name='home_index'), path('inspection/', DocsListView.as_view(template_name='inspection_list.html'), name='inspection'), path('inspection/<slug:slug>', DocDetailView.as_view()), path('purchase/', DocsListView.as_view(template_name='purchase_list.html'), name='purchase'), path('purchase/<slug:slug>', DocDetailView.as_view()), path('rooms/', DocsListView.as_view(template_name='rooms_list.html'), name='rooms'), path('rooms/<slug:slug>', DocDetailView.as_view()), path('homedoc-create/', DocCreateView.as_view(), name='doc_create'), path('homedoc-update/<slug:slug>', DocUpdateView.as_view(), name='doc_update'), path('confirm-delete/<slug:slug>', DocDeleteView.as_view(), name='doc_delete'), ] models.py class HomeDocs(models.Model): name = models.CharField(max_length=255) img … -
Show Bootstrap 5 Modal on Page Load with Django Messages
I've been playing around with Bootstrap 5 lately. I've got an idea that involves showing a modal on page load, but it's not working. In the developer tools console, I'm seeing this error: Uncaught ReferenceError: bootstrap is not defined Here's what I've got so far: List view template {% block head %} {{ block.super }} <script> var test_modal = new bootstrap.Modal( document.getElementById('notification') ); test_modal.show(); </script> {% endblock head %} . . . {% if messages %} <div class="modal" id="notification" tabindex="-1"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title">Modal title</h5> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <div class="modal-body"> {% for m in messages %}#} {{ m }} {% endfor %} </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-bs-dismiss="modal"> Ok </button> </div> </div> </div> </div> {% endif %} I know the block.super and messages are working as I've tested these bits independently of setting this up together. I've tried putting the if messages in the modal-body but this doesn't seem to help. I was thinking that maybe the JS was being called before the template could get access to the objects. All the SO posts about this type of thing are super old and use jQuery and button triggers, both of which … -
Breaking for/if loops in HTML within Django
I am using HTML Templates in Django and searching through a list of objects. If one of them exists, I want to print something out. However, once that is printed. I do not want to print any more, even if more exist. (i.e. if the condition is met on one of the objects I want to print out the same thing I would if the condition is met on 100 of the objects) Here's what I have so far: {% for object in objects %} {% if object.attr1 == true %} Placeholder {% endif %} {% endfor %} If object.attr1 is true for any of the objects I want to print placeholder. But I only want to do it once. Difficulties within Django models have made it so that using this type of for loop is one of my only solutions. Is this possible? -
Populate Django username field with generated username
I would like the user name field for my Django registration to populate with the following function - def generateUsername(): username = firstname[0] + middlename[0] + lastname[0] + randomStringDigits(6) + getDateTimeStr() return username I am currently using the UserCreationForm model from Django and would prefer to find away to integrate into this, however if the best option is to custom my own user model then I am happy to do this also. views.py - def register(request): if request.method == 'POST': form = UserRegisterForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') messages.success(request, f'Account created for {username}') return redirect('login') else: form = UserRegisterForm() return render(request, 'users/register.html', {'form': form}) forms.py - class UserRegisterForm(UserCreationForm): email = forms.EmailField() firstname = forms.CharField(max_length=20) middlename = forms.CharField(max_length=20) lastname = forms.CharField(max_length=20) class Meta: model = User fields = ['email', 'firstname', 'middlename', 'lastname'] -
How to locally host a Django project?
I am trying to run a Django website, and I want the ability for all devices that are connected to the same router as my computer to be able to access the website. I have looked in several places, and questions like this, or this. Both approaches didn't work. I can access the website from my computer, but not from my cellphone, for example. (Both connected to 'X' network) I really don't know what to do since I can't find another answer, possibly because I am not searching for the question correctly, but I would love it if anyone could help me. -
STATICFILES_DIRS error when trying to migrate tables - django heroku
I've been trying to get my project up on Heroku for almost 2 days now! Worked through a lot of problems but now I can't seem to migrate the new database due to an error with static files. All of my pages on website are live and working except one page, I was getting a 500 error. I turned debug on to see what was going on and it needs the new database to be migrated. I run the command heroku run python manage.py migrate but am getting the following error: SystemCheckError: System check identified some issues: ERRORS: ?: (staticfiles.E002) The STATICFILES_DIRS setting should not contain the STATIC_ROOT setting. Here is my relevant base-settings file: import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(os.path.join(__file__, os.pardir)))) STATIC_URL = '/static/' # STATICFILES_STORAGE = "whitenoise.storage.CompressedManifestStaticFilesStorage" STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] and my prod settings:import os from .base import * import dj_database_url DEBUG = True ADMINS = [ ('name', 'email') ] try: SECRET_KEY = os.getenv('SECRET_KEY') except: print("Error getting key") ALLOWED_HOSTS = ['*'] DATABASES = { 'default': { } } db_from_env = dj_database_url.config(conn_max_age=600) DATABASES['default'].update(db_from_env) STATIC_ROOT = os.path.join(BASE_DIR, 'static/') Any help would be greatly appreciated!! This has been a huge pain getting the website even able to deploy with … -
TypeError at /bokeh.html----join() argument must be str or bytes, not 'dict'
enter image description here bokeh.html view.py [2]: https://i.stack.imgur.com/XiEDm.png showing error -
Django Dynamic Settings
I am creating a portable Django server that will be used by different people on separate servers. Am I able to create dynamic settings for each user that they can change? For example Time Zone: instead of having TIME_ZONE = "America/New_York" in settings.py, can I have a settings page that allows them to update the configuration of the Django settings without them actually accessing the server? I also want to use this with Cors Headers for the CSRF_TRUSTED_ORIGINS = [] setting. Thank you. -
Need to know the required frameworks for project
I need to build a university portal website for my university project. In addition I also need to make a google chrome extension for taking auto attendance using webcam and also monitor browser traffics. This extension will be connected to the server. Right now I only know Django framework. Can someone please help me by telling which frameworks I need to learn to make this work. I've no experience. Thanks. -
Error when using encrypted SearchField as key for custom user model (Django): AttributeError: 'NoneType' object has no attribute '_meta'
I have followed this tutorial to customize the user model in my django app: https://testdriven.io/blog/django-custom-user-model/ The idea is to get rid of "username" and use "email" as the user key. I could follow the instructions and it worked allright, no problem. Apart from that, I need all my database fields to be encrypted (and, some of them, searchable). So I used this library: https://pypi.org/project/django-searchable-encrypted-fields/ And, also, no problem. I could encrypt my DB fields. The issue comes when I also try to encrypt my Django customUser's "email" field, by doing this: class CustomUser(AbstractBaseUser, PermissionsMixin): _email_data = fields.EncryptedCharField(max_length=100, blank=True) email = fields.SearchField(hash_key="94fd9321e57f061805...redacted...43d9485776dee73a", encrypted_field_name="_email_data", unique=True) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) date_joined = models.DateTimeField(default=timezone.now) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = CustomUserManager() def __str__(self): return self.email This breaks my user model. After doing this, when I try to create a superuser I get this error (after typing the email address): (base) C:\Users\jaume\Desktop\Projects\repos\whistleblower>python manage.py createsuperuser Email: admin@admin.com 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 "C:\ProgramData\Anaconda3\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\ProgramData\Anaconda3\lib\site-packages\django\core\management\__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\ProgramData\Anaconda3\lib\site-packages\django\core\management\base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "C:\ProgramData\Anaconda3\lib\site-packages\django\contrib\auth\management\commands\createsuperuser.py", line 79, … -
I have a problem hosting my django website on Cpanel Console
enter image description here i get this error in my Cpanel. its a django website -
code working on jupyter-notebooks but indexing error in django
df = pd.read_csv('balancesheet.csv') c = df['TotalAssets'].values[-1] This is the code not really complicated but throws TypeError: string indices must be integers in django, working ok on jupyter-notebooks and python env, is it a version related issue ? i'm using python 3.7.9 and Django 2.2.17 -
Only one page loads running Django with Nginx and uWSGI - "504 Gateway time-out"
I'm running Django with Nginx and uWSGI. When I load up my app, it all looks fine, but then none of the other pages load. For instance, I load up my login page, and then after entering my username and password, the page just sits there loading. Not even any error messages. After around 2 minutes, I get a "504 Gateway time-out" page. I've already ruled out any problems with my authentication system, because I can turn off "@login_required" and each page loads (But again, I can't access other pages after loading up the initial page). I've also tried restarting the Docker container, switching around the ports, and checking that Nginx and my database are running. I get the following output after I run sudo docker-compose -f docker-compose-deploy.yml up --build: Building app Step 1/19 : FROM python:3.8-alpine ---> 64df5e2068e3 Step 2/19 : ENV PATH="/scripts:${PATH}" ---> Using cache ---> e76b22f5b7da Step 3/19 : COPY ./requirements.txt /requirements.txt ---> Using cache ---> fb7943523b91 Step 4/19 : RUN apk add --update --no-cache --virtual .tmp gcc libc-dev linux-headers ---> Using cache ---> 5f8d10408c3a Step 5/19 : RUN pip install -r /requirements.txt ---> Using cache ---> c428d1ecd21c Step 6/19 : RUN apk del .tmp ---> Using … -
Amazon WS S3: I'm getting this error message: "The bucket you are attempting to access must be addressed using the specified endpoint."
how can I address the bucket using the correct endpoint? I'm using Django to create my app. -
what does hazard sign mean in sublime text?
I just write some codes in sublime text and when I try to save it some hazard sign appear beside the lines somebody knows what does it mean? -
Compare dates and times in Django
How to use comparative operators on date and time What is the problem in the example below? in models.py start_sale=models.DateTimeField(default=datetime.datetime(2018,5,3)) in views: time = datetime.datetime.now() in template: {% if course.start_sale|date < time.date and course.start_sale|time < time.time %} {% else %} {% endif %} this code dont show error but dont work dont compare datetime