Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Change the way image upload field renders from a form in django?
I have the following code in template: {{ form.profile_picture }} The Profile picture field in the form is derived from a model as Meta. The Model is as follows: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE,primary_key=True) bio = models.TextField(max_length=100, blank=True) location = models.TextField(max_length=50, blank=True) date_of_birth = models.DateField(null=True, blank=True) profile_picture = models.FileField(default='default_pic.png') When the field is rendered on the webpage, it looks like this: I want to change this button to look somewhat different like an edit button. -
How to generate swagger for django rest api where my views are fucntion based view
I have search so many sites,even document but cannot find a complete steps to create swagger for function based views in django. Thanks in advance -
JSONField reference a model like One to One within the JSON
Stupid question time! :) I don't think this is possible but I need to ask in case I'm wrong. Is it possible to create a one to one relationship to a normal Django model in the JSON of a JSONField? Example: Django Model (Example): class TheModel(models.Model): example = models.CharField(max_length=255) something = models.CharField(max_length=255) dt = models.DateTimeField() Django model in separate app (Example): class JsonModel(models.Model): json_stuff = JSONField(default=list) The JSON itself will be a list of dictionaries of will have multiple layers but some need to hold a reference to the "TheModel" to be presented in a template (the same way a One to One relationship would). JSON (Example): [{"title": "A Title", "body": [{"line": "Some text", "reference": TheModel}, {"line": "More Text", "reference": None }]} It's looking like I'll have to loop through the JSON and insert the reference manually in the view. -
Django UpdateView without form to update object
I am using class based views with django 1.9 and I am trying to figure out how to update an object(After clicking a button) without using the form. I do not need any user input to update the object but I am still getting an error message that the template is missing. Can you help me? -
HTML doesn't see django form (django form doesn't render/display)
I created simple form in django. I tried do it in many different ways check all posibilities but still my HTML code doesn't see this form. Code looks like : forms.py from django import forms class TimeTable(forms.Form): title = forms.CharField(max_length=100, required=True) time_start = forms.DateTimeField() time_end = forms.DateTimeField() views.py from home.forms import TimeTable from django.shortcuts import render def schedule(request): if request.method == 'POST': form = TimeTable(request.POST) if form.is_valid(): pass else: form = TimeTable() return render(request, "registration/schedule.html", {'schedule_form': form}) urls.py from django.contrib import admin from django.urls import path, include from django.views.generic.base import TemplateView urlpatterns = [ path('admin/', admin.site.urls), path('accounts/', include('django.contrib.auth.urls')), path('', TemplateView.as_view(template_name='home.html'), name='home'), path('accounts/login/', TemplateView.as_view(template_name='registration/login.html'), name='login'), path('schedule/', TemplateView.as_view(template_name='registration/schedule.html'), name='schedule'), ] schedule.html {% block calendar %} <div class="calendar_create"> <form method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">Submit</button> </form> {% endblock %} </div> HTML only see this <button> mark rest is missing. I tried do it with many tutorials, django documentation and all this stuff doesn't work for me. What I'm doing wrong ? -
Can ForeignKey.limit_choices_to work for grandparent choices in Django 1.11?
I am using Django v1.11 I have the following relations: SubProject has many Quotation Quotation has many QuotationLineItem SubProject is many to many with Scope through ScopeInSubProject QuotationLineItem belongs to Scope via ForeignKey where the scope_id is default null So I like to ensure that when the user does assign a scope value, it's limited to the list of Scope records associated with its grandparent model (SubProject). For e.g. SubProject ABC is associated with Scope A1 and A2. A QuotationLineItem is associated with SubProject ABC indirectly via a Quotation record. Then when I try to save Scope for this very QuotationLineItem, I cannot save anything other than A1 and A2. I came across this concept called limit_choices_to, so I was wondering how do I use it in my specific case? If I don't use this concept, how do I ensure this restriction somehow? Do I write extra validation logic? -
How to use prismjs in django?
can someone tell exact how to use prismjs in django blog app. I tried but not working. I just want step by step guidence from very start to end. Thanks in advance ! -
Docker: User localhost instead of db to connect to PostgresDatabase
I'm running into problems when using Docker. To connect from Django application to the Postgres database I have to use: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'postgres', 'USER': 'postgres', 'HOST': 'db', 'PORT': 5432, } } However to run tests via pytest in my Pipenv shell I have to change 'Host': from db to localhost. Is there a way that I can always use localhost? Docker-Compose: version: '3' services: db: image: postgres ports: - "5432:5432" web: build: . env_file: .env volumes: - .:/code ports: - "8000:8000" depends_on: - db container_name: test Dockerfile: # Pull base image FROM python:3 # Set environment varibles ENV PYTHONUNBUFFERED 1 # Set work directory RUN mkdir /code WORKDIR /code # Install dependencies RUN pip install --upgrade pip RUN pip install pipenv COPY ./Pipfile /code/Pipfile RUN pipenv install --deploy --system --skip-lock --dev # Define ENTRYPOINT COPY ./docker-entrypoint.sh /docker-entrypoint.sh RUN chmod +x /docker-entrypoint.sh ENTRYPOINT ["/docker-entrypoint.sh"] # Copy project COPY . /code/ -
Saving files in a S3 subfolder
If I'm not mistaken, there are no real folders in S3. But there seems to be a possibility to save files with path's so it looks like a folder (when navigated through the AWS console, the folders are even visible). Having a FileField in Django, how would I append a folder name to it? E.g. the below works but is being put in the root bucket, which becomes cluttered very quickly. I'd love to put all those files in a 'subfolder' class presentation(models.Model): """ Holds the presentation themselves""" author = models.ForeignKey(User, on_delete=models.CASCADE) file = models.FileField( null=False, blank=False, help_text='PPT or other presentation accessible only to members', storage=protected_storage, ) protected_storage = storages.backends.s3boto3.S3Boto3Storage( acl='private', querystring_auth=True, querystring_expire=120, # 2 minutes, try to ensure people won't/can't share ) -
Does django 1.11 orm support using group in regexp_replace postgresql function?
So I use django 1.11 and postgresql 9.6.6 which support regexp_replace function. I want to make such query: from django.db.models import Func, F, Value from customsite.models import CustomSite CustomSite.objects.all().update(site_field=Func(F('site_field'), Value('(foo)(bar)'), Value('\\1-\\2'), Value('gm'), function='regexp_replace')) Can I do it? Does orm of django support this syntax? In my case, there is a simple replacement with a hyphen. But I want use groups \\1 and \\2. Could you help me, please? -
OperationalError : FATAL: no pg_hba.conf entry for host "127.0.0.1", user "fibzadmin", database "fibz", SSL off
I have been struggling with this issue for a few days now. I have read numerous other SO threads and it seems like my django app is having difficulty connecting to the postgres database. I am not sure why that is happening though. I am hoping some of the experts out there can take a look and tell me why this might be happening. I have pasted some of my configuration here. This is what my settings.py contains DATABASES = { 'default': { 'ENGINE': 'django.contrib.gis.db.backends.postgis', 'NAME': 'fibz', 'USER':"fibzadmin", "PASSWORD":"fibzadmin", "HOST":"localhost", "PORT":"5432", } } This is what my pg_hba.conf and postgresql.conf look like sudo vim /var/lib/pgsql9/data/pg_hba.conf Output: local all all trust # IPv4 local connections: host all power_user 0.0.0.0/0 md5 # IPv6 local connections: host all other_user 0.0.0.0/0 md5 host all storageLoader 0.0.0.0/0 md5 host all all ::1/128 md5 following are the main uncommented lines listen_addresses = '*' port = 5432 max_connections = 100 and this is from the psql (fibzVenv) [admin]$ sudo su - postgres Last login: Fri Nov 23 07:13:53 UTC 2018 on pts/3 -bash-4.2$ psql -U postgres psql (9.2.24) Type "help" for help. postgres=# \du List of roles Role name | Attributes | Member of ------------+------------------------------------------------+----------- postgres | … -
Django: Search Multiple Fields of A Django Model with Multiple Input field (with Drop Down) in HTML
How can I implement a Drop-Down search in Django where users can search through a listing of second hand cars. The HTML search page will have 3 dropdown search input for Brand, Colour, Year. Once users select a choice of brand, colour and year, the listings will return a list of cars that matches that requirement. class SecondHandCar(models.Model): brand = models.CharField(max_length=250, unique=True) slug = models.SlugField(max_length=250, unique=True) description = models.TextField(blank=True) colour = models.CharField(Category, on_delete=models.CASCADE) year = models.IntegerField(blank=False) I would appreciate any ideas on what I need to do. I had a look at Q lookups, django haystack, but I'm unsure which would fit my needs. I think I would appreciate seeing how I could integrate this with the HTML side of things to pass the query from multiple input fields to Django. -
calcul time between 2 hours in django
I try to calculate the time elapsed between 2 hours but also to make a sum for the day and the week. I tried several methods but none was congruent and I dry completely, no more ideas. class Timesheet(models.Model): owner = models.ForeignKey(User, on_delete = models.CASCADE) title = models.CharField(max_length = 64, verbose_name = _("Title")) start = models.DateTimeField(verbose_name = _("Start time")) end = models.DateTimeField(verbose_name = _("End time")) allDay = models.BooleanField(blank = True, default = False, verbose_name = _("All day"), help_text = _("If it's a full day work, just click 'Now' for start/end")) week = models.IntegerField(verbose_name = "working week") def __str__(self): return "{}".format(self.title) def save(self, *args, **kwargs): if not self.pk: self.week = datetime.datetime.now().isocalendar()[1] if self.allDay: self.start = datetime.datetime(year = datetime.datetime.today().year, month = datetime.datetime.today().month, day = datetime.datetime.today().day, hour=8, minute=00) self.end = datetime.datetime(year = datetime.datetime.today().year, month = datetime.datetime.today().month, day = datetime.datetime.today().day, hour=17, minute=30) super(Timesheet, self).save(*args, **kwargs) In the hope that you can help me. Regards, -
Django Rest Framework custom error messages
I am trying to add custom field error messages for SlugRelated field as follows: class Test(serializers.ModelSerializers): team = serializers.SlugRelatedField(queryset=Team.objects.all(), slug_field='name', error_messages={"does_not_exist": "Team not found"}) Works as expected. My query is how do I pass the team name dynamically in the error message. I tried the following but it did not work: class Test(serializers.ModelSerializers): team = serializers.SlugRelatedField(queryset=Team.objects.all(), slug_field='name', error_messages={"does_not_exist": f"Team {team} not found"}) -
Unable to send django emails using localhost on cloud server
Setting.py --- Email is not working and not giving any error on cloud server ALLOWED_HOSTS = ['*'] EMAIL_HOST = 'localhost' EMAIL_HOST_USER = '' EMAIL_HOST_PASSWORD = '' EMAIL_PORT = 25 EMAIL_USE_SSL = False EMAIL_USE_TLS = False DEFAULT_FROM_EMAIL = 'webmaster@healthondemand.com' EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' Thanks in advance -
Passing django user as redirect request header
I have a (non-django) application A that requires a username to login. This app allows for pre authorization, which I want to provide from my django application B. However app A requires that the username is set as a remote_user request header. What I tried to do is create a view in django app B that redirects to app A passing a remote_user header. urls.py url(r'^{0}to_app_a$'.format(DJANGO_BASE), 'app.views.to_app_a') views.py def to_app_a(request): response = redirect('http://app_a') response['remote_user] = request.user return response The problem with that is that the header is lost on redirect and never reaches the request to http://app_a external app. It has been suggested to use cookies instead, but unfortunately app A won't accept anything else than a remote_user request header. Has anyone come up with a solution to such issue? Thank you -
Django rest framework pass field errors in the extra_kwargs dictionary
I am customizing the does_not_exist error message for a SlugField in my serializer as follows: class PolicyCreateUpdateSerializer(serializers.ModelSerializer): source_ip_group = serializers.SlugRelatedField(queryset=IPGroup.objects.all(), slug_field='name', error_messages={"does_not_exist": "Custom"}) enabled = serializers.BooleanField() class Meta: model = Policy fields = ['id', 'name', 'source_ip_group', 'enabled'] This works as expected.However, when I try to add this in the Meta attribute of the class, it does not work. class PolicyCreateUpdateSerializer(serializers.ModelSerializer): source_ip_group = serializers.SlugRelatedField(queryset=IPGroup.objects.all(), slug_field='name') enabled = serializers.BooleanField() class Meta: model = Policy fields = ['id', 'name', 'source_ip_group', 'enabled'] extra_kwargs = {'source_ip_group': {"error_messages": {"does_not_exist": "Custom"}}} What am I doing wrong ? -
VSCode: "Go to definition" from JS url (view url) to the Django view
I am using sublime now and want to switch to the vscode but one functionality of sublime holding me so far. In the posted image below left side is test.js and right side is view.py having simple test_view definition. If I use go to definition on the "test_view" (at line url: "/test_app/test_view/"+$routeParams.id) in the JS, sublime redirects to the test_view definition of the Django view. I am looking similar functionality/configuration in the VSCode. -
OpenCv Python Django, How can save the image path to my database after resizing it
I have a model which need to hold image path and all my image is being saved to the specifics dir, but i want resize the image with OpenCv because i needs all images to save the same width and height but when i resize it is being is being saved in my project root dir img = OpenCV.imdecode(NP.fromstring(getMainFile.read(), NP.uint8), OpenCV.IMREAD_UNCHANGED) print("w & h before resize: ", img.shape) default_h = 3264 default_w = 4896 resizeImg = OpenCV.resize(img, (default_w, default_h)) print("w & h before resize: ", resizeImg.shape) OpenCV.imshow("The Images", resizeImg) print(resizeImg) genInt = random.randint(1,3445565632) """ after imwrite the image is being saved in project root dir, in this point i want to take the variable "storeImg" and save to models and saved to my database so when i print the variable type is a "class bool" type but i want get the path of image and send it to models """ storeImg = OpenCV.imwrite('{}.jpg'.format(genInt), resizeImg) print(type(storeImg)) print(storeImg) OpenCV.waitKey(0) OpenCV.destroyAllWindows() print(img) print(type(img)) -
how can i run spesefic migration sector in django
now im trying to migrate empty django project. when enter this command python manage.py showmagrations result is admin [ ] 0001_initial [ ] 0002_logentry_remove_auto_add [ ] 0003_logentry_add_action_flag_choices auth [ ] 0001_initial [ ] 0002_alter_permission_name_max_length [ ] 0003_alter_user_email_max_length [ ] 0004_alter_user_username_opts [ ] 0005_alter_user_last_login_null [ ] 0006_require_contenttypes_0002 [ ] 0007_alter_validators_add_error_messages [ ] 0008_alter_user_username_max_length [ ] 0009_alter_user_last_name_max_length contenttypes [ ] 0001_initial [ ] 0002_remove_content_type_name myapp [ ] 0001_initial sessions [ ] 0001_initial is this situation how can i migrate all of 0001_initial? or how can i run spesific migrtaion step? ex) admin 0001_initial only -
Azure web app Error during WebSocket handshake
I am building a web app that uses web sockets , it is running just fine offline , but when hosted online on azure , it returns , if i am using port 443 failed: Error during WebSocket handshake: Unexpected response code: 302 or if i am using any other port (8080 , ...) failed: Error in connection establishment: net::ERR_CONNECTION_TIMED_OUT I have tried solutions like websockets connection does time out but with no success so far , in my azure account i have enabled websocekts and added * in cors the problem occurs when i write in my jaavscript $(document).ready(function(){ var socket = new WebSocket('wss://mywebsiteonazure.azurewebsites.net:443/chat/'); socket.onopen = websocket_welcome; ... ... -
Prompt auth (request.user) for password again before saving in Django admin
I'd like to prompt an auth user in Django admin to enter their password to verify it matches before saving a model (using save_model override). I thought this would be something simple to do, but can't find any documentation or threads on this. Thanks in advance. -
how to convert pdf file to Excel file using Django
I am trying to convert pdf file to Excel using Django, please anyone can please how to convert pdf to excel. I am trying, but the format does not working properly. -
How to integrate Django server with Nodejs SocketIO server
Im finding a solution in integrate Client, Django and NodeJS. My task is building a server which user can message to each other. I have 2 solutions: From Client send request to Django server. Django server will create Message in Database and push a notification to NodeJS server(SocketIO), then Client will get change from NodeJs server. With this solution, I want to ask how can I push request socket from Django to Node? From Client send request to Socket server. Socket server will create Message in Database, then send it to Client. This solution is good or bad? Need improved? I really need a solution to work. Please help me if your guys have experience! Thanks in advance! -
Cant render Objects and a Form in a CreateView class Django
I'm simply trying to render objects and a form with a Create view class. Whenever my page loads it renders the objects or the form but not both at the same time. Is There any way of doing that? Heres my code. Hopefully, I provided enough information urls.py - views.py - html template or file - models.py (if needed) - And The Page: