Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
while I am hovering on main category then I am getting a drop down of sub category. but it hiding behind another div. How to prevent
while I am hovering to an main category I am getting fine sub category drop down but the sub category drop down is hiding behind the image as you can see in the image I have attached.So here I have use "z-index:1" but it is not working so how to solve this issue please let me know <div class="dropdownCategory"> <a class="dropbtnCat" href="{% url 'coupons' Categories.cat_name %}">{{Categories.cat_name}}<i class="arrow-indicator fa fa-angle-right" aria-hidden="true"></i></br></a> <div class="dropdown-contentCat"> {% for subCategories in SubCategoriesBar %} {% if Categories.cat_id == subCategories.parent_id %} <a href="{% url 'coupons' subCategories.cat_name %}">{{subCategories.cat_name}}</a> {% endif %} {% endfor %} </div> </div> css .dropdown-contentCat { display: none; position: absolute; background-color: #f1f1f1; min-width: 160px; box-shadow: 0px 8px 16px 0px rgb(0 0 0 / 20%); z-index: 1; left: 101%; top: -2px; border-top: 2px solid #DB0038; font-size: 14px; } -
How to save data in both (user and profile) tables using django signals in a single request?
I have a register form with fields(firstname, lastname, username, email, dateofbirth, phoneno.) I have used signals to create a record in userprofile. whenever a new userdata is added to the user table what i want is whenever user post the request. the data should get saved in user table and then the signal creates a record in profile table and then the remaining data should also get populated in there respected fields. As I'm receiving all the data from user at the registration time. views.py def register(request): if request.method == "POST": print(request.POST) first_name = request.POST.get('first-name') <-----user table last_name = request.POST.get('last-name') <-----user table username = request.POST.get('username') <-----user table email = request.POST.get('email') <-----user table gender = request.POST.get('gender') <-----profile table date_of_birth = request.POST.get('date-of-birth') <-----profile table address = request.POST.get('address') <-----profile table phone_number = request.POST.get('mob-number') <-----profile table ans_1 = request.POST.get('ans-1') <-----profile table ans_2 = request.POST.get('ans-2') <-----profile table User.objects.create_user(first_name=first_name, last_name=last_name, email=email, username=username, last_login=timezone.now()) return render(request, 'authentication/register.html') signals.py @receiver(post_save, sender=User) def create_user_info(sender, instance, created, **kwargs): if created: UserInformation.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_info(sender, instance, **kwargs): instance.userinfo.save() -
Django-cron check running proceses
Is there any way to get the crons that are runging and wich one? if any. I'm usign the library Django-Cron: https://django-cron.readthedocs.io/en/latest/index.html ¿Why? I want to allow the user to start a process with an action from Admin site. But if the process is running I will skip the order and deliver the message that there's a process already running. Thank you. -
Django change temporary path while uploading files
By default Django stores all its temp files in "/tmp" when files are uploaded. I tried to change the FILE_UPLOAD_TEMP_DIR in settings.py to give a custom path. But Django fails to take the new path. Tried the following properties in settings.py FILE_UPLOAD_HANDLERS = ( 'django.core.files.uploadhandler.MemoryFileUploadHandler', 'django.core.files.uploadhandler.TemporaryFileUploadHandler', ) FILE_UPLOAD_MAX_MEMORY_SIZE = 2621440 FILE_UPLOAD_TEMP_DIR = "/datadrive/test" MEDIA_ROOT = '/datadrive/test' SESSION_FILE_PATH = '/datadrive/test' FILE_UPLOAD_DIRECTORY_PERMISSIONS = 0o644 FILE_UPLOAD_PERMISSION = 0o644 -
I can't view my template with render in django
My template with called hello.html <h1>Hello World</h1> My views.py from django.shortcuts import render from django.http import HttpResponse def say_hello(request): return render(request,'hello.html') Also if i try return HttpResponse('Hello World') it is working. But rander is not working. -
HTML Modal not functioning in Django application
I am trying to implement this codepen into my Django program. I don't know why, but I just can't get it to work. I have all of the classes and everything names correctly, but my program does not do anything. I want the user to be able to click on the view button and have an HTML overlay exactly like the one in the codepen come up, but for some reason nothing is happening when I click on the button. Can someone please take a look and tell me what I am doing wrong? Thank you. HTML: {% extends 'suppliesbase.html' %} {% load static %} {% block content %} <div class="row"> {% for donation in donations %} <div class="col-lg-4"> <img class="thumbnail" src="{{donation.imageURL}}"> <div class="box-element product"> <h6><strong>{{donation.title}}</strong></h6> <hr> <button class="btn btn-outline-success" id="openModalBtn" href="#">View</button> <h4 style="display: inline-block; float: right"><strong>Free!</strong></h4> </div> </div> {% endfor %} </div> <!--Modal Overlay Content --> <div id="modal-overlay"> <div id="modal"> <div class="head"> <a id="close-modal-button" href="javascript:;"></a> </div> <div class="content">Modal content</div> </div> </div> <script> var openModalButton = document.getElementById("open-modal-button"); var closeModalButton = document.getElementById("close-modal-button"); var modalOverlay = document.getElementById("modal-overlay"); var modal = document.getElementById("modal"); // function that open modal and display the overlay openModalButton.addEventListener("click", event => { modalOverlay.classList.add("modal-overlay-visible"); modal.classList.add("modal-visible"); }); // function that closes the … -
Django: Ignore transaction for given update
I have a long-running process that should be atomic (Larger update of an application's data). However, during the update, I'd like to let the user know about the progress. How can I update a model from within the transactioned code, such that it is not part of said transaction? One potential solution would be to use non-DB storage, such as files, or a second DB connection with the same credentials. Both don't feel like the "right" way to do it... -
Django-selenium How to make download button work on a webclient of another website
I am building a website with Django. It displays the content of another website by scraping parts of its HTML with selenium and incorporating that code in my webpage to make it look better. For example, in one page, a table is passed to my website through the context and it's incorporated this way {% extends 'home.html' %} {% block content %} {{ table_name|safe }} {% endblock %} This table also has a download button in each row, and the number of rows changes over time (I don't know if that matters but anyway). In the table the download button is displayed but it doesn't work. Is there any way I can make it work? You should also know that the download button does not redirect to a link. -
Try, Except is not giving required result in django serializers create method. the getobject statements gives required result if put is outside try:
class BeneficiarySerializer(serializers.Serializer): class Meta: model = Beneficiary fields ='__all__' def create(self, validated_data): try: available = Beneficiary.objects.get(coupon_code=validated_data['coupan_code']) raise serializers.ValidationError("The provided coupon code is already utilized") except: return super().create(validated_data) class Coupon(models.Model): sl_no = models.CharField(max_length=50, primary_key=True) c_code = models.CharField(max_length=50, blank=True) def __str__(self): return self.c_code class Beneficiary(models.Model): name = models.CharField(max_length=50) coupon_code = models.ForeignKey(Coupon, on_delete=models.CASCADE) def __str__(self): return self.name purpose is to issue a coupon to only one person, if the same coupon code is issued to another in that case Serializers should raise and error that the key is issued to someone. if i put the code in try and except every time the verification fails, the same coupon code is allotted to many, if use objects.get outside try: statement is return result is found. please let me know if i am not using try: except in proper way or any other way to deal with this situation -
Why Python String auto convert into Date in microsoft excel
I am writing data into a CSV file. file contains data related to student marks like 6/10, which means 6 out of 10. issues are when I open this file with Microsoft excel 6/10 becomes 6-Oct. here is anyone have an idea how can we stop to converting a string to date. need solution from code side not an excel side -
NameError: name 'StudentsSubscription' is not defined IN DJANGO SAVE METHOD
I am trying to filter entries from the child model in parent model save method to show in admin pannel,But getting this error class StudentsSubscription(models.Model): student = models.ForeignKey('student.Student', on_delete=models.CASCADE,blank=True,null=True,help_text = "This Field Is Mandatory") enrolled_activity = models.ForeignKey('student.EnrolledActivity', on_delete=models.CASCADE,blank=True,null=True,help_text = "This Field Is Mandatory") teachers_class = models.ForeignKey('teacher.TeachersClass',on_delete=models.CASCADE,blank=True,null=True,related_name='subscription_name') demo_class = models.BooleanField(default=False,blank=True,null=True) is_finished = models.BooleanField(default=False,blank=True,null=True) channel_name = models.CharField(max_length=250,blank=True,null=True) count = models.IntegerField(default=0,blank=True,null=True) room_id = models.IntegerField(blank=True,null=True) is_active = models.BooleanField(default=False,blank=True,null=True) class TeachersClass(models.Model): class_name = models.CharField(max_length=250,blank=True,null=True) description = models.TextField(blank=True,null=True) batch_size = models.IntegerField(default=0) seats_left=models.IntegerField(default=0) image = models.ImageField(upload_to='teacher/class',blank=True,null=True) teacher = models.ForeignKey(Teacher,on_delete=models.CASCADE,blank=True,null=True,help_text = "This Field Is Mandatory") grade = models.ForeignKey(Grade,on_delete=models.CASCADE,blank=True,null=True,help_text = "This Field Is Mandatory") activity = models.ForeignKey(Activity,on_delete=models.CASCADE,blank=True,null=True,help_text = "This Field Is Mandatory") days = models.ManyToManyField(DaysOfWeek,blank=True) date = models.DateField(blank=True,null=True,help_text = "This Field Is Mandatory") start_time = models.TimeField(blank=True,null=True,help_text = "This Field Is Mandatory") end_time = models.TimeField(blank=True,null=True,help_text = "This Field Is Mandatory") is_active = models.BooleanField(default=False,blank=True,null=True) agora_token = models.CharField(max_length=250,blank=True,null=True) free_trial = models.BooleanField(default=False,blank=True,null=True) background1 = models.CharField(max_length=250,blank=True,null=True) background2 = models.CharField(max_length=250,blank=True,null=True) button_color1 = models.CharField(max_length=250,blank=True,null=True) button_color2 = models.CharField(max_length=250,blank=True,null=True) image = models.ImageField(upload_to='class/image',blank=True,null=True) def save(self, *args, **kwargs): all_admissions=StudentsSubscription.objects.filter(teachers_class__class_name=self.class_name).count() print(all_admissions) super(TeachersClass, self).save(*args, **kwargs) I am unable to figure out the issue -
How to access a file outside from a docker container?
I am using django as my framework. To manage the server we are using docker. When I try to run: docker-compose exec -T web python3 manage.py shell < /data01/ipse/litework/second_level_controller/load.py to load some data I get the following Error: File "/code/second_level_controller/DataBaseLoader.py", line 53, in load_filenames with open(os.path.join(self.data_directory, 'manifest.txt')) as f: FileNotFoundError: [Errno 2] No such file or directory: '/data01/ipse/rawdata/manifest.txt' But the file /data01/ipse/rawdata/manifest.text exists and I can acces the file normally with: nano /data01/ipse/rawdata/manifest.txt How can I access the file correctly? -
Looking for guidance on creating a search engine using a django web framework [closed]
Hi i would like to look for guidance on creating a search engine using a django web framework. I am not to sure how to proceed as I do not really have an experience on this. I would like to create a search engine on the website that I am building, whereby it will search from a shortlisted list of websites. -
Django - when user submits a form, tables are created, but the connection between the tables is not
i am working on a small project where a customer can go to my website and register phone numbers associated to their name. it is a connection-wise registration (where number1 <--> number2 is one connection), so only two phone numbers are ever registered per session. when viewing a particular phone number (in admins panel, for instance), i want to see the id of the user it belongs to and the id of the connection it is part of. When i view a connection the same way, i want to see who registered that particular connection, and the two phone numbers that were registered in the same session. my problem: all of the foreign keys give a "django.db.utils.IntegrityError: NOT NULL constraint failed" error. I had to set null=True for all of the foreign keys for the customer's data to be submitted at all. the ManyToManyField doesn't give any bugs - but it doesn't limit each Connection to only the two phone numbers registered in the session like it should. and so, this kind of structured connection outlined above isn't made when the data is added. it's like each phone number and each connection and each user becomes its own little island, … -
Add Task doesnot working in django in ToDo List
this is task_list.html <!--if we didnt create this tasklis.html we get error becoz as said in views .py it looks for tempate we diidnt cdreated any list on template et--> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>To Do List By Manasi</title> </head> <body> {% if request.user.is_authenticated %} <p>{{ request.user }}</p> <a href="{% url 'logout' %}">Logout</a> {% else %} <a href="{% url 'login' %}">Login</a> {% endif %} <hr> <h2>WELCOME To My To List! </h2> <a href="{% url 'create-task' %}">Add task</a> <table bgcolor="yellow" align="center" border="2px"> <tr> <th>Task Name</th><th> Task Details</th><th>Edit Task</th><th align="center">Delete Task</th> </tr> {% for task in tasks %} <!--for task in object_list %}this is when we havent created objet context list yet in view.pywhen view.py only contains model=Task--> <tr><td align="center">{{task.title}}</td><td align="center"><a href=" {% url 'task' task.id %}">View</a></td><td align="center"><a href=" {% url 'update-task' task.id %}">Edit</a></td> <td align="center"><a href=" {% url 'delete-task' task.id %}">Delete Task</a></td></tr> <!--i think this 'task' in url is context_objct_name in views.py but its false--> {% empty %} <!--this is django template format for empty condition likewise ele etc.--> <tr><td>No item</td></tr> {% endfor %} </table> </body> </html> **this is task_form.html for add task ie.create task** <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Create task Form</title> </head> <body> <h1>Create … -
Django style.css is not found
Error :Not Found: /{ % static 'css/style.css' % } "GET /%7B%20%%20static%20'css/style.css'%20%%20%7D HTTP/1.1" 404 2378 When i want to link my style.css to django project it throws an error. html : <!DOCTYPE html> {% load static %} <html> <head> <meta charset="utf-8"> <title>Have a Good Day</title> <link rel="stylesheet" href="{ % static 'css/style.css' % }" > </head> <body> <h1 class="ok">Great it works</h1> </body> </html> settings.py: STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] Note : DEBUG=True Folder structure : newproject : app1: migrations static css style.css templates init.py admin.py apps.py models.py tests.py urls.py views.py It is only for development . not deployment. -
How to import python code like a interface or service like in Laravel
I have this code in python for generating statistics, how can I optimize and make as many classes as possible to import this code https://gyazo.com/6aaca72d6c27595f619f026a40ece496 My code https://gyazo.com/440f5f25f8643245479ab29ab8e079c3 My structure -
Nested query in Django ORM
i'm try to remove duplicated row with distinct or annotate then measure count of something.(mysql:8 ,django:2.2) sql select t1.cp_id, count(*) from ( SELECT user_id, product_id, cp_id, count(*) as cnt FROM A where created_at between '2021-07-12' and '2021-07-13' group by user_id, product_id, cp_id ) as t1 group by t1.cp_id my queryset A.objects.filter( created_at__gte='2021-07-12', created_at__lt='2021-07-13' ).values('cp_id', 'user_id', 'product_id').annotate(cnt=Count('cp_id')).values('cp_id').annotate(count=Count('cp_id')) this queryset sql SELECT A.cp_id, COUNT(cp_id`) AS count FROM A WHERE ( created_at >= 2021-07-11 19:30:00 AND created_at < 2021-07-12 19:30:00 AND ) GROUP BY cp_id, created_at ORDER BY created_at ASC I'm confused why Django ignores the order of my commands and executes the last query commands on the original table (not the table where the duplicate data is deleted) Thanks if you have a solution or idea to remove the rows that have the same 'cp_id', 'user_id', 'product_id' (not from the database), then count the number of cp_ids -
URL automatically changes & it gives me the error of Page not found
"127.0.0.1:8000/adminpanel/edit_gallary/29" So this is the main problem when I first edit it works properly. But when I want to edit the second time URL automatically changes & it changes this way. "127.0.0.1:8000/adminpanel/edit_gallary/edit_gallary/29" This is my views.py file: def edit_gallary(request,gallaryid): table = gallary.objects.get(id=gallaryid) gallary_form = gallaryform(instance=table) if request.method=='POST': form = gallaryform(data=request.POST, files=request.FILES, instance=table) if form.is_valid(): form.save() table=gallary.objects.all() return render(request,"gallary1.html",{'table':table}) context = {'gallary_form':gallary_form} return render(request,'edit_gallary.html',context) This is my URLS.py file: path('edit_gallary/<int:gallaryid>',views.edit_gallary,name="edit gallery"), This is my edit_gallary.html file: {% extends 'index.html' %} {% block content %} <body> <div class="main-wrapper"> <div class="app" id="app"> <header class="header"> <div class="header-block header-block-collapse d-lg-none d-xl-none"> <button class="collapse-btn" id="sidebar-collapse-btn"> <i class="fa fa-bars"></i> </button> </div> <div class="header-block header-block-nav"> <ul class="nav-profile"> <li class="profile dropdown"> <a class="nav-link dropdown-toggle" data-toggle="dropdown" href="#" role="button" aria-haspopup="true" aria-expanded="false"> <div class="img" style="background-image: url('https://avatars3.githubusercontent.com/u/3959008?v=3&amp;s=40')"> </div> <span class="name">Admin</span> </a> <div class="dropdown-menu profile-dropdown-menu" aria-labelledby="dropdownMenu1"> <div class="dropdown-divider"></div> <a class="dropdown-item" href="#"> <i class="fa fa-power-off icon"></i> Logout </a> </div> </li> </ul> </div> </header> <aside class="sidebar"> <div class="sidebar-container"> <div class="sidebar-header"> <div class="brand"> <div class="logo"> <span class="l l1"></span> <span class="l l2"></span> <span class="l l3"></span> <span class="l l4"></span> <span class="l l5"></span> </div> Compare school </div> </div> <nav class="menu"> <ul class="sidebar-menu metismenu" id="sidebar-menu"> <li> <a href="insert_school"> <i class="fa fa-home"></i>Back</a> </li> </ul> </nav> </div> </aside> <div class="sidebar-overlay" id="sidebar-overlay"></div> <div class="sidebar-mobile-menu-handle" … -
How to sync a large CSV file with Django model
I want to process item report every hour for multiple accounts in my system. There are around 150k+ records in each csv. I want to sync report with database in the following way. Create record if it does not exists Update if it is present I want to do this in bulk (in one database query) Currently I am doing get or create for each record. I am using Postgres=13.2, Django=3.2.5 and python=3.9 -
Passing a URL into render_as_string
Is there a way to pass a URL instead of a template name in render_as_string. If not what can we use? # something like this def my_view_(request): if request.POST.get == 'POST': is_ajax = request.META.get('HTTP_X_REQUESTED_WITH') == 'XMLHttpRequest' if is_ajax: return JsonResponse(data={ 'string_template': render_as_string('a url here'), # or we have something other than render_as_string which takes URLS }) -
If a queryset value is in a list
I'm new to python but am surprised I can't find another post with a similar question to mine. I'm trying to find a way to compare whether a queryset value is inside a list. Take this as an example: account_roles = <QuerySet [<Group: admin>, <Group: customer>]> allowed_roles = ['admin', 'customer', 'supplier', 'observer'] if account_roles in allowed_roles: print('Authorised') Essentially a user has account_roles and I only want to print 'authorised' if a user with an admin or customer role is present. I can only get a comparison working for a single value, but an the entire list of values. Example working for a single value only: if request.user.groups.exists(): group = request.user.groups.all()[0].name if group in allowed_roles: return view_fn(request, *args, **kwargs) Can someone show me how this is done? -
Activation of virtual environment for python in PowerShell the parenthesis not showing does it matter when shell confirms env is on?
My PowerShell virtual environment activates the virtual environment for my Django project but does not show the parenthesis does it really matter. C:\Users\xxx\.virtualenvs\mb-g7VMb0x7 already activated. I cannot use Scripts\activate as I installed my virtualenv using pipenv not virtualenv -p python . which normal carry the scripts folder. On my Vscode the parenthesis shows that I am in a virtual environment (mb) PS E:\Dev\mb. -
How to make redirecting to services in Django / Vue / Nuxt / nginx docker-compose app work?
I'm building Django / Vue / Nuxt (not yet included) app; I would like Django to run after calling localhost/backend/, and Vue after calling localhost/panel/. So far I've managed to create docker-compose.yml shown below: version: "3" services: web: build: context: ./web restart: always volumes: - static_volume:/usr/local/src/app/static - media_volume:/usr/local/src/app/media ports: - 1300:80 depends_on: - backend - panel backend: build: context: ./izba-backend dockerfile: Dockerfile.prod args: GIT_USER_NAME: ${GIT_USER_NAME} GIT_USER_EMAIL: ${GIT_USER_EMAIL} command: gunicorn backend.wsgi:application --bind 0.0.0.0:8000 environment: DB_HOST: db DB_PORT: 3306 SECRET_KEY: ${SECRET_KEY} DEBUG: ${DEBUG} ALLOWED_HOSTS: ${ALLOWED_HOSTS} ports: - 8000:8000 depends_on: - db volumes: - static_volume:/usr/local/src/app/static - media_volume:/usr/local/src/app/media db: image: mariadb restart: always environment: MYSQL_ROOT_PASSWORD: ${MYSQL_ROOT_PASSWORD} MYSQL_DATABASE: ${MYSQL_DATABASE} panel: build: context: ./izba-panel ports: - 8080:8080 volumes: static_volume: media_volume: and set of nginx's .conf files for backend and panel services: backend.conf upstream backendapp { server backend:8000; } server { listen 80; location /backend/ { proxy_pass http://backendapp/; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_redirect off; } location /static/ { alias /usr/local/src/app/static/; } location /media/ { alias /usr/local/src/app/static/; } } panel.conf upstream panelapp { server panel:8080; } server { listen 80; location /panel/ { proxy_pass http://panelapp/; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_redirect off; } } Unfortunately, the presented configuration does not work - it works only … -
Django Allauth and Salesforce: No_Oauth_State: State was not valid
I am having trouble setting up Salesforce as an auth provider for my Django application using Django Allauth, getting "No_Oauth_State: State was not valid" whenever I try to log in. What I've done: I made a connected app in Salesforce as documented here: https://trailhead.salesforce.com/en/content/learn/projects/build-a-connected-app-for-api-integration/create-a-connected-app I followed the steps outlined in the Salesforce documentation (https://help.salesforce.com/articleView?id=sf.sso_provider_sfdc.htm&type=5) to setup Salesforce as an auth provider. I pasted the consumer key and secret from my connected app into the auth provider settings and copied the callback uri (https://{my_sf_domain}/services/authcallback/salesforce) from my auth provider into the callback uri field of the connected app, as stated in the docs. I configured Salesforce as a provider in my django application as stated in the Allauth docs (https://django-allauth.readthedocs.io/en/latest/providers.html#salesforce) What happens when I try to log in: My application returns a 302 with the Location header set to: https://my.sf.domain/services/authcallback/salesforce/services/oauth2/authorize?client_id={super_secret}&redirect_uri=http://my.django.app.domain/accounts/salesforce/login/callback/&scope=id+openid&response_type=code&state={a_random_string_of_length_12} Salesforce returns a 302 at the uri the above Location header refers to, now with the Location header set to: https://my.sf.domain/_nc_external/identity/sso/ui/AuthorizationError?ErrorCode=No_Oauth_State&ErrorDescription=State+was+not+valid&ProviderId={auth_provider_id} I am unsure how to debug this. Why is the state not valid? Does Salesforce expect the state parameter to be of a certain format?