Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to optimise my query in a standard way?
Here I am making a model to track the views of the some pages. If some user visit some page with some url then this model will created . In this case this is working fine for now. But I have a question that If the table gets to big later (since the SESSION_COOKIE_AGE will be just for 1/2 hours) then there will be a lot data. One option could be deleting objects older than x_month but I if I did so then I will not get the actual count. I think db indexing will help to optimize the query but I am not familiar with database indexing much. For example in most cases page_url will be used as a filter then I should be adding db_index=True in my page_url field. ? Will this db indexing solve the problem? Or any other suggestion for better approach for this scenario ? class WebSiteVisitor(models.Model): page_url = models.CharField(max_length=30, editable=False) user_ip = models.CharField(max_length=30, null=True, editable=False) session = models.CharField(max_length=30, null=True, editable=False) date = models.DateTimeField(auto_now_add=True) # create if not WebSiteVisitor.objects.filter(page_url=url, session=request.session.session_key).exists(): # model create then # get visit count of the page return WebSiteVisitor.objects.filter(page_url=page_url).count() -
How to capture session id of a logged django user? [closed]
Is there a way to capture the session id of a particular logged-in user in django? -
Use the same view to manage ajax and non-ajax request: how to run a function to return HttpResponse with zip folder attached?
I have a view that either run a celery task to produce a zip folder only if zip folder does not already exist: a user message is displayed with a link that allowed user to download the zip folder when task is completed (export:download view is called when user click the link) but as task may take long time, I want to limit running this task once a day If zip folder already exist (identified by user, content and date), instead of running the task, I want zip floder to be downloaded but I did'nt not mange to do that. I try to implement a function that would be equivalent of download view but nothing is return I also thought about switching export button (that run export view) with a link that call the download view using JQuery but it is quite complicated and looking for a more simple way ''' Ajax query to export filtered data ''' @login_required def export(request): ... if zipexist: # -> HERE SHOULD call function to return ZIP folder already existing return JsonResponse ({"zip_exist": True}, status = 200) else: if request.is_ajax() and request.method == "POST": # asynchronous task using celery task = filtered_export.delay(user.id,study.id,database.id,selected_import,data,datadictionnary) return JsonResponse( … -
Django Foreign Key is not relating to users
I think this problem has a really simple solution, but I've been on google for a few hours and haven't managed to solve it. The website I am working on lets user add movies to a watchlist. It has a search function to look through movies with by title using the OMDB API (which works just fine). It then renders out all the movie posters and titles alongside a button assigned to each movie. The button then takes the img src link, the title and release year of the specific movie and sends an AJAX POST request to the movie_forms form. The request does work as it adds the data to the model but when I send the post request, the foreign key is blank (it shows as '-----' on the admin view). Here's my code! urls.py urlpatterns = [ path('', views.homepage, name='homepage'), path('signup/', views.signup_view, name='signup'), path('login/', views.login_view, name='login'), path('logout/', views.logout_view, name='logout'), path('movie_form/', views.mlf_view, name='movie_form'), ] views.py def mlf_view(request): form = MovieListForm() if request.method == 'POST' and request.is_ajax(): print(request.body) form = MovieListForm(request.POST) if form.is_valid() and request.is_ajax(): title = form.cleaned_data.get('title') img_link = form.cleaned_data.get('img_link') plot = form.cleaned_data.get('plot') release_date = form.cleaned_data.get('release_date') score = form.cleaned_data.get('score') form.user = request.user form.save() print('form is valud') return JsonResponse({"title": … -
How can I add the quantity from value to the cart sessions using ajax in django?
Problem When i click on the add to cart button the url cart_add is triggered and the product value is added to it but the issue is that the quantity form value is not retrieved due to which the product is actually not added to the cart. The code i have written is as follows Script $(document).on("click",".Id_submit",function(event){ event.preventDefault(); var selector = $(this).closest(".productID") console.log(selector.find("form").attr('action')) const form_data = { csrfmiddlewaretoken: $('#transactionIDValue input[name="csrfmiddlewaretoken"]').val() } $.ajax({ type : 'POST', url: selector.find("form").attr('action'), data: form_data, success: function() { alert("Product added to cart") } }); }); HTML <form id='transactionIDValue' class="d-inline" method="post"> {{cart_product_form}} {% csrf_token %} <input type="submit" class="btn btn-primary shadow px-5 py-2 Id_submit" value="Add To Cart"> </form> Views.py @require_POST @csrf_exempt def cart_add(request, product_id): cart = Cart(request) product = get_object_or_404(transactions, id=product_id) form = CartAddProductForm(request.POST) if form.is_valid(): cd = form.cleaned_data print(cd) cart.add(product=product, quantity=cd['quantity']) else: print('error') print(cart) # request.session['items_total'] = cart.product.count() return HttpResponseRedirect(reverse('main:home'),'success') ISSUE Now, the issue is that when the {{cart_product_form}} is called the quantity drop is set to the page but when i click on the add_to_cart the value from it is not added to cart, so i rechecked it even didn't even gets in the form validation check in the views. Can anyone help through this issue. … -
Django admin site not logging in after production
I have deployed my django app on digitalocean. The site works properly, but I am not able to login to my django admin interface with superuser credentials also -
Login page issues while using react js and Django api
I am creating a simple login page using react js and Django api. I am able to login but unable to go to my dashboard as it is throwing error like "Unhandled Rejection (TypeError): Cannot read property 'status' of undefined" I am using Visual Studio Code The full code is as below: Login.js import React, { useState } from 'react'; import axios from 'axios'; import { setUserSession } from './Utils/Common'; function Login(props) { const [loading, setLoading] = useState(false); const username = useFormInput(''); const password = useFormInput(''); const [error, setError] = useState(null); // handle button click of login form const handleLogin = () => { setError(null); setLoading(true); axios.post('http://localhost:8000/account/user/signin', { mobile_number: username.value, password: password.value }).then(response => { setLoading(false); setUserSession(response.data.token, response.data.user); props.history.push('/dashboard'); }).catch(error => { setLoading(false); if (error.response.status === undefined) setError(error.response.data.message); else setError("Something went wrong. Please try again later."); }); } return ( <div> Login<br /><br /> <div> Username<br /> <input type="text" {...username} autoComplete="new-password" /> </div> <div style={{ marginTop: 10 }}> Password<br /> <input type="password" {...password} autoComplete="new-password" /> </div> {error && <><small style={{ color: 'red' }}>{error}</small><br /></>}<br /> <input type="button" value={loading ? 'Loading...' : 'Login'} onClick={handleLogin} disabled={loading} /> </div> ); } const useFormInput = initialValue => { const [value, setValue] = useState(initialValue); const … -
Django – remove the trailing slash from 'sitemap.xml/'
I am using Django's sitemap framework and have a sitemap index. My urls file looks like this: urls = [ path('', include('movies.urls')), path('', include('accounts.urls')), ... path('admin/', admin.site.urls), ] urlpatterns = i18n_patterns(*urls, prefix_default_language=True,) sitemaps = { 'main': MainSitemap, 'movies': MoviesSitemap, } urlpatterns.extend([ path('sitemap.xml', views.index, {'sitemaps': sitemaps}), path('sitemap-<section>.xml', views.sitemap, {'sitemaps': sitemaps}, name='django.contrib.sitemaps.views.sitemap'), ]) This is implemented in accordance with the recommendations in the documentation of Django. The problem is that I always get 404 when trying to access my sitemap index: example.com/sitemap.xml. This occurs because a redirect occurs automatically to the non-existent example.com/sitemap.xml/ URL with a trailing slash. How can I avoid a slash being appended to the .xml sitemap file? I have tried using re_path but to no avail. -
No module named 'ebcli.core'
Traceback (most recent call last): File "C:\Users\Debarun\AppData\Local\Programs\Python\Python39\Scripts\eb", line 12, in import ebcli.core.ebcore ModuleNotFoundError: No module named 'ebcli.core' The file code is import sys import ebcli.core.ebcore def main(): return ebcli.core.ebcore.main() if name == 'main': sys.exit(main() -
Is it compulsory to go on Microsoft page when Django app integrating with Microsoft Active Directory
I have integrated my Django app with azure active directory. My app perfectly sign in and sign out through Django app. The main issue is I have to go on Microsoft sign in page every time. so my question is - Is it compulsory to go on Microsoft page or we can do authentication using my Django sign in page but authentication should be from Microsoft. Please provide the detailed document or information if we can do without using Microsoft sign in page. For integration I have used "Django-auth-adfs" library "https://django-auth-adfs.readthedocs.io/en/latest/". -
Is it possible to build a DApp with Django and web3.js?
I am building a Dapp. The site infrastructure was built with Django, before I realised I want it to have something to do with crypto and blockchain. We want it to be able to talk and communicate the ethereal blockchain. So we have to use a web3 package, either web3.js (javascript), or web3.py (python). Unfortunately, web3.py is not as developed as web3.js, which is why all my endeavors to utilize Django for metamask integration have not been successful. So I think I have no choice but to use javascript. But clearly I don’t want to abandon all the work done with Django… So, is it possible to build a Dapp, with the overall UI and website infrastructure using Django, while the parts that are blockchain-related (say metamask initialisation), be built with javascript and locally-contained? Is this possible? Would there be hidden security risks? -
drf-passwordless Override EmailAuthSerializer to add custom fields
In drf-passwordless (https://github.com/aaronn/django-rest-framework-passwordless), is it possible to override this class to allow adding other custom fields? e.g. In my case is an administrator who register the user email. I already modified the send_email_with_callback_token function to include the token into a link but I also want to be able to add other custom codes to the link so that the user will be redirected appropriately based on the administrator wishes. How do I override this class to add some more serialisers fields? Thanks. class EmailAuthSerializer(AbstractBaseAliasAuthenticationSerializer): @property def alias_type(self): return 'email' email = serializers.EmailField() -
Views function not getting triggered
My views function isn't getting triggered and I can't figure out why. Currently, I'm not seeing any errors - but my image isn't being created. This means the views function is not being triggered, as the image generation function works perfectly outside of the views function. Views.py def views_function(request): print('checkpoint') def make_image(Na, Fe, Gb, Ty, Fs, Fl): #This doesn't seem to be getting triggered (can't see the print statement output anywhere) #Lots of chart plotting code here try: fig1 = plt.gcf() plt.draw() print('saving file') fig1.savefig(f'../media/fig{User.profile.chart.url}.png', dpi=100) except: print('save failed') return render(request, 'AppName/plot.html', {'title': 'plot'}) if request.method == 'POST': print('checkpoint') return make_image(100, 1, 16, 1, 1000, 600) and render(request, 'AppName/plot.html', {'title': 'plot'}) HTML button: <button type="submit" action="{% url 'AppName:views_function' %}" class="btn btn-light" style="width: 515px;">Run</button> URL Pattern: path('home/plot/', views.views_function, name='views_function'), Can anyone see what's wrong? Any ideas are appreciated, I'm getting nowhere right now. I would also really appreciate if someone could confirm for me where I would see the output for my views_function print statements. -
Problem with Jinja code if condition in django web application
I am trying to use an if condition in html using jinja code, The Boolean value called "is_verified" is false. But the code prints exactly opposite of what it is expected to do, What's going wrong here? {% for info in infos %} {% if info.is_verified == "false" %} <h4>Verification status: PENDING</h4> {% else %} <h4>Verification status: APPROVED</h4> {% endif %} {% endfor %} -
django-admin command : ModuleNotFoundError: No module named 'mysite'
I have seen multiple post about that problem but I still can't fix it. I have tried: set DJANGO_SETTINGS_MODULE=mysite.settings.dev but when I try django-admin test I get that error message: ModuleNotFoundError: No module named 'mysite' I also tried to add the variable to my environment variables (that works) but I keep receiving that error. Here's where my settings file is located (dev imports base). -
Djanog: How to update an image without reloading the page
I am working in Djnago and I want to update the image without reloading the page. At first, I have used Ajax for post method so that the page should not reload after submitting the form, and it is working properly. Then I used Ajax for get method for receiving the image, and it is working too but to see the the new image, I have to refresh the page. The views.py file: # def product_create_view(request): def bfs_view(request): form = BFSForm(request.POST or None) if form.is_valid(): form.save() form = BFSForm() try: image_url_info = None num_states_explored = None final_solution = None text_file = open("BFS\outputs\maze.txt", "w") field_name = 'description' input_value = BFS.objects.latest('id') field_object = BFS._meta.get_field(field_name) field_value = field_object.value_from_object(input_value) field_string_value = str(field_value).split("\n") text_file.writelines(field_string_value) text_file.close() m = Maze("BFS\outputs\maze.txt") print("Maze:") m.print() print("Solving...") m.solve() print("States Explored:", m.num_explored) print("Solution:") m.print() m.output_image("BFS\outputs\maze.png", show_explored=True) m.output_image("static/search/bfs/maze.png", show_explored=True) image_url_info = "/../../../static/search/bfs/maze.png" num_states_explored = m.num_explored # final_solution = ''.join(m.end_result) final_solution = str(''.join(m.end_result)) print(''.join(m.end_result)) get_bfs_image_view(request) # BFS.objects.latest('id').delete() except: print("BFS ERROR: Error in the try session of BFS in view.py") context = { 'form': form, 'image_url': image_url_info, 'states_explored': num_states_explored, 'solution': final_solution} return render(request, "BFS/bfs.html", context) def post_bfs_view(request): if request.method == "POST" and request.is_ajax(): bfs_view(request) return JsonResponse({"success":True}, status=200) return JsonResponse({"success":False}, status=400) def get_bfs_view(request): if request.method == … -
Docker Compose to Cloud Run
i created a docker compose file containing django apps and postgresql, and it runs perfectly. then I'm confused whether I can deploy this docker compose file to the google container registry to run a cloud run? version: "3.8" services: app: build: . volumes: - .:/app ports: - 8000:8000 image: django-app container_name: django_container command: > bash -c "python manage.py migrate && python manage.py runserver 0.0.0.0:8000" depends_on: - db db: image: postgres volumes: - ./data/db:/var/lib/postgresql/data environment: - POSTGRES_DB=postgres - POSTGRES_USER=nukacola - POSTGRES_PASSWORD=as938899 container_name: postgres_db thank you for answering my question -
Django filtering with OR condition
I have a Models.py declared thus class Age(models.Model): ageChoices=( ('Child', 'Child'), ('Adult', 'Adult'), ('Old', 'Old'), ) age = models.CharField(max_length=5, choices=ageChoices) class Meta: verbose_name_plural='1. Age' def __str__(self): return self.age class Gender(models.Model): genderChoices=( ('Male', 'Male'), ('Female', 'Female'), ('Others', 'Others'), ) gender = models.CharField(max_length=8, choices=genderChoices) class Meta: verbose_name_plural='2. Gender' def __str__(self): return self.gender class Images(models.Model): title =models.CharField(max_length=50) age=models.ForeignKey(Age, on_delete=models.CASCADE) gender=models.ForeignKey(Gender, on_delete=models.CASCADE) def __str__(self): return self.title This is the filters.py file class ImagesFilter(django_filters.FilterSet): age = ModelMultipleChoiceFilter(queryset=Age.objects.all(),widget=forms.CheckboxSelectMultiple()) gender = ModelMultipleChoiceFilter(queryset=Gender.objects.all(),widget=forms.CheckboxSelectMultiple()) class Meta: model = Images fields = [ 'age', 'gender'] There are two images with these properties for example Image 0001: Child, Male Image 0002: Old, Female In the filter appearing on the rendered template, if I choose "child", then Image 0001 appears. If I choose "Female", with "child" filter selected, I would like to have both images displayed. (Basically OR condition). What is now given is an AND condition, and so with "Female" and "Child" filters applied, I get no images. How can I modify my code to bring OR functionality? Searching on the net gives OR functionality over combining querysets with OR (|) but I am not sure how this can be applied to my case. Thanks in anticipation -
Python celery database result storage specify table name
I am currently attempting to migrate a Django web application from python 2.7 to 3.8, but during the migration we would like to run a blue/green setup with both environments operating somewhat separately from each other. We use celery for task execution and in Python 2.7 we were storing the results of tasks in a database table named 'celery_taskmeta', currently our Python 3.8 environment is also trying to use this table name but failing due to differences in table DDL. We noticed in celery documentation that it is possible to control this based on: https://docs.celeryproject.org/en/v4.4.6/userguide/configuration.html#database-table-names but cannot seem to make this work based on the example given in the documentation. For example we've tried specifying; results_backend = settings.CELERY_RESULT_DB_TABLE_NAMES and also in django settings; CELERY_RESULT_DB_TABLE_NAMES = { 'task': 'python38_taskmeta', 'group': 'python38_groupmeta', } But we still see Celery using the table name of 'celery_taskmeta' and it seems like the documentation is a little vague when it comes to this parameter, would anyone happen to know how this setting can be provided to the app? -
In Django using all auth i want to make a custom API without REST framework for following info i provided below
In this i will enter UID ,email,username using POSTMAN and it will check whether uid exist or not,if it exist it will login user,if it did not and if same email exist in User model,it will create entry for same email in social account table along with generating token,so user can login through social email id also.Can u explain me which method or what should i use to create all entries and generate token.I will also specify logintype in POSTMAN as like google or facebook.and if user does not exist in user table also,it will create new one using email and username -
GitLab CI with Django project and MS SQL Database cannot login
Have the following .gitlab-ci.yml: image: python:latest stages: - test services: - name: mcr.microsoft.com/mssql/server:2019-latest alias: mssql variables: ACCEPT_EULA: Y SA_PASSWORD: $SA_PASSWORD MSSQL_HOST: mssql SECRET_KEY: $SECRET_KEY DEBUG: "True" DB_NAME: $DB_NAME DB_USER: $DB_USER DB_PASSWORD: $DB_PASSWORD DB_HOST: mssql # This folder is cached between builds # http://docs.gitlab.com/ee/ci/yaml/README.html#cache cache: paths: - ~/.cache/pip/ before_script: - python -V - curl https://packages.microsoft.com/keys/microsoft.asc | apt-key add - - curl https://packages.microsoft.com/config/ubuntu/20.04/prod.list > /etc/apt/sources.list.d/mssql-release.list - apt-get update -q && apt-get install nodejs build-essential libssl-dev libffi-dev python3-dev unixodbc-dev -yqq - apt-get install -y msodbcsql17 - apt-get install -y mssql-tools - pip install -r requirements.txt test: script: - python manage.py makemigrations - python manage.py migrate - python manage.py loaddata - python manage.py collectstatic - python manage.py test --keepdb With following error: System check identified some issues: File "/usr/local/lib/python3.9/site-packages/sql_server/pyodbc/base.py", line 312, in get_new_connection conn = Database.connect(connstr, django.db.utils.OperationalError: ('HYT00', '[HYT00] [Microsoft][ODBC Driver 17 for SQL Server]Login timeout expired (0) (SQLDriverConnect)') Cleaning up file based variables 00:01 ERROR: Job failed: exit code 1 Anyone have a solution, made various changes all with the same error. The Login timeout expired is the persistent error, tried setting the DB_HOST to "127.0.0.1" with no success so far. -
how to search a slug in different table and add the item to Many-to-many field in orderItem table Django?
I want to add many different product table in OrderItem item field class OrderItem(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) ordered = models.BooleanField(default=False) item = models.ForeignKey( gamingpc, on_delete=models.CASCADE, blank=True, null=True) product = models.ForeignKey( PcComponent, on_delete=models.CASCADE, blank=True, null=True) -
Django migration already applied but I don't have the migration file
A migration was applied to the database, and the table "blacklist_id" exists (and is populated with rows.) I want to add a new Model and make a migration, but whenever I call makemigrations Django thinks that the blacklist_id model is new and attempts to make a migration for that, which causes an error. I don't want to remove the table from the server because it has data in it - what can I do? -
Django models objects return None
I have this model in my Django app. class Kilometer(models.Model): kilometers = models.IntegerField() It work when with a form I save data on my database (I can see the objects on the admin page) but I have issue when I want to access the data in django shell. >>> from forms.models import Kilometer >>> test = Kilometer(1) >>> print(test) Kilometer object (1) >>> print(test.kilometers) None I have the same problem with all my models. -
Change Meta with Rest API Javascript
I have a web app, where Django with Django-rest-framework is set as the backend and html+css+javascript on the frontend. And they communicate using RestAPI. So... My Django is available on the pages: 'domain.com/api' and 'domain.com/admin'. On the page 'domain.com' my frontend part is available. And my question is... Are there any ways to change Meta on the frontend using Django? And I also need analytics to see these Meta and in-browser searches show the description and title, that I got from my backend model.