Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Server is showing GET /new_event/?csrfmiddlewaretoken when i click on save button
I am building a BlogApp and I am trying to save the form without having to refresh the page. AND it is working correctly in localhost BUT when i deploy site and try to save then it is showing GET /new_event/?csrfmiddlewaretoken=RbieckElBjOL2hVs8NmIw2q4QWRDAQW8obXnd01xkLYI6171lFM2JxsOX in server log. It works sometimes but most of the time it is keep showing the error and form is not saving. template.html <div class="container-fluid"> <form id="friend-form"> {% csrf_token %} {{ form|crispy }} <div class = "col text-center"> <input type="submit" class="edit-button" value="Save" /> </div> <form> </div> <hr/> <div class="container-fluid"> <table class="table table-striped table-sm" id="my_friends"> <tbody> </tbody> </table> </div> <script> $(document).ready(function () { $("#friend-form").submit(function (e) { e.preventDefault(); var serializedData = $(this).serialize(); $.ajax({ type: 'POST', url: "{% url 'EditBlogAjax' post.id %}", data: serializedData, success: function (response) { var instance = JSON.parse(response["instance"]); var fields = instance[0]["fields"]; $("#my_friends tbody").prepend( `<h2>Saved</h2>` ) }, error: function (response) { alert(response["responseJSON"]["error"]); } }) }) }) </script> views.py def EditBlogAjax(request,blogpost_id): post = Blogpost.objects.get(id=blogpost_id) post_owner = post.user if request.is_ajax and request.method == "POST": form = Form(request.POST,request.FILES,instance=post) if form.is_valid(): instance = form.save(commit=False) instance.user = request.user instance.save() ser_instance = serializers.serialize('json', [ instance, ]) return JsonResponse({"instance": ser_instance}, status=200) else: return JsonResponse({"error": form.errors}, status=400) return JsonResponse({"error": ""}, status=400) I have tried many times … -
Django Group model not showing up in Django admin
I cannot see Django Group model on the admin page. I get an error if I try and register it from the admin.py file saying that Group is already registered. I cannot see it even if I unregister and register it again. What could be wrong here? -
Django: How to update an image without refreshing the page?
I am working in Djnago and I want to update an image without reloading or refreshing the page. I have used Ajax for get method to receive 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 == "GET" and request.is_ajax(): 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') … -
Search date range in range of two model fields
I'm trying to use django-filters dateFromToRangeFilter to find out if start and end date is in any range with two field in model: class dates(models.Model): date_from = models.DateField() date_to = models.DateField() I don't know where to start because normal behavior of this filter is to search if one model date field is in range of start_date and end_date of filter. I'm searching for solution to find out if two model Date fields is in range of o range provided by user in form. (any overlaping is ok) -
Django ORM - filter doesn't apply to a set
Why filter doesn't apply? It returns the all details records for each master. models class Master(models.Model): pass class Detail(models.Model): master = models.ForeignKey(Master, models.CASCADE, related_name='details') some_field = models.BooleanField() serializers class DetailListSerializer(serializers.ModelSerializer): class Meta: model = Detail fields = ('some_field',) class MasterListSerializer(serializers.ModelSerializer): details = DetailListSerializer(many=True) class Meta: model = Master fields = ('id', 'details') views data = Master.objects.filter(details__some_field=True) serializer = MasterListSerializer(data, many=True) -
Trouble trying to host 2 django webs on the same apache2 server
I have been pulling my hair out with this and I dont know what else I should do. For context, I am trying to host 2 django websites on the same Apache2 server. I am able to setup 1 website with ease but whenever I try to add a second one everything breaks. At the momento both webs are located in in /home/my_usr dir. So we would have /home/my_usr/web1 and /home/my_usr/web2. My web1-web2.conf file looks like: WSGIDaemonProcess web1 python-home=/home/my_usr/web1/env python-path=/home/my_usr/web1 WSGIProcessGroup web1 WSGIDaemonProcess web2 python-home=/home/my_usr/web2/env python-path=/home/my_usr/web2 WSGIProcessGroup web2 <VirtualHost *:80> # The ServerName directive sets the request scheme, hostname and port that the server uses to # identify itself. This is used when creating redirection URLs. In the context of virtual hosts, the # ServerName specifies what hostname must appear in the request's Host: header to match this virtual # host. For the default virtual host (this file) this value is not decisive as it is used as a last # resort host regardless. However, you must set it for any further virtual host explicitly. #ServerName www.example.com ServerAdmin webmaster@localhost # Available loglevels: trace8, ..., trace1, debug, info, notice, warn, # error, crit, alert, emerg. It is also possible to configure … -
Getting a Django API call to respond with simple json
This should be a really simple thing to do.... but I seem to be going round in circles - rather than return model data, I need to return a dataset calculated from several tables I'm extending an existing app that has a suite of API calls & UI rendering. Django == 2.2.1 djangorestframework == 3.9.3 The routing is defined thus: router.register('issn', views.IssnDataSet, basename='issn') (using router = DefaultRouter()) The class is thus: class IssnDataSet(viewsets.ModelViewSet): lookup_field = 'resource__e_issn' # looking through a relationship lookup_url_kwarg = 'id' filter_backends = (DjangoFilterBackend,) filterset_class = EntitlementFilterSet # does clever user permissions filtering serializer_class = HackSerializer def get_queryset(self): data = dict() issn = self.kwargs.get('id') qs = Entitlement.objects ## Do filtering to get the subset we want for entitlement in qs.all(): ## Do stuff to build the data dict from various relationships, deductions, and calculations return data # needed else it barfs for some reason @classmethod def get_extra_actions(cls): return [] and the serializer: class HackSerializer(serializers.Serializer): def to_representation(self, instance): return json.dumps(instance) The data object that IssnDataSet creates is something like: {'Accounting, Business & Financial History': { 'title': 'Accounting, Business & Financial History', 'p_issn': '0958-5206', 'e_issn': '1466-4275', 'dates': [ {'start': '2005-01-01', 'end': '2005-12-31'}, {'start': '2007-01-01', 'end': '2007-12-31'}, {'start': '2006-01-01', 'end': … -
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