Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to use JSON data on Django View
I need to use data as JSON from an API in Django View here is my JSON data; [{'Count': 5491}] I need to pass just value of the "Count" key to HTML and views.py is as below; def serviceReport(request): data = mb.post('/api/card/423/query/json') context = { 'count' : data['Count'] } return render(request, 'service_report.html', context) I get error like this; Exception Type: TypeError Exception Value: list indices must be integers or slices, not str What I want is to pass value of count key to service_report.html and also I want to pass multiple JSON datas like data2, data3 as data on views.py how can I do it? -
Django object filter - highest bid for every item
I want to filter an object which contains the highest price for each listing_id. from models.py class Listing(models.Model): title = models.CharField(max_length=64) class Bid(models.Model): listing_id = models.ForeignKey(Listing, on_delete=models.CASCADE, related_name="listing") user_id = models.ForeignKey(User, on_delete=models.CASCADE, related_name="user") price = models.DecimalField(max_digits=19, decimal_places=2, blank=False, validators=[MinValueValidator(1)]) Can I get some advice guys? -
How to add dictionary values as model object values into postgres in django
this is the model.py from django.db import models from datetime import datetime from postgres_copy import CopyManager class state_data(models.Model): date = models.DateTimeField(default=datetime.now) state = models.CharField(max_length=200) death = models.IntegerField() hospitalizedIncrease = models.IntegerField() def __str__(self): return self.state I have this model. and i have some dictionary like {'date' :12/2/1985,'state ':'fgyu', 'death':1245, 'hospitalizedIncrease':58} I wanted to add dictionary values [12/2/1985,fgyu,1245,58] into database created by the model after migrations please help me todo this. -
Create equivalent paths in Django urls.py
I am attempting to create 2 url prefixes that would be equivalent in my app (this is due to some aesthetic user requirements), and am unsure the best way to go about this. The most straightforward option would be to create another set of urlpatterns with the alternate prefix. However, this would be repetitive and make maintenance more difficult. Is there a simpler way to make foo/<str:key>/ equivalent to bar/<str:key> and staff/<str:key>/ equivalent to foo/<str:key>/staff/? Current URLS urlpatterns = [ path('foo/<str:key>/welcome/', views.welcome), path('foo/<str:key>/dashboard/', views.dashboard), path('foo/<str:key>/staff/dashboard/', views.staff_dashboard), ] Desired Patterns urlpatterns = [ # Original paths path('foo/<str:key>/welcome/', views.welcome), path('foo/<str:key>/dashboard/', views.dashboard), path('foo/<str:key>/staff/dashboard/', views.staff_dashboard), # Alternate paths to the same pages path('bar/<str:key>/welcome/', views.welcome), path('bar/<str:key>/dashboard/', views.dashboard), path('staff/<str:key>/dashboard/', views.staff_dashboard), ] -
token blacklist outstandingtoken
token_blacklist_outstandingtoken is The Collection In Mongodb Database Which Django REst Framework Use To Store Tokens Assigned To Recently Registered Users, It Stores Access Token Well For First User Register, But It Makes Error While Inserting Second UserError Details: djongo.sql2mongo.SQLDecodeError: FAILED SQL: INSERT INTO "token_blacklist_outstandingtoken" ("user_id", "jti", "token", "created_at", "expires_at") VALUES (%(0)s, %(1)s, %(2)s, %(3)s, %(4)s) Params: [11, 'fe4bbe67b6a4413e81cfca6b4e2919aa', 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ0b2tlbl90eXBlIjoicmVmcmVzaCIsImV4cCI6MTYwOTE3Nzc4MCwianRpIjoiZmU0YmJlNjdiNmE0NDEzZTgxY2ZjYTZiNGUyOTE5YWEiLCJ1c2VyX2lkIjoxMX0.JtyGSL_nJ4iiKXqijvxCkipxMQAxTksFKEP6g5qPGiI', datetime.datetime(2020, 12, 14, 17, 49, 40, 602304), datetime.datetime(2020, 12, 28, 17, 49, 40)] Pymongo error: {'writeErrors': [{'index': 0, 'code': 11000, 'keyPattern': {'jti_hex': 1}, 'keyValue': {'jti_hex': None}, 'errmsg': 'E11000 duplicate key error collection: patientStatus.token_blacklist_outstandingtoken index: token_blacklist_o_jti_hex_d9bdf6f7_uniq dup key: { jti_hex: null }', 'op': {'id': 10, 'user_id': 11, 'jti': 'fe4bbe67b6a4413e81cfca6b4e2919aa', 'token': 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ0b2tlbl90eXBlIjoicmVmcmVzaCIsImV4cCI6MTYwOTE3Nzc4MCwianRpIjoiZmU0YmJlNjdiNmE0NDEzZTgxY2ZjYTZiNGUyOTE5YWEiLCJ1c2VyX2lkIjoxMX0.JtyGSL_nJ4iiKXqijvxCkipxMQAxTksFKEP6g5qPGiI', 'created_at': datetime.datetime(2020, 12, 14, 17, 49, 40, 602304), 'expires_at': datetime.datetime(2020, 12, 28, 17, 49, 40), '_id': ObjectId('5fd7a5b444a87611a60654ae')}}], 'writeConcernErrors': [], 'nInserted': 0, 'nUpserted': 0, 'nMatched': 0, 'nModified': 0, 'nRemoved': 0, 'upserted': []} -
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) )