Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Do i have to install django again when i create a new project directory?
I am setting up a new project. I have installed virtual environment. But Do I have to install django again in that directory?? -
Django get client computer user name in view.py
To simplify my question. Client Computer Hostname = MyPC_011 Client Computer logged in username = user-A In views.py I want to use client machine logged in username(user-A) when user access django website page. This is my view.py def home_view(request): # Get IP address of client computer client_ip = request.META.get('REMOTE_ADDR') # Get Host Name of client computer client_host = request.META.get('REMOTE_HOST') return render(request, 'index.html') I get IP address by REMOTE_ADDR, REMOTE_HOST is empty, USER and USERNAME display server username. 'GATEWAY_INTERFACE': 'CGI/1.1', 'SERVER_PORT': '8000', 'REMOTE_HOST': '', 'CONTENT_LENGTH': '', 'SCRIPT_NAME': '', 'SERVER_PROTOCOL': 'HTTP/1.1', 'SERVER_SOFTWARE': 'WSGIServer/0.2', 'REQUEST_METHOD': 'GET', 'PATH_INFO': '/', 'QUERY_STRING': '', 'REMOTE_ADDR': '192.168.5.107', ' How to get client machine logged in username when user access django website page? -
Bind two models
I need something like this: class Group(models.Model): id = models.IntegerField(primary_key=True) name = models.TextField() torrents = # Link to torrents in group class Torrent(models.Model): id = models.IntegerField(primary_key=True) group = # Link to group name = models.TextField() hash = models.TextField(max_length=32) file = models.FileField(blank=True, null=True) and next in code: group = Group.objects.create(id=123, name="Test group") # some code... Torrent.objects.create(id=321, group=group, name="Test torrent", hash="hash") then: Torrent.objects.get(id=321).group.torrents.all() What I need to use? ForeginKey in Torrent to group and ManyToMany in Groups to torrents? -
How to get the next day's date in django.utils.timezone
I want to set the status of a task as due today, due tomorrow, overdue or upcoming if the date that the task is due on is today, yesterday (or before that) or tomorrow (or after tomorrow) This is what I do to compare today : if (timezone.now().date == k["due_on"].date) : task.status = "due today" I want to write similar logics for future or past something like this: if (k["due_on"].date == tomorrow) : task.status = "due tomorrow" and so on. Please help -
How to customize error messages in django rest framework?
How to customize error messages in django rest framework? I'm trying to do it clean. Without much code. But this is what I'm trying to do, it does not work. Thank you in advance for your attention. from rest_framework import serializers class serializerVenda(serializers.Serializer): tipo = serializers.CharField() amount = serializers.CharField( error_messages={ "required": "Amount cannot be empty." }) -
How to fill up a Django Field in a form which is dependent on another django dropdown value using AJAX?
I have a Django Form in which there is a dropdown field using ModelChoiceField in forms.py for the field which is retrieving data from a model's attribute. I want to pass the data through AJAX to my views and query another field's value using the data through Ajax. And send it back to the template such that this value should be automatically filled in another field of the same form. I am able to get data through the views and query from the desired model too. What should I do next to get the queried data to be placed onto the field in the form? I have already tried using this blog: https://simpleisbetterthancomplex.com/tutorial/2018/01/29/how-to-implement-dependent-or-chained-dropdown-list-with-django.html But, he provides a method for using it for 2 dependent dropdowns and I tinkered the code according to my requirements but didn't work out. I also tried getting the value of dropdown through console but it doesn't show in the console whereas all the other input type fields show the value in the console. So, I am not sure whether the data of dropdown is getting through AJAX or not. Should the data of dropdown be visible in the console or not? AJAX of form_template.html {% … -
How to filter data displayed in a table in django?
I have a project where when a user enters a vehicle no, the database is filtered and a table containing that vehicle no and the information corresponding to is displayed. I further want to filter this displayed table, eg: if the user chooses to see quantity greater than 18kl, then the matching vehicle number with quantity greater than 18 is displayed. Also I want to hide the columns selected by the users as there are many columns. Can someone tell me how to do this in django, or suggest some better ways. (I am providing only the related code snippet.) forms.py class VehicleSearch(forms.Form): vehicl[![enter image description here][1]][1]e_no = forms.CharField(widget=forms.TextInput(attrs={'class': 'special'}), required=False) #filter form class Filter(forms.Form): capacity_grp = forms.ChoiceField(label='Show only', widget=forms.RadioSelect, choices=[('abv', '>18 kl'), ('blw', '<18 kl')], required=False) views.py def search(request): form_1 = forms.VehicleSearch() if request.method == 'POST' and 'btnform1' in request.POST: form_1 = forms.VehicleSearch(request.POST) if form_1.is_valid(): vehicle_no = form_1.cleaned_data['vehicle_no'] transport = models.Transport.objects.filter(vehicle=vehicle_no) my_dict.update({'transport': transport}) return render(request, 'search.html', my_dict) search.html /Vehicle form/ <form id="f1" method="POST"> {% csrf_token %} {{form_1.as_p}} <p style="padding: 10px;"><button class="myButton" name="btnform1">Search</button></p> </form> /*Table display*/ <div class="submain"> {% if transport %} <table id="transportation"> <thead> <th>Vehicle</th> <th>Carrier</th> <th>Location No</th> <th>MCMU</th> <th>Location</th> <th>Customer Code</th> <th>Zone</th> <th>Quantity</th> <th>RTKM</th> <th>KL* KM</th> <th>Amount</th> <th>Load</th> … -
Can we restrict any group to see search and filter option of user section in django admin?
I know how to apply search fields and filtering options in django admin but I want to allow them to only specific groups , any suggestion please...?? I have following code in my userAdmin. class UserAdmin(admin.ModelAdmin): list_display('username','department','dob','employee_id','email') search_fields = ('username','department','employee_id','email') list_filter = ('department',) -
Django how do I delete pictures on the server if the image on ckeditor is deleted
I have uploaded some images within the CKEditor, and uploaded images are stored on the server, when I delete the image on the editor, the image stored on the server is not deleted. Django 2.2, python 3.7, postgresql. my question: can I set it on ckeditor or on models? if can how to create a condition when the upload image is automatically deleted when removed on ckeditor? -
docker-compose , PermissionError: [Errno 13] Permission denied: '/manage.py'
After doing many research I didn't found any solution worked for me. I am trying to run command in docker-composer to start project with django-admin docker-compose run app sh -c "django-admin startproject app ." Every time I am getting the error: Traceback (most recent call last): File "/usr/local/bin/django-admin", line 10, in <module> sys.exit(execute_from_command_line()) File "/usr/local/lib/python3.7/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.7/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python3.7/site-packages/django/core/management/base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python3.7/site-packages/django/core/management/base.py", line 364, in execute output = self.handle(*args, **options) File "/usr/local/lib/python3.7/site-packages/django/core/management/commands/startproject.py", line 20, in handle super().handle('project', project_name, target, **options) File "/usr/local/lib/python3.7/site-packages/django/core/management/templates.py", line 155, in handle with open(new_path, 'w', encoding='utf-8') as new_file: PermissionError: [Errno 13] Permission denied: '/manage.py' My docker file FROM python:3.7-alpine MAINTAINER anubrij chandra ENV PYTHONUNBUFFERED 1 COPY ./requirements.txt /requirements.txt RUN pip install -r /requirements.txt RUN mkdir /app COPY ./app /app RUN adduser -D dockuser USER dockuser My docker-compose.yml version: "3" services: app: build: context: . ports: - "8000:8000" volumes: - ./app:/app command: > sh -c "python manage.py runserver 0.0.0.0:8000" I applied solution suggested in but it didn't worked [PermissionError: [Errno 13] Permission denied: '/code/manage.py' Ubuntu version : Distributor ID: Ubuntu Description: Ubuntu 18.04 LTS Release: 18.04 Codename: bionic -
How To Import CSV data in a product base application in django
I am working a product base application , where a master table name is "Product" and also some specific product tables. The Master Product Table related to other table by foreign key. Basically all the common attribute of products is belong to Master product table and specific attributes belongs to their own tables. So I want to upload data in tables by CSV files . So how to upload data from one CSV file to Multiple Tables ? -
Correct Offset on Canvas
I am attempting to draw on an HTML5 Canvas using some JavaScript from a PubNub tutorial. Currently the cursor will only draw on the canvas in the right position if the canvas covers the entire page, or in other words if it is at (0,0). It seems to be an issue with calculating the offest, and I have tried writing various offset variables into my code, but I have had no luck. Here is what I've currently got Javascript (function() { var canvas = document.getElementById('drawCanvas'); var ctx = canvas.getContext('2d'); var color = document.querySelector(':checked').getAttribute('data-color'); canvas.width = Math.min(document.documentElement.clientWidth, window.innerWidth || 300); canvas.height = Math.min(document.documentElement.clientHeight, window.innerHeight || 300); ctx.strokeStyle = color; ctx.lineWidth = '10'; ctx.lineCap = ctx.lineJoin = 'round'; document.getElementById('colorSwatch').addEventListener('click', function() { color = document.querySelector(':checked').getAttribute('data-color'); }, false); var isTouchSupported = 'ontouchstart' in window; var isPointerSupported = navigator.pointerEnabled; var isMSPointerSupported = navigator.msPointerEnabled; var downEvent = isTouchSupported ? 'touchstart' : (isPointerSupported ? 'pointerdown' : (isMSPointerSupported ? 'MSPointerDown' : 'mousedown')); var moveEvent = isTouchSupported ? 'touchmove' : (isPointerSupported ? 'pointermove' : (isMSPointerSupported ? 'MSPointerMove' : 'mousemove')); var upEvent = isTouchSupported ? 'touchend' : (isPointerSupported ? 'pointerup' : (isMSPointerSupported ? 'MSPointerUp' : 'mouseup')); canvas.addEventListener(downEvent, startDraw, false); canvas.addEventListener(moveEvent, draw, false); canvas.addEventListener(upEvent, endDraw, false); function drawOnCanvas(color, plots) { ctx.strokeStyle … -
How to upload and save image files manually on Graphene?
I am trying to upload and save image files using Django Graphene and axios. I uploaded files with no problem. I confirmed that files were transferred to the Django server. The problem is the image files do not get saved on the Django server. I uploaded images like const formData = new FormData(); const query = `...' formData.append('query', query); this.state.contents.map((content, index) => { formData.append('images['+index+']', { uri: content.image.uri, type: 'image/jpeg', name: 'image' + index + 'jpeg', }) await axios({ data: formData, I tried three ways to upload images. for file in info.context.FILES: image = models.Image(post=post, file=file) image.save() In this way, I can save Image models, but image files are nowhere. I tried to save the image files using a form. for file in info.context.FILES: form = forms.ImageForm(initial={'file': file, 'post': post}) if form.is_valid(): form.save() This invokes an error stating "Select a valid choice. That choice is not one of the available choices" I tried to save it with a formset as well. data = { 'images-TOTAL_FORMS': str(len(info.context.FILES)), 'images-INITIAL_FORMS': '0', 'images-MAX_NUM_FORMS': '10', } formset = forms.ImageFormSet(data, info.context.FILES, instance=post) if formset.is_valid(): formset.save() This formset just returns an empty formset and it does not save any data. How to upload and save image files manually … -
Creating a simple python calculation to show in the admin panel on a specific object record
I'm fairly new to python and am working on a new django project and want to display calculations in the admin panel for specific records, using the record data. This would also be replicated on the user interface (which is not built yet). I have learned the basic storing and manipulating of variables for other calculations made from basic user input. This is a little different as it is done within the admin panel. I am using PyCharm but PyCharm is telling me there are errors. I also used the link here to see if I could get this to work: https://www.reddit.com/r/django/comments/6xigr3/how_to_show_calculated_field_in_django_admin/ I realize the code below is not correct, but am also not sure if i'm referencing the variables correctly to access them from within the main function? How does defining this function change when used in the admin panel vs. the user interface? Thank you for any help on any questions above! # Create a class to calculate the volume by first converting inches to ft, then to cubic yd class Volume(models.Model): linear_ft = models.DecimalField('Length in feet: ', max_digits=200, decimal_places=2) depth_in = models.DecimalField('Depth in inches: ', max_digits=200, decimal_places=2) width_in = models.DecimalField('Width in inches: ', max_digits=200, decimal_places=2) # Convert … -
How do I know if Amazon successfully sent the email
In my django project, I am sending emails using Amazon-ses and some of the emails I have to send are critical. In this case I want to make sure that my email has been sent successfully, so that if not sent, I can resend it. Is there any way for me to know if the email was sent successfully? -
How to use django server work with Angular Universal to render the first page
https://angular.io/guide/universal I've read this. The example is for node express. I'm using django server, how to work with angular universal to render the first page. -
Success_url in Django
I'm new to Django(version 2.2.2) and could use some help. I'm creating a very simple webpage which includes a form. I included a success_url property when creating a CreateView for the form in the views.py file. Once a user inputs the details and clicks on submit, it'll redirect them to the homepage. Everything seems to work well except the success_url. It won't redirect to the homepage and instead, causes an error. Does anyone know how to do this? Student model in models.py: from django.db import models class Student(models.Model): name = models.CharField(max_length = 25) age = models.IntegerField() email = models.EmailField() created_date = models.DateTimeField(auto_now = True) def __str__(self): return self.name views.py: from django.shortcuts import render from django.views.generic import CreateView from app.forms import StudentForm class StudentView(CreateView): template_name = 'create_student.html' form_class = StudentForm success_url = '/home/' app.urls file: from django.urls import path from app.views import StudentView urlpatterns = [ path('create_student', StudentView.as_view(), name = 'create_student'), ] project.urls file: from django.contrib import admin from django.urls import include, path urlpatterns = [ path('admin/', admin.site.urls), path('', include('app.urls')), ] HTML file: <form method="POST"> {% csrf_token %} {{form.as_p}} <button> Submit </button> </form> -
Django mod wsgi on wamp internal server error
Actually I have successfully Installed the mod_wsgi on windows but when I add some config on httpd.conf file on apache Error occurs. LoadFile "c:/programdata/anaconda3/python37.dll" LoadModule wsgi_module "c:/programdata/anaconda3/lib/site-packages/mod_wsgi/server/mod_wsgi.cp37-win_amd64.pyd" WSGIPythonHome "c:/programdata/anaconda3" and in my httpd.conf file: LoadModule wsgi_module "c:/programdata/anaconda3/lib/site-packages/mod_wsgi/server/mod_wsgi.cp37-win_amd64.pyd" WSGIScriptAlias / "C:/Users/MyUser/Documents/MyFirstDjangoProj/student_management_system/student_management_sys/student_management_sys/wsgi.py" WSGIPythonHome "c:/programdata/anaconda3" WSGIPythonPath "C:/Users/MyUser/Documents/MyFirstDjangoProj/student_management_system/student_management_sys" Require all granted Require all granted Require all granted -
How to receive two or more forms in a function in django
As the title says, i am working with two forms in a template. And i was wondering if there is a way to send two or more forms to save it to the function. Becuase i dont know how can i "detect" the correct form that has to save. This is my two forms: Form 1 from the 'enterprise'instance <form method="POST" action='' enctype="multipart/form-data"> {% csrf_token %} <h4><strong>Datos de empresa:</strong></h4> <!--Foto del miembro de equipo--> <h6><strong>Subir logo:</strong></h6> <input type="file" name="image_path"> <!--Full name--> <div class="form-group row"> <div class="col-sm-6 mb-3 mb-sm-0"> <strong>Nombre de empresa:</strong> </div> <div class="col-sm-6 mb-3 mb-sm-0"> <strong>Número de teléfono:</strong> </div> <div class="col-sm-6 mb-3 mb-sm-0"> <input class= "form-control" type="text" name="name" maxlength="20" value="{{enterprise.name}}"> </div> <div class="col-sm-6"> <input class= "form-control" type="tel" pattern="[0-9]{4}-[0-9]{3}-[0-9]{4}" name="phone_number" value="{{enterprise.phone_number}}"> </div> </div> <!--Username and email is same in this case--> <strong>Correo electrónico:</strong> <div class="form-group"> <input class= "form-control" type="email" name="email" value="{{enterprise.email}}" > </div> <!--Date of birth--> <strong>Fecha de fundación:</strong> <div class="form-group"> <input class= "form-control" type="date" name="date" value="{{enterprise.date}}" > </div> <!--Direction--> <strong>Dirección:</strong> <div class="form-group"> <textarea class= "form-control" rows="6" name="direction" value="{{enterprise.direction}}">{{enterprise.direction}}</textarea> </div> <!--Description--> <strong>Descripción de empresa:</strong> <div class="form-group"> <textarea class="form-control" rows="6" type="text" name="description" value="{{enterprise.description}}">{{enterprise.description}}</textarea> </div> <!--Employees--> <strong>Número de empleados (aproximado):</strong> <div class="form-group"> <input class= "form-control" type="number" name="employees" min=1 value="{{enterprise.employees}}"> </div> <!--Button--> <hr> … -
Importing data from google api to my database
I need to create view which import data from google books api and save in my model, I have no Idea how to do this in Django. For now I have this view but I don't know if this is good and what's next def book_search(self, request): value = input() apikey = input() params = {'q': value, 'key': apikey} response = request.get('https://www.googleapis.com/books/v1/volumes', params=params) bookapi = response.json() -
How can I get extra data from a linkedin profile?
I'm using social-auth-app-django to implement the login with social networks, but I'm looking for profile information, such as: photo, email, etc! I already set up my settings but I can't get the information! SOCIAL_AUTH_LINKEDIN_OAUTH2_KEY ='' SOCIAL_AUTH_LINKEDIN_OAUTH2_SECRET = '' SOCIAL_AUTH_LINKEDIN_OAUTH2_SCOPE = ['r_basicprofile', 'r_emailaddress'] # These fields be requested from linkedin. SOCIAL_AUTH_LINKEDIN_OAUTH2_FIELD_SELECTORS = [ 'email-address', 'picture-url', ] SOCIAL_AUTH_LINKEDIN_OAUTH2_EXTRA_DATA = [ ('id', 'id'), ('firstName', 'first_name'), ('lastName', 'last_name'), ('emailAddress', 'email_address'), ('public-profile-url', 'public_profile_url'), ('pictureUrl', 'picture_url'), ] This is the result: "email_address": null, "public_profile_url": null, "picture_url": null, Thank you! -
Retrofit post cannot successfully send json data to django server
Everyone, I recently developing a server-client system, in server side, I use django and restframework to interact with android applications. In client side, I use android and retrofit to send and get data from server.When I Get data from server, everything is fine, But when I try to post data from android to django, It has some errors. Specifically, It successfully post data to server but doesnot shown in django views. I first use postman to test if I can post data to the URL http://192.168.*.**:8001/api/output and it works, But When I use android application to send post data to http://192.168.*.**:8001/api/output, it can also post successfully Here are my django server code class OutputInfoView(ModelViewSet): serializer_class = OutPutInfoSerializer def get_queryset(self): return models.OutputInfo.objects.all() class OutPutInfoSerializer(serializers.ModelSerializer): class Meta: model = models.OutputInfo fields = ['id', 'user', 'lx', 'ly', 'room', 'activity', 'sound'] # router url routers = routers.DefaultRouter() routers.register(r'output', views.OutputInfoView,basename='OutputInfo') urlpatterns = [ path('', include(routers.urls)) # path('output', views.OutputInfoView.as_view(), name='output'), ] In my android client, I user retrofit to post data: public interface JsonPlaceHolderAPI { @Headers({"Content-Type: application/json"}) @POST("output") Call<List<Sender>> createUser(@Body RequestBody body); } This is the main activity loading HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(); loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY); OkHttpClient okHttpClient = new OkHttpClient.Builder() .addInterceptor(loggingInterceptor) .build(); Retrofit retrofit = new … -
How to populate a model at the end of the user registration
I have the model 'AuthCustomUser(AbstractUser)' for the registration of a new user. In it will be saved the necessary data for the login, for example: name, email and password. On the other hand, I have the model 'MetaUser (models.Model)' that I will use for the additional information of the user, for example: address, telephone, etc. I want to create a relationship between both models at the moment of the end of the registration by the user. In the model 'MetaUser(models.Model)' I have a foreign key: 'user = models.ForeignKey (settings.AUTH_USER_MODEL, on_delete = models.CASCADE)' When the user is registered the data will be entered in the model 'AuthCustomUser (AbstractUser)', then I want to insert the user's 'ID' in the model 'MetaUser (models.Model)' to make the relation of the foreign key between both Models. Finally, the user will start session immediately after finishing his registration, and he will be given access to the home.html. These are my models: class MetaUser(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) screen_orientation = models.CharField(default='landscape', max_length=9) def __str__(self): return self.name class AuthCustomUser(AbstractUser): def __str__(self): return self.name And you are my view of the registry: class SignUp(generic.CreateView): form_class = CustomUserCreationForm success_url = reverse_lazy('login') template_name = 'signup.html' def form_valid(self, form): form.save() username = … -
How build filter with ForeignKey related_name field
I need to write view with FilterSet and everything was fine until searchfileds were in one model but when I'm trying to add related to field I'm getting:AttributeError: 'ManyToOneRel' object has no attribute 'get_transform'. How can I add related to field to my filter? My filter: class BookFilter(FilterSet): class Meta: model = Book fields = { 'title': ['icontains', ], 'authors': ['icontains', ], 'published_date': ['iexact', ], 'language': ['iexact', ], 'industry_identifiers': ['icontains', ], } My Models: class Book(models.Model): title = models.CharField(max_length=75, verbose_name='Book title') authors = models.CharField(max_length=150, verbose_name='Authors') published_date = models.IntegerField( validators=[validate_book_published_date, max_year_validator], verbose_name='Publishing date') pages = models.CharField(max_length=4, verbose_name='Number of pages') language = models.CharField(max_length=2, verbose_name='Language') image = models.URLField(verbose_name='Image', default=None, blank=True) class Meta: ordering = ('title',) def __str__(self): return f'{self.title} written by {self.authors}' class IndustryIdentifiers(models.Model): type = models.CharField(max_length=25, verbose_name='Type') identifier = models.CharField(max_length=25, verbose_name='Identifier') book = models.ForeignKey(Book, on_delete=models.CASCADE, verbose_name='Book', related_name='industry_identifiers') def __str__(self): return f'{self.type}: {self.identifier}' -
How to retrieve input data from one form to another form in Django?
I am trying to create an app which create an user with unique id using forms and add that user to a data table . I need to retrieve the field input data from previous form to new form with some new fields related to that user and give another unique id to that user with other data table I am beginner in Django , I have done couple of online bootcamps . I have search my problem online on many platforms but didn't got expected result . maybe I am not getting right term to represent my problem.