Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Date field is not getting saved in the admin database
models.py class Add_Timelog(models.Model): project=models.ManyToManyField(Project) client=models.ManyToManyField(Client) Job=models.ManyToManyField(Add_Job) #Date = models.DateField(max_length=100 ,auto_now_add=True,editable=True) Date= models.DateField(default = datetime.date.today) Hours=models.TimeField(null=True) def __str__(self): return str(self.Date) settings.py DATE_INPUT_FORMATS = ('%Y-%m-%d') When I posted a date in the api for the date field it is getting posted. But when I look that in the admin database it is showing as '%' in the date field, and if I tried to change the entry it is getting stored as 'undefined' and while saving the entries it is throwing an error as "enter a valid date". kindly help me to resolve this issue. Attached the screenshot of admin for your reference. enter image description here -
Django admin log table is empty
tech geeks. Somehow my Superuser got deleted and some of my data is missing. To check whether somebody with superuser credentials did it. I wanted to check Django admin logs but when I checked the django_admin_log table it was empty. Can u guys tell me how can I check who deleted my data or a way to get back my data? -
Django view skips checking permission classes
I'm trying to filter lists according to: the user can work with all of their lists the user can use safe methods on public lists I have this code: In views.py: class LinkListViewSet(viewsets.ModelViewSet, generics.ListAPIView, generics.RetrieveAPIView): queryset = LinkList.objects.all() serializer_class = LinkListSerializer permission_classes = [IsOwnerOrPublic] In permissions.py: class IsOwnerOrPublic(BasePermission): def has_permission(self, request, view): return request.user and request.user.is_authenticated def has_object_permission(self, request, view, obj): return obj.owner == request.user or ( obj.public and (request.method in SAFE_METHODS)) The problem is, I believe the view just skips checking the permission classes and returns all lists, and I am not sure why, or how to fix it. -
what are the limitations of accessing an environment variable in cmd prompt
I have declared an environment variable named DB_PASSWORD in the windows command prompt, when I run echo %DB_PASSWORD% it returns the exact value I just set but when I run another command prompt in the same directory alongside the first command prompt and try to access the variable, It does not give me the variable I set, My question is how does the environment variables work on this particular issue and how I can access a variable in all Instance of windows command prompt because sometimes I found it useful having more than one instance of cmd opened side to side commands images -
SyntaxError: cannot assign to literal when passing simple string
I'm passing simple string but giving can not assign to literal model = "/model-best", disable=['tokenizer'] print(model) -
Pyhtho Django. the messaa is from python file and i want to show it in HTML his code is working but I want the message will show as pop up or alert
Pyhtho Django. the messaa is from python file and i want to show it in HTML his code is working but I want the message will show as pop up or alert Register {% if messages %} {% for result in messages %} <b style="color: green;">{{result}}</b> {% endfor %} {% endif %} -
How to use django.contrib.humanize filter in DRF serializers
is it possible to use the Django humanize filter for drf on the serializers i have tried putting naturaltime in the to_representation method like below def to_representation(self, instance): representation = super(ListUsersSerializer, self).to_representation(instance) representation['last_login'] = instance.last_login(naturaltime) but it didn't work -
How to fix Apps aren't loaded yet error in Django
I am a beginner in Django and SQL. We have four tables Including Category, Seller, Product, Product_Seller. Each product has one category. each seller can sell a product. Suppose you do not sell the same product multiple times and each seller sells each product at most once. We want to find products that have more than 5 sellers. and we want to find the second category that has the largest number of products. I want to run the SQL code in Django. I have configured the setting for using ORM, but when I run the program it has a 'Apps aren't loaded yet' error. please let me know how can I fix it. here is the code: import os import sys import django from django.conf import settings INSTALLED_APPS = [ 'orm', 'myapps', ] DATABASES = { 'default': { 'ENGINE' : 'django.db.backends.mysql', 'NAME' : 'db', 'USER' : 'admin', 'PASSWORD' : '', 'HOST' : 'localhost', } } settings.configure( INSTALLED_APPS = INSTALLED_APPS , DATABASES = DATABASES , ) django.setup() if __name__ == "__main__": from django.core.management import execute_from_command_line execute_from_command_line(sys.argv) import manage from orm.models import Label if __name__ == '__main__': Label.objects.create(name='test') print(Label.objects.get(name='test')) from django.db import models from django.db import connection class Category(models.Model): title = models.CharField(max_length=128) … -
Django channels cannot receive chat message
I am new to django websocket channel. I have followed a tutorial and something doesn't work on the code. I am trying to understand and use the django channel and created a group room to broadcast a message to a particular group. Now from the code below, it shows no error but doesn't broadcast or response the message that I am trying to test. Here is the full code: import django django.setup() import json import traceback from functools import wraps from urllib import parse as urlparser from asgiref.sync import sync_to_async from channels.generic.websocket import AsyncJsonWebsocketConsumer from django.contrib.auth.models import User from django.utils import timezone from django.conf import settings class QueueConsumer(AsyncJsonWebsocketConsumer): @sync_to_async def _get_headers(self): return dict(self.scope['headers']) async def connect(self): get_dept_code = self.scope['url_route']['kwargs']['deptcode'] self.room_name = get_dept_code self.room_group_name = f'room_{self.room_name}' await self.channel_layer.group_add( self.room_group_name, self.channel_name ) await self.accept() async def disconnect(self, close_code): print("Disconnected") await self.channel_layer.group_discard( self.room_group_name, self.channel_name ) async def receive(self, json_data): response = json.loads(json_data) event = response.get("event", None) data = response.get("data", None) if(event == 'EVENT_CALL'): await self.channel_layer.group_send(self.room_group_name, { 'type': 'chat_message', 'message': "hello", 'event': "EVENT_CALL", }) # Receive message from room group async def chat_message(self, res): r_headers = await self._get_headers() if not r_headers.get(b'origin') or (r_headers.get(b'origin') and not self._check_origin(r_headers.get(b'origin'))): return False await self.send(bytes_data=json.dumps({"payload": res}).encode()) -
Update Django 2.14 to 3.x Any reasons?
Just want to get suggestions and your expertise, guys. I have a small Django project with 2.2.14 version and got suggestions from dependancy_bot to update it to the new 2.2.24 version. At the same time I`m reviewing Django-related books and blogs, and now more commonly mentioned the new 3.x versions. So, is it worth migrating, and what is your story? P.S. My current project focus on REST framework API and low-code platform mobile App interaction, with simple blogging and view-generated pages from embedded SQLite. In mind Dash integration and light-ML cloud services. -
How can I separate button operation in javascript and Django?
I made sign up form page using Django. When I fill in the register form, data is included in database. But, when I click the email check button, register button also is clicked and the page is reloaded. How can I separate these two button? $('.email-check-btn').click(function (){ const email = $('#email').val() if (email === ''){ alert('please check the form') } $.ajax({ type: 'GET', url: 'email-check?email=' + email, datatype: 'json', success: function (response){ if (response.result !== 'success') { alert(response.data) return } if (response.data === 'exist') { alert('that email is already exist!') $('#email').val('').focus() } else { alert('good, you can use it!!') } } }) }) def email_check(request): try: user = get_user_model().objects.get(email=request.GET['email']) except Exception as e: user = None result = { 'result': 'success', 'data': 'not exist' if user is None else 'exist' } return JsonResponse(result) def sign_up(request): if request.method == 'GET': user = request.user.is_authenticated if user: return redirect('/main') else: return render(request, 'sign_in_and_up.html') elif request.method == 'POST': user_id = request.POST.get('username', '') password = request.POST.get('password', '') password2 = request.POST.get('password2', '') nickname = request.POST.get('nickname', '') email = request.POST.get('email', '') if password != password2: return render(request, 'sign_in_and_up.html', {'error': 'check your password'}) else: if user_id == '' or password == '' or nickname == '' or email … -
How can I create a proper sql statement from this django model?
I'm trying to insert data retrieved by scraping into the DB created by the following models. However, I realized that using django's bulk_create or the external library based on it, bulk_create_or_update, is likely to make the logic too complex. (I felt that orm should be used for simple CRUD, etc.) So I'm thinking of using Row SQL to save the data, for both maintainability and speed. I'm not familiar with sql at all, so I'd like to get some advice from you guys. What SQL code is preferable to this? Each page to be scraped has multiple pieces of information, and there are multiple pages in total. I'd like to scrape all the pages first, add them to a dictionary, and then save them in a batch using sql, but I don't know the best way to do this. from django.db import models from django.forms import CharField # Create your models here. # province class Prefecture(models.Model): name=models.CharField("都道府県名",max_length=10) # city class City(models.Model): prefecture = models.ForeignKey(Prefecture, on_delete=models.CASCADE, related_name='city') name=models.CharField("市区町村名",max_length=10) # seller class Client(models.Model): prefecture = models.ForeignKey(Prefecture, on_delete=models.CASCADE, related_name='client',null=True,blank=True) city = models.ForeignKey(City, on_delete=models.CASCADE, related_name='client',null=True,blank=True) department = models.CharField("部局",max_length=100) # detail class Project(models.Model): name = models.CharField("案件名",max_length=100) serial_no = models.CharField("案件番号",max_length=100,null=True,blank=True) client = models.ForeignKey(Client, on_delete=models.CASCADE, related_name='project') # … -
how to define init in serializer to set all fields required=False in Django rest?
I have a model in which data is filled through a form in the frontend by API call. I have an update api in which all the fields are set to required=False. I have done it in the following way: class LeadSerializer(serializers.ModelSerializer): email= serializers.EmailField(required=False) phone = serializers.CharField(required=False) first_name = serializers.CharField(required=False) last_name = serializers.CharField(required=False) class Meta: model = Lead # fields = '__all__' # depth = 1 fields = ['id','title','first_name','last_name','address','company_name', 'city','state','country','phone','source','mobile', 'email','gender','date_created','lead_status'] Here I have shown only four fields as required=False But I need this for all the fields. How to set all fields to false by writing init function here inside the serializer instead of writing every field manually? PS I am using same serializer (the above one) for creating, listing and updating. -
Is it possible to manage local files with deployed Django app?
I have a Django app that is deployed on Heroku. The app aims to support auditability of documents that we have on our disk that is shared by few computer in our local network. Django app stores information such as: who has added the file, when it was created, what is the category of the file etc. Generally it helps us to find the file we need quickly and have some order. Is it possible for the Django app deployed on Heroku (or elsewhere) to upload/download files to our shared disk? We don't want to have physical files stored on the internet as they contain private information. But we want to have additional data about these files accessible from our Django app so that everybody can log in via website and have overview of all information of the files. We also want to be able to manage the files from the app (add new document, delete existing document). I was trying to set MEDIA_ROOT to our shared disk path but I think that's not possible because Django app deployed on Heroku will be looking inside of the system it is hosted on. Is it possible to manage files on shared … -
Django: forms.MultipleChoiceField Not Displayed
I am a beginner in Django/Python. Am having problem with djangos MultipleChoiceField in that it is not been displayed both in the loaded HTML in the browser and the page being displayed. The other aspects of the form such as my email field are been rendered successfully. forms.py class CustomSetForm(forms.Form): choice = () def __init__(self, qs, *args, **kwargs): super().__init__(*args, **kwargs) requirements = qs.required self.choice = list(requirements.split(',')) print(self.choice) email = forms.EmailField(label='', max_length=100, required=True, widget=forms.TextInput( attrs={'class': 'form-group form-control input-lg ', 'placeholder': 'Email'}), ) qualifications = forms.MultipleChoiceField(required=True, widget=forms.CheckboxSelectMultiple, choices=choice) views.py def get_job_requirements(request, *args, **kwargs): selected_job_title = kwargs.get('job_title') obj_model = Author.objects.get(job_title=selected_job_title) form = CustomSetForm(obj_model) context = {'form': form} try: if request.method == "GET": return render(request, 'requirements/job_specs.html', context) if request.method == "POST": if form.is_valid(): email = form.cleaned_data.get('email') job_title_obj = Author.objects.get(job_title=selected_job_title) qualifications = form.cleaned_data.get('qualifications') applicant = Applicants.objects.create(email=email, job_title=job_title_obj, qualifications=qualifications) applicant.save() return JsonResponse({'created': True}) return render(request, 'requirements/job_specs.html', context) except Exception as e: print(e) return render(request, 'requirements/job_specs.html', context) My Html <form method="post" id="application-form"> {% csrf_token %} {{ form.email }} {{ form.qualifications.as_p }} <div class="bg-light row" > <div class="" id="btn-box"> <div class="col-md-12 d-grid gap-2 col-6 "> <button type="submit" class="btn btn-primary btn-lg">Save</button> </div> </div> </div> </form> HTML in browser <form method="post" id="application-form"> <input type="hidden" name="csrfmiddlewaretoken" value="og1mWWpCR6rwxOw19fhUp4jX4KfFqbmeczbTwO92zNYtXBoESiZbi5biugeOj8N0"> <input type="text" name="email" class="form-group … -
how to transfer pandas dataframe from django(backEnd) to tkinter(frontEnd)?
I am making tkinter program using django server. but I have trouble transper pandas dataframe that is calculated in django server. my django server @csrf_exempt def test(request): myColumn=['a', 'b'] myIndex = ['2020', '2021', '2022'] rows = [ [100, 120], [101, 121], [102, 122], ] result = pd.DataFrame( rows, columns=myColumn, index=myIndex ) print(result) return HttpResponse(result) # django print result a b 2020 100 120 2021 101 121 2022 102 122 my frontEnd tkinter def _calculation(self): url = "http://127.0.0.1:8000/test" response = requests.post(url) data = StringIO(str(response.content,'utf-8')) df=pd.read_csv(data) print(df) #tkinter print result Empty DataFrame Columns: [ab] Index: [] -
Difference between list() and get_queryset() in ModelViewSet - Django?
If i want to override the behaviour of list action of the viewset, which function do i have to override? I have the following viewset and model: class UsecaseViewSet(viewsets.ModelViewSet): serializer_class = UsecaseSerializer queryset = Usecase.objects.all() authentication_classes = (authentication.JWTAuthentication,) permission_classes = (permissions.DjangoModelPermissions,) class Usecase(models.Model): id = models.BigAutoField(primary_key=True) name = models.CharField(max_length=255) ......... when list action is called, i would like to add few fields from another model. i want to filter by usecase_id and get run_time etc from this model. class UsecaseJobLogs(models.Model): id = models.BigAutoField(primary_key=True) date = models.DateField(auto_now=True) run_time = models.TimeField() job_id = models.IntegerField() usecase_id = models.IntegerField() -
How to runserver once in django and keep getting correct web test results?
I made a website with django that tests personal-color (input is a picture), and I have gathered a few test results to see if the web test results will be the same as my already tested data. However, everytime I run the test by > python manage.py runserver I get the correct result only the first time, and when I re-test with another input, I get wrong results. To get the correct result, I have to stop the server by Ctrl+C and then do python manage.py runserver again to get the right result with another input picture I want to test. Can anybody help me with this problem? I want to get the correct results from a multiple of pictures without having to runserver again everytime I want to test a picture. -
inlineformsetfactory jquery add value in table row
Below is my output and i want to add some data values in second line of table how can I get it from my below jscript. please help me out on this. [tableoutput][1] -
How to create an order with also seller as a foreign key to the orders table similar to customer field?
Here is some customization, I am trying to achieve. In creating rest API’s using DRF section, for the orders API, while creating orders we are getting the user id or creating one if it not exists from the customer object. Now, consider there is another model seller which has same foreign key relationship similar to customer field to the orders table. Now what to do in this situation to create an order? How to get the user id with both customer and seller in the serializer and what changes has to be done for the view? Whole orders api is the same, just I have added the sellers model with three fields sellername, phone and foreign key to user model. [models.py][1] [serializer.py][2] [views.py][3] As you can see when I only pass the customer object, I am getting the user id back so how to implement also for seller object -
News Display Plugin Formulation in Django and Python
Any thoughts on the best django plug ins for managing an external news library on a site and also cropping, and creating different images sizes for different styles, Weve custom built ours but since the images *thumbnails, large size and medium size should be internally cropped pre display and be adaptive for all devices am not getting a consistent result. Also amateur hour on this side but not all django projects on github contain consistent screenshots of the functioning and this is visual appearance is critical for this function. CSS Cropping tools are producing an inconsistent result and the cropping tools that i think hold the key to making sure our news always looks good. Links would be appreciated. -
RabbitMQ + Celery. RabbitMQ creates new process every 60 seconds
My goal is to create task that sends notification email when user's comment receives a reply. I'm using WSL Ubuntu, Django, Celery + RabbitMQ The problem is every 60 second RabbitMQ creates new '/usr/lib/erlang/erts-10.6.4/bin/epmd -daemon' process (hereinafter the PROCESS), without closing the previous one. As shown in logs I started RabbitMQ server at 12:05, first PROCESS started at 12:05, after that RabbitMQ creates new PROCESS every minute. USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND root 338 0.0 0.0 16016 4420 tty1 S 12:05 0:00 sudo rabbitmq-server root 339 0.0 0.0 10656 1928 tty1 S 12:05 0:00 /bin/sh /usr/sbin/rabbitmq-server root 346 0.0 0.0 15116 2796 tty1 S 12:05 0:00 su rabbitmq -s /bin/sh -c /usr/lib/rabbitmq/bin/rabbitmq-server rabbitmq 347 0.0 0.0 10656 1860 ? Ss 12:05 0:00 sh -c /usr/lib/rabbitmq/bin/rabbitmq-server rabbitmq 348 0.0 0.0 10656 1904 ? S 12:05 0:00 /bin/sh /usr/lib/rabbitmq/bin/rabbitmq-server rabbitmq 455 0.0 0.0 14400 2248 ? S 12:05 0:00 /usr/lib/erlang/erts-10.6.4/bin/epmd -daemon rabbitmq 530 0.8 0.4 5345524 74892 ? Sl 12:05 0:11 /usr/lib/erlang/erts-10.6.4/bin/beam.smp -W w -A 128 -MBas ageffcbf -MHas ageffcbf -MBlmbcs 512 -MHlmbcs 512 -MMmcs 30 -P 1048576 -t 5000000 -stbt db -zdbbl 128000 -K true -B i -- -ro rabbitmq 575 0.0 0.0 14400 2212 … -
How to find intersection of regular and multilingual querysets in Django
I have two querysets: Regular Django queryset: <QuerySet [1160567, 1160906...]> Django Multilingual queryset: <MultilingualOrderQueryset [710330, 710326, 710325, ...]> I have tried: _.intersection(regular_qs, multilang_qs) But it gives me a programming error. Although both querysets were retrieved by appending values_list('id', flat=True) to their respective object managers, I assume they still contain their respective models that are not compatible. What is the best way to find common elements in these two querysets? One way would be to convert them to sets and then do regular python intersection, but I was wondering if there is a better/more efficient approach? -
InterfaceError from Dockerized Django to local MySql connection
Trying to connect local MySQL database from docker Django, unfortunately getting interface error don't know what's wrong. Host Machine Info: Macbook Pro M1 Mysql Database Version: Mysql 8 docker-compose.yml version: '3' services: django: build: ./project volumes: - ./project:/project ports: - "8081:8000" restart: unless-stopped nginx: image: nginx volumes: - ./nginx.conf:/etc/nginx/nginx.conf - ./project/media:/usr/share/nginx/media - ./project/static:/usr/share/nginx/static ports: - "80:8080" restart: unless-stopped local_settings.py DATABASES = { 'default': { 'NAME': 'db_name', 'ENGINE': 'django.db.backends.mysql', 'USER': 'username', 'PASSWORD': 'password', 'HOST': 'host.docker.internal', 'PORT': '33060', } } error traceback -
how to display form error if form fields are empty or invalid in rest_framework.by default the rest_framework points to the json endpoints
I have created a studentCreate Api view that accepts the post request. if the request is valid the form data is serialized and saved but if the form is invalid or empty it needs to redirected back to the form . But by default the form errors are redirected to the rest_framework json api. How can i achive this in rest_framework class StudentCreate(APIView): serializer_class=StudentSerializer def post(self,request): serializer=StudentSerializer(data=request.data) student=request.data if serializer.is_valid(): serializer.save() return redirect('student-list') return redirect('/',{"serializer":serializer,'message':"form fields are not valid"}) this is my form for creating new student instance <div class="container"> {% if message %} {{message}} {% endif %} <form action="{% url 'student-create' %}" method="POST"> {% csrf_token %} <div class="form-group"> <label for="name">Name</label> <input type="text" class="form-control" name="name" placeholder="Enter name"> </div> <div class="form-group"> <label for="age">age</label> <input type="number" class="form-control" name="age" placeholder="age"> </div> <div class="form-group"> <label for="address">address</label> <input type="text" class="form-control" name="address" placeholder="address"> </div> <div class="form-group"> <label for="grade">grade</label> <input type="number" class="form-control" name="grade" placeholder="grade"> </div> <div class="form-group"> <label for="major">major</label> <input type="text" class="form-control" name="major" placeholder="major"> </div> <button type="submit" class="btn btn-primary">Submit</button> </div> the urlpattern for create urlpatterns = [ path("student/", StudentCreate.as_view(), name="student-create"), path("student-list/", StudentList.as_view(), name="student-list"), path("students-detail/<int:pk>/", StudentDetail.as_view(), name="student-detail"), ]