Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
DJANGO - NoReverseMatch at /create/
I am fairly new to Django and for my certification, I am working on cloning Wikipedia. I was able to get the wiki and editing commands to work but having difficulties creating new entries. This is my function to create a new entry: ** Main urls.py** urlpatterns = [ path('admin/', admin.site.urls), path('', include("encyclopedia.urls")) ] urls.py from django.urls import path from . import views urlpatterns = [ path("", views.index, name="index"), path ("wiki/<str:title>", views.entry, name="entry"), path ("edit/<str:title>", views.edit, name="edit"), path ("create/<str:title>", views.create, name="create") ] views.py class Post(forms.Form): title = forms.CharField(label= "Title") textarea = forms.CharField(widget=forms.Textarea(), label='') def create(request, title): if request.method == "POST": form = Post(request.POST) if form.is_valid(): title = form.cleaned_data["title"] textarea = form.cleaned_data['textarea'] entries : util.list_entries() if title in entries: return render(request, "encyclopedia/error.html", { "form": Search(), "message": "Page already exists", "type": "exists" }) else: util.save_entry(title,textarea) page=util.get_entry(title) page_converted = md.convert(page) return render(request, "encyclopedia/create.html", { "form": Search(), 'page': page_converted, "title": title }) else: return render(request, "encyclopedia/create.html", { "form": Search(), "post": Post() }) MY TEMPLATE Creating a new entry {% extends "encyclopedia/layout.html" %} {% block title %} Create {% endblock %} {% block body %} <form method="post" action="{% url 'create' %}"> {% csrf_token %} <h4 class="display-2">Create new page:</h4> <h6 class="post-title">Title: {{post.title}}</h6> {{post.textarea}} <br> <input class="save … -
Django + JS != CSRF
I've found that if i link my html with js in my django project it thow the CSRF verification failed. Request aborted. If I don't link html with that js it works well. So how can I solve this problem? Here is views.py and style.js file: The site is about weather. If I press button to search weather with not linked js it works fine. views.py def index(request): owm = pyowm.OWM(":)") mgr = owm.weather_manager() if(request.method == "POST"): form = CityForm(request.POST) form.save() form = CityForm() city = City.objects.last() result = get_todays_weather(mgr, city.name) forecast_hourly = get_todays_forecast(mgr, city.name) context = { "info": result, "forecast_hourly": forecast_hourly, "form": form } return render(request, "index.html", context) style.js var check = function () { var hours = new Date().getHours(); hours = 3 if (hours < 5 ) { document.getElementById("header_id").style.background = "linear-gradient(to bottom, #692dad, #442aa3)"; document.getElementById("brand_id").style.color = "#f9fbfc"; document.getElementById("body_id").style.background = "#8f7cd6"; document.getElementById("brand_id").style.color = "#f9fbfc"; var elements = document.getElementsByClassName("nav-link"); for(var i = 0; i < elements.length; i++) { if(elements[i].className != "nav-link active") { elements[i].style.color = "#f9fbfc"; } } document.getElementById("search_btn").style.color = "#f9fbfc" document.getElementById("second_card_id").style.background = "linear-gradient(to bottom, #692dad, #442aa3)"; var cards = document.getElementsByName("card"); for(var i = 0; i < cards.length; i++) { cards[i].style.background = "linear-gradient( white 25%, #692dad 50%, white 75% )"; … -
How to disable Django Generics Filters Case-Sensitivity
I'm using Django Generics to get and filter my data. But it's Case-Sensitive and I wounder if there's a way to disable it? for example if I send this request, I don't get any results, because the mail address in the database is Test.test@test.com http://127.0.0.1:8000/api/users/?email=test.test@test.com I tried to use __iexact, but it didn't work! Serializer: class UserSerializer(serializers.ModelSerializer): class Meta: model = models.User fields = ("__all__") View: class all_users(generics.ListAPIView): serializer_class = eden_serializers.UserSerializer filterset_fields = ('__all__') permission_classes = [DjangoModelPermissionsWithRead, ] def get_queryset(self): return models.User.objects Url: path('api/users/', views.all_users.as_view()), -
Django ASGI/Daphne: postgres connection timeout
In my project I am using a PG database. Now that I've deployed the app to the production server, I' ve switched from the test db (PG 10) to the production db (PG 9). When connecting the Django backend to the test db, everything works perfectly fine, but when I connect it to the production db, it works only for a couple minutes and then, after some time of inactivity for example, the whole site stops working properly. This is the data from daphne: log on imgur What pg settings could cause this? I don't really think that it's an issue with the app's config, because with the other db everything is working correctly. This prod_db is placed on an external server btw. -
DRF - How to get a single item from a QuerySet?
I want to get objects with the pk I send through request but I want only one item from the queryset. I want BatchLog objects that their batch_id is same as the pk and my query returns multiple items within that query. I just want one of them and it doesn't matter which one it is. def get_queryset(self): return BatchLog.objects.filter(batch_id=self.kwargs["pk"]) It returns QuerySet<[BatchLog, BatchLog]> but I need QuerySet<BatchLog> How can I achieve it? Thanks. -
Taxi project with Django
I am going to make a taxi project's server side. As we know taxi app has a realtime location updates. How to develop this feature in correct way? Is Django channels good solution for this situation, If yes could give more guide how to develop. -
How to capture a numeric value from a URL in Django 3?
Am I using (\d+) correctly?? when I'm using it, I get error Page not found! when I'm not using it, I get (Field 'id' expected a number but got ''.) app/urls.py from django.conf.urls import url from . import views urlpatterns = [ url(r'^reporters/(?P<report_id>\d+)$', views.report, name="entries"), ] views.py def report(request, report_id): """show a reporter's all reports""" reporter_n = Reporter.objects.get(id=report_id) entries = reporter_n.entry_set.order_by('-date_added') context = {'reporter_n': reporter_n, 'entries': entries} return render(request, "newsblog/reports.html", context) -
'NoneType' object is not iterable for serializers
I am trying to pull data to create function from serializer but i am getting an error Models class Article(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) author = models.ForeignKey(User,on_delete=models.CASCADE,related_name='articles') caption = models.CharField(max_length=250) class ArticleTags(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) tag = models.CharField(max_length=20,null=True,blank=True) article = models.ForeignKey(Article, on_delete=models.CASCADE,null=True,blank=True, related_name='posttags') Serializers class ArticleCreateSerializer(serializers.ModelSerializer): images_set = ArticleImagesViewSerializer(source='images',required=False,many=True) tags_set = ArticleTagViewSerializer(source='posttags',required=False,many=True) class Meta: model = Article fields = ('images_set','tags_set','id') def create(self,validated_data): images = self.context['request'].FILES.getlist('images_set') articleinit = Article.objects.create(**validated_data) tags = self.validated_data.get('tags_set',None) for imageinit in list(images): m2 = ArticleImages(article=articleinit , image= imageinit ) m2.save() for taginit in list(tags): m3 = ArticleTags(article=articleinit , tag = taginit) m3.save() return articleinit This is the error with the line: File "C:server\accounts\serializers.py", line 146, in create for taginit in list(tags): TypeError: 'NoneType' object is not iterable Why am i getting this error? -
Uncaught Error: Module build failed (from ./node_modules/babel-loader/lib/index.js): SyntaxError. Something went wrong with react and babel
I have some problems with React using Django. Everything was fine, until i wrote some text using cyrillic letters right into my react component code. Then i get this error in chrome console: Uncaught Error: Module build failed (from ./node_modules/babel-loader/lib/index.js): SyntaxError: C:\Users\Lenovo B590\Documents\DEV\React-DDJ.TWT\music_controller\frontend\src\components\createroompage.js: Unexpected token, expected ";" (43:20) [0m [90m 41 | [39m }[0m [0m [90m 42 | [39m[0m [0m[31m[1m>[22m[39m[90m 43 | [39m [33mОСТАНОВИЛСЯ[39m [33mНА[39m [33mТОМ[39m [33mЧТО[39m [33mПОЛУЧАЮ[39m [33mBAD[39m [33mREQUEST[39m [33mНА[39m [33mМОИ[39m [33mКЛЮЧ[39m [33m-[39m [33mЗНАЧНИЕ[39m[0m [0m [90m | [39m [31m[1m^[22m[39m[0m [0m [90m 44 | [39m[0m [0m [90m 45 | [39m fetch([32m'api/crapiview'[39m[33m,[39m requestOptions)[33m;[39m[0m [0m [90m 46 | [39m }[0m at Object._raise (C:\Users\Lenovo B590\Documents\DEV\React-DDJ.TWT\music_controller\frontend\node_modules\@babel\parser\lib\index.js:748:17) at Object.raiseWithData (C:\Users\Lenovo B590\Documents\DEV\React-DDJ.TWT\music_controller\frontend\node_modules\@babel\parser\lib\index.js:741:17) at Object.raise (C:\Users\Lenovo B590\Documents\DEV\React-DDJ.TWT\music_controller\frontend\node_modules\@babel\parser\lib\index.js:735:17) at Object.unexpected (C:\Users\Lenovo B590\Documents\DEV\React-DDJ.TWT\music_controller\frontend\node_modules\@babel\parser\lib\index.js:9097:16) at Object.semicolon (C:\Users\Lenovo B590\Documents\DEV\React-DDJ.TWT\music_controller\frontend\node_modules\@babel\parser\lib\index.js:9079:40) at Object.parseExpressionStatement (C:\Users\Lenovo B590\Documents\DEV\React-DDJ.TWT\music_controller\frontend\node_modules\@babel\parser\lib\index.js:12190:10) at Object.parseStatementContent (C:\Users\Lenovo B590\Documents\DEV\React-DDJ.TWT\music_controller\frontend\node_modules\@babel\parser\lib\index.js:11786:19) at Object.parseStatement (C:\Users\Lenovo B590\Documents\DEV\React-DDJ.TWT\music_controller\frontend\node_modules\@babel\parser\lib\index.js:11650:17) at Object.parseBlockOrModuleBlockBody (C:\Users\Lenovo B590\Documents\DEV\React-DDJ.TWT\music_controller\frontend\node_modules\@babel\parser\lib\index.js:12232:25) at Object.parseBlockBody (C:\Users\Lenovo B590\Documents\DEV\React-DDJ.TWT\music_controller\frontend\node_modules\@babel\parser\lib\index.js:12218:10) at eval (webpack://frontend/./src/components/createroompage.js?:1:7) at Object../src/components/createroompage.js (http://127.0.0.1:8000/static/frontend/main.js:2:4127) at __webpack_require__ (http://127.0.0.1:8000/static/frontend/main.js:2:251468) at eval (webpack://frontend/./src/components/homepage.js?:6:73) at Object../src/components/homepage.js (http://127.0.0.1:8000/static/frontend/main.js:2:7470) at __webpack_require__ (http://127.0.0.1:8000/static/frontend/main.js:2:251468) at eval (webpack://frontend/./src/components/app.js?:6:67) at Object../src/components/app.js (http://127.0.0.1:8000/static/frontend/main.js:2:2509) at __webpack_require__ (http://127.0.0.1:8000/static/frontend/main.js:2:251468) at eval (webpack://frontend/./src/index.js?:2:76) Obviously its due to cyrillic letters, so i deleted it. Then i tryed to refresh the page and i got the same error. Finally i even deleted all the code in src\components\createroompage.js … -
i have this error on my cpanel django project
App 4075094 output: /opt/passenger-5.3.7-9.el7.cloudlinux/src/helper-scripts/wsgi-loader.py:26: DeprecationWarning: the imp module is deprecated in favour of importlib; see the module s documentation for alternative uses App 4075094 output: import sys, os, io, re, imp, threading, signal, traceback, socket, select, struct, logging, errno -
Unable to load other class based views , Django
I created a form and saved data using post method Here is view.py file. I can't able to move to fetch/ which is FetchDataView.as_view() in url.py class InsertTaskView(View): def get(self, request, *args, **kwargs): return render(request, "addtask.html",{}) def post(self, request, *args, **kwargs): if request.method == "POST": task_tracker = { 'task_name': request.POST.get('task_name'), # html form name attribute will be passed inside . 'task_date': request.POST.get('task_date'), # Creating a python dicitionary to pass it in form 'task_time': request.POST.get('task_time'), 'task_description':request.POST.get('task_details'), 'task_status': request.POST.get('task_status') } form = TaskTrackerForm(task_tracker) # Passing data to form to save if form.is_valid(): #check form validation try: form.save(commit=True) # saving data inside database using for method save except Exception as e: logging.info(e) # inserting log in log file json_data = json.dumps(form.errors) #getting form error and converting it into json return render(request, 'addtask.html', {'msg':json_data, 'status':400}) #render error on html page json_data = json.dumps({"msg":'Resource Created Succesfully'}) # if data inserted successfully print("Success") #logging.info(msg:"S") #success message on server return render(request, 'addtask.html', {'msg':'date inserted successfully', 'status':200}) # render success message on client browser class FetchDataView(View): def get(self, request, *args, **kwargs): alltasks = TaskTracker.object.all() return render(request,"fetchdata.html",{"alltasks":alltasks}) def post(self, request, *args, **kwargs): return HttpResponse('POST request!') I think I am having some error in the views.py file. I posted here … -
How to ensure Django updates html to reflect changes?
Expected Result: I expect to see <p>B<p/> when I edit my home page from <p>A<p/> to <p>B<p/>, save changes in the editor, and refresh the browser. Actual Results: I'm seeing <p>A<p/> when I edit my home page from <p>A<p/> to <p>B<p/>, save changes in the editor, and refresh the browser. A week ago I was getting the "Expected results" but I noticed a few days ago I'm getting the results explained in "Actual Results". Now Only when I restart the server by running docker-compose up restart I'm getting the expected results. Why simple HTML changes not being updated when I refresh the browser? I'm using Django 3.1 and Python 3.7. Edit: Docker file: # Pull base image FROM python:3.7-slim # Set environment varibles ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # Set work directory WORKDIR /projects # Install dependencies COPY Pipfile Pipfile.lock /projects/ RUN pip install pipenv && pipenv install --system # Copy project COPY . /projects/ docker-compose.yml version: "3.7" services: web: build: . command: python /projects/manage.py runserver 0.0.0.0:8000 # command: gunicorn guyanaNPPM_project.wsgi -b 0.0.0.0:8000 environment: - "DJANGO_SECRET_KEY=hidden for security reasons" - "DJANGO_DEBUG=True" - "DJANGO_SECURE_BROWSER_XSS_FILTER=True" - "DJANGO_SECURE_SSL_REDIRECT=False" - "DJANGO_SECURE_HSTS_SECONDS=0" - "DJANGO_SECURE_HSTS_INCLUDE_SUBDOMAINS=False" - "DJANGO_SECURE_HSTS_PRELOAD=False" - "DJANGO_SESSION_COOKIE_SECURE=False" - "DJANGO_CSRF_COOKIE_SECURE=False" volumes: - .:/projects ports: … -
Why does mock patch only work when running specific test and not whole test suite?
I'm using Django and Pytest specifically to run the test suite and am trying to test that a specific form shows up with expected data when a user hits the site (integration test). This particular view uses a stored procedure, which I am mocking since the test would never have access to that. My test code looks like this: #test_integrations.py from my_app.tests.data_setup import setup_data, setup_sb7_data from unittest.mock import patch ... # Setup to use a non-headless browser so we can see whats happening for debugging @pytest.mark.usefixtures("standard_browser") class SeniorPageTestCase(StaticLiveServerTestCase): """ These tests surround the senior form """ @classmethod def setUpClass(cls): cls.host = socket.gethostbyname(socket.gethostname()) super(SeniorPageTestCase, cls).setUpClass() def setUp(self): # setup the dummy data - this works fine basic_setup(self) # setup the 'results' self.sb7_mock_data = setup_sb7_data(self) @patch("my_app.utils.get_employee_sb7_data") def test_senior_form_displays(self, mock_sb7_get): # login the dummy user we created login_user(self, "futureuser") # setup the results mock_sb7_get.return_value = self.sb7_mock_data # hit the page for the form self.browser.get(self.live_server_url + "/my_app/senior") form_id = "SeniorForm" # assert that the form displays on the page self.assertTrue(self.browser.find_element_by_id(form_id)) If I run this test itself with: pytest my_app/tests/test_integrations.py::SeniorPageTestCase The tests pass without issue. The browser shows up - the form shows up with the dummy data as we would expect and it all … -
Apache2 virtualhost is activated but not listening
I have 3 Django apps, app1, app2 and app3 running on a DigitalOcean droplet. I am using nginx as a reverse proxy for domains, domain1, domain2 and domain3 that point to apache2 virtualhosts listening on ports 8081,8082 and 8083 respectively. They are all using mod_wsgi. When I try to access each on their respective domains, I am getting 503 bad gateway nginx error on app3's domain3 /var/log/nginx/error.log has this error at the bottom: .... 2020/12/14 13:16:48 [error] 3173#3173: *4 connect() failed (111: Connection refused) while connecting to upstream, client: <mylocalip>, server: "<domain3>", request: "GET / HTTP/1.1", upstream: "http://127.0.0.1:8083/", host: "<domain3>" Running sudo netstat -plant | grep apache gives: tcp 0 0 0.0.0.0:8080 0.0.0.0:* LISTEN 3165/apache2 tcp 0 0 0.0.0.0:8081 0.0.0.0:* LISTEN 3165/apache2 tcp 0 0 0.0.0.0:8082 0.0.0.0:* LISTEN 3165/apache2 I have not configured anything configured for port 8080 It seems to me like apache2 is not listening on port 8083 for connections when it should be. When I run sudo less /var/log/apache2/app3-err.log I get: [Mon Dec 14 13:11:14.326120 2020] [wsgi:info] [pid 3168:tid 140698250652736] mod_wsgi (pid=3168): Attach interpreter ''. [Mon Dec 14 13:11:14.342745 2020] [wsgi:info] [pid 3168:tid 140698250652736] mod_wsgi (pid=3168): Adding '/path/to/app3' to path. app3-access.log is empty /var/log/apache2/error.log has the following: … -
How to import cache setup into views.py
I have a seperate code for cache creation in another file in my project directory... authentication.py caches_folder = "./.spotify_caches/" if not os.path.exists(caches_folder): os.makedirs(caches_folder) def session_cache_path(): return caches_folder + request.session.get("uuid") oauth = SpotifyOAuth( redirect_uri="http://127.0.0.1:8000/spotify/authorize", scope='user-library-read', show_dialog=True, cache_path=session_cache_path() ) So I am trying to use the oauth in views.py by importing from .authentication import oauth views.py def login(request): if not request.session.get("uuid"): request.session["uuid"] = str(uuid.uuid4()) authorize_url = oauth.get_authorize_url() return redirect(authorize_url) ERROR : return caches_folder + request.session.get("uuid") NameError: name 'request' is not defined I reckon it is because request.session.get("uuid") is defined outside a view but I do not want to be creating oauth in separate views all the time. How do I manage this best? edit: def session_cache_path(uu_id): return caches_folder + uu_id oauth = SpotifyOAuth( redirect_uri="http://127.0.0.1:8000/spotify/authorize", scope='user-library-read', show_dialog=True, cache_path=session_cache_path(uu_id) ) -
how to filter on a field from another Model in nested Serializer
I have the following 3 models (third model Shop not important). There are shops, products, and shopitems (which shop has which item and at which price they offer it). class Product(models.Model): name=models.CharField(max_length=100) class Shopitem(models.Model): product = models.ForeignKey(Product, related_name='shopitems', on_delete=models.CASCADE) price=models.IntegerField() #shop field is not important to my question shop = models.ForeignKey(Shop, related_name='shopitems', on_delete=models.CASCADE) In my ProductSerializer, I made a nested serializer to ShopItemSerialzer, which works great. But how can I get list of all products, which are filtered by the shopitem price? And most importantly, the price is a query parameter, which I will get in my get_queryset() in the viewset, with the GET request 127.0.0.1/?price=500. Similar questions are asked a lot on stackoverflow, but none of them sadly didn't solve it for me. One solution I saw was to add this function to my Product model, and call it from the serializer: class Product(models.Model): name=models.CharField(max_length=100) def some_function(self): return ShopItem.objects.filter(product=self, price__gt=340) class ProductSerializer(serializers.ModelSerializer): shopitems=ShopItemSerializer(many=True, read_only=True,source="some_function") And this works good, but not great. The value 340 that I filter on the price must be hard coded into that function. How can I pass any parameter to it, that I get with self.request.query_params['price'], to this some_function? I also saw other solutions, that … -
Why Django doesn't find a modules which PyCharm finds well?
I tries to build my first Django project. I've created 'superlist' project and 'lists' app inside. My project tree: pycharm_project_folder | superlist | lists superlist manage.py ... | venv My lists/views.py: from django.shortcuts import render def home_page(): """home page""" pass My superlist/urls.py from django.urls import path from superlist.lists import views urlpatterns = [ path('/', views.home_page, name='home') # path('admin/', admin.site.urls), ] My lists/test.py from django.test import TestCase from django.urls import resolve from superlist.lists.views import home_page class HomePageTest(TestCase): """тест домашней страницы""" def test_root_url_resolves_to_home_page_view(self): """корневой url преобразуется в представление домашней страницы""" found = resolve('/') self.assertEqual(found.func, home_page) So, when I run python3 manage.py test I see ModuleNotFoundError: No module named 'superlist.lists' I don't understad why I got it because paths were suggested by PyCharm -
Django passing argument missing ) javascript
I'm having a trouble why this keep telling me Uncaught SyntaxError: missing ) after argument list I have a list and I want to retrieve it through passing into javascript. Is there anyone know what's the problem? Please give me some help. This is what it looks like: views.py: def sample(request): getlist = request.POST.getlist('batch[]') format = {'list': getlist} return render(request,'sample.html', format) sample.html: {% if list %} <button type="button" id="reports_btn" class="btn btn-secondary round btn-min-width mr-1 mb-1" onClick = "reports('{{list}}')" >sample</button> {% endif %} javascript: function reports (list) { console.log(list) } Updated my function views.py: @login_required(login_url='log_permission') def sap_payroll(request): classifications = Person.objects.all().values('classification').distinct() category = Person.objects.all().values('category').distinct() payroll_batch = Person.objects.all().values('payroll_batch').distinct() batch_it = Person.objects.all().values('batch_it').distinct() paid = Person.objects.all().values('paid').distinct() type_payout = Person.objects.all().values('type_payout').distinct() paid_with = Person.objects.all().values('paid_by').distinct() province = request.POST.get('province', False) municipality = request.POST.get('municipality', False) barangay = request.POST.get('barangay', False) payout_type = request.POST.get('type_payout', False) status = request.POST.get('stats', False) dte_from = request.POST.get('dte_from', None) dte_to = request.POST.get('dte_to', None) getlist = request.POST.getlist('batch[]') if request.method=='POST': shes = ['1','2'] # sample testing print("doda") print(type_payout) if getlist and dte_from and dte_to : user_list = Person.objects.filter(date_receive__range=[dte_from, dte_to] , payroll_batch__in = getlist ) bene = UserFilter(request.POST, queryset=user_list) elif getlist: user_list = Person.objects.filter(payroll_batch__in = getlist) bene = UserFilter(request.POST, queryset=user_list) elif dte_from and dte_to: user_list = Person.objects.filter(date_receive__range=[dte_from, dte_to]) bene = UserFilter(request.POST, … -
Django translation redirect back to the current page
How to redirect back to the current page. In my site I'm implementing two language which is 'en' and 'fa' right now It's working but doesn't redirect to current page like docs.djangoproject.com we have instead it redirect me to home 'localhost:8000/fa/' or /en here is the code: for template hearders.py <li class="dropdown default-dropdown"> <form action="{% url 'selectlanguage' %}" method="POST">{% csrf_token %} <input name="next" type="hidden" value="{{ redirect_to }}"> <select name="language"> {% get_current_language as LANGUAGE_CODE %} {% get_available_languages as LANGUAGES %} {% get_language_info_list for LANGUAGES as languages %} {% for language in languages %} <option value="{{ language.code }}"{% if language.code == LANGUAGE_CODE %} selected{% endif %}> {{ language.name_local }} ({{ language.code }}) </option> {% endfor %} </select> <input type="submit" value="{% trans 'Go' %}"> </form> </li> code for urls.py is: path('selectlanguage', views.selectlanguage, name='selectlanguage'), and for views.py is: def selectlanguage(request): if request.method == 'POST': # check post cur_language = translation.get_language() lasturl= request.META.get('HTTP_REFERER') lang = request.POST['language'] translation.activate(lang) request.session[translation.LANGUAGE_SESSION_KEY]=lang #return HttpResponse(lang) return HttpResponseRedirect(lang) -
Django - Select a specific pk at a view where multiple pk's are available
I'm currently building a support page where people can open each ticket as a box. Problem now is that I need to seperate the pk for each opened suppot ticket where people can reply on as I have everything on a single page and a single view and a single form but with multiple pk's, as all support tickets of the user are getting displayed: def support(request, pk=None): template = 'App_Support/support.html' form = SupportTicketMessagesForm() if request.method == "POST": support_ticket = get_object_or_404(SupportTickets, pk=pk) form = SupportTicketMessagesForm(request.POST) if form.is_valid(): support_ticket_reply = form.save(commit=False) support_ticket_reply.author = request.user support_ticket_reply.content_object = support_ticket support_ticket_reply.save() messages.success(request, 'Reply has been added successfully') return redirect('support') else: messages.error(request, 'Something went wrong') return redirect('support') else: list_support_tickets = sorted( chain( SupportTickets.objects.filter(requester=request.user, status=0) ), key=attrgetter('creation_date'), reverse=True ) paginator = Paginator(list_support_tickets, 10) page = request.GET.get('page') support_tickets = paginator.get_page(page) args = {'support_tickets': support_tickets, 'form': form } return render(request, template, args) My problem is at the following two lines: support_ticket = get_object_or_404(SupportTickets, pk=pk) support_ticket_reply.content_object = support_ticket As I'm unable to properly access the pk of just one object/Support Ticket, as in this view I only have multiple pk's I can potentially reply onto. So how to select? In addition, please also see my models.py logic: referential_models = … -
How do I show checkbox value checked if it already exists in Database?
If user checks Orange and banana then save it. The value Orange and Banana will be stored in Database(Postgresql). Now when I open the checklist page(As shown In the image),Checkbox Orange and banana should be checked and Kiwi, Apple and Grapes should be unchecked Here is models.py class details(models.Model): name = models.CharField(max_length = 20) class savedata(models.Model): checked_value = models.CharField(max_length=50) Here is views.py def choice(request): list = details.objects.values('name') done = savedata.objects.get(pk = 16) temp = done.checked_value print(list) print(done) print(temp) if request.method == "POST": data = savedata() data.checked_value = request.POST.get('checked_values') data.save() return render(request, 'choice.html',{'list':list,'data':data,'done':done,'temp':temp}) else: return render(request, 'choice.html',{'list':list,'done':done,'temp':temp}) When I print list I get: <QuerySet [{'name': 'Orange'}, {'name': 'Kiwi'}, {'name': 'Banana'}, {'name': 'Apple'}, {'name': 'Grapes'}]> When I print done I get: savedata object (16) When I print temp I get: Orange, Banana Here is Django Template choice.html {% for l in list %} {%if temp in list.name %} <input style="font-weight: bold;display:inline-block;" type="checkbox" class="chkcvalues" name="ip" value="{{l.name}}" checked> {{l.name}}<br /> {%else%} <input style="font-weight: bold;display:inline-block;" type="checkbox" class="chkcvalues" name="ip" value="{{l.name}}"> {{l.name}}<br /> {%endif%} {% endfor %} <input type="text" name="checked_values" id="txtvalues" /> <button id="but1" type="submit" class="save"> Save</button> <a id="but2" type="submit" class="home" href="{% url 'fruit' %}"> Home</a> The problem with this code is it always goes into else … -
django form choicefield update after every query
i have created a webapp. this is how it works user inputs a number mapped with a product csv file corresponding to that product gets downloaded you are presented with a form which contains one property name along with choices available for that property issue i am facing is, this whole process works for first search only after that whenever user enters any different number for any other product ideally choicefield in the form should get updated, but it dont get updated, i have deployed this app on heroku,if i restart all dynos this fixes the problem but just for time being. i mean for only one search, again same problem happens link to the app: https://abcd4.herokuapp.com/ link to the code: https://drive.google.com/drive/folders/1zlKowvcpK5NOnmAZFstDPC1oWTH97WmX?usp=sharing problem is not about the deployed platform i.e heroku i faced same issue when i ran app on localhost on localhost also restarting app solved the problem forms2.py from django import forms from django.core import validators def mergefunction(s1,s2): merged = [] for i in range(0, len(s1)): tup = (s1[i],s2[i]) merged.append(tup) return merged class GeeksForm(forms.Form): import csv import pandas as pd filename = r"downloaded1.csv" data = open(filename, encoding = "utf8") csv_data = csv.reader(data) data_lines = list(csv_data) total_row = (len(data_lines)) … -
How to use reverse filtering and removing duplicates in annotate using Django ORM
Hello I am having flowing model structure class TestModelA(AuditFields, Model): id = models.AutoField(primary_key=True) modelb = models.ForeignKey( TestModelB, on_delete=models.SET_NULL, blank=True, null=True ) class TestModelB(AuditFields, Model): id = models.AutoField(primary_key=True) modelc = models.ForeignKey( TestModelC, on_delete=models.SET_NULL, blank=True, null=True ) class TestModelC(AuditFields, Model): id = models.AutoField(primary_key=True) value = models.charfield(max_length=255, blank=True) I'm making a query like this qs = TestModelA.objects.values('modelb__modelc__value').annotate( count=Count('modelb__modelc__value'), ).distinct() Later some other filters applied to this initial queryset "qs" For that I am having another model class TestModelD(AuditFields, Model): id = models.AutoField(primary_key=True) modela = models.ForeignKey( TestModelA, on_delete=models.SET_NULL, blank=True, null=True, related_name="associated_modela") rating = models.charfield(max_length=255, blank=True) Then this is out new qs qs = (TestModelA.objects.values('modelb__modelc__value').annotate( count=Count('modelb__modelc__value'), ).distinct()).filter(associated_modela__rating = 'Sample') But the issue is that if two TestModelD objects under a single TestModelA object , it duplicating In the above scenario (if two TestModelD objects under a single TestModelA object) Currently I am getting output like this <SoftDeletionQuerySet [{'modelb__modelc__value': 'Large', 'count': 2}]> But my expected output is <SoftDeletionQuerySet [{'modelb__modelc__value': 'Large', 'count': 1}]> -
Transfer Class-based view to another
I created a DetailView class that can receive links from categories or posts from a website. In the “get_object ()” method, I identify if it is Category or Post models (by url slug). The URLs for this class are listed below: /category/ /category/subcategory/ /category/post/ /category/subcategory/post/ The class got too long because the categories and posts have specific behaviors. I was wondering if it is possible to "transfer" one class to another to handle specific information? For example: GenericView redirect to CategoryView after identifying that it is the url: / category / or for PostView, if it is / category / post / NOTE: I am transferring the Wordpress site to Django, so I cannot change the url structure. Is there any way to do this? Do you suggest another better solution? -
how to overwrite dj_rest_auth registration package on django rest project
I'm creating a full stack app using django rest + react. (backend) config.urls sign up path path('accounts/signup/', include('dj_rest_auth.registration.urls')), i need to overwrite the package so i can sign up using: password + password_confirm instead of the built in password1 + password2 Hopefully someone will know how to do it