Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to avoid duplicate values from queryset
I am having three models class Records(Model): plan = models.ForeignKey(Plan, on_delete=models.CASCADE, related_name="records_plan", null=True) observation = models.CharField(max_length=255, blank=True) description = models.TextField(null=True, blank=True) rating = models.CharField(max_length=255, blank=True) class Plan(Model): plan_title = models.CharField(max_length=255, blank=True) plan_size = models.ForeignKey(Size, on_delete=models.CASCADE, related_name="%(class)s_size", null=True) description = models.TextField(null=True, blank=True) class Size(Model): value = models.CharField(max_length=255, blank=True) order = models.CharField(max_length=255, blank=True) In this I need to draw a chart of plan based on size of the plan my initial queryset is qs = Plan.objects.values('plan_size__value').annotate( count=Count('plan_size__value'), ).order_by("-plan_size__order").distinct() Using this query i'm able to get a queryset with data and field The same queryset I would like to apply a filter on later stages of my code qs = qs.filter(records_plan__rating = 'low') In this case I am getting the output , but values are duplicating (Example, if a plan having two records my chart need to consider it as a single plan , but here it comes as two plans),how to fix this Or how do I get the distinct value of plan while filtering it with record model -
What is the best way to create a website. Django or React Js or Angular Js or Node Js [closed]
I have finished a course on web development and I learn Django and a bit of react js. I want to know what is the best way to create a website that is used in real-life web applications. Well I searched through google and found that most web applications are made with React Js and firebase I want to know if I should go with Django or React Js with Firebase or with Angular Js with Firebase or should I go with node.js I want to know what's really used in real-life web applications so I can start practicing or if there are recommended courses please do tell me and I would like a description of why I should go with that so I could make a decision with what web development part I should go with or what is the best at least. Thanks, -
Select multiple rows from list to perform action [closed]
I have a Table-List which is getting their values from the Database, where each row is a representation of a model in the DB. Now I want to make them selectable (checkbox), to multiple delete or submit entries. As now I can only delete entries by deleting them row for row. I dont have any idea at all how to achieve this, hopefully someone has an directional idea? -
Error in django testing: 'str' object has no attribute '_meta'
I am getting the following error when I try to execute testing (coverage run --source='.' manage.py test project) and the problem is that I don't even know in which file the error is happening. I'm not getting any error while executing the python manage.py runserver / makemigrations / migrate commands. I would really appreciate if someone would help me out pin-poining the source of the error! Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/Users/virtual-env/lib/python3.7/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/Users/virtual-env/lib/python3.7/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/virtual-env/lib/python3.7/site-packages/django/core/management/commands/test.py", line 23, in run_from_argv super().run_from_argv(argv) File "/Users/virtual-env/lib/python3.7/site-packages/django/core/management/base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "/Users/virtual-env/lib/python3.7/site-packages/django/core/management/base.py", line 371, in execute output = self.handle(*args, **options) File "/Users/virtual-env/lib/python3.7/site-packages/django/core/management/commands/test.py", line 53, in handle failures = test_runner.run_tests(test_labels) File "/Users/virtual-env/lib/python3.7/site-packages/django/test/runner.py", line 695, in run_tests old_config = self.setup_databases(aliases=databases) File "/Users/virtual-env/lib/python3.7/site-packages/django/test/runner.py", line 616, in setup_databases self.parallel, **kwargs File "/Users/virtual-env/lib/python3.7/site-packages/django/test/utils.py", line 174, in setup_databases serialize=connection.settings_dict['TEST'].get('SERIALIZE', True), File "/Users/virtual-env/lib/python3.7/site-packages/django/db/backends/base/creation.py", line 77, in create_test_db run_syncdb=True, File "/Users/virtual-env/lib/python3.7/site-packages/django/core/management/__init__.py", line 168, in call_command return command.execute(*args, **defaults) File "/Users/virtual-env/lib/python3.7/site-packages/django/core/management/base.py", line 371, in execute output = self.handle(*args, **options) File "/Users/virtual-env/lib/python3.7/site-packages/django/core/management/base.py", line 85, in wrapped res = handle_func(*args, **kwargs) File "/Users/virtual-env/lib/python3.7/site-packages/django/core/management/commands/migrate.py", line 245, in handle fake_initial=fake_initial, File "/Users/virtual-env/lib/python3.7/site-packages/django/db/migrations/executor.py", line 117, in migrate … -
How to auto add a field in django admin model calculating age
is it possible to add an age field that is auto filled in the runtime based on another date of birth field at the django admin interface, i added a screenshot trying to explain more what i mean my models.py class FamilyMember(models.Model): transaction = models.ForeignKey(Transaction, on_delete=models.CASCADE) family_group = models.ForeignKey(FamilyGroup, on_delete=models.CASCADE, null=True, blank=True) name = models.CharField(max_length=100, null=True, blank=True) date_of_birth = models.DateField(null=True, blank=True) relationship = models.ForeignKey(Relationship, on_delete=models.PROTECT) dependant_child_age_range = models.ForeignKey(DependantChildAgeRange, null=True, blank=True, on_delete=models.PROTECT) care_percentage = models.PositiveSmallIntegerField( null=True, blank=True, validators=[ MaxValueValidator(100), ]) income = models.DecimalField(max_digits=6, decimal_places=2, null=True, blank=True) rent_percentage = models.PositiveSmallIntegerField( null=True, blank=True, validators=[ MaxValueValidator(100), ]) admin.py class FamilyMemberInline(admin.TabularInline): def formfield_for_foreignkey(self, db_field, request, **kwargs): action = request.META['PATH_INFO'].strip('/').split('/')[-1] if action == 'change': transaction_id = request.META['PATH_INFO'].strip('/').split('/')[-2] if db_field.name == "family_group": kwargs["queryset"] = FamilyGroup.objects.filter(transaction=transaction_id) return super(FamilyMemberInline, self).formfield_for_foreignkey(db_field, request, **kwargs) model = FamilyMember extra = 0 def sufficient_info_provided (self, obj): return obj.sufficient_information_provided sufficient_info_provided.boolean = True readonly_fields = ['sufficient_info_provided',] -
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 = …