Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Djnago FileField: Prevent saving file onto file system when uploading
I have a simple app in this github repo. There is ready database. There are two models: from django.db import models from django.db.models import FileField class Task(models.Model): name = models.CharField(max_length=20) class TaskAttachment(models.Model): task = models.ForeignKey(Task, on_delete=models.CASCADE) file = FileField() binaries = models.BinaryField() content_type = models.TextField() def save(self, force_insert=False, force_update=False, using=None, update_fields=None): self.binaries = self.file.file.read() self.content_type = self.file.file.content_type super().save(force_insert, force_update, using, update_fields) Note: please do not ask why I'm saving files in database and not in file system or s3. Registered TaskAttachment model in admin: from django.contrib import admin from tasks.models import TaskAttachment class TaskAttachmentAdmin(admin.ModelAdmin): exclude = ['content_type'] admin.site.register(TaskAttachment, TaskAttachmentAdmin) The problems I faced with that is that uploaded files are being saved to file system: As far as I save binaries in database I do not want files being saved on file system. How could I prevent saving files to file system when uploading files and get file content from database binaries field when fetching TaskAttachment model instance? -
What is the main purpose of the admin site?
Well I been working on Django for a short time as a backend developer (maintainant). And most of the Django sources that I work on, do not have the Django Admin Site. However, when I look up any document of Django. There will be a big section relating about the Django Admin site. So I wonder, what is the main purpose of the Django Admin Site, and in which scenario we gonna use it and in your case, how often you interact with Django Admin Site. -
Notification-like system for django
I'm developing an app for builders. I want to have a button on one page, that will be "I need material" and when that button is pushed, I need to notify, let's say John, on another tablet, that the user, who's working on X, needs material. I need to have it sent without reloading either page, so John can just sit back and when the page that John's tablet will be on starts flashing and information appear, John will know where he needs to go. Any ideas on what to use? I don't want to use extensions if possible. Thanks -
Dynamically populate one Django Form field based on selection in another
I have a model with a list of choices as follows: models.py class Choice_class(models.Model): options = ( ('None', 'none'), ('one', 'one'), ('two', 'two'), ('three', 'three'), ) option_values = ( ('None', 0), ('one', 1), ('two', 2), ('three', 3), ) user_choice = models.CharField(max_length = 5, choices = options, default = 'None') choice_value = models.IntegerField() and a form as follows: forms.py class Choice_class(models.Model): options = ( ('None', 'none'), ('one', 'one'), ('two', 'two'), ('three', 'three'), ) option_values = ( ('None', 0), ('one', 1), ('two', 2), ('three', 3), ) user_choice = models.CharField(max_length = 5, choices = options, default = 'None') choice_value = models.IntegerField(default = option_values[#BASED ON USER CHOICE IN FIELD ABOVE] ) I'd like to populate the choice_value field with a default value from option_values based on what user selects for the user_choice field. I'd rather not do this through js (although it's an option) because I feel like there should be a way to do this through the framework in the same form. I realise that I also have the option of doing the logic for this in views.py: if choice_value == 'None': '''populate with default value based on user_choice as defined by dict in views file etc''' but I'd rather do this within … -
Getting AttributeError: 'ASGIRequest' object has no attribute 'get' in daphne django
I'm trying to run my fastapi code on daphne webserver instead of uvicorn, because my end goal is to run it on Android, where uvicorn is not available. I've been debugging my app for hours at this point. Setting it all up. Here is my code: settings.py """ Django settings for myproject project. Generated by 'django-admin startproject' using Django 3.2.6. 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 # 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 = 'django-insecure-_n5hy*-sk6y0&mcgu6&_s*+ql5fvujw+ndccjobc0g8lryx!^z' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] 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', ] ROOT_URLCONF = 'myproject.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'myproject.wsgi.application' # Database # https://docs.djangoproject.com/en/3.2/ref/settings/#databases DATABASES = { 'default': … -
Django google picker API key
I'm setting up google picker API within a Django app and am trying to figure out how to handle the API key and other settings properly. I am wondering if the way I am doing it is a security risk. I set the values using environment variables like so: # views.py @staff_member_required def upload(request): context = { 'GOOGLE_DEVELOPER_KEY': os.environ.get('GOOGLE_DEVELOPER_KEY'), 'GOOGLE_CLIENT_ID': os.environ.get('GOOGLE_CLIENT_ID'), 'GOOGLE_APP_ID': os.environ.get('GOOGLE_APP_ID') } return render(request, 'upload.html', context) # upload.html <script type="text/javascript"> var developerKey = "{{ GOOGLE_DEVELOPER_KEY }}"; var clientId = "{{ GOOGLE_CLIENT_ID }}" var appId = "{{ GOOGLE_APP_ID }}"; function createPicker() { if (pickerApiLoaded && oauthToken) { var view = new google.picker.View(google.picker.ViewId.DOCS); //view.setMimeTypes("image/png,image/jpeg,image/jpg"); var picker = new google.picker.PickerBuilder() .enableFeature(google.picker.Feature.NAV_HIDDEN) .enableFeature(google.picker.Feature.MULTISELECT_ENABLED) .setAppId(appId) .setOAuthToken(oauthToken) .addView(view) .addView(new google.picker.DocsUploadView()) .setDeveloperKey(developerKey) .setCallback(pickerCallback) .build(); picker.setVisible(true); } } </script> You have to be logged in securely to see the page. But the way I am setting the values, once you are logged in you can simply view the HTML and see the developer key, client id, etc. Is this a problem? Should I be doing this a different way? -
Error loading psycopg2 module: Library not loaded: libpq.5.dylib
I am trying to run a Django project with Postgres database by PyCharm professional. I use Postgres 13.4 installed via postgressapp (UNIVERSAL with all currently supported versions) and python 3.9 (in venv). I work on Mac with Apple M1 chip, macOS Big Sur. I faced the following well-known problem: django.core.exceptions.ImproperlyConfigured: Error loading psycopg2 module: dlopen(/Users/mymac/PyCharmProjects/projectname/venv/lib/python3.9/site-packages/psycopg2/_psycopg.cpython-39-darwin.so, 2): Library not loaded: /opt/homebrew/opt/postgresql/lib/libpq.5.dylib Referenced from: /Users/mymac/PyCharmProjects/projectname/venv/lib/python3.9/site-packages/psycopg2/_psycopg.cpython-39-darwin.so Reason: image not found With searching, I found some discussions like this: https://github.com/psycopg/psycopg2/issues/1216. It seems that the most relevant solution is "RyanDurk commented on Jan 27": $ brew install libpq --build-from-source $ export LDFLAGS="-L/opt/homebrew/opt/libpq/lib" $ pip install psycopg2 Unfortunately, in my case it does not help. Then, I found some recommendations here: Library not loaded: /usr/local/lib/libpq.5.4.dylib and tried them. In particular, I tried to reach libpq.5.dylib via symlink like: ln -s /Library/PostgreSQL/13/lib/libpq.5.dylib /opt/homebrew/opt/postgresql/lib/libpq.5.dylib (the solution marked as accepted by topic starter), but also unsuccessfully. I tried to install postgres from postgresql.org, then uninstall/reinstall postgres with homebrew, then gem uninstall pg -> bundle install with the same result. I have run the same project successfully before, on the mac with Intel chip and PyCharm community edition. Also the same project runs normally on Linux. If you have any … -
How to connect a database to two Django projects and access models?
I have a local Django server running and it stores data to a PostgreSQL cluster and I'm trying to access same database in my different Django project how can I achieve this I've tried by creating same models and copying migrations folder in my local server but it din't worked for me, and how can I access the data from PostgreSQL in my second project. -
Not able to use static image after getting the value of dictionary key and using it in HTML template. Unable to use value in HTML
Blockquote I have loaded the static <div class="row"> <img src="{% static 'wea_app/icons/{{ mainresult.icons }}.png' %}"> <div> Blockquote If I print the 'icons', I get the value in terminal. The value name also matches the name of the static file. How can I pass it to the static path which contains the image of my weather. I just want the value to pass to path so I can get the image according to the weather from my static folder. **<!-- myviews.py file -->** mainresult = { "city":city, "temprature": a['current']['temp'], "description": a['current']['weather'][0]['description'], "icons": a['current']['weather'][0]['icon'], "feels": a['current']['feels_like'], "windspeed" : a['current']['wind_speed'], "timezone" : a['timezone'], "pressure" : a['current']['pressure'], "humidity" : a['current']['humidity'], "dt" : a['current']['dt'], } context = {"mainresult":mainresult} return render(request,'wea_app/index.html',context) -
Django model TextField display zip code format
In my models.py, I have a zip code field that are in TextField format: class Merged(models.Model): zip_code = models.TextField(db_column='Zip Code', blank=True, null=True) However, there are some invalid zip codes like sagaponack 11962 lindenhurst 11757 I just want to display the 5-digit zip code without any other texts. What I have tried and failed In serializers.py, I tried to apply a RegexField to the zip_code column: class MergedSerializer(serializers.HyperlinkedModelSerializer): zip_code = serializers.RegexField(regex=r'^\d{5}') class Meta: model = Merged fields = '__all__' It did not work. How do I solve this in a way that does not only change how it displays, but also ensures that sorting works properly (i.e. ignore the text part, only sort based on zip codes) -
How to create tags that are different, which are unique to the blogs in django wagtail
Hello I am following this tutorial, https://docs.wagtail.io/en/stable/getting_started/tutorial.html# and I am on the tags portion. Question I have is, how do I create tags thats different for each application. I have two apps, LibBlog and libnewsblog. If i create a tag for Blog called School, I want it to only search Blog. Same thing for Libnews. Right now When I click on the Tag "School" it shows up posts from both LibBlog and LibNewsBlog. -
Django and chart.js - one bar per 'date' in model
I have a model that contains a date and a number. There are multiple inputs from the same date that I want to merge into 1 bar on the chart. How can I show each date only once but add up all of the totalPacks under that date? model: Views: def homepage(request): labels = [] data = [] queryset = DailyCountsModel.objects.order_by('-date') for jobs in queryset: labels.append(jobs.date) data.append(jobs.totalPacks) return render(request,'index.html', { 'labels': labels, 'data': data, }) Currently this chart will show one bar per entry.. I can't think of how I could do this. Any ideas? I'm guessing somehow I would need to check to see how many items they are with the 'date' of 2021-08-23 and add up the 'totalPacks', I'm just not sure how I would do this -
CPanel Slug in Django
I'm new in posting in Stackoverflow. I'm sorry if my English isI'm using CPanel to host my web, but when I try to deploy my web, the route to Technopark and route with format year/month/slug are not working properly, which the page opened is not as expected. Here I attach my script for home/desajono/webdesajono/desajono/views.py : And here is the result if the application is run in the local : 127.0.0.1/technopark: [enter image description here][1] 127.0.0.1/2021/08/pentingnya-olahraga-untuk-menurunkan-risiko-kepara : [enter image description here][2] But if the application is run in hosting, the result is like these pictures : https://desajono.com/technopark : [Technopark Page][3] https://desajono.com/2021/08/pentingnya-olahraga-untuk-menurunkan-risiko-kepara : [Slug Page][4] [1]: https://i.stack.imgur.com/CNq0f.png [2]: https://i.stack.imgur.com/ulGx3.png [3]: https://i.stack.imgur.com/wfRAu.jpg [4]: https://i.stack.imgur.com/JvwIy.jpg And here are some of my important codes that maybe you can use to give suggestion : from django.contrib import admin from django.urls import path, include admin.autodiscover() from django.conf import settings from django.conf.urls.static import static from django.conf.urls import include, url urlpatterns = [ path('admin/', admin.site.urls), path('', include('desajono.urls')), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) print("Ini URL di mysite : {}".format(urlpatterns)) home/desajono/webdesajono/desajono/urls.py : from django.urls import path from django.conf.urls import url from . import views urlpatterns = [ url(r'', views.index, name='index'), url(r'^<int:year>/<int:month>/<slug:slug>/', views.see_article, name='article-detail'), url(r'^technopark/', views.open_technopark, name='technopark'), ] print('Ini URL … -
Context data not used when form is invalid
i am creating a view using formview class and using get_context_data to display some information on the test html page alongside the form i error which i am facing is when the form gets invalid i get in get_context_data context['username'] = data['username'] KeyError: 'username' i am not sure why the context data not getting picked up when the form invalidates class TestView(LoginRequiredMixin,FormView): form_class = TestForm template_name = 'test.html' def get_context_data(self, **kwargs): context = super(CredentialsView, self).get_context_data(**kwargs) if self.request.user.is_authenticated: data = TestViewSet.as_view({'get': 'list'})(self.request).data context['username'] = data['username'] context['firstname'] = data['firstname'] context['lastname'] = data['lastname'] context['validstartdate'] = data['validstartdate'] context['validenddate'] = data['validenddate'] return context def form_valid(self, form): password = form.cleaned_data['password'] if form.is_valid(): return self.query_api(password) else: return super(TestView, self).form_valid(form) -
Django and google earth engine not running on heroku
I have deployed Django app with gene map on Heroku Build is successful but got an error : -- error -- Please authorize access to your Earth Engine account by running earth engine authenticate in your command line, and then retry. --- error --- even I have run command on Heroku CLI -- Heroku run earth engine authenticates and authenticated successfully but still got this error I have used this reference -- https://bikeshbade.com.np/tutorials/Detail/?title=Interactive%20web%20mapping%20with%20Django%20and%20Google%20Earth%20Engine&code=15 -
How can I avoid infinite loop when reformatting url hash with Jquery event 'hashchange'
Issue Background I have set up my webpage to use identifiers with prefix #s- to differentiate anchor links from other page identifiers. The window.location.hash changes to hash which moves the frame to the content in focus but also triggers the hashchange listener causing a loop. What I've tried I have it working for whenever the hash has changed but the only instance it does not work is when the same link it pressed (as I use this in the condition to stop the infinite loop). The code for this was: $(window).on('hashchange', function(e) { if ($(location).attr('hash') != last_hash) { manageHash() } }); What I want I'd like to be about to find a condition or method to allow users to select a link to change the hash but also allow them to re-select the same link as many times as they want without causing a loop. JS last_hash = '' function manageHash() { var hash = $(location).attr('hash'); if($('#s-'+hash.substring(1)) != 0 && '#s-'+hash.substring(1) != '#s-' ) { last_hash = hash window.location.hash = '#s-'+hash.substring(1); } } $(window).on('hashchange', function(e) { if ($(location).attr('hash') != last_hash) { manageHash() } }); $(document).ready(function() { manageHash() }) HTML <div class="contentSubSectionContainer contentSubSection" id="s-{{ subsection.slug }}"> <h2 class="contentSubSectionFont1Bold">{{ subsection.sub_section_title }}:</h2> <div … -
how to do if contion check with variable (true or false) inside django template
how to do if contion check with variable (true or false) inside django template <select id="company_id" name="company_id" class="form-control " > <option value="">Select Company {{company_id}}</option> {% for row in brands %} {% if row.id == company_id %} <option value="{{ row.id }}" >{{ row.title }} </option> {% else %} <option value="{{ row.id }}" selected>{{ row.title }} </option> {% endif %} {% endfor %} </select> -
Audio file could not be read as PCM WAV, AIFF/AIFF-C, or Native FLAC; check if file is corrupted or in another format/ speech to text view python
my speech to text view doesn't work and I have the file wav but I got this error Traceback (most recent call last): File "C:\Users\privet01\Desktop\python projects\projex x\myvev\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\privet01\Desktop\python projects\projex x\myvev\lib\site-packages\django\core\handlers\base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\privet01\Desktop\python projects\projex x\alpha1\appsolve\views.py", line 636, in spechtotext with sr.AudioFile(sound) as source: File "C:\Users\privet01\Desktop\python projects\projex x\myvev\lib\site-packages\speech_recognition\__init__.py", line 236, in __enter__ raise ValueError("Audio file could not be read as PCM WAV, AIFF/AIFF-C, or Native FLAC; check if file is corrupted or in another format") ValueError: Audio file could not be read as PCM WAV, AIFF/AIFF-C, or Native FLAC; check if file is corrupted or in another format [23/Aug/2021 13:26:44] "POST /spechtotext/ HTTP/1.1" 500 152359 This is my view import speech_recognition as sr from django.core.files.storage import FileSystemStorage def spechtotext(request) : if request.method=='POST': if request.FILES['theFileINEEd'] and '.mp3' in str(request.FILES['theFileINEEd'].name).lower() : myfile = request.FILES['theFileINEEd'] fs = FileSystemStorage('') filename = fs.save(str(request.user)+"speachtotext.WAV", myfile) file_url = fs.url(filename) full_link='http://127.0.0.1:8000'+file_url # changeble to life mode r = sr.Recognizer() print(type(filename)) print('hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh') r = sr.Recognizer() import sys print(sys.version_info) print('qqqqqqqqqqqqqqqqqqqqqqqqq'+str(filename)+'aaaaaaaaaaaaaaaaaaaa') hellow=sr.AudioFile(str(filename)) sound = str(filename) with sr.AudioFile(sound) as source: r.adjust_for_ambient_noise(source) print("Converting Audio To Text ..... ") audio = r.listen(source) try: print("Converted Audio Is : \n" + … -
string parameters passing do not working in dajango
view.py when i test my api with post man ,postman indicate tha this urls do not exist(404 not found) any solution please url postman:localhost:8000/photoByCategory/nature/ @api_view(['GET']) @permission_classes((permissions.IsAuthenticated,)) def photo_by_categorie(request, category=False): if request.method == 'GET': if category: photo_by_cat = Photo.objects.filter(category=category) serializer = PhotoSerializer(photo_by_cat, many=True) return Response(serializer.data, status=status.HTTP_200_OK) urls.py re_path(r'photoByCategory/(?:(?P<category>\d+)/)?$', views.photo_by_categorie, name='photo_by_categorie'), -
Django form choicefield doesn't rendering empty field
I have a form that has a choicefield, choice as follow - TYPE = (('','Select type'), ('college', 'College'), ('university', 'University')) class Form(ModelForm): type = forms.ChoiceField(choices=TYPE) As the document says `` Unless blank=False is set on the field along with a default then a label containing "---------" will be rendered with the select box. To override this behavior, add a tuple to choices containing None; e.g. (None, 'Your String For Display'). Alternatively, you can use an empty string instead of None where this makes sense - such as on a CharField.``` I tried usign '' & None, both doesnt work ! It just shows the 'Select type' and immediately disappears ! Please help -
Django how to make timezone aware CustomTimeField?
from django.db import models class CustomTimeField(models.DateTimeField): .... Goal: I need to store the date in form of datetime but I need this field to return only the hour:minute:second and eliminate the rest. I tied: to handle this in the serializers but I am using three serializers for the same model so it can be overwhelming to do that especially when I tried to use one serializer and override it for each usage. -
Hide all records in Django admin unless a search query is entered
We have a Python-2.7 and Django project (version 1.11) that has lots of models registered on it (Users app, Invitations app, Profiles app, etc...) First thing I'm trying to do is create a group for some users that will have only viewing permissions when they log on to the Django admin and see limited models from the entire list. Second thing is to not have any records shown by default when you enter one of the models you're allowed to view. You must search for something in order for matching records to appear so that only results associated with that user is shown. Is this possible and if yes, how do I implement this? -
How to check user permission in ModelViewSet
I am want to check permission of the user in my ModelViewSet to understand how much data must be given to him? -
Django : Error: 'duplicate key value violates unique constraint'
I have to save images with s3 when creating a new object for my website. I have a code to save my images that I use in my model's save method. When I use the django administration panel, I can easily create my object without any error. But when I try to create my object throught my view, I get this error : Error: 'duplicate key value violates unique constraint « store_shop_pkey »' I think that in my serializer's create method, I try to save my object twice : once for the image and once for the rest of my object's keys. I don't know how to resolve this issue. It works well with PUT method. Here is my code : models.py : class Shop(models.Model): name = models.CharField(max_length=255) category = models.ForeignKey(ShopCategory, on_delete=models.SET_NULL, null=True, blank=True) description = models.TextField(blank=True, null=True) path = models.CharField(max_length=255, unique=True, null=True, blank=True) # Set a null and blank = True for serializer mustBeLogged = models.BooleanField(default=False) deliveries = models.FloatField(validators=[MinValueValidator(0),], default=7) message = models.TextField(null=True, blank=True) banner = models.ImageField(null=True, blank=True) def save(self, *args, **kwargs): try: """If we want to update""" this = Shop.objects.get(id=self.id) if self.banner: image_resize(self.banner, 300, 300) if this.banner != self.banner: this.banner.delete(save=False) else: this.banner.delete(save=False) except: """If we want to create … -
Hi i want to convert django project to exe format
Hi i want to convert django project to exe format I have converted python file to exe. But don't know about django to exe. Please anyone help me to do this