Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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? -
Django Admin Panel not showing on production
I have recently deployed project on linux server. I can't access admin panel by going to my-domain/admin. i can view it when running project locally but on production it says "This site can't be reached" -
Use params for raw sql query
params = ', '.join([str(x) for x in list(user_domain_ids)]) latest_entries = DNSEntryHistory.objects.raw(SELECT t1.* from dnsapi_dnsentryhistory t1 where t1.date= (SELECT MAX(date) FROM dnsapi_dnsentryhistory t2 where t1.id=t2.id) and history_type='delete' and domain_id IN (%s)",[params]) I have a request and i want to send value separated by comma in my IN statement. This request works if the variable is hardcoded with a fstring but i don't want to get this solution because of SQL Injection issues. When I print the query it show -> SELECT t1.* from dnsapi_dnsentryhistory t1 where t1.date= (SELECT MAX(date) FROM dnsapi_dnsentryhistory t2 where t1.id=t2.id) and history_type='delete' and domain_id IN (2544, 1) which seems correct. Also when i use the printed request as the executed one, it works, so i'm so confused -
How to solve blank page after posting the form problem?
I want to send a basic form to views. I create everything that it need but when I submit the post, it doesn't send a return a blank page. This is my form and app:reports is the same page with form, because I want to return the same page. I need the values of year_one and year_two. <form method="post" action="{% url 'app:reports' %}"> {% csrf_token %} <label for="year_one">Select year 1:</label> <select id="year_one" name="year_one"> {% for case in query_trend %} <option value="{{case.date_created__year}}" >{{case.date_created__year}}</option> {% endfor %} </select> <label for="year_two">Select year 2:</label> <select id="year_two" name="year_two"> {% for case in query_trend %} <option value="{{case.date_created__year}}">{{case.date_created__year}}</option> {% endfor %} </select> <button onclick="test()">click</button> </form> And this is my view if self.request.method == 'POST': year_one = self.request.GET.get('year_one') year_two = self.request.GET.get('year_two') return HttpResponseRedirect('fdm:outstanding_reports') What should I do for using these values in views? -
How to properly show .dwg file in Reactjs web application
Currently, I want to render a large .dwg file in the reactjs web application, the .dwg file will be retrieved from my django server. Also, I will be doing some filtering onto the .dwg file to show the coordinate of different IoT devices. After hours of research, I found out there are two ways of showing .dwg file in the reactjs web application. Either using autodesk forge viewer extension in reactjs, however, there are little tutorials on how to implement that step by step. Another solution is to convert .dwg file to .dxf file and render it in the web. I want to know which solution is better, and please point me out if I am wrong about the solutions. I mean I really want to do it with the standard practice. Much appreciated. -
what is the best frontend framework to use with django [closed]
what is the best frontend framework to use with django? -
Django REST API booleanfield filter in view (e.g. filter(is_published=True) )
I will filter is_published=1 in REST API view. I want to receive only published articles. And i using MongoDB database. models.py: class Post(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) title = models.CharField(max_length=500, verbose_name="Başlık") content = RichTextUploadingField(max_length=10000) is_publish = models.BooleanField(default=0) created_date = models.DateField(auto_now_add=True, null=True, blank=True, editable=False) . . . view.py (I guess error is here): class PostList(generics.ListAPIView): serializer_class = PostSerializer permission_classes = [permissions.IsAuthenticated] filter_backends = [filters.SearchFilter] search_fields = ['content', 'title'] def get_queryset(self): queryset = Post.objects.filter(is_published=True).order_by("-created_date") return queryset serializers.py: from .models import Post from rest_framework import serializers class PostSerializer(serializers.ModelSerializer): class Meta: model = Post exclude = ['author'] my error code: DatabaseError at /post/list/ No exception message supplied -
Django dependant filters using json list variable contained within a foreign key
I have a form the a user can fill in. What I want is a dependant dropdown menu such that when a router (ce_hostname) is selected, the ports (l2_interfaces) for that router are selectable from the second dropdown (ce_wan_port). The list of ports are stored as a json list in the router and the router is stored as a foreign key. models.py #Unique order. Top of heirachy tree class Order(models.Model): order_name = models.CharField(max_length=100, unique=True)#, null=True, blank=True) #Unique name of order #For CE router definition. Required for all orders. class Ce_Base(models.Model): ce_hostname = models.CharField(max_length=15, validators=[CE_HOSTNAME_REGEX], verbose_name="CE Hostname", help_text="Hostname of router.") l2_interfaces = JSONField(null=True) #Layer 2 interfaces #For defining WAN links class Ce_Pe(models.Model): order_reference = models.ForeignKey(Order, null=True, on_delete=models.CASCADE) #Order reference ce_hostname = models.ForeignKey(Ce_Base, null=True, on_delete=models.CASCADE, verbose_name="CE Hostname", help_text="Hostname of CE router.") ce_wan_port = models.CharField(max_length=500, null=True, blank=True) For the purposes of my dropdown, the ce_wan_port should be a dropdown menu of the l2_interfaces, which appears after a ce_hostname is selected. Example l2_interfaces data [ "Gi0/0/0", "Gi0/0/1", "Gi0/0/2" ] forms.py class Ce_PeForm(ModelForm): class Meta: model = Ce_Pe fields = ['ce_hostname', 'ce_wan_port',] def __init__(self, *args, order_reference, **kwargs): super().__init__(*args, **kwargs) order_id = str(order_reference.id) self.fields['ce_hostname'].queryset = Ce_Base.objects.filter(order_reference=order_id,) This is currently filtering for ce_hostname objects within the same … -
Django Aggregate Min Max Dynamic Ranges
I have following model class Claim: amount = models.PositiveIntegerField() I am trying to create Api that dynamically sends response in such way that amount ranges are dynamic. for example my minimum Claim amount is 100 and max is 1000 i wanted to show json in this way { "100-150":2, "150-250:3, "250-400:1, "400-500":5, "above_500":12 } I tried doing this way assuming my data range is between 1-2000 but this becomes of no use if my minimum amount lies in between 10000, 100000 d = Claim.objects.aggregate(upto_500=Count('pk', filter=Q(amount__lte=500)), above_500__below_1000=Count('pk', filter=Q(amount__range=[501, 999])), above_1000__below_2000=Count('pk', filter=Q(amount__range=[1000, 2000])), above_2000=Count('pk', filter=Q(amount__gte=2000)) ) any idea how we can make dynamic way of getting amount ranges and throwing it to front end. -
How to get a number in html page in humanized format(comma separated and same )
I am running a django project. I want to get some value, that is generated in my JS file, in html page in humanized format. That is if my value is 2678282, it should be presented as 2,678,282. And width for 111,111 and 999,999 should be same. I know {{load humanize}} can be used if we are getting data from views.py file. Like {{data.Value|floatformat:2|intcomma}} But I have value generated in my JS file.. As $("#text-number").text(data.Value) and I am placing it in html in span tag as <span id="text-number"></span> Here how can I get its humanized format? -
How to setting token authentication (Djoser) with AbstractUser
I'm a new learner of REST, and now I want to build a token authentication (Djoser) for my app with AbstractUser for CRUD users based on Djoser, some examples tutorials using AbstractBaseUser, PermissionsMixin, and BaseUserManager instead of AbstractUser, so it advanced with Me ! I want to start with a simples way! Here is my model: class User(AbstractUser): username = models.CharField(max_length=50, unique=True, blank=False) password = models.CharField(max_length=100, blank=False) email = models.EmailField(unique=True, blank=False) phone = models.CharField(max_length=10, unique=True, blank=True, null=True) serializers.py class UserSerializer(serializers.ModelSerializer): apartment = serializers.StringRelatedField( many=True, required=False) class Meta: model = User fields = [ 'id','username','password','email','phone','apartment' ] extra_kwargs = {'password': {'write_only': True}} views.py class UserViewSet(viewsets.ModelViewSet): queryset = CustomUser.objects.all() serializer_class = UserSerializer permission_classes = [ permissions.IsAuthenticatedOrReadOnly, IsOwnerUserOrReadOnly] -
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. In models.py 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. Can some one help me. Thank you -
Crispy forms field_class not applying correctly
I have a Django form in which I use crispy-forms along with bootstrap5. Everything was alright until I wanted to changed the Layout of my form. As my form is constructed dynamically, I just wanted to define the value of a set element item which is under the form (field_name, layout_index). The goal was to define it as a FieldWithButton, as I couldn't find another way to do that. To do that, I modified my helper in the __init__ method of my form : self.helper[item[1]] = Div(FieldWithButtons(item[0], StrictButton("Add item")), id=f'div_id_{item[0]}', css_class='mb-3 row') This is rendered nearly correctly in my form, I have the FieldWithButton with Div etc. However, the div which contains my FieldWithButton doesn't take the field_class of my helper that I defined, and instead creates a <divclass='col-10'>...</divclass='col-10'>. There's juste a space which disappeared and messed everything up. How can I either remove the class='col-10' part of my div and put it as its class or differently define my Field as a FieldWithButton ? Here's my whole form class if needed : class ScriptInputForm(forms.Form): def __init__(self, *args, **kwargs): variables = kwargs.pop('variables') # All variables to render variables_names = [*variables] # under the form {'name':['type', 'description']} super().__init__(*args, **kwargs) for var … -
Django url adding twice the request.path to the URL
in Django, if I use {% url 'logout' %}, the path is added twice to the URL. An example of it: if I click logout btn the URL looks like https://server_name/appname/appname/logout/ which does not exist, and actually I want to have https://server_name/appname/logout/ Here are my code. template: <li class="nav-item"> <a class="nav-link btn btn-logout" tabindex="-1" href="{% url 'logout' %}" >Logout</a > </li> url: urlpatterns = [ path('', views.index, name='index-pages'), re_path(r'^login/$', views.login_page, name='login'), re_path(r'^logout/$', views.logout_user, name='logout'), ] main app url: urlpatterns = [ path('', include('pages.urls')), path('dashboards/', include('dashboards.urls')), path('django_plotly_dash/', include('django_plotly_dash.urls')), re_path('admin/', admin.site.urls), ] but if I change the template to <li class="nav-item"> <a class="nav-link btn btn-logout" tabindex="-1" href="logout" >Logout</a > </li> it is working, however, I have in some other places which I can't change. How can I prevent Django from adding the path to URL? -
Django - problem in workink with annotate
I want write a query for select best users(I have a model with name "LastResult". The best user is the one who have more LastResult object.) best_users = LastResult.objects.filter(answer__accept=True).annotate(solved_count=).order_by("-solved_count", "-time") in solved_count I want get LastResult.objects.filter(answer__accept=True).filter(user=user #I do not know what to write in this part).count() and next I can order objects with solved_count field LastResult Model: class LastResult(models.Model): time = models.DateTimeField(default=timezone.now) user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='user_send_file', null=True, blank=True) question = models.ForeignKey(ProgrammingQuestion, on_delete=models.CASCADE, related_name='question_a', null=True, blank=True) answer = models.ForeignKey(ProgrammingQuestionAnswer, on_delete=models.CASCADE, related_name='answer_qu', null=True, blank=True) Thanks for any help. Thank you for your prompt reply. It is essential :)