Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Templates: How i can compare two strings in javascript
I want to compare two strings, one of the two strings is to be choosed by the user from a drop down list(using django-widget-tweaks) : this is the code field in my template: html <p >{{ form.category_column.label_tag }}</p> <p id="category_column_id">{% render_field form.category_column autocomplete="off" hx-get="/sizescolumn/" hx-target="#id_sizes_column" %}</p> code javascript: <script> var btn = document.getElementById("clickMe"); btn.addEventListener("click", alertMe); function alertMe(){ var select = document.getElementById('category_column_id').value; if(select === "Flate" ){ div.style.opacity = "1"; div.querySelector('p').innerText = 'You can not choose Flate category in column'; setTimeout(function(){ div.style.opacity = "0"; }, 6000); event.defaultPrevented(); }else { div.style.opacity = "0"; } } </script> ----->but this code it doesn't work , no message shown if the selected value is "Flate". any help please -
Accessing the attributes/elements of a form in Django
Hello so I've a form and I'm trying to make it so that when that form is validated. But before it is saved. It will create a new instance of a EC_Node and save the command given in the Command_Form not only to the Command_Node but to the EC_Nodes. Which should have a manytoone relationship with the Command_Nodes and which should record all commands send to a command_node. But this will only work if when entering a command for the Command_Node I also capture that in a EC_Node. Which I don't know how to do exactly although I'm some ideas. So any advice would be greatly appreciated. Relevant Code follows. Relevant views.py def update(request, host_id): host_id = Command_Node.objects.get(pk=host_id) form = Command_Form(request.POST or None, instance=host_id) if form.is_valid(): # Original suggestion was command_form = Command_Form.objects.first() command_form = form['host_id'] command_form.EC_Node_set.all() # <- not sure with all _ and Maj here form.save() return redirect('home') return render (request, 'update.html', {'host_id':host_id,'form':form}) forms.py class Command_Form(ModelForm): class Meta: model = Command_Node fields = ('host_id','current_commands') host_id = forms.ModelChoiceField( required=True, queryset=Beacon.objects.all(), widget=forms.SelectMultiple( attrs={ 'class': 'form-control' }, ) ) current_comamnds = forms.ChoiceField( required=True, choices=CHOICES ) def save(self, **kwargs): EC_Node.objects.create( command=self.cleaned_data["current_commands"], Command_node=self.instance ) return super().save(**kwargs) models.py class Command_Node(models.Model): host_id = models.ForeignKey(Beacon, on_delete=models.CASCADE) … -
my code is not working in updating record in django
I am making a employee management system in django. i have created all the fields create, read, delete and filter but I am unable to write update field.please someone help me.. This is my views.py file def update_emp(request,emp_id=0): context={} obj= get_object_or_404(Employee, id=emp_id) # obj=Employee.objects.get(id=emp_id) form = employeeForm(request.POST or None, instance = obj) if form.is_valid(): form.save() return HttpResponseRedirect('/'+id) context['form'] = form return render(request, 'update_emp.html' ,context) This is my urls.py file from django.urls import path , include from . import views urlpatterns = [ path('', views.index, name = 'index'), path('all_emp', views.all_emp, name = 'all_emp'), path('add_emp', views.add_emp, name = 'add_emp'), path('remove_emp', views.remove_emp, name = 'remove_emp'), path('remove_emp/<int:emp_id>', views.remove_emp, name = 'remove_emp'), path('filter_emp', views.filter_emp, name = 'filter_emp'), # path('update_emp', views.update_emp, name = 'update_emp'), path('update_emp/<int:id>', views.update_emp, name='update_emp'), ] This is my update_emp.html file <div class="main"> <form method="POST"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="Update"> </form> This is my forms.py file from django import forms class employeeForm(forms.Form): fname=forms.CharField(label="Value1",required=False,widget=forms.TextInput(attrs={'class':'form-control'})) lname=forms.CharField(label="Value2",required=True,widget=forms.TextInput(attrs={'class':'form-control'})) -
TypeError: answer() missing 2 required positional arguments: 'Poll' and 'Answers' - django
I want to specify one of the table fields using serializers, but I get the following error Error : TypeError: answer() missing 2 required positional arguments: 'Poll' and 'Answers' code : serializers.py from rest_framework import serializers from .models import Answers, Poll ,Options from authUser.models import User class pollSerializer(serializers.ModelSerializer): class Meta: model = Poll fields = ["pollAnswer" ] pollAnswer = serializers.SerializerMethodField(method_name="answer") def answer(self , Options :Options , Poll:Poll , Answers :Answers ): poll = Poll.objects.get(pk=Poll.pk) polltype = poll["pollType"] if polltype == 0 : return Poll.pollAnswer if polltype == 1: options = Options.objects.filter(pollId=Poll.pk) big = 0 oid = 0 for i in options: if big < Answers.objects.filter(pollId=Poll.pk ,optionId=i.pk).count(): big = Answers.objects.filter(pollId=Poll.pk ,optionId=i.pk).count() oid = i.pk return oid -
How to integrate Bokeh Server into Django
Currently I have a Bokeh server running. I can access it and when I push some buttons then Python code runs in the background and finally a figure is plot. Now I need to add some things: I want users to authenticate. Users should be able to save results to a database. Some general data (costs, the same for everybody) should also be obtained from a database. User sessions should be stored. In the end multiple apps will be made available to users. Not all users will have access to all apps. Authentication should solve this. So I think I should integrate the Bokeh server into Django using server_document(). However, I am not able to find a minimal working example. It would be nice if that example includes the topics from my list. -
Django Channels Rest Framework V3 @model_observer message is None
I tried to find anything in the documentation of model observer which could explain under which conditions the model observer is called with message = None, but there was nothing particularly hinting into the right direction. From what I unterstand from the example: class MyConsumer(GenericAsyncAPIConsumer): queryset = User.objects.all() serializer_class = UserSerializer @model_observer(Comments) async def comment_activity( self, message: CommentSerializer, observer=None, subscribing_request_ids=[] **kwargs ): await self.send_json(message.data) @comment_activity.serializer def comment_activity(self, instance: Comment, action, **kwargs) -> CommentSerializer: '''This will return the comment serializer''' return CommentSerializer(instance) @action() async def subscribe_to_comment_activity(self, request_id, **kwargs): await self.comment_activity.subscribe(request_id=request_id) The message should be the output of the CommentSerializer so the only way a message to become null is, if the serializer would return nothing ?! To check if this is the case I added logs prints which sadly indicate that the serializer is receiving data and thous there is no reason the message could be None. Its also occurring only from time to time so any advice about misunderstanding of how the observer works internally will be highly appreciated. In our implementation: class StorageConsumer(ListModelMixin, AsyncAPIConsumer): """ Async API endpoint that allows Storage updates to be pushed. """ async def accept(self, **kwargs): await super().accept() await self.model_change_bess.subscribe() @model_observer(Bess) async def model_change_bess(self, message, … -
Filter data via ajax and django
Hello By sending the value received from the dropdown and sending it to the server via ajax, I filtered my data and sent the result to the template. However, I can see the result through the web developer tools in the response tab, but the result is not visible on the web page. What is the reason? -
how to exit from the loop in python
I'm looping all the rows and I want to return it but even after looping all the rows and even data is saving in the database but its not getting exit from it due to which I'm getting an error as 'str' object has no attribute 'get'. I don't know where I'm going wrong This what I tried Views.py: @api_view(['POST']) def SaveUserResponse(request): if request.method == 'POST': cursor = connection.cursor() if request.data: for ran in request.data: auditorid =ran.get('AuditorId') print('SaveUserResponse auditorid---', auditorid) ticketid = ran.get('TicketId') Agents = ran.get('Agents') Comments = ran.get('Comments') Supervisor = ran.get('Supervisor') sid = 0 print('sid--', sid) qid = ran.get('QId') print('qid---', qid) answer = ran.get('Answer') cursor.execute('EXEC [dbo].[sp_SaveAuditResponse] @auditorid=%s,@ticketid=%s,@qid=%s,@answer=%s,@sid=%s', (auditorid,ticketid,qid,answer, sid)) result_st = cursor.fetchall() print('sp_SaveAuditResponse', result_st) for row in result_st: print('sp_SaveAuditResponse', row) return Response(row[0]) print('after after') return Response(0) Here, is the payload: [{"AuditorId":130,"Agents":"","Supervisor":"","TicketId":"325423432","QId":42,"Answer":"2","SID":"0","Comments":""}, {"AuditorId":130,"Agents":"","Supervisor":"","TicketId":"325423432","QId":43,"Answer":"2","SID":"0","Comments":""}, {"AuditorId":130,"Agents":"","Supervisor":"","TicketId":"325423432","QId":44,"Answer":"2","SID":"0","Comments":""}, {"AuditorId":130,"Agents":"","Supervisor":"","TicketId":"325423432","QId":45,"Answer":"2","SID":"0","Comments":""}, {"AuditorId":130,"Agents":"","Supervisor":"","TicketId":"325423432","QId":46,"Answer":"3","SID":"0","Comments":""}, {"AuditorId":130,"Agents":"","Supervisor":"","TicketId":"325423432","QId":47,"Answer":"5","SID":"0","Comments":""}, {"AuditorId":130,"Agents":"","Supervisor":"","TicketId":"325423432","QId":48,"Answer":"5","SID":"0","Comments":""}, {"AuditorId":130,"Agents":"","Supervisor":"","TicketId":"325423432","QId":49,"Answer":"2","SID":"0","Comments":""}, {"AuditorId":130,"Agents":"","Supervisor":"","TicketId":"325423432","QId":50,"Answer":"5","SID":"0","Comments":""}] -
How to have dedicated instances for celery containers when deploying django project using docker-compose on elastic beanstalk?
I have a web-app that uses celery for heavy calculations. It was deployed on AWS with elastic beanstalk, using docker-compose. The broker is Amazon SQS, while redis is used as result backend. Here is the docker-compose file to understand the structure: version: '3.8' volumes: data: driver_opts: type: "nfs" o: "addr=XXXXXXXXXXXXXXXXXXXXXXX,rw,nfsvers=4.1,rsize=1048576,wsize=1048576,hard,timeo=600,retrans=2,noresvport" device: ":/" static: services: web: build: ./web command: > bash -c "python3 manage.py migrate && python3 manage.py collectstatic --noinput && gunicorn APPNAME.asgi:application --access-logfile '-' --error-logfile '-' --capture-output --enable-stdio-inheritance -k uvicorn.workers.UvicornWorker -b 0.0.0.0:8000" volumes: - data:/home/webserver/data/ - static:/home/webserver/static/ ports: - "8000:8000" depends_on: - redis celery: build: ./web command: celery -A APPNAME worker -Ofair -l INFO volumes: - data:/home/webserver/data/ depends_on: - web redis: image: redis:6.2.6-alpine ports: - "6379:6379" nginx: build : ./nginx ports: - "80:80" depends_on: - web volumes: - static:/home/webserver/static/ It works well, including the celery tasks. Now, I would like to separate the web/redis/nginx services from the celery containers that would have their own dedicated instances, with the ability to scale. Is there a proper way to do that (using CLI)? Should I consider separate beanstalk applications? -
Why can't I see Loading... while scrolling?
Based on this tutorial This is my views: def All( request ): p=product.objects.all().order_by('id') pa=Paginator(p,20) page=request.GET.get('page') pro=pa.get_page(page) return render(request,'home.html',{'pro':pro}) This is my template: <div class="grid"> {%for p in pro%} <div class='card'> <img src="{{p.image}}"></img> <p id="id">{{p.description}}</p> <a href="{{p.buy}}" target='_blank' rel='noopener noreferrer'> <button ><span class="price"> ${{p.price}}</span> buy</button> </a> </div> {%endfor%} {% if pro.has_next %} <a class='more-link' href="?page={{pro.next_page_number}}">Next</a> {% endif %} <div class="loading" style="display: none;"> Loading... </div> <script> var infinite = new Waypoint.Infinite({ element: $('.grid')[0], onBeforePageLoad: function () { $('.loading').show(); }, onAfterPageLoad: function ($items) { $('.loading').hide(); } }); </script> </div> I have downloaded dependencies correctly and I included some links in my html to use them, but currently I can not find what is wrong with my code. Why can't I see Loading... while scrolling? -
How Can I Add Country Flags to Django Phonenumber Widget
I have used django-phonenumber-field in my project with Babel which is working fine with drop down of all countries with their international dialing code. My problem is that I want each country flag attached to their names so that the phonenumber field will be smaller. Attached is the what I presently have. This is exactly what I want to achieve with django-phonenumber-field. And you can observe that my phone number fields are two; one has the international code and the other field is where the phone number is to be entered whereas I want all in one field with Countries Flags. Anticipating your prompt answer, thanks. -
Products are not deleted from cart
Firstly my code had an error then I ask about it in StackOverflow. Then someone helped me to fix this error. Here is the link: get() returned more than one OrderProduct -- it returned 3 [First error][1] But I have a new problem now. Products are not deleted from the cart when someone ordered them. I do not know why this happened. But before the first fix, products were deleted from the cart successfully. Now the first bug is fixed but I am faced with the second bug. Please help me, products are not deleted from the cart. I have already put a link to my first bug. This is my views.py after fixing the first bug: def process_order(request): transaction_id = datetime.now().timestamp() data = request.POST name = data['name'] email = data['email'] phone = data['phone'] address = data['address'] city = data['city'] state = data['state'] zipcode = data['zipcode'] if request.user.is_authenticated: customer = request.user.customer order, created = Order.objects.get_or_create(customer=customer, complete=False) shipping_info = ShippingAddress.objects.create( customer=customer, order=order, address=address, city=city, state=state, zipcode=zipcode ) order_data = cart_data(request) cart_total_price = order_data['order'].cart_total_price cart_products_quantity = order_data['order'].cart_products_quantity products = order_data['products'] product_list = '' for item in products: product_list += f'{item.product.name}: {item.quantity} шт. {item.total_price}\n\n' else: customer, created = Customer.objects.get_or_create( name=name, email=email, phone=phone ) … -
django file field not saving file to s3 bucket folder when updating
I am uploading file to s3 bucket in the below path: bucket/folder/{custom_id}/file I have the below method which I am calling in Model. In DRF Post method, the file is getting saved correctly to s3 and I am able to retrieve the path in GET. But when I try to upload new files in PUT method, the filename is getting saved in db, but the file is not saving in s3 bucket. custom upload path def upload_path_handler(instance, filename): return f'{FILES_FOLDER}/{id}/{filename}' In Models.py cc_file = models.FileField( db_column='CCFilename', blank=True, null=True, upload_to=upload_path_handler ) This method is working in POST API call of DRF. How do I save new file to s3 if the file is getting changed on update of the field. -
Is the location or scope important in a web push service worker?
I have a Django web app that contains a service worker designed for handling push notifications. Everything is working beautifully. In the many articles, tutorials and documentation it is written that the location and scope of service workers is important and to make sure to put it at the root of the domain. See for example this article, that states: Service worker file must registered at the root directory of your website. And: I’ve spend 15 hours to learn that fact. You guys are lucky ! So when I first created my service worker in Django, I had to make sure to set the scope correctly. I created a View that served the JS code of the service worker as a template, just so that I could set the Service-Worker-Allowed header: class ServiceWorkerView(TemplateView): template_name = 'web_push/web_push_service_worker.js' def get(self, request, *args, **kwargs): response = super().get(request, *args, **kwargs) response.headers['Content-Type'] = 'application/javascript' response.headers['Service-Worker-Allowed'] = '/' return response That template contained the push handling code: self.addEventListener('push', function(event) { ... self.registration.showNotification(...) ... }) As mentioned: this works fine. But now I wonder: why does the scope matter? I just changed things around and moved the code of the service worker to a standard location inside … -
Creating charts in django - errors on javascript
I want to create a chart with some data from my db, I did the same think like I saw on the internet, but I got a few errors base.html <script> $(document).ready(function(){ {% block scripts %} {% endblock scripts %} }) </script> The errors are on the row {% block scripts %} {% endblock scripts %} Why it's showing me this errors? I am new in Js... Here is the video that I watched: https://www.youtube.com/watch?v=B4Vmm3yZPgc -
Reset all migrations in al databases? ProgrammingError relation does not exist
I have an issue: ProgrammingError at /admin/accounts/goal/add/ relation "accounts_goal" does not exist LINE 1: INSERT INTO "accounts_goal" ("id_user_id", "name", "descript... I have any problem with my db before when I deleted all migrations (because I had an unknown issue). Then I deleted all migrations, make migrations again and it worked. After that I want to deploy my project. I had an old project before deleting migrations and it worked very cool. I uploaded the new migrations (after deleting in my local) to Heroku. And it's all ok. But when I go to my admin panel and trying to enter to my model "goal" I had an issue: ProgrammingError at /admin/accounts/goal/add/ relation "accounts_goal" does not exist LINE 1: INSERT INTO "accounts_goal" ("id_user_id", "name", "descript... I think it happened because I deleted migrations. So I think I need to reset db and delete all migrations again or I need to delete all my project and deploy again to fix the problem. Am I right? -
How to add to Django subdirectory url
I have a couple of URLs like https://servename_name/appname/, now my question is how can add the to my URLs the appname. I have tried with FORCE_SCRIPT_NAME='appname' but it does not help. -
Django localhost:8000 not found, but server works [closed]
I have situations: My urls.py: urlpatterns = [ path('admin/', admin.site.urls), path('themes', ListThemeView.as_view()), path('themes/<int:theme_id>', ThemeView.as_view()), path('levels', LevelView.as_view()), path('categories', CategoryView.as_view()), path('words/<int:word_id>', WordView.as_view()), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) I start server: python3.10 manage.py runserver Starting development server at http://127.0.0.1:8000/ but: http://localhost:8000/ - not found http://localhost:8000 - not found http://localhost:8000/admin - not found http://localhost:8000/admin/ - WORKS With url http://127.0.0.1:8000 the same situation -
Django- how to capture visitor Ip and social profiles
I would like to collect some information like their IP address and social profiles like Facebook accounts on my Django website along with the timestamp when they visited for marketing purposes how can we do that? -
Django | Don't show the foreign key valules in dropdown which are already assigned
I am working on a Hostel management system and new in Django field. I have a model Student and Bed . The models code is below: class Bed(models.Model): name = models.CharField("Bed No.",max_length=200) room = models.ForeignKey(Room, on_delete=models.CASCADE, default='1') class Meta: verbose_name_plural = "Bed" def __str__(self): return self.name class Student(models.Model): name = models.CharField("name",max_length=200) cell_no = models.CharField("cell No",max_length=200) photo = models.ImageField(upload_to ='students_pics/') emergency_cell_no = models.CharField("Emergency Cell No", max_length=200) bed = models.ForeignKey(Bed, on_delete=models.CASCADE, null=True, blank=True) created_at = models.DateTimeField(auto_now_add=True) class Meta: verbose_name_plural = "Student" def __str__(self): return self.name I want that when I select a bed from Student Model dropdown, there should only display the beds which are not already assigned to some other students. I have tried something like: bed = models.ForeignKey(Bed, on_delete=models.CASCADE, null=True, blank=True).exclude(----) but it does not work. I have searched around Please help. -
ImportError: DLL load failed while importing _gdal: The specified procedure was not found
I am trying to install GDAL and I always get this error message: ImportError: DLL load failed while importing _gdal: The specified procedure was not found. I have the Python 3.8.10 (tags/v3.8.10:3d8993a, May 3 2021, 11:48:03) [MSC v.1928 64 bit (AMD64)] on win32 and use the wheel: GDAL-3.3.3-cp38-cp38-win_amd64.whl Can it be that I am using the wrong wheel version and if so how do I find the right one? where you can finde the wheels: https://www.lfd.uci.edu/~gohlke/pythonlibs/#gdal my code: from asyncio.windows_events import NULL from traceback import print_tb from osgeo import gdal from numpy import meshgrid from numpy import linspace map = Basemap(projection='tmerc', lat_0=0, lon_0=3, llcrnrlon=1.819757266426611, llcrnrlat=41.583851612359275, urcrnrlon=1.841589961763497, urcrnrlat=41.598674173123) ds = gdal.Open("C:/elevation.tif") data = ds.ReadAsArray() x = linspace(0, map.urcrnrx, data.shape[1]) y = linspace(0, map.urcrnry, data.shape[0]) xx, yy = meshgrid(x, y) cs = map.contour(xx, yy, data, range(400, 1500, 100), cmap = plt.cm.cubehelix) plt.clabel(cs, inline=True, fmt='%1.0f', fontsize=12, colors='k') plt.show() (this is a basemap example) -
Dash deployment with NGINX-Uwsgi-Django failiing when running with multiprocess
I have a stack that looks like this: NGINX (nginx.conf): worker_processes 8; events { worker_connections 1024; use epoll; multi_accept on; accept_mutex off; } upstream django { server 127.0.0.1:8001; server 127.0.0.1:8002; server 127.0.0.1:8003; server 127.0.0.1:8004; server 127.0.0.1:8005; server 127.0.0.1:8006; server 127.0.0.1:8007; server 127.0.0.1:8008; } location /api { uwsgi_pass django; uwsgi_read_timeout 600; uwsgi_param Host $host; uwsgi_param X-Real-IP $remote_addr; uwsgi_param X-Forwarded-For $proxy_add_x_forwarded_for; uwsgi_param X-Forwarded-Proto $http_x_forwarded_proto; uwsgi_param QUERY_STRING $query_string; uwsgi_param REQUEST_METHOD $request_method; uwsgi_param CONTENT_TYPE $content_type; uwsgi_param CONTENT_LENGTH $content_length; uwsgi_param REQUEST_URI $request_uri; uwsgi_param PATH_INFO $document_uri; uwsgi_param DOCUMENT_ROOT $document_root; uwsgi_param SERVER_PROTOCOL $server_protocol; uwsgi_param HTTPS $https if_not_empty; uwsgi_param REMOTE_ADDR $remote_addr; uwsgi_param REMOTE_PORT $remote_port; uwsgi_param SERVER_PORT $server_port; uwsgi_param SERVER_NAME $server_name; } The uwsgi files are all identicall except for the corresponding sockets. They are like this (mysite.xml): <uwsgi> <socket>127.0.0.1:8001/api</socket> <chdir>/var/www/MY_API</chdir> <module>nimgenetics.wsgi:application</module> <debug>true</debug> </uwsgi> When I run uwsgi with a single process, it works fine. But when I run uwsgi with several processes on the different sockets [8001-8008], the whole app works fine except the Dash graphs. I get the following error: Unable to find stateless DjangoApp called app Any guesses of how can I solve this in order to run Dash with multiprocessing with NGINX+UWSGI+Django? -
Why i can not able to update my datan django
I can not able to edit data in my django project settings.py Django settings for superAdmin project. Generated by 'django-admin startproject' using Django 4.0.4. import os from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent TEMPLATE_DIR =os.path.join(BASE_DIR,'templates') STATIC_DIR = os.path.join(BASE_DIR,'static') SECRET_KEY = 'django-insecure-pqeid(n@vcuz-nj_+qphdlmcabz58w7cb#h3)hidden' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'sa', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'superAdmin.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [TEMPLATE_DIR], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'superAdmin.wsgi.application' # Database # https://docs.djangoproject.com/en/4.0/ref/settings/#databases DATABASES = { 'default': { 'ENGINE':'django.db.backends.mysql', 'NAME': 'super', 'USER' : 'root', 'PASSWORD': '', 'HOST':'localhost', 'PORT':'3306' }, 'sales': { 'ENGINE':'django.db.backends.mysql', 'NAME': 'salesteam', 'USER' : 'root', 'PASSWORD': '', 'HOST':'localhost', 'PORT':'3306' }, 'client': { 'ENGINE':'django.db.backends.mysql', 'NAME': 'django', 'USER' : 'root', 'PASSWORD': '', 'HOST':'localhost', 'PORT':'3306' } } # Password validation # https://docs.djangoproject.com/en/4.0/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/4.0/topics/i18n/ LANGUAGE_CODE = … -
Django - How to handle the UNIQUE constraint when import a excel fields
I was did a small project to import file excel and show data it. I'm using django-import-export lib In models.py I had student_id(unique =true) class Student(models.Model): school = models.CharField(max_length=100) district = models.CharField(max_length=100) student_id = models.CharField(max_length=50, unique= True, error_messages={'unique':"This email has already been registered."}) stu_class = models.CharField(max_length=30) name = models.CharField(max_length=100) date = models.CharField(max_length=200) sex = models.CharField(max_length=20) place_of_birth = models.CharField(max_length=100) ethnic = models.CharField(max_length=50) location = models.CharField(max_length=255) phone_number = models.IntegerField(blank=True) total_grade_1 = models.PositiveSmallIntegerField(blank=True) total_grade_2 = models.PositiveSmallIntegerField(blank=True) total_grade_3 = models.PositiveSmallIntegerField(blank=True) total_grade_4 = models.PositiveSmallIntegerField(blank=True) total_grade_5 = models.PositiveSmallIntegerField(blank=True) total_5_years = models.PositiveSmallIntegerField(blank=True) plus = models.PositiveSmallIntegerField(blank=True, null= True, default=0) total_all = models.PositiveSmallIntegerField(blank=True, null=True) decripsion = models.CharField(max_length=255) def __str__(self): return self.name How I show errors_message when I import another file excel had same id_student in data. I was try to take the id_student to compare with the data import in but seen like I do it worng. views.py def simple_upload(request): if request.method == "POST": student_resource = StudentResource() dataset = Dataset() new_student = request.FILES['myfile'] if not new_student.name.endswith('xlsx'): messages.error(request, 'You Must Import Excel File!') return redirect("upload") else: messages.success(request, 'Import Success!') imported_data = dataset.load(new_student.read(), format='xlsx') for data in imported_data: value = Student( data[0],data[1],data[2],data[3],data[4],data[5],data[6],data[7],data[8],data[9],data[10], data[11],data[12],data[13],data[14],data[15],data[16],data[17],data[18],data[19],data[20], ) # if Student.student_id == Student(data[3]): # messages.error(request, 'You Must Import Excel File!') # return redirect("upload") # else: … -
Serialize filtered related fields in Django Rest framework
In my project, I have three models: Group, User and Challenge. Each user is a member of some groups and each challenge is intended for one or more groups. class Group(TimeStampedModel): name = models.CharField(max_length=255) class User(AbstractUser): user_groups = models.ManyToManyField(Group) class Challenge(TimeStampedModel): ... groups = models.ManyToManyField(Group, null=True, blank=True) I also have a serializer for Challenge models that serializes all challenge data and related groups using a GroupSerializer. class ChallengeSerializer(serializers.ModelSerializer): groups = GroupSerializer(many=True) class Meta: model = Challenge fields = [..., "groups"] My current APIView for serializing list of challenges. class ChallengeList(generics.ListAPIView): queryset = Challenge.objects.all() serializer_class = ChallengeSerializer permission_classes = [permissions.IsAuthenticated] pagination_class = PageNumberPagination def get_queryset(self): user_groups = self.request.user.user_groups.all() return Challenge.objects.filter(groups__in=user_groups).distinct() When serializing a Challenge object, a list of all related groups is serialized. Is it possible to only serialize related Group objects that are also related to our currently logged in user?