Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
DRF object with slug_field="" doesn't exist
I'm creating a very simple api with drf and that's my problem: I have this code in serializers.py: class PostSerializer(serializers.ModelSerializer): comments = serializers.SlugRelatedField( queryset= Comment.objects.all(), many= True, slug_field='body' ) class Meta: model = Post fields = ['pk', 'user', 'title', 'content', 'comments', ] read_only_fields = ['pk', 'user'] When l open api/1 in my browser l get this as expected: { "pk": 1, "user": 1, "title": "Lorem", "content": "First post", "comments": [ "My Comment", "Second Comment" ] } When l try to update this with PUT method all fields work fine, except comments, when l try to add a new one it gives me this error: { "comments": [ "Object with body=my new comment does not exist." ] } How do l solve that, so when l add a new comment it's get pushed to db? -
I use bootstarp navbar. When I scroll up.. the block content appear behind the navbar. Navbar fixed on the top
I use bootstarp navbar. When I scroll up.. the block content appear behind the navbar. Navbar fixed on the top. My Navbar <main id="navfix" class="m-5"> <nav class="navabar_bgc py-0 navbar navbar-expand navbar-light fixed-top"> {% include 'sidebar.html' %} <div class="collapse navbar-collapse" id="collapsibleNavId"> <ul class="navbar-nav ml-auto mt-lg-0"> <div>...</div> </ul> </div> </nav> </main> <div class="block__content"> {% block content %} {% endblock %} </div> My css: #navfix { width: 100%; } .navabar_bgc { background-color: rgba(103, 250, 34, 0.4) !important; box-shadow: 0px 0px 8px !important; z-index: 10 !important; } .block__content { z-index: 5; overflow: auto; } Any other suggestion please give me..Thanks. -
how to link to search results in pagination Django 3.1
I want to implement pagination on the search results page of my site. My Django project has a few apps that have different models and the search will look in every table for results. for ex.: # views.py def search(request): queryset_list_ip_sensor = Ip_sensor.objects.all() queryset_list = ControlValves.objects.all() queryset_list_water_quality_sensor = Water_quality_sensor.objects.all() context = { 'ip_sensors': result_list_ip_sensor, 'controlvalves': result_list_control_valves_2, 'water_quality_sensor': result_list_water_quality_sensor, 'values': request.GET, 'keywords': keywords } return render(request, 'pages/search.html', context) I implemented pagination like this: # views.py def search(request): # ... result = (result_list_ip_sensor, result_list_control_valves, result_list_water_quality_sensor) paginator = Paginator(result, 1) page = request.GET.get('page') paged_queries = paginator.get_page(page) context_pagination = {'ip_sensors': result_list_ip_sensor, 'controlvalves': result_list_control_valves_2, 'water_quality_sensor': result_list_water_quality_sensor, 'queries': paged_queries, 'keywords': keywords, 'values': request.GET } return render(request, 'pages/search.html', context_pagination) Before pagination I used to show results like this: {% if ip_sensors %} {% for ip_sensor in ip_sensors %} <div class="col-12 col-sm-12 col-md-4 col-lg-4 col-xl-4 mb-4"> <div class="card"> <div class="card-header"> I/P Sensor </div> <img class="card-img-top" src="{{ ip_sensor.cover.url }}" alt=""> <div class="card-body"> <div class="text-center"> <h4 class="text-dark">{{ ip_sensor.title }}</h4> <p> {{ ip_sensor.description | truncatewords:10 }}</p> </div> <hr> <div class="row py-2 text-dark"> <div class="col-6"> Product Name: {{ ip_sensor.product_name | truncatewords:2 }}</div> <div class="col-6"> Usage: {{ ip_sensor.usage | truncatewords:4}}</div> </div> <hr> <a href="{% url 'ip_sensor_item' ip_sensor.title %}" class="btn btn-light btn-block">More Info</a> </div> … -
How to play a generated mp3 on the user's browser?
My django view.py generates an mp3 file on the server at ./speech.mp3 after user interaction. How do I play it on the user's browser? If I just play the mp3 file using python code in view.py, it'll only be played on the server PC, not the user's browser. I'm thinking of 2 solutions: Either I have to pass the mp3 to the user's browser through ajax OR upload it to a cloud service. Not sure how to approach though. -
Django : Tables in SQL duplicates
I'm trying to migrate my migrations and I get those weird duplicated tables inside my SQL database. I have used Meta class for all my models to change their names inside the database: class Meta: db_table = 'User_Computer_Knowledge' I have two apps (accounts - for authentication and else, main - for all other things) Pastebin links: My whole accounts model My whole main model After migrating I get these results : What's the problem? -
Django limit user view rights for model object
I have an app with multiple users from different companies. I need to restrict access such that certain users from certain companies can only see model objets relevant to their company. For e.g. when I display a drop-down in a template, I want the dropdown contents to be different for each user based on their predefined permissions. I am not a developer so I may be reading the Django documentation poorly, but if I were to guess it doesn't seem possible. If indeed it is not straight forward via Django built-ins, is there any clever workaround? -
Bootstrap DatePickerPlus Format Doesn't Change
I am using Bootstrap DatePickerPlus and although I'm setting the format to DD/MM/YYYY, the form is often failing validation with the error Enter a valid date/time as it is trying to validate as MM/DD/YY. For example, 23/02/2020 will fail, but 02/23/2020 will pass. I have tried many things but the stuff I have tried seems to be for Django's DatePicker, not Bootstrap's DatePickerPlus. Any help would be greatly appreciated. models.py date = models.DateTimeField('Date (dd/mm/yyyy)', default=now) forms.py class Meta: model = Booking fields = '__all__' widgets = { 'date': DatePickerInput( options={ "format": "DD/MM/YYYY", "showClose": False, "showClear": False, "showTodayButton": False, } ), } Thank you. -
Error during WebSocket handshake: Unexpected response code: 400-ReactJs and django socket.io
I've a django socketio as server and reactjs as client django server wsgi.py import os from django.core.wsgi import get_wsgi_application from app.views import sio import socketio os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'quantsite.settings') django_app = get_wsgi_application() application = socketio.WSGIApp(sio, django_app) views.py import os from django.http import HttpResponse import socketio async def index(request): return web.Response(text="hello", content_type='text/html') @sio.event async def connect(sid, environ): print('Client connected',sid) await sio.emit('message', "good") @sio.event async def disconnect(sid): print('Client disconnected',sid) @sio.on('message') async def message(sid, data): print("server received message!", data) await sio.emit('reply', data) Client side-Reactjs import io from 'socket.io-client'; let socket ; componentDidMount() { socket=io('localhost:8000',{transports:['websocket']}); socket.on('connect', ()=> { console.log("connected"); // true }); socket.on('message', function(msg){console.log('message!', msg)}); socket.on('reply', function(msg){console.log('reply!', msg)}); socket.on('disconnect', () => { console.log(socket.connected); // false }); } When i'm running both cilent and server,i'm getting error WebSocket connection to 'ws://localhost:8000/socket.io/?EIO=3&transport=websocket' failed: Error during WebSocket handshake: Unexpected response code: 400 at client side and "GET /socket.io/?EIO=3&transport=websocket HTTP/1.1" 400 11 at server side socket.io-client verison-2.3.0 -
Django - accessing a stored excel file in Django model viewer
I am trying to access excel files through the django-admin model viewing portal. Each excel file is generated through a seperate algorithm, and is already in a directory called excel_stored each excel file is generated with an ID that corresponds to its model # in django. So it would be excel_%ID%.xlsx or excel_23.xlsx for example. I want my django FileField() to access the relevant excel file so that I can download it from my django admin portal, just like I can access my other model information (city name, time uploaded, etc). Here is a pseudo-code of what I'd want to do: My models.py would look like this excel = models.FileField() The process of saving would look like this create_excel() ### EXCEL WAS SAVED TO DIR: excel_stored ### save_excel = Model(excel = file.directory((os.path.join(BASE_DIR, 'lead/excel_stored/excel_%s.xlsx' %ID)) save_excel.save() Id then be able to download it like this https://i.stack.imgur.com/4HRUU.gif I know there's a lot I'm missing, but most documentation I find refers to uploading an excel file through forms, not accessing it. I've been stuck on this for a while, so I'd appreciate some direction! Thank you! -
"Visual" set up project page for django?
I would like to sell app to lot of people. The problem i got is, i don't want people have to set variable into settings.py file, because they have no knowledge into programmation. So i would like to know if it's possible to do this kind of stuff : They connect to the site on admin (or maybe just connect first time) That redirect them to a page with form They choose their settings and that update it directlty into settings.py Like that they will just set the project with a beautiful view, and they have no edition of settings.py to do manually. Thank for your help ! -
How to count Artist in ManyToMany Field in Django
i want to count the number of videos made by a single artist so please tell me where am i wrong? Here is My code in admin.py File class ArtistAdmin(admin.ModelAdmin): list_display = ['name', 'date_of_birth', 'artist_videos'] def artist_videos(self, obj): count = 0 for artistcount in Artist.objects.all(): if artistcount.name == VideoList.artists: count = count + 1 return count And her is my code in models.py class Artist(models.Model): name = models.CharField(max_length=200) date_of_birth = models.DateTimeField() def __str__(self): return self.name class VideoList(models.Model): title = models.CharField(max_length=200) artists = models.ManyToManyField(Artist) def __str__(self): return self.title -
How to save json in django database?
I need to save json file from API in database (postgresql) using django. I have classic model which extends the AbstractUser with the default fields for first name, last name and etc. I made a research but can't find how to achieve saved json from API in database while using django. I will appreciate any help or guide. -
Recieving errors when running server with manage.py
im trying to run a server on my laptop, when in the console i type 'python manage.py runserver' i recieve some errors. could it be i need to import some modules i tried 'pip install python-cron' but that didnt work. the error says: [2020-11-10 09:04:47,241] autoreload: INFO - Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/threading.py", line 932, in _bootstrap_inner self.run() File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/utils/autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/core/management/commands/runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/utils/autoreload.py", line 76, in raise_last_exception raise _exception[1] File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/core/management/__init__.py", line 357, in execute autoreload.check_errors(django.setup)() File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/utils/autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/apps/config.py", line 90, in create module = import_module(entry) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 973, in _find_and_load_unlocked ModuleNotFoundError: No module named 'django_cron' the cron.py file i have is: from django.contrib.auth.models import User import os import datetime from crontab import CronTab #from django_common.helper import send_mail from … -
How to configure Geonode's geoserver on my ubuntu server using nginx
I have configured geonode and it is working fine on my local machine. I have proceeded to move it to an ubuntu server and I am using Nginx and gunicorn. I am having a challenge in starting my GeoServer on this URL 'geonode1.local.com/geoserver where I get the error below in my error.log: 2020/11/10 07:36:38 [error] 825#825: *7 "/usr/share/nginx/html/geoserver/web/index.html" is not found (2: No such file or directory), client: 197.232.113.55, server: geonode1.local.com, request: "GET /geoserver/web/ HTTP/1.1", host: "geonode1.local.com" my question: How do I get GeoServer to start on this URL? Do I need to install tomcat9 on my server? /etc/nginx/sites-available/geonode server { listen 80; server_name geonode1.local.com; location = /favicon.ico { access_log off; log_not_found off; } location ^~ /static/ { alias /home/user/Geosites/geonode/static/; } location ^~ /uploaded/ { alias /home/user/Geosites/geonode/uploaded/; } location /geoserver/ { proxy_set_header Host $http_host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; } # gunicorn wsgi proxy location / { proxy_pass http://unix:/run/gunicorn.sock; proxy_pass_header Server; proxy_set_header Host $http_host; proxy_redirect off; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Scheme $scheme; proxy_connect_timeout 20; proxy_read_timeout 20; } location ^~ /static/admin/ { alias /home/user/Geosites/geosite_env/lib/python3.6/site-packages/django/contrib/admin/static/admin/ } } -
default integer value for non-primary field in django with postgresql
I have a non-primary key integer field in my Django model and I use Postgresql for database. class TestModel(models.Model) pid = models.IntegerField(blank=True) some_field = models.CharField() I want my pid field to have default values, that appear in database, I set the serial type for the pid field on the DB side alter column pid type serial not null; but when I create some record without without specifying value for pid, Django gives an error "null value in column "pid" violates not-null constraint", although it works fine when inserting data via SQL directly into database. I found this Django and PostgreSQL sequence for primary key autoincrement, but it's not working for me -
How to query ManyToManyField linked with a Foreign Key and that Foreign Key is linked with another Foreign Key?
I have created a TimeTable model that is linked to the Period Model via ManyToManyField and the Period Model is linked to the PeriodData via a Foreign Key. The models are working fine but I have very little idea of how to query the data. Here is the TimeTableModel - TimeTable Model class TimeTable(models.Model): class_id = models.OneToOneField(Classes, on_delete=models.CASCADE) monday = models.ManyToManyField('Period', related_name='monday', blank=True) tuesday = models.ManyToManyField('Period', related_name='tuesday', blank=True) wednesday = models.ManyToManyField('Period', related_name='wednesday', blank=True) thursday = models.ManyToManyField('Period', related_name='thursday', blank=True) friday = models.ManyToManyField('Period', related_name='friday', blank=True) saturday = models.ManyToManyField('Period', related_name='saturday', blank=True) Period Model class Period(models.Model): period_id = models.CharField(unique=True, max_length=50) class_id = models.ForeignKey(Classes, on_delete=models.CASCADE) period1 = models.ForeignKey('PeriodData', related_name='period1', blank=True, null=True, on_delete=models.CASCADE) period2 = models.ForeignKey('PeriodData', related_name='period2', blank=True, null=True, on_delete=models.CASCADE) period3 = models.ForeignKey('PeriodData', related_name='period3', blank=True, null=True, on_delete=models.CASCADE) period4 = models.ForeignKey('PeriodData', related_name='period4', blank=True, null=True, on_delete=models.CASCADE) period5 = models.ForeignKey('PeriodData', related_name='period5', blank=True, null=True, on_delete=models.CASCADE) PeriodData Model class PeriodData(models.Model): period_data_id = models.CharField(unique=True, max_length=50) class_id = models.ForeignKey(Classes, on_delete=models.CASCADE) subject_id = models.ForeignKey(Subject, null=True, on_delete=models.SET_NULL) teacher = models.ForeignKey(Teacher, null=True, on_delete=models.SET_NULL) start_time = models.TimeField() end_time = models.TimeField() Let's say that there is a class1 and on monday it has maths as its period1 and bio as its period2 and so on. And there's another class2 and on monday it has physics as its period1 … -
django digitalocean deploy cannot serve static files
[![enter image description here][1]][1]I try to deploy my app on digitalocean, when i configure the ngnix server, everything works except all the css and js file are not being served. I have done collectstatic, and my /etc/nginx/sites-available looks like this server { listen 80; server_name my ip; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/djangodeploy/portfolio-blog; } location /media/ { root /home/djangodeploy/portfolio-blog; } location / { include proxy_params; proxy_pass http://unix:/home/djangodeploy/portfolio-blog/mysite.sock; } } and my file structure looks like this [1]: https://i.stack.imgur.com/sg34k.png -
Convert datetime.date to django compatible date
I am reading data from an excel file and the date is being read in the following format: 'Date': datetime.date(2020, 2, 3) #yyyy-mm-dd whereas the Django allows the following date format: date: "2020-02-03T06:06:39.548Z" How can I convert the datetime.date to the compatible date format ? -
Unit Testing in Python Djnago
I am using Django==3.0.3 djangorestframework==3.11.0 python ==3.6.8 I want to write unit testing for API and no need to use any database(no need of mock database) that mean I want to mock the database call and write unit test cases how can i write which property is used for this Showing my api @api_view(['POST']) @permission_classes([IsAuthenticated]) def employee_entry(request): try: login = User.objects.get(pk=request.user.id) validationmsg = '' emp_data = request.data if not emp_data: validationmsg = validation["FDP15"] elif emp_data["EmployeeName"] is None or emp_data["EmployeeName"] == '': validationmsg = validation["FDP1"] elif emp_data["EmployeeCode"] is None or emp_data["EmployeeCode"] == '': validationmsg = validation["FDP2"] elif Employee.objects.filter(EmployeeCode=emp_data["EmployeeCode"]).count() > 0: validationmsg = validation["FDP3"] if validationmsg != '': return Response({msg: validationmsg}, status=status.HTTP_400_BAD_REQUEST) employee = Employee( EmployeeName=emp_data["EmployeeName"], EmployeeCode=emp_data["EmployeeCode"], Security=emp_data["Security"], CreatedDate=date.today(), CreatedUser=login, ) employee.save() if emp_data["Security"] == 1: device = Device.objects.filter(~Q(DeviceStatus=static_values["const0"])) employee.Device.set(device) elif emp_data["Security"] == 0: device = Device.objects.filter(~Q(DeviceStatus=static_values["const0"]), DefaultAccess=True) employee.Device.set(device) return Response({"EmployeeId": employee.EmployeeId}, status=status.HTTP_200_OK) except(KeyError, TypeError, ValueError) as ex: logging.getLogger("error_logger").exception(repr(ex)) return Response({msg: validation["FDP21"]}, status=status.HTTP_400_BAD_REQUEST) except Exception as ex: logging.getLogger("error_logger").exception(repr(ex)) return Response({msg: validation["FDP23"]}, status=status.HTTP_400_BAD_REQUEST) -
Django form validation with FileField
I am having some trouble getting a file to post via a form using generic class-based view CreateView. Below is what i have so far. I am not quite sure how to handle the file and if request.FILES is getting the file being posted or if there is something else i need to be doing to capture the file information in the form. I have tried following the docs, however no luck in getting something working. File uploads as a blank field. views.py # Create class FileUploadCreateView(BSModalCreateView): template_name = 'fileupload/create-file.html' form_class = FileUploadModelForm success_message = 'Success: File was uploaded.' success_url = reverse_lazy('files_list') # Add required field my_user prior to posting form def form_valid(self, form): form = FileUploadModelForm(self.request.POST, self.request.FILES) self.object = form.save(commit=False) self.object.my_user = self.request.user self.object.file_status = 'ready' return super().form_valid(form) -
How to save search query result into the model with Django?
This is for revert/rollback the table. I have a query like this: query = Table.objects.all() it takes all entries in the Table. I will delete it later: Table.objects.all().delete() Now I want to save query into Table. How can I do that? -
Django failed to read static files from Azure Blog storage
Here is my application settings.py, command "python manage.py collectstatic" works fine and pushing static files to azure STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'dist', 'static'), ] STATICFILES_STORAGE ='backend.custom_azure.AzureStaticStorage' DEFAULT_FILE_STORAGE = 'backend.custom_azure.AzureMediaStorage' AZURE_ACCOUNT_NAME = os.environ['AZURE_ACCOUNT_NAME'] AZURE_ACCOUNT_KEY = os.environ['AZURE_ACCOUNT_KEY'] AZURE_CUSTOM_DOMAIN = os.environ['AZURE_CUSTOM_DOMAIN'] STATIC_LOCATION = 'static' STATIC_URL = f'http://xxxxxxxx.blob.core.windows.net/static/' AZURE_LOCATION = os.environ['AZURE_LOCATION'] AZURE_CONTAINER = os.environ['AZURE_CONTAINER'] MEDIA_LOCATION = "media" MEDIA_URL = f'https://{AZURE_CUSTOM_DOMAIN}/{MEDIA_LOCATION}/' While running the application server looking for the static files and fails, server looking for different path, I can see static files in Azure [10/Nov/2020 05:24:47] "GET /static/js/app.fa77985a.js HTTP/1.1" 404 77 [10/Nov/2020 05:24:47] "GET /static/css/chunk-vendors.102171f9.css HTTP/1.1" 404 77 [10/Nov/2020 05:24:47] "GET /static/css/app.0f5f9b8e.css HTTP/1.1" 404 77 [10/Nov/2020 05:24:47] "GET /static/js/chunk-vendors.56f4d0fa.js HTTP/1.1" 404 77 Following the doc available at https://medium.com/@DawlysD/django-using-azure-blob-storage-to-handle-static-media-assets-from-scratch-90cbbc7d56be -
How to get the object type and name on Django
I have this obj details on my Django context debug u'non_homepage_obj': <Organisation: text-org>, This is the context related to it 'non_homepage_obj': obj.primary_publisher, How to get the <Organisation: text-org> into string, which i can put the Organisation or the name of Organisation into use later on? I already tried str(obj.primary_publisher) but it's only get the text-org, and not passing the Organisation. Thanks -
Django Calculation inside HTML
I wanted to do something simmilar to this suing django. but somehow i it doesn't work. how do i fix it? for statik in statistik{ print(statik*total/100) } Is there any documentation regarding what I'm trying to implement to my django app? Thank you Here's the HTML : {% if statistics %} {% for statik in statistics|slice:":4" %} <div class="mb-3"> <div class="small text-gray-500">{{ statik.name }} <div class="small float-right"><b>{{ statik.voters }} of {{ total }} Voters</b></div> </div> <div class="progress" style="height: 12px;"> <div class="progress-bar bg-success" role="progressbar" style="width: {{ statik.voters * total/100 }}%" aria-valuenow="50" aria-valuemin="0" aria-valuemax="100"></div> </div> </div> {% endfor %} {% else %} <p>END TABLE</p> {% endif %} -
How do I query that spans multiple relationships?
Here's a simplified version of my model class: class BlogPost(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) content = models.TextField(blank=True, null=True) timestamp = models.DateTimeField(auto_now_add=True) class UserProfile(models.Model): user = models.OneToOneField(User, related_name = 'profile') first_name = models.CharField(max_length=120, blank=True, null=True) last_name = models.CharField(max_length=120, blank=True, null=True) following = models.ManyToManyField(User, related_name = 'followed_by', blank=True, through='FollowingRelation') class FollowingRelation(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) userprofile = models.ForeignKey(UserProfile, on_delete=models.CASCADE) timestamp = models.DateTimeField(auto_now_add=True) I'd like to query all rows from BlogPost that have been created by the session user, plus all other posts created by the users that the sessionUser is following, but has a timestamp greater than or equal to the timestamp when the session user started following.