Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django navlink URL are not working and receiving no error
enter image description here I have used django URL on navlink for some reasons unable to click on them and there is no error returning just nothing is happening. <nav class="main-nav"> <!-- ***** Logo Start ***** --> <a href={% url 'home_page' %} class="logo"> <img src={% static "assets/images/templatemo-eduwell.png" %} alt="EduWellTemplate"> </a> <!-- ***** Logo End ***** --> <!-- ***** Menu Start ***** --> <ul class="nav"> <li class="scroll-to-section"><a href={% url 'home_page' %} class="active">Home</a></li> <li class="scroll-to-section"><a href={% url 'services' %}>Services</a></li> <li class="scroll-to-section"><a href={% url 'contact_us' %}>Contact Us</a></li> <li class="scroll-to-section"><a href={% url 'home_page' %}>Login</a></li> <li class="scroll-to-section"><a href={% url 'home_page' %}>Buy now</a></li> </ul> <a class='menu-trigger'> <span>Menu</span> </a> <!-- ***** Menu End ***** --> </nav> urlpatterns = [ path('admin/', admin.site.urls), path('', views.home_page, name='home_page'), path('about-us/', views.about_us, name='about_us'), path('contact-us/', views.contact_us, name='contact_us'), path('services/', views.our_services, name='services') ] -
React i18next fails to load translation after in build
I don't know why react i18next display loading namespace fails on the debug console. I tried many suggestions without success. I'm using the react build folder inside Django project. It works fine on localhost:3000 only which is crazy but once i try to use the build folder I get the above error on the debug console i18n.js : import i18n from 'i18next'; import { initReactI18next } from 'react-i18next'; import Backend from 'i18next-http-backend'; import LanguageDetector from 'i18next-browser-languagedetector'; // don't want to use this? // have a look at the Quick start guide // for passing in lng and translations on init const Languages = ['ar', 'en', 'fr'] i18n .use(Backend) .use(LanguageDetector) .use(initReactI18next) // passes i18n down to react-i18next .init({ lng: 'en', react: { useSuspense: true, }, // the translations // (tip move them in a JSON file and import them, // or even better, manage them via a UI: https://react.i18next.com/guides/multiple-translation-files#manage-your-translations-with-a-management-gui) supported: ["en", "fr", "ar"], fallbackLng: "en", detection: { order: ['path', 'cookie', 'htmlTag', 'localStorage', 'subdomain'], caches: ['cookie'], }, debug: true, whitelist: Languages, interpolation: { escapeValue: false, // not needed for react as it escapes by default }, nsSeperator: false, keySeperator: false, backend: { loadPath: '/locales/{{lng}}/{{ns}}.json', }, }); export default i18n; index.js : import … -
Why does Django ORM do operations on my timestamp field even if I didn't setup TIME_ZONE and USE_TZ in my settings.py
Django ORM seems to be converting my timestamp in a weird way and I'm not sure why. Currently, our app doesn't have the settings TIME_ZONE and USE_TZ. There wasn't any need so far so we didn't use it. Now, I'm trying to show some specific timestamp details while we don't have the settings mentioned above The insert to the database (postgresql) works ok. the field that I'm using is timestamp with time zone. The timezone set in my local DB is "Asia/Singapore" db value is: "2022-07-01 23:09:14.253877+08" which is correct. Now, if I try to retrieve this value, what I get from the Django object is: 2022-07-01 10:09:14.253877. which is totally of and not even close to UTC. The timestamp value got converted to a different timezone (like for MST which is -7 from UTC). But it's actually not following any pattern since I also had some test data added at 1:11:00PM but the stamp retrieved from the Django ORM is 00:11:28.848820 To summarize, my question is how does Django ORM treat a timestamp value if TIME_ZONE and USE_TZ settings are not configured. I was naive to expect that it will retrieve the value as is from the database but … -
Django Rest Framework"detail": "Method \"GET\" not allowed."
I;m trying to build api by using django rest framework but I got the issue. @api_view(['PUT', ]) def api_update_blog_view(request, title): try: post = Post.objects.get(title=title) except Post.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) if request.method == 'PUT': serializer = PostSerializer(post, data=request.data) data = {} if serializer.is_valid(): serializer.save() data["success"] = "update successful" return Response (data=data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) urlpatterns = [ path('<str:title>/update', api_update_blog_view, name="update"), ] When I'm trying to update post I can see "detail": "Method "GET" not allowed." error. Where is the issue ? -
django startproject problem in python everywhere
I have been struggling with this problem in python everywhere. how could I resolve it? -
how to add an image in a django project?
I created a search bar in a Django project and I want to add an image to it. The code for this search bar is in the templates folder listed by Django. Here is the code: /*For search bar*/ input { background-image:url(" images/loup.png "); background-position:left; background-repeat:no-repeat; padding-left:18px; width:175px; } ... ... <input type="search" name="search" placeholder="Search here..." autofocus x-webkit-speech/> In the same templates folder, I created an images folder which contained the image to display in the bar. But when I run my Django server, the search bar shows on a page, but the image does not. In order for Django to list the image path on the hard drive, I took inspiration from this question and the Django documentation and I added to my urls.py file this: urlpatterns +=static(settings.IMAGE_URL, document_root=settings.IMAGE_ROOT) and this to my settings.py file: IMAGE_URL = 'templates/images/' IMAGE_ROOT = os.path.join(BASE_DIR,'images') the STATIC_URL variable being already defined in my settings.py file. I moved my images folder into the staticfiles folder generated by Django. The error still reoccurs. Even when I change the path of my image in my index.html file: background-image:url(" ../staticfiles/images/loup.png "); -
Render in Django without return
I like to write code for a website using django where the user can make a request to a backend. Since the request takes some time to get the answer from the backed, I like to render the same page to include a loading animation. For this purpose, I set a variable "show_loading" on "true" to display the loading animation via the hmtl-file. The code is as follows: views.py def UploadView(request): show_loading = True context["show_loading"] = show_loading render(request,'UPLOAD.html',context) data = {} #something else happening, just logical operations return render(request,'UPLOAD.html',context) UPLOAD.html: {% if show_loading %} <div class="loader"> <div class="inner one"></div> <div class="inner two"></div> <div class="inner three"></div> </div> {% endif %} The problem is that the render function is not working by the first render line (without return) but with the second render line (with return). So the question is, does render always need return or what I am doing wrong here, that the render does not work without return? Thanks for your help in this matter. PS: I wish not to use javascript or something else, I like to use the django function with context -
Use dataset registed in on pipelines in AML
I was following the SDK v2 Python tutorial in order to create a pipeline job with my own assets. I notice that in this tutorial they let you use a csv file that can be downloaded but Im trying to use a registered dataset that I already registered by my own. The problem that I facing is that I dont know where I need to specify the dataset. The funny part is that at the beginning they create this dataset like this: credit_data = ml_client.data.create_or_update(credit_data) print( f"Dataset with name {credit_data.name} was registered to workspace, the dataset version is {credit_data.version}" ) But the only part where they refer to this dataset is on the last part where they # the line: registered_model_name = "credit_defaults_model" # Let's instantiate the pipeline with the parameters of our choice pipeline = credit_defaults_pipeline( # pipeline_job_data_input=credit_data, pipeline_job_data_input=Input(type="uri_file", path=web_path), pipeline_job_test_train_ratio=0.2, pipeline_job_learning_rate=0.25, pipeline_job_registered_model_name=registered_model_name, ) For me this means that I can use this data like this (a already registered dataset), the problem is that I don't know where I need to do the changes (I know that in the data_prep.py and in the code below but I don´t know where else) and I don't know how to set this: … -
if file and not file._committed: AttributeError: 'Template' object has no attribute '_committed'
Here I want to create or get an entry from DB. The problem is when I'm referring to the template inside media/templates/emails/nice.html. I'm unable to get that and getting the error mentioned in the title. my template settings in setting.py is following; TEMPLATE_DIR = BASE_DIR / 'media/templates' 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', ], }, }, ] Next I;m working in accounts/test.py # CREATE Template data = { "user":user, "platform_subscriber":project, "name": "Test one", "html_template": loader.get_template("emails/nice.html") } email_template, created = EmailTemplate.objects.custom_get_or_create(data) print("The key",email_template) self.email_template = email_template.id error; if file and not file._committed: AttributeError: 'Template' object has no attribute '_committed' ---------------------------------------------------------------------- Ran 1 test in 3.440s -
Responsive List django
Good afternoon ! I'm building a "Family Tree" website using django python but I have one problem, this is computer list my list when i use computer, if I use my mobile phone i have this problem mobile list. I use library django-mptt who bulid this list: <ul class="root"> {% recursetree GT %} <br><li> <details open class="detail"> <summary><a href="{% url 'person-detail' node.id %}?id={{node.id}}">{{ node.name }} </a><span><sup>{% if node.date_birthday|date:'d.m' == '01.01' %} ({{node.date_birthday|date:'Y'}} - {{node.date_death|date:'Y'}} г.г) {% else %}({{node.date_birthday|date:'d.m.Y'}} - {{node.date_death|date:'d.m.Y'}} г.г){% endif %}</sup></span></summary> {% if not node.is_leaf_node %} <ul class="children"> <a href="#">{{ children }}</a </ul> {% endif %} </details> </li> {% endrecursetree %} How can I make a responsive list using CSS or JS so that it displays correctly on the phone ? -
Update a datetime field in django using an ajax call
I have a Profile model assigned to a user which contains the field : consent = models.DateTimeField(default=timezone.now, blank=True, null=True) I have created a switch in frontend in which the user gives consent for data tracking or no and and ajax call for handling the response. It seems to work fine , it is printing the correct outputs but the datetime does not save in the database. Any idea what is wrong? def user_consent(request): edited_user = request.user # if no user is specified, then we take the signed in user if request.is_ajax and request.method == "GET" : value = request.GET['toggle'] print(value) if value == 'true': edited_user.profile.consent = timezone.now() edited_user.save() print(edited_user.profile.consent) return JsonResponse({"ok": "no errors"}, status=200) else: edited_user.profile.consent = None edited_user.save() print(edited_user.profile.consent) return JsonResponse({"ok": "no errors"}, status=200) return JsonResponse({"error": "there was an error"}, status=400) The outputs im getting in console : [01/Jul/2022 14:53:50] "GET /users/consent?toggle=false HTTP/1.1" 200 19 true 2022-07-01 14:53:51.911242+00:00 [01/Jul/2022 14:53:51] "GET /users/consent?toggle=true HTTP/1.1" 200 19 false None [01/Jul/2022 14:53:53] "GET /users/consent?toggle=false HTTP/1.1" 200 19 true 2022-07-01 14:53:55.522132+00:00 [01/Jul/2022 14:53:55] "GET /users/consent?toggle=true HTTP/1.1" 200 19 false None [01/Jul/2022 14:55:08] "GET /users/consent?toggle=false HTTP/1.1" 200 19 -
Name xmlrpc is not defined
Im trying to extract data from odoo using xml-rpc api. import xmlrpc.client url = "https://xxxxxx.odoo.com/" db = "xxxxxxx" username = " " password = "" common = xmlrpc.client.ServerProxy('{}/xmlrpc/2/common'.format(url)) However it said that name 'xmlrpc' is not defined, it is very weird since xmlrpclib is part of the standard library in Python, i dont need to install it. Can you suggest solution for this? Thanks. -
How to map virtual environment's Python instead of the global on Windows production server for a django project
I have a Django project running on the production on Windows 10. I am using nginx and waitress. I've been using the global Python on my server (Python 3.9.5). I was wondering how I can use a virtual environment instead of the global on the production server? I can't figure out how I can map my django application to the new python in the virtual environment. Any ideas how I can accomplish that? -
Django url-erro
Am a begineer in django and i am trying to link my django app's(called base) urls into the my project urls file but i keep getting errors And yes i created a file for urls in my app called apps.urls from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('base.urls')),] -
Cannot establish connection from Django to MySQL
I built 2 containers, one for project with python-3.4.10 and another for MySQL (with mysql-5.7-debian). When I try to run any command for example: python manage.py makemigrations {name} or python manage.py runserver 0.0.0.0:8000 it gives me the following error: django.db.utils.OperationalError: (2003, 'Can\'t connect to MySQL server on \'127.0.0.1\' (111 "Connection refused")') I have literally tried everything and went through each stack issues related to it. But the issue still persists. When I connect on MySQL Workbench (which is installed on my base OS: Windows 11) with the running MySQL container, it gets connected but when I run the command of python manage.py ... on the different container it shows me the above error. Could you please help me out here? Thank you. settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 's_db', 'USER': 'root', 'PASSWORD': 'root', 'HOST': '127.0.0.1', 'PORT': '3306', } } docker-compose.yaml version: '3.8' services: web: image: s-compose:latest ports: - 8000:8000 command: > sh -c "python manage.py runserver 0.0.0.0:8000" volumes: - ./s:/home/app/webapp depends_on: - database database: image: mysql:5.7-debian ports: - 3306:3306 environment: MYSQL_ROOT_PASSWORD: root .Dockerfile FROM python:3.4.10 ENV Dockerhome=/home/app/webapp RUN mkdir -p $Dockerhome WORKDIR $Dockerhome COPY ./sansthaonline $Dockerhome RUN pip install -r req.txt; exit 0 EXPOSE 8000 ## testing … -
.env file didn't copy into docker container on AWS EBS
I have the following project structure locally |-- docker-compose.yml |-- docker-entrypoint.sh |-- Dockerfile |-- nginx | `-- loc | `-- nginx.conf |-- poetry.lock |-- pyproject.toml `-- src |-- my_project | |-- asgi.py | |-- __init__.py | |-- settings.py | |-- urls.py | `-- wsgi.py |-- __init__.py |-- manage.py |-- .env In Dockerfile I have the following line COPY /src/ /workdir/ Elastic Beanstalk takes env variable and stores them in .env file by the following path /var/app/current then when the container has been built, the env file wasn't copied inside. I made a workaround by copying .env file COPY .env /workdir/ but it doesn't look like a good solution. Should I move everything from /src folder to one level above? -
How do I update an existing many to many field in Django REST?
I have a plot model like this: class Plot(models.Model): garden = models.ForeignKey('perma_gardens.Garden', on_delete=models.CASCADE) plant = models.ManyToManyField('perma_plants.Plant', related_name='%(class)s_plant', blank=True) def __str__(self): return self.name It contains a field for plants in many to many. In my database, I already have several plants created. And I would like to be able to update the plot model by adding plants to it by ID, I realized a function partial_update in the views.py file but when I update the plot by adding a plant to it based on its ID, it tells me that: "A plant object with this custom id field already exists." Here is my serializers.py file : class GardenSerializer(serializers.ModelSerializer): class Meta: model = Garden fields = ('id', 'name',) class PlantSerializer(serializers.ModelSerializer): class Meta: model = Plant fields = ('custom_id', 'name', "category", 'image', 'facility_rate', 'sunshine_index', 'irrigation_index') class WritePlotSerializer(WritableNestedModelSerializer, serializers.ModelSerializer): plant = PlantSerializer(many=True) class Meta: model = Plot fields = '__all__' Here is my views.py file : class PlotViewSet(viewsets.ModelViewSet): queryset = Plot.objects.all() def create(self, request, *args, **kwargs): serializer = WritePlotSerializer(data=request.data, many=isinstance(request.data, list)) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) def partial_update(self, request, *args, **kwargs): instance = self.queryset.get(pk=kwargs.get('pk')) serializer = WritePlotSerializer(instance, data=request.data, partial=True) serializer.is_valid(raise_exception=True) serializer.save() return Response(serializer.data) def delete(self, request, pk): snippet = … -
How can i see my installed Django on Centos 7 server?
I newly installed django on centos 7 server but how can i see my working django website. I have server ip address and also website. Firstly Do I need to change the domain dns with the server ip address? -
Django WebSocket Routing "Not route for path"
I'm trying to get a simple Django Web App with WebSockets going, and can't get the routing to work. I have a basic Consumer, ProgressConsumer, that is used as base for two other Consumers. class ProgressConsumer(WebsocketConsumer): max_anims = None def connect(self): # self.set_max_anims() self.log_cache = "" print("Websocket connected.") if (not self.max_anims): raise NotSetError("max_anims not set") self.room_group_name = "progress" self.accept() self.start_progress_update() def start_progress_update(self): cached_progress = 0 progress = 0 while progress != 100.0: time.sleep(1) if (updates := self.get_log_updates()) == "": continue if "Error" in updates: self.send(json.dumps({"error": updates})) self.clean_log() self.close(3000) return if (progress := self.calculate_progress(updates)) == cached_progress: continue self.send(json.dumps({ 'type': 'progress', 'message': progress, })) cached_progress = progress def disconnect(self, close_code): print("Websocket disconnected. Code: ", close_code) def get_log_updates(self) -> str: if self.log_cache == self.get_log_cache(): return "" s1 = set(self.log_cache.split("\n")) s2 = set(self.get_log_cache().split("\n")) self.log_cache = self.get_log_cache() return str(s1.symmetric_difference(s2)) def calculate_progress(self, difference: str) -> float: if not "Animation" in difference: return 0.0 animation_id = float(re.search("Animation (\d+)", difference).group(1)) return ((animation_id + 1) / self.max_anims) * 100.0 def clean_log(self): raise NotImplementedError("clean_log not implemented") def get_log_cache(self) -> str: raise NotImplementedError("get_log_cache not implemented") The two other consumers are: class FunctionImagesProgressConsumer(ProgressConsumer): max_anims = 4 def clean_log(self): with open("function_images/project_files/logs/_ComplexFunctionScene.log", "w") as f: f.write("") def get_log_cache(self) -> str: with open("function_images/project_files/logs/_ComplexFunctionScene.log", "r") as … -
Django : Ignore a __in type filter in the queryset if it searches the empty list
Having this code sequence queryset = self.filter( brand_id__in=( UserObjectPermission.objects.filter( content_type=brand_ctype, user=user, ).values_list('object_pk') ) ) If there is no UserObjectPermission object that matches the filter content_type=brand_ctype, user=user then the end result will be empty queryset, because brand_id __in will search in [empty queryset]. But I need the reverse. If there is no UserObjectPermision object for this filter (content_type=brand_ctype, user=user) then return all objects, that is, ignore this filter ( brand_id__in=(UserObjectPermission.objects.filter( content_type=brand_ctype, user=user, ).values_list('object_pk') ) I need the brand_id__in filter to run only if there is at least one object in the queryset I hope I was quite understood. Please help) -
Redirecting the user to the same page after POST
I'm building a tournament organizing tool but I have run into an issue. I have a view called index (currently the only view) that shows the tournament leaderboard as well as a table of unfinished matches and a table of finished matches. For each of the unfinished matches I have added an input field for each player where the user can type the scores. Each match also has a submit button. What I want to happen is that when the submit button is clicked, the match is finished and the match result (the scores in the input fields) are saved to the database. I then want the user to see the same page again (with the match moved from unfinished to finished). The problem I'm having is getting the player to be redirected to the same page again. I've tried looking around for similar questions and the answers to them and I have tried a couple of different things like if request.method == "POST": return render(request, './') or if request.method == "POST": return redirect(request.path) or if request.method == "POST": return index(request) all of them redirect me to /index.html which does not exist - my urlpatterns look like this urlpatterns = … -
How to reference a file from root folder to any django app folder
Here i'm create to create an entry which takes a HTML file input. Now I'm trying to do with the following code but getting permission denied. How can I reference that HTML template in my testcase. # CREATE EMAIL TEMPLATE data = { "user":user, "platform_subscriber":project, "name": "TESTCASE TEMPLATE", "html_template": "../nice.html" } email_template, created = EmailTemplate.objects.custom_get_or_create(data) print("The key",email_template) self.email_template = email_template.id log : aise SuspiciousOperation("Attempted access to '%s' denied." % name) django.core.exceptions.SuspiciousOperation: Attempted access to '../nice.html' denied. -
Best way to create a dropdown of values from the same model and save it as text in a Charfield of same model
I have a model "TnaTemplateModel" class TnaTemplateModel(models.Model): id = models.UUIDField(primary_key = True,default=uuid.uuid4, editable=False) template_name = models.ForeignKey(TemplateNameModel, verbose_name="template name", null=False, blank=False, on_delete=models.CASCADE, help_text="Select the template") process_name = models.ForeignKey(ProcessModel, verbose_name="process name", null=False, blank=False, on_delete=models.CASCADE, help_text="Select the process") sequence = models.IntegerField(verbose_name="Process Sequence",null = False,blank = False) is_base = models.BooleanField() dependent_process = models.CharField(verbose_name="Dependent Process",null=True, blank= True,max_length= 150) formula = models.IntegerField(verbose_name="Formula", null= True,blank = True) remarks = models.CharField(verbose_name="Process remarks", null= True, blank = True,max_length= 300) class Meta: unique_together = ["template_name", "process_name"] def __str__(self): return str(self.template_name) I need to save entries from a form where dependent_process field will be a list of all processes in TNATemplateModel with the desired template_name and where is_base = True. For this I have created 2 views and 2 forms 1 each for first saving all the entries with is_base = True and second for saving entries which will have a dependent_process as a dropdown from the previously added is_base = true processes. Views.py #for saving processes with is_base = true def baseprocesscreatenew(request,pk): template_name = TemplateNameModel.objects.get(id=pk) data = {'template_name': template_name.id,'is_base': True} dependent_list = TnaTemplateModel.objects.filter(template_name = template_name.id) if request.method == 'POST': form = BaseProcessModelformNew(request.POST,initial= data) if form.is_valid(): form.save() return HttpResponseRedirect(reverse('templatepointslist_new',kwargs={'pk':pk})) else: form = BaseProcessModelformNew(initial= data) print(form.errors) return render (request,"tna/template_tna/baseprocessmodel_create.html",{'form':form,'dependent_list':dependent_list}) #for saving dependent … -
Django admin not showing users after user customization
I customized my user authentication. Using Django 3. In models.py I have; class User(AbstractUser): is_patient = models.BooleanField(default=False) is_dentist = models.BooleanField(default=False) is_manager = models.BooleanField(default=False) In views.py I have below for user creation and login; def create_account_dentist(request): if request.method == 'POST': #Create Dentist Type User username = request.POST.get('username') password = request.POST.get('password') mobile_num = request.POST.get('mobilenum') user_profile = User() user_profile.username = username user_profile.email = username user_profile.set_password(password) user_profile.is_dentist = True user_profile.is_staff = True user_profile.is_active = True user_profile.mobile_number = mobile_num user_profile.save() login(request, user_profile) return redirect(reverse('dentist-section')) My sttings.py : AUTH_USER_MODEL = 'myapp.User' When i check /admin page i see only groups section. But i want to see the users, permissions and user groups together. My DB tables are : auth_group, auth_group_permissions, auth_permission, django_admin_log, django_content_type, django_migrations, django_session, myapp_dentist, myapp_manager, myapp_patient, myapp_user, myapp_user_groups, myapp_user_user_permissions Although i created users in myapp_user, i dont see and manage them in django admin page Below is screeshot from myapp_user table : -
Multiple translations for given entity in Django
I have a Django app, where one of the universal entities is called Organization. But this is a multitenant applications, and some tenants call their organizations 'Companies', another call them 'Pharmacies' - it depends of their business type. The types of organization are known upfront, so I can prepare translations for their names (in two or more languages) and store a preference which one to use. My question is: how can I select translation in the view depending of the tenant setting?