Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Text editor summernote for admin panel Django loading very slowly
I have an Enterprise model and there are more than 60 fields in this model, Summernote-Django has been added to the text editor. In my case, 25 fields in one model have been added to the text editor by the Summernote-Django, the problem is that this model on the admin panel is very, very slow to load. How can I optimize Summernote-Django? I added 'lazy': True to the settings, but it didn't help.Perhaps you would recommend another library for adding text editors to the django administration more optimized? Here is a screenshot on the Enterprise page, on dev tools shows that more than 100 js/jQuery files are being uploaded from Summernote-Django -
Multiple templates in a single Listview
I have some ListViews implemented seperately with different template_names with similar model,How can i use implement them in one single List view that can take multiple templates? Views.py class ManagerOpenedTicketView(LoginRequiredMixin,TemplateView): template_name = 'app/pm_open_tickets.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['tickets'] = Ticket.objects.filter(status = 'Opened',created_by = self.request.user) return context class ManagerCompletedTicketView(LoginRequiredMixin,TemplateView): template_name = 'app/pm_completed_tickets.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['tickets'] = Ticket.objects.filter(status = 'Completed',created_by = self.request.user) return context -
What is the difference in using Django Rest API vs django.contrib.auth to build a login/logout app
I am new to Django and I want to build a login and logout for a chat app I am making which I plan to deploy eventually. From the online tutorials I see, there are some that use the Django Rest API framework, and some use the pre-installed django.contrib.auth Is there any difference in choosing which to use? -
Trying to stay DRY in Django: Refactoring repetitive code in Views
I have a lot of different list views for tables. Each view differs only in the template used. My only successful strategy involves using a decorator containing the common code and then returning 'pass' for the view function. The problem I face is if I want to add individual code to a specific list view that differs from the others. Is there a better way of doing this? Here is my decorator: def my_decorator(html=""): def my_decorator(*args, **kwargs): def wrapper(request, *args, **kwargs): bacteria = Bacteria.objects.all() bacteria_count = bacteria.count() bacteriaFilter = BacteriaFilter(request.GET, queryset=bacteria) bacteria = bacteriaFilter.qs remaining = bacteria.count() common_tags = Bacteria.tags.most_common()[:8] ''' context = {"bacteria": bacteria, 'common_tags': common_tags, 'bacteria_count': bacteria_count, 'bacteriaFilter': bacteriaFilter, 'remaining': remaining} ''' return render(request, html, locals()) return wrapper return my_decorator And here are several examples (I have over 15 tables) of the list view functions: @my_decorator(html="bacteria/generalPhysiology.html") def general_physiology_view(request): pass @my_decorator(html="bacteria/enzymeActiveTable.html") def enzyme_activity_table_view(request): pass -
Django autocomplete light Select2 widget not appearing
I have been following the DAL tutorial and can access a json object at http://127.0.0.1:8000/entry/river-autocomplete/?q=S So i know my view is working. Beyond that I cannot seem to get anything but the standard widget for ForignKey. From looking at the following posts in stackoverflow I feel that some static files or javascript libraries are not loading properly but for the life of me I cannot figure out how to fix this. django-autocomplete-light template not rendering autocomplete widget django-autocomplete-light displays empty dropdown in the form Below are all of the files that I think pertain to this issue. If I can clarify things any further please let me know. views.py #autocomplete view class RiverAutocomplete(autocomplete.Select2QuerySetView): def get_queryset(self): #User filtering code goes here if not self.request.user.is_authenticated: return River.objects.none() qs = River.objects.all() if self.q: qs = qs.filter(river_name__istartswith=self.q) return qs models.py class River(models.Model): river_name = models.CharField(max_length=50) aw_id = models.CharField(max_length=20) state = models.CharField(max_length=5) def __str__(self): return "{river}".format(river=self.river_name) class JournalEntry(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) date = models.DateField() river = models.ForeignKey("River", on_delete=models.CASCADE) flow = models.FloatField() description = models.TextField(max_length=250) public = models.BooleanField(default=False) # picture = models.ImageField() def __str__(self): return "{river}--{date}".format(river=self.river, date=self.date) forms.py from django import forms from . import models from .widgets import FengyuanChenDatePickerInput from dal import autocomplete class … -
How to disable access to a django APIs based on is_active boolean field?
I have an author's model with a field: is_active = models.BooleanField(default=False) I wish to restrict access to the author whose is_active=False. I can use something like this in every api: get_object_or_404(uuid=id, is_active=True) But I wish to globally restrict access to the UUID whose is_active=false, instead of actually writing this statement in every api. Is there a way I can do that? -
Django Rest Framework nested relationship performance on SerializerMethodField
I have been looking for an answer but get none. This is the situation: I have 3 models defined like this: class State(models.Model): name = models.CharField(max_length=150, null=False) code = models.CharField(max_length=5, null=False) class City(models.Model): name = models.CharField(max_length=150, null=False) code = models.CharField(max_length=7, null=False) state = models.ForeignKey(State, related_name='cities', on_delete=models.RESTRICT) class Home(models.Model): code = models.CharField(max_length=25, null=False city = models.ForeignKey(City, related_name='homes', on_delete=models.RESTRICT) The response that the people needs on homes is something like this [ { "code": "10011", "city": "Municipio 1", "state": "Departamento 1" }, { "code": "10012", "city": "Municipio 1", "state": "Departamento 1" } ] I was able to create that response doing this with the serializer: class HomeSerializer(serializers.ModelSerializer): city = SlugRelatedField(slug_field='name', queryset=City.objects.all()) state = SerializerMethodField() class Meta: model = Home fields = ['code', 'city', 'state'] def get_state(self, obj): return obj.city.state.nombre But Im not sure if this is the right way to do it, home is a table that is gonna grow up a lot (maybe 1M+ rows), and I am thinking that this solution is gonna hit the database multiple times. Now I know that I can add filtering and pagination, but I am concern about the performance of this solution. I also tried with depth = 2 but they hated it. I've … -
How to change the renaming pattern when there are duplicate files
Let's say I upload a file to my Django App (A.pdf) Over time I realize that that file contains an error. I want to upload that file back to my website and keep the old file, but I want the file name to change to A(1).pdf I implemented a drag & drop system with Dropzone.js and everything is working but, when a file is duplicated the system assigns new names randomly. This is an example: How can I get rid of the _QXjmarl string and replace it with (N) pattern? E.g. (1), (2), (3)...(45), (N) Dropzone.js: var Drop = Dropzone.options.DidDropzone = { autoProcessQueue: false, //stops from uploading files until user submits form paramName: "filename", // The name that will be used to transfer the file maxFilesize: 1024, // Maximum size of file that you will allow (MB) clickable: true, // This allows the dropzone to select images onclick acceptedFiles: '.psd, .csv, .doc, .docx, .xls, .xlsx, application/csv, application/docx, application/excel, application/msword, application/pdf,application/vnd.ms-excel, application/vnd.msexcel, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, text/anytext, text/comma-separated-values, text/csv, text/plain, image/*, video/*,', //accepted file types maxFiles: 20, //Maximum number of files/images in dropzone parallelUploads: 20, previewTemplate: '<div class="dz-preview dz-image-preview">'+ '<div class="dz-image">'+ '<img data-dz-thumbnail />'+ '</div>'+ '<div class="dz-details">'+ '<div class="dz-filename"><span data-dz-name></span></div>'+ '<div class="dz-size" data-dz-size></div>'+ '</div>'+ … -
On adding a Model using the Admin Panel in Django, is there a way to implement altering other Models?
I am using the standard Admin Panel in Django that has a Model, Product, that contains its information. the Product has a TextField() Summary of words. I would like to implement a Keyword model that has a single word. The idea is that the Keyword would be applied to multiple Products if the Product has the Keyword's word in its Summary. I am trying to implement that when the Admin in the Admin panel adds a Keyword model, the server would automatically assign each Product that Keyword. The issue is that I do not know how to edit the Admin Panel's add function to edit other models upon adding one model. My current understanding in Django is that you could create a custom view to add a Keyword, but I would like to have the option to implement it in the Django Admin Panel as well. -
Using manytomany field as foreignkey in the other class under model in Django
Models.py Here I am trying to use the attribute: working_hours which is manytomany - as a foreignkey in other model please help me sort the concern if possible class AvailableTime (models.Model): available_time = models.CharField(max_length=100) def __str__(self): return str(self.available_time) class AttendantAvailability(models.Model): attendant_name_choices=[('AN1',"Ipsum Lorem"), ('AN2',"Lorem Lorem"),] attendant_name = models.CharField(max_length=3, choices=attendant_name_choices) def attendant_name_lookup(self): for choice in self.attendant_name_choices: if choice[0] == self.attendant_name: return choice[1] return '' booked_date = models.DateField(null=True, blank=True) working_hours = models.ManyToManyField(AvailableTime) def __str__(self): return str(self.working_hours) class ServiceDetail(models.Model): name = models.ForeignKey(ServiceName, null=True, on_delete=models.CASCADE,) category_name = models.ForeignKey(Category, default = None,on_delete=models.CASCADE,) preferred_time = models.ForeignKey(AttendantAvailability) def __str__(self): return str(self.preferred_time) This isn't working for me !! I need to use the Manytomany field "working_hours " as the foreignkey in other class ERROR: self.models_module = import_module(models_module_name) File "C:\Users\User\AppData\Local\Programs\Python\Python39\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 680, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 850, in exec_module File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "C:\Users\User\Service_Management\Salon_Services\models.py", line 45, in <module> class ServiceDetail(models.Model): File "C:\Users\User\Service_Management\Salon_Services\models.py", line 122, in ServiceDetail preferred_time = models.ForeignKey(AttendantAvailability) NameError: name 'AttendantAvailability' is not defined Please help! -
trouble with Django Channels and connecting with Flutter
Problem: When trying to connect to channels, I get an error in flutter: WebSocketChannelException: WebSocketException: Connection to 'http://"###my ip ###":8000/ws/joingroup/8598969d-3dfa-4017-849c-dcbb71c1f9f0/#' was not upgraded to websocket I am using the websocket channel package and in a flutter controller I have: WebSocketChannel? channel; //initialize a websocket channel bool isWebsocketRunning = false; void startStream() async { if (isWebsocketRunning) return; //check if socket running var url = 'ws://${ip}:8000/ws/joingroup/${Get.parameters['groupid']}/'; this.channel = WebSocketChannel.connect( Uri.parse(url), //connect to a websocket ); channel!.stream.listen( (event) { print(json.decode(event)); }, onDone: () { isWebsocketRunning = false; }, onError: (error) { debugPrint('ws error $error'); } ); } question 1) why does it say 'http://..." when I clearly outlined it as a ws url. in the back end I am using django channels. app routing:: from django.urls import re_path from django.urls import path #this is utilizing relative paths. this is more advanced paths. # from . import consumers websocket_urlpatterns = [ path('ws/joingroup/<slug:groupid>/', consumers.ChatConsumer ) ] and routing for project: # mysite/routing.py from channels.auth import AuthMiddlewareStack #hooking into auth that django provides^ from channels.routing import ProtocolTypeRouter, URLRouter from channels.security.websocket import AllowedHostsOriginValidator import myapp.routing from django.core.asgi import get_asgi_application # the allowedhosts is for what ever is in your allowehost in setting.py application = ProtocolTypeRouter({ # (http->django … -
Timestamps are added to the model with a different timezone
I am aware that thousands of similar questions have been asked on SO, but after researching a few hours I did not find any solution that worked. I am using Django 3.2.8 I have checked many StackOverflow questions and answers, none have worked for me. For example this one I also checked the official docs like ten times. Here is my models.py: from django.db import models from django.contrib.auth.models import User class FileHistory(models.Model): filename = models.FileField(null=True, blank=True, upload_to="project_files/") user = models.ForeignKey( User, null=True, blank=True, on_delete=models.SET_NULL, ) timestamp = models.DateTimeField(auto_now_add=True, blank=True) And my settings.py (truncated), following the suggested configuration (L10N false and Time_Zone changed to 'Asia/Tokyo': TIME_ZONE = 'Asia/Tokyo' USE_I18N = True USE_L10N = False USE_TZ = True -
Django: timezone conversion inside templates
I am attempting to convert UTC dates to my users timezones. All dates are stored in the database as UTC and each users timezone is also stored (captured when they signed up). The problem is, when I use timezone.activate(user_timezone) to try and convert the dates to the users timezone in my templates using the {% timezone on %} template tag, it keeps returning the same UTC date. I have tried every settings configuration possible but the problem continues. views.py from dateutil.relativedelta import relativedelta import def home(request): if request.method == 'GET': #users stored timezone e.g 'america/chicago' users_tz = reqeuest.user.timezone #activate users timezone timezone.activate(request.user.timezone) return render(request, 'home.html') home.html {% load tz %} ... {% localtime on %} <div style="float: right;"><b>Registered: </b> {{ user.registered_date }}</div> {% endlocaltime %} settings.py ... USE_I18N = True USE_L10N = True TIME_ZONE = 'UTC' -
encrypt and decrypt image using javascript
My server using this python function to encrypt and decrypt images. I want to do the same encryption in the frontend and send to this function in the backend. how to convert this method into JavaScript def encrypted_decrypted_image(image): key = 48 count = 0 for index, value in enumerate(image): count += 1 image[index] = value ^ key if count == 10: break return image -
How to use HTMLCalendar
I'm using Django, and I'm using the HTMLCalendar module to print a calendar on a page. Currently, the code below works fine, but when the date between 'from date' and 'to date' is more than 2days, I want to express it in one line instead of adding an event to each date belonging to the period. No matter how hard I searched, I couldn't find any posts with similar difficulties, and I haven't been able to solve them on my own for several days. Help! [models.py] class Leave(models.Model): title = models.CharField(max_length=50, blank=True, null=True) from_date = models.DateField(blank=True, null=True) end_date = models.DateField(blank=True, null=True) memo = models.TextField(blank=True, null=True) user = models.ForeignKey(User, on_delete=models.SET_NULL, blank=True, null=True) is_deleted = models.BooleanField(default=False) create_date = models.DateTimeField(auto_now_add=True) update_date = models.DateTimeField(auto_now=True) @property def get_html_url(self): url = reverse('leave:leave_edit', args=(self.id,)) return f'<div class="event-title" colspan="{self.end_date - self.from_date}"><a href="{url}" style="color:black;"> {self.title} </a></div>' [forms.py] class LeaveForm(ModelForm): class Meta: model = Leave # datetime-local is a HTML5 input type, format to make date time show on fields widgets = { 'from_date': DateInput(attrs={'type': 'datetime', 'class': 'datepicker', 'autocomplete': 'off'}, format='%Y-%m-%d'), 'end_date': DateInput(attrs={'type': 'datetime', 'class': 'datepicker', 'autocomplete': 'off'}, format='%Y-%m-%d'), 'user': Select(attrs={"disabled": 'disabled'}), } fields = ['title', 'from_date', 'end_date', 'memo', 'user'] def __init__(self, request, *args, **kwargs): super(LeaveForm, self).__init__(*args, **kwargs) # input_formats … -
django allauth send me to /accounts/social/signup/# after I complete my authentication with google sing-in
I integrated djang0-allauth with my app but something is not fully working. Every time I try to login/sign by visiting http://127.0.0.1:8000/accounts/google/login/ and following the google auth flow, I am eventually sent to http://127.0.0.1:8000/accounts/social/signup/ where I am stuck in some sort of loop of sing-in and sing-up. I guess I didn't set-up my settings properly? Or maybe I need to do something with the adapters.py Just for context, I have a custom user model which maybe is also creating issues? settings """ Django settings for mywebsite project. Generated by 'django-admin startproject' using Django 3.2.5. For more information on this file, see https://docs.djangoproject.com/en/3.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.2/ref/settings/ """ from pathlib import Path import os import django_on_heroku import django_heroku import cloudinary import cloudinary_storage import dj_database_url from decouple import config import cloudinary.uploader import cloudinary.api # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = os.environ.get('DJANGO_SECRET_KEY', False) #env docs https://apple.stackexchange.com/questions/356441/how-to-add-permanent-environment-variable-in-zsh LOCAL = os.environ.get('ARE_WE_LOCAL', False) # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True DEBUG_PROPAGATE_EXCEPTIONS = … -
How to get the duration of video when file is uploaded in the Django view.(with ffprobe)
I am creating a video streaming service with the Django. I want to get the duration of video when the video is uploded. So i've installed ffmpeg with brew (Mac OS), and created the command with subprocess but didn't working. I don't know what I have to do. These are things that I tried. views.py class MovieUpload(user_mixins.MoiveUploadPermissionView, FormView): """MovieUpload View""" form_class = forms.MovieUploadForm template_name = "movies/movie_upload.html" def form_valid(self, form): movie = form.save() filename = movie.video.path result = subprocess.check_output( f'ffprobe -v quiet -show_streams -select_streams v:0 -of json "{filename}"', shell=True, ).decode() fields = json.loads(result)["streams"][0] duration = fields["tags"]["DURATION"] print(duration) movie.user = self.request.user movie.save() return redirect(reverse("movies:detail", kwargs={"pk": movie.pk})) I tried this, but makes the error: Command 'ffprobe -v quiet -show_streams -select_streams v:0 -of json "/Users/bami/Documents/cineacca/uploads/SampleVideo_1280x720_20mb.mp4"' returned non-zero exit status 1. I tried with just filename, not filepath but the error was the same. class MovieUpload(user_mixins.MoiveUploadPermissionView, FormView): """MovieUpload View""" form_class = forms.MovieUploadForm template_name = "movies/movie_upload.html" def form_valid(self, form): movie = form.save() filename = movie.video.path duration = subprocess.check_output( [ "ffprobe", "-i", f"{filename}", "-show_entries", "format=duration", "-v", "quiet", "-of", "csv=%s" % ("p=0"), ] ) print(duration) movie.user = self.request.user movie.save() return redirect(reverse("movies:detail", kwargs={"pk": movie.pk})) This code makes the same error. class MovieUpload(user_mixins.MoiveUploadPermissionView, FormView): """MovieUpload View""" form_class = forms.MovieUploadForm template_name … -
Django and HTML- how to apply styling to specific answers
I am working on a Django project where I have a survey form and this corresponding HTML syntax : <label for="id_form-{{ forloop.counter0 }}-answer">Answer:</label> {% for answer in answers %} <label for="id_form-{{ forloop.counter0 }}-answer"> <input type="radio" name="form-{{ forloop.parentloop.counter0 }}-answer" id="id_form-{{ forloop.counter0 }}-answer" value="{{answer.id}}"> {{answer.text}} {% if answer.image %} <img src="/static/mysurveys/{{answer.image}}.png"> {% endif %} </label> {% endfor %} This syntax is working fine for now, but my question is, how can I get rid of the for loop so that I can apply specific stylings to each answer? In this case, the user is supposed to select an image from a group of images as the answer, and I just want the images to be arranged in a circle container. I have tried something like this: <label for="id_form-{{ forloop.counter0 }}-answer">Answer:</label> <div class="circle-container"> <label for= 'id_form-{{ forloop.counter0 }}-answer' class='center'> <input type="radio" name="form-{{ forloop.parentloop.counter0 }}-answer" id="id_form-{{ forloop.counter0 }}-answer" value="{{answer.id}}"> <img src="/static/mysurveys/female_neutral.png"> </label> <label for= 'relaxed' class='deg22_5'> <input type="radio" name="form-{{ forloop.parentloop.counter0 }}-answer" id="id_form-{{ forloop.counter0 }}-answer" value="{{answer.id}}"> <img src="/static/mysurveys/female_relaxed.png"> </label> But, with this code the answer is not being recorded in the database and I am getting an error that says: Formset is NOT valid. [{'answer': ['This field is required.']}]. Please, let me know of any … -
Can django-tenants work for project that has a general section and company accounts
I working on a project that will have a main section where the users will have access to sections common to all (for example forums where they can communicate) and company accounts that will only be accessible to those that are members of that account. I have set up django-tenants but I am finding that out of the box it does not seem to work as I thought it would. For example, the tenant accounts have access to the forums even though the forums are only in the "shared apps" settings. The forums linked from the tenant accounts are empty but the should not even exist. Apparently "shared apps" means a shared schema. Another problem is that currently a tenant superuser has the ability to change content that is in a shared app. For example the tenant1 superuser could add/delete forums. This superuser can also see users for the whole site. Is there a way to setup django-tenants so that there is essentially a main project with sections that all users have access to but tenant users only have access to apps in the "TENANT_APPS" section of the settings.py file from inside of the tenant account (ex: tenant1.sitename.com)? -
i create project in django & when I try to run program it shows error of invalid interpreter selected for the project
And after adding a valid interpreter it again shows the error. it was a previously made project and was working without any issue but now it is not working. #help THANK YOU IN ADVANCE. ERRORS: jobs.Job.image: (fields.E210) Cannot use ImageField because Pillow is not installed. HINT: Get Pillow at https://pypi.python.org/pypi/Pillow or run command "pip install Pillow". System check identified 1 issue (0 silenced). C:\Users\Admin\Desktop\portfolio>pip install pillow; Requirement already satisfied: pillow in c:\users\admin\appdata\local\programs\python\python39\lib\site-packages (8. 2.0) -
django change view that is colled with `http://127.0.0.1:8000/login/`
I am trying to change the view that is being called when someone hit the url http://127.0.0.1:8000/login/ on my app. I tried the following solution (not sure what I am doing thought)but i didn't work so I was wondering if anyone else had any idea. from django.contrib import admin from django.urls import path, include from django.views.generic.base import RedirectView urlpatterns = [ path('admin/', admin.site.urls), path('', include('action.urls')), path('r/', include('urlshortener.urls')), path('myusermodel/',include('myusermodel.urls')), path('login/',RedirectView.as_view(url='myusermodel', permanent=False), name='index'), path('accounts/', include('allauth.urls')), -
Django-compressor has a JS cache folder that is using an absurd amount of space
I woke up this morning to alerts from sentry that my production server has completely run out of space. It took some time figuring out the cause via ncdu, and the results were that my static folder had used over 60GB of space, specifically, CACHE/js that django-compressor is using. I am not completely sure what is happening, or why there are over 500,000 js files where each file is following this format: output.<random string>.js. From my understanding, shouldn't there only be a small number of js files cached? My project doesn't even have that many scripts! It seems to me that every user is getting their own output file, instead of the same cached files being shared to everyone. Base settings: # STATIC # ------------------------------------------------------------------------------ # https://docs.djangoproject.com/en/dev/ref/settings/#static-root # STATIC_ROOT = str(ROOT_DIR / "static") STATIC_ROOT = os.path.join(BASE_DIR, "static/") # https://docs.djangoproject.com/en/dev/ref/settings/#static-url STATIC_URL = "/static/" # https://docs.djangoproject.com/en/dev/ref/contrib/staticfiles/#std:setting-STATICFILES_DIRS # STATICFILES_DIRS = [os.path.join(BASE_DIR, "static")] # https://docs.djangoproject.com/en/dev/ref/contrib/staticfiles/#staticfiles-finders STATICFILES_FINDERS = [ "django.contrib.staticfiles.finders.FileSystemFinder", "django.contrib.staticfiles.finders.AppDirectoriesFinder", "compressor.finders.CompressorFinder", ] COMPRESS_ENABLED = True COMPRESS_PRECOMPILERS = ( ('text/x-scss', 'django_libsass.SassCompiler'), ) COMPRESS_FILTERS = { "css": [ 'compressor.filters.css_default.CssAbsoluteFilter', # 'compressor.filters.cssmin.CSSMinFilter', 'core.CSSMinFilter.CSSMinFilter', ] } production settings: CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.memcached.PyMemcacheCache', 'LOCATION': '127.0.0.1:11211', } } I originally installed django-compress to fix issues where users … -
How to add a model containing a FilePathField item to an admin panel
I've set up a model which contains a FilePathField() item with the path '/img'. The img folder is located in a static folder in that app and the whole setup works perfectly when adding items through the shell interface. The problem comes in when I try to set up the admin panel to include this model where I get a FileNotFoundError when trying to open existing items or add new ones. The error is: FileNotFoundError at /admin/work_done/project/2/change/ [WinError 3] The system cannot find the path specified: '/img' To get around this I changed the path property to the absolute path with: path=f'{Path(__file__).parent.absolute()}/static/img') This makes the admin panel work but when I add items with that in place the image doesn't show up because it's looking for an image at localhost:8000/static/C%3A/.../static/img/image.png. Is there a way to make this work in admin and have the image show up? I've only found an answer to getting it working in admin but that doesn't mention the image not working in the website. The code I'm using to actually display the image is '{% static project.image %}'. I have tried changing it to '{% url project.image %}' as a long shot but unsurprisingly it didn't … -
Error on Docker-Compose with a Django - postgres db
I'm trying to create a Django application with docker. To get a more scalable application I'm trying to run a Postgres db in a different container. To be more specific, I just followed the tutorial at this link: https://docs.docker.com/samples/django/ The docker compose is this, in which I set the username, psw and name of the database version: "3.9" services: db: image: postgres volumes: - ./data/db:/var/lib/postgresql/data environment: - POSTGRES_DB=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" depends_on: - db The connection of the database in settings.py of Django is done in these lines: # settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'postgres', 'USER': 'postgres', 'PASSWORD': 'postgres', 'HOST': 'db', 'PORT': 5432, } } When I try to run the whole project, with the command docker-compose up the web application (which is the Django application) responds with this error: django.db.utils.OperationalError: SCRAM authentication requires libpq version 10 or above I really don't undestand what's wrong in here. Have to update the python - linux container that runs the Django application? Thank you really much in advance for all the help you will get me. -
Python: Django Framework - urls.py: No "name"-Attribute in path()?
I'm currently trying to link from one HTML-Page to another one. Some Tutorials told me I need to link with an url inside the .html-file to the specific path I've been defining before. So that's what I did: <a id ="register" href="{% url 'register_view' %}"> register now</a> and inside my urls.py of the app "login" I also wanted to call the path "register_view" with the name-attribute: urlpatterns = [ path('', login_view), path('register/', register_view, name="register_view"), ] but the problem is: it won't find the attribute "name" inside `path() and I have no idea why. Can you help me out here? Thanks in Advance!