Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
IntegrityError: FOREIGN KEY constraint failed
I am trying to post a form(ReviewForm) but I get the error FOREIGN KEY constraint failed when my form tries to save.Any help please?Thanks in advance. Here is my views.py code(the post function in the view class) def post(self,request,*args,**kwargs): pk=self.kwargs.get("pk") di = self.kwargs.get("di") dis=get_object_or_404(Disease,pk=di) pestiside=Pestiside.objects.get(pk=pk,disease=dis) if request.method=='POST': user = request.user form= ReviewForm(request.POST) if form.is_valid(): form.save() comment=form.cleaned_data.get('comment') new_review=Review.objects.create(author=user,pes_id=pestiside_id,comment=comment) new_review.save() return redirect('diagnose:pestiside') Here is my models.py code: class Review(models.Model): author= models.ForeignKey(User,default=1, on_delete=models.CASCADE) time = models.DateTimeField(auto_now_add=True, blank=True) pes = models.ForeignKey(Pestiside,default=0,on_delete=models.CASCADE) comment = models.CharField(max_length=200) Here is my forms.py code: class ReviewForm(forms.ModelForm): class Meta: model=Review fields=('comment',) Here is my stacktrace,the error shows at form.save() in views.py : Traceback (most recent call last): File "/home/risper/django_projects/env01/lib/python3.6/site-packages/django/db/backends/utils.py", line 86, in _execute return self.cursor.execute(sql, params) File "/home/risper/django_projects/env01/lib/python3.6/site-packages/django/db/backends/sqlite3/base.py", line 396, in execute return Database.Cursor.execute(self, query, params) The above exception (FOREIGN KEY constraint failed) was the direct cause of the following exception: File "/home/risper/django_projects/env01/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/risper/django_projects/env01/lib/python3.6/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/risper/django_projects/env01/lib/python3.6/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/risper/django_projects/env01/lib/python3.6/site-packages/django/views/generic/base.py", line 71, in view return self.dispatch(request, *args, **kwargs) File "/home/risper/django_projects/env01/lib/python3.6/site-packages/django/views/generic/base.py", line 97, in dispatch return handler(request, *args, **kwargs) ***File "/home/risper/django_projects/Tomadoc/diagnose/views.py", line 276, in post form.save()*** File "/home/risper/django_projects/env01/lib/python3.6/site-packages/django/forms/models.py", … -
Django: Setting a cookie asynchronously
To set a cookie, I used this on Django docs.. blog/models.py class Post(models.Model): author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) title = models.CharField(max_length=180, null=False) text = tinymce.models.HTMLField() created_date = models.DateTimeField(auto_now_add=True, editable=False) published_date = models.DateTimeField(null=True, default=None) def __str__(self): return self.title def publish(self): self.published_date = timezone.now() self.save() class Like(models.Model): post = models.ForeignKey(Post, on_delete=models.DO_NOTHING) liked = models.BooleanField(default=False) timestamp = models.DateTimeField(auto_now_add=True, editable=True) visitor_uid = models.CharField(max_length=37) def __str__(self): return self.visitor_uid[:5] blog/views.py import uuid def make_cookie(request, pk): post = get_object_or_404(Post, pk=pk) like = Like() like.post = post like.visitor_uid = str(make_uuid()) like.save() request.session[post.pk] = like.visitor_uid Making a HttpResponse('Some HTML') which redirects. I don't want this behaviour to happen without the refreshing/redirecting. Also referred this from GFG but even they are redirecting... Any ideas? -
Django can't resolve url path 404
Hi I'm having a very annoying issue with django: I've setup many urls paths and they all work fine except one and I really can't figure out why: Urls urlpatterns = [ # path('foods/search', food_search), path('food_list/', FoodListVersionListCreateAPIView.as_view(), name='foodList-list'), path('all_foods/<str:survey>/<str:string>', FoodListCreateAPIView.as_view(), name='food-list'), path('food_classification/', FoodClassificationListCreateAPIView.as_view(), name='foodClassification-list'), path('food/<str:survey>/<str:string>/', FoodDetailAPIView.as_view(), name='food-detail'), ] Views class FoodListCreateAPIView(generics.ListCreateAPIView): queryset = Food.objects.all() serializer_class = FoodSerializer filter_backends = [DjangoFilterBackend, filters.SearchFilter] filterset_fields = ['description', 'food_code', 'cofid_code', 'foodex_code', 'food_classification'] search_fields = ['food_list', 'SYSTEM_TIME'] permission_classes = [permissions.IsAuthenticatedOrReadOnly] def get_queryset(self): assert self.queryset is not None, ( "'%s' should either include a `queryset` attribute, " "or override the `get_queryset()` method." % self.__class__.__name__ ) survey = self.request.query_params['survey'] food = self.request.query_params['string'] raw_queryset = perform_food_search(survey, food) queryset = Food.objects.filter(pk__in=[i.pk for i in raw_queryset]) if isinstance(queryset, QuerySet): # Ensure queryset is re-evaluated on each request. queryset = queryset.all() return queryset Error message -
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: …