Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ValueError at / (Required parameter name not set)
I am trying to make a blog app using django and python. I am also trying to use s3 buckets for storage and heroku for deployment.I am follow a tutorial online by coreymschafer. I am doing everything exactly as the tutorial, yet i am getting that error. I have no idea what to do. Please help! I have also installed boto3 and django-storages. However, I feel that the problem is with boto3 for some reasonenter image description here. i have attached a screenshot of the problem,also just wanted to state that there is no problem with base.html PLEASE HELP! THANK YOU I added these to my settings.py file: AWS_ACCESS_KEY_ID = os.environ.get('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = os.environ.get('AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = os.environ.get('AWS_STORAGE_BUCKET_NAME') AWS_S3_FILE_OVERWRITE = False AWS_DEFAULT_ACL = None DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' -
Avoid Typing "python" Before Django Commands in VS Code
I am setting up a new Windows 10 computer and somehow on my old Windows 10 computer I was able to configure VS Code so that I do not have to type "python" before Django commands in the VS Code command prompt. For example, I can type "manage.py runserver" instead of "python manage.py runserver". Frustratingly, I can't figure out how to replicate this on my new machine. Any advice would be greatly appreciated. -
Django Cleaning Form Data On Multiple Forms
I need help cleaning my form data on my website's forms to prevent data from being tampered with and for validation reasons where the validation is not lost. I pasted the code in dpaste links because it is rather long for stackoverflow. How would I do this for each of the forms? Views.py: https://dpaste.org/wPxt Forms.py: https://dpaste.org/7R9A -
post data into database without template in django
I want to post data into database without using templates in django. Here is my model class: class Employee(models.Model): eno = models.IntegerField() ename = models.CharField(max_length=20) esal = models.FloatField() eadd = models.TextField(max_length=40) def emp(request): eno = request.POST[1289], ename = request.POST['siddarth'], esal = request.POST[20190.24], eadd = request.POST['india'], save_data = Employee.objects.create(eno=eno,ename=ename,esal=esal,eadd=eadd) save_data.save() return JsonResponse(save_data) -
Django page urls.py in Repl gives path didn't match any of these error
I get the following problem while runing a TO_DO_LIST app on Repl.it using Django. ''' Using the URLconf defined in main.urls, Django tried these URL patterns, in this order: ^admin/ ^$ [name='home'] add_todo/ delete_todo/<int:todo_id> The current path, delete_todo/1/, didn't match any of these. ''' My urls.py file is: ''' urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^$', views.home, name='home'), path('add_todo/', views.add_todo), path('delete_todo/<int:todo_id>',views.delete_todo), ] ''' - -
Serialize the response as nested field in django rest framework
I had been trying to make a nested json instead of flat json. What I am getting is, { "field1": "value1", "field2": "value2" } And I am trying to make as, { "field1": "value1", "extra": { "x1" : "value2", "comment": "my comment" } } My model is simple, class MyModel(BaseMeta): field1 = models.CharField(db_column='field1', primary_key=True, max_length=11) field2 = models.CharField(db_column='field2') Serializer is class MyModelSerializer(serializers.Serializer): class Meta: model = MyModel fields = ['field1', 'field2'] The solution is the following, class MyModelSerializer(serializers.Serializer): extra = serializers.SerializerMethodField('get_extra') class Meta: model = CowMating fields = ['field1', 'extra'] def get_extra(self, obj): return { 'x1': obj.field2, 'comment': 'my comments' } But I am wondering if its possible to write another serializer like, class ExtraSerializer(serializers.Serializer): x1 = serializers.CharField(source='field2') comment = "my comment" and the serializer would be in the ModelSerializer, class MyModelSerializer(serializers.Serializer): extra = ExtraSerializer() class Meta: model = MyModel fields = ['field1', 'extra '] Please give some advice. Thanks in advance. -
Django Rest FrameWork and React Native: Live Video Streaming For Mobile App
I am in the planning phase of using django restframework for the backend and react native for the front end for a mobile app development. One of the requirements is to implement a robust and scale-able live video streaming functionality. I am unfamiliar with live video streaming. What is the best approach in building this functionality? -
Is there any way to hide text from being inspected in dev tools or click + inspect?
There is some text that I want to hide from users. So far, I used <body oncontextmenu="return false;"> and a JavaScript function below: <script> document.onkeydown = function(e) { if(event.keyCode == 123) { return false; } if(e.ctrlKey && e.shiftKey && e.keyCode == 'I'.charCodeAt(0)) { return false; } if(e.ctrlKey && e.shiftKey && e.keyCode == 'C'.charCodeAt(0)) { return false; } if(e.ctrlKey && e.shiftKey && e.keyCode == 'J'.charCodeAt(0)) { return false; } if(e.ctrlKey && e.keyCode == 'U'.charCodeAt(0)) { return false; } } </script> However, this doesn't stop an individual from opening up dev tools and seeing the text. Is there any way to hide or at least obfuscate a <p> tag? Here is the part of the code I want to hide. It's in Django: <p class="mb-1 multiline-ellipsis">{{item.itemDescription}}</p> <!--thing that I want to hide from inspection--> I am new to web development, so please help. -
I can't access to not translated field in django
I use django-modeltranslation and I can't access to not translated fields. Please give me some advices. model.py class JobOffer(models.Model): CHOICE = ( ('あり', 'あり'), ('なし', 'なし'), ) OFFER_STATUS=(('1','制作未完了'),('2','申込み中'),('3','掲載中'),) user = models.OneToOneField(settings.AUTH_USER_MODEL, verbose_name='user',on_delete=models.PROTECT, null=True) title = CharField(_('募集タイトル'),max_length=300,null=True) job = models.TextField(_('仕事内容・求める人材')) promote = CharField(_('昇給あり'),choices=CHOICE,max_length=10,null=True,blank=True,default='なし') bonus = CharField(_('賞与あり'),choices=CHOICE,max_length=10,null=True,blank=True,default='なし') created_at = DateTimeField(auto_now_add=True) status = CharField(_('求人掲載状況'),choices=OFFER_STATUS,max_length=100,default='2') def __str__(self): return self.bonus transration.py from modeltranslation.translator import translator, TranslationOptions from .models import JobOffer class JobOfferTranslationOptions(TranslationOptions): fields = ('title','job') translator.register(JobOffer, JobOfferTranslationOptions) settings.py from django.utils.translation import ugettext_lazy as _ LANGUAGES = [ ('ja', _('日本語')), ('en', _('English')), ('vi',_('Tiếng việt nam')), ('id',_('Orang indonesia')), ] LANGUAGE_CODE = 'ja' MODELTRANSLATION_DEFAULT_LANGUAGE = 'ja' views.py def jobOffer_manager(request): user = request.user jobOffer = JobOffer.objects.get_or_create(user=user) context = {'jobOffer':jobOffer,} return render(request,'company/jobOffer_manager.html',context) jobOffer_manager.html <div> <h2>{{ jobOffer.status }}</h2> <h2>{{ jobOffer.get_status_display }}</h2> </div> I can't see anything. please help me. thanks. -
How can I stop AJAX from resetting my multiple django-smart-selects dropdown values that should be set by database?
I have multiple django-smart-selects dropdowns all working and chained together to choose region, then subregion, then country, then state, then county then city. These values are able to be selected and then saved to database. But when changeform is opened again after save, all dropdowns are set to their respective values and then just before page finishes loading all but the first chained dropdown resets to blank value of "-----". It appears that the my AJAX file "https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js" is causing this. When I remove the script, it all updates to respective values, but then the AJAX is gone that triggers the selections from one to another and then the django-smart-selects won't work as expected. -
Selenium Connection Refused on Apache Web Server
I have an app that runs selenium on user requested URLs. The app works completely fine on the django dev server on an aws ec2 instance. Deploying the same project--on the same server--on an apache prod web server creates the following error (if I allow django debug to remain on): Exception Type: TimeoutException at / Exception Value: Message: connection refused I am using the geckodriver with firefox v. 71 and the newest geckodriver. I point to the absolute path of the geckdriver: from selenium import webdriver options = webdriver.FirefoxOptions() options.headless = True driver = webdriver.Firefox(options=options, executable_path=path_to_driver, service_log_path=path_to_log) ... Currently I am not using pyvirtualdisplay whereas everything worked fine on the same server in dev. When I did try to use pyvirtualdisplay I had the same results. I think it may be a permissions issue with apache and the webdriver, but I'm not sure. I did grant apache executable permissions to the geckodriver: -rwxrwxr-x 1 ubuntu www-data 7008696 Jan 8 03:02 geckodriver Any thoughts? -
Order_by, search filter, and pagination at same time in Django
When using pagination on a query we have to pass the ?q= along with the pagination for the pagination to keep the query on page #2 etc. I am wondering how to add complex filtering and ordering using multiple HTML forms? Take this example where I have a search bar and a drop-down button which handles the "ordering". Can I put these together so that I can submit a query and order the query all from the client side? Would like to only use HTML here. HTML: <div class="btn-group"> <!--Search Bar--> <form class="mb-0 ml-auto mr-auto"> <input name="q" placeholder="Filter test results..." style="width:330px;" type="text"> </form> </div> <div class="btn-group"> <!--Order By Button--> <button class="btn btn-default btn-sm dropdown-toggle ml-auto mr-auto" data-toggle="dropdown" type="button"> <span class="fa fa-sort"></span> Order By </button> <ul class="dropdown-menu" role="menu"> <li> <form class="small-form" method="get"> <input name="ordering" type="hidden" value="-end"> <input class="btn btn-link link-black btn-sm" type="submit" value="Date: most recent"> </form> </li> </div> -
passing data of Enterkey event from angular component to service using Subject import
I am new to angular 8.I have to integrate the angular front with django backend for the search application. so basically i am fetching the data(enter key event ->user input)from searchbox component. then i am passing this value to service(which communicates to Django) by passing parameters to service function. searchbox component import { Component, OnInit, ComponentFactoryResolver } from '@angular/core'; import {COMMA, ENTER} from '@angular/cdk/keycodes'; import { djApiService } from 'src/app/layout/main-content/searchcontent/services/djapi.service'; @Component({ selector: 'app-searchcontent', templateUrl: './searchcontent.component.html', styleUrls: ['./searchcontent.component.scss'] }) export class SearchcontentComponent implements OnInit { searchs: string; public constructor(private _dapiservice: djApiService ) { this._dapiservice.getcommentsbyparameter('this.searchs'); } searchText(search:string) { this.searchs = search; console.log(search); } } HTML code of searchbox component <input type="text" placeholder="Search here" class="" (keydown.enter) = "searchText($event.target.value)"> <span><img src="assets/images/search.svg"></span> Service function code(to get data from django) import { Injectable, Input } from '@angular/core'; import { Observable, Subject } from 'rxjs'; import { HttpClient ,HttpParams } from '@angular/common/http'; import { HttpHeaders } from '@angular/common/http'; @Injectable() export class djApiService { //@Input() search:string; //search = 'PLM' getcommentsbyparameter$: Observable<any>; httpHeaders = new HttpHeaders({'Content-type': 'application/json'}); private getcommentsbyparameterSubject = new Subject<any>(); constructor(private httpclient: HttpClient) { this.getcommentsbyparameter$ = this.getcommentsbyparameterSubject.asObservable(); } getcommentsbyparameter(search:string) { let params1 = new HttpParams().set('search',search); this.getcommentsbyparameterSubject.next(this.httpclient.get("http://127.0.0.1:8000/SEARCH/add",{params:params1})); console.log(search); } } service returns the backend output and sends the … -
how to identify the user that created an entry into the django model?
i am working on creating a notifications application . It works using django signals . Whenever a new instance of a model is created , i would invoke a code that will create a new instance of my notifications model. This notifications data is then filtered and rendered on my notifications page. The issue with this now is that whenever a new instance of a model is created , a notification will be created for the creator himself , which does not make sense. Therefore , Im thinking if its possible to pass the request.user parameter into my signal somehow. Here is my code for a better illustration of the problem: Here is my Notifications model: class Notifications(models.Model): time = models.DateTimeField(auto_now=True) target = models.ForeignKey(User , on_delete=models.CASCADE) message = models.TextField() object_type = models.CharField(max_length=100) object_url = models.CharField(max_length=500,default = 'test') is_read = models.BooleanField(default=False) Here is my signal, i was thinking of adding something like an .exclude method as shown below: def CreateSalesTaskNotification(sender, **kwargs): if kwargs['action'] == "post_add" and kwargs["model"] == SalesExtra: print(kwargs['instance'].salesExtra.all()) for person in kwargs['instance'].salesExtra.all().exclude(user = request.user): Notifications.objects.create( target= person.user, message='You have been assigned a task.', object_type = 'sales_task') m2m_changed.connect(CreateSalesTaskNotification, sender=SalesTask.salesExtra.through) Here is my SalesTask model: class SalesTaskingComments(models.Model): comment_id = models.AutoField(primary_key=True) salesExtras … -
The view blog.views.add_comment_to_post didn't return an HttpResponse object. It returned None instead
View didn't return an HttpResponse object. It returned None instead. And also in the bottom of the page it says "You're seeing this error because you have DEBUG = True in yourDjango settings file. Change that to False, and Django willdisplay a standard page generated by the handler for this status in models.py: class Comment(models.Model): post = models.ForeignKey('blog.Post',related_name='comments',on_delete=models.CASCADE) author = models.CharField(max_length=200) text = models.TextField() created_date = models.DateTimeField(default=timezone.now) approved_comment = models.BooleanField(default=False) def approve(self): self.approved_comment = True self.save() def get_absolute_url(self): return reverse("post_list") def __str__(self): return self.text in views.py: @login_required def add_comment_to_post(request, pk): post = get_object_or_404(Post,pk=pk) if request.method == "POST": form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.post = post comment.save() return redirect('post_detail', pk=post.pk) else: form = CommentForm() return render(request, 'blog/comment_form.html',{'form':form}) @login_required def comment_approve(request,pk): comment = get_object_or_404(Comment,pk=pk) comment.approve() return redirect('post_detail',pk=comment.post.pk) @login_required def comment_remove(request,pk): comment = get_object_or_404(Comment,pk=pk) post_pk = comment.post.pk comment.delete() return redirect('post_detail',pk=post_pk) in comment_form.html: {% extends 'blog/base.html' %} {% block content %} <h1>New comment</h1> <form method="POST" class="post-form"> {% csrf_token %} {{form.as_p}} <button type="submit" class="save btn btn-default">Post Comment</button> </form> <script>var editor = new MediumEditor('.editable');</script> {% endblock %} -
Django DecimalField what is the maximum value of max_digits?
Hi i'm trying to design my model which contain a field that supposed to store a really big integer number. Why is it big ? because when the front end send the data up to the server, the float number get converted into integer (for example: 2.44444444 will get converted to 244444444). Reading through the Django model fields docs i see that bigintegerfield only support up to 9223372036854775807 which is 19 digits(64 bits). I'm afraid that won't be enough so i think i should use DecimalField since it support max_digits like so: DecimalField(max_digits=40, decimal_places=0, default=0) #it will act like an integer because decimal_place=0 But i don't know how what the maximum value of max_digits since it don't seems to be mentioning about it in the docs and i still can't find any informations about it after googling If anyone know what the maximum amount max_digits in DecimalFields, it would be a great help. -
Python version problem under os.system(python)
I am having a problem of python version control. Currently I am working on a django project. Since my aim is using manage.py runserver to create a local server as an 'exe', I use pyinstaller to pack os.system('python manage.py runserver') in a standalone file. But when I apply, it failed. I found the reason is my python version in the django environment is 3.5.2, but this action needs python version 3.7. My python version is 3.7.5, which is definitely not 3.5.2, and the wired point is, I have never installed python 3.5.2. I have checked my Anaconda environment I CAN NOT find a place to set my python version, but I notice that when I use os.system(python), it shows the version of my Anaconda is 4.1.1, which IS NOT my installed version 4.7. So I am totally confused. If you have any ideal, I will be appreciate for your help. -
without using templates post data into database using only views file
I want to post data into database directly by writing views in django without using templates. In model class i am using four fields such as (eno,ename,esal,eadd). For these fields i wanna post data into database directly only with the help of using views. This is my model class : class Employee(models.Model): eno = models.IntegerField() ename = models.CharField(max_length=20) esal = models.FloatField() eadd = models.TextField(max_length=40) This is my view.py file: def emp(request): eno = request.POST[1289], ename = request.POST['siddarth'], esal = request.POST[20190.24], eadd = request.POST['india'], save_data = Employee.objects.create(eno=eno,ename=ename,esal=esal,eadd=eadd) save_data.save() return JsonResponse(save_data) For that using view.py file directly i want to post data into database for model class fields and return response as JsonResponse. -
Exception handling in Celery?
I have a group of tasks each of which make a request to a standard oauth API endpoint, and are dependent on a bearer_token. The tasks will raise an exception during response processing if the bearer_token is expired. There is also a refresh_bearer_token task, which handles updating the token once it expires. Here is a pseudo-code for that: from proj.celery import app bearer_token = '1234' class OauthError(Exception): pass @app.task def api_request(): response = request(bearer_token, ...) if response.bearer_token_expired: raise OauthError('oauth') @app.task def refresh_bearer_token(): ... How can I schedule the refresh_bearer_token task to execute whenever an OauthError is raised? The only solution I can find is using the link_error kwarg like this: @app.task def error_callback(uuid): exception_msg = AsyncResult(uuid).get(propagate=False, disable_sync_subtasks=False) if exception_msg = 'oauth': refresh_bearer_token.delay() else: raise api_request.apply_async(link_error=error_callback.s()) But this seems sub-optimal for several reasons, most notably because it spawns a synchronous child task within another synchronous child task, which strongly discourged in the docs. Is there a more pythonic way of exception catching in celery? For example: def catch(func_that_requires_oauth): try: func_that_requires_oauth.delay() except OauthError: refresh_bearer_token.delay() | func_that_requires_oauth.delay() -
Django Jsignature not passing the form.is_valid()
jsignature: https://github.com/fle/django-jsignature I have managed to display the signature pad: But when i tried to submit the form. i noticed that it could not pass the is.valid function and when i tried to printout the errors here is what i get: <ul class="errorlist"><li>signature<ul class="errorlist"><li>This field is required.</li></ul></li></ul> Here's my code in view: form = SignatureForm(request.POST) if form.is_valid(): signature = form.cleaned_data.get('signature') if signature: # as an image signature_picture = draw_signature(signature) # or as a file signature_file_path = draw_signature(signature, as_file=True) else: print(form.errors) -
How to use search filter when slug is used in URL path
I am trying to add search and ordering filters to a page which is dynamically created with a <slug:slug>. The issue is that as soon as I add my ordering filter I get: Reverse for 'quiz-results-filtered' with no arguments not found. 1 pattern(s) tried: ['tests\/results\/(?P[-a-zA-Z0-9_]+)\/$'] If I am reading this correctly it is telling me that it can't determine the page when the filter is empty. Problem is that when I do not have the HTML ordering filter on the page it works just fine. Order_by button HTML: <!-- Order By Button--> <button class="btn btn-default btn-sm dropdown-toggle ml-auto mr-auto" data-toggle="dropdown" type="button"> <span class="fa fa-sort"></span> Order By </button> <ul class="dropdown-menu" role="menu"> <li> <form action="{% url 'quiz-results-filtered' %}" class="small-form" method="get"> <input name="ordering" type="hidden" value="-end"> <input class="btn btn-link link-black btn-sm" type="submit" value="Date: most recent"> </form> </li> URL: path('tests/', include([ path('results/<slug:slug>/', views.QuizMarkingFilteredList.as_view(), name='quiz-results-filtered'), ... Views.py (although irrelevant some people made needlessly ask for this): class QuizMarkingFilteredList(PermissionRequiredMixin, LoginRequiredMixin, QuizMarkerMixin, ListView): model = Sitting template_name = 'quiz/sitting_filtered_list.html' permission_required = ('quiz.view_sittings',) permission_denied_message = 'User does not have permissions to view quiz sittings.' def get_ordering(self, *args, **kwargs): ordering = self.request.GET.get('ordering', 'end') return ordering def get_queryset(self): queryset = super(QuizMarkingFilteredList, self).get_queryset() queryset = queryset.filter(complete=True) queryset = queryset.filter(user__supervisor__exact=self.request.user) queryset = queryset.filter(quiz__url=self.kwargs['slug']) … -
django attribute error ------>AttributeError: module 'django.contrib.auth.views' has no attribute 'login', 'logout'
AttributeError: module 'django.contrib.auth.views' has no attribute 'login', 'logout' from django.contrib import admin from django.urls import path from django.conf.urls import url, include from blog import views from django.contrib.auth import views urlpatterns = [ path('admin/', admin.site.urls), url(r'',include('blog.urls')), url(r'accounts/login/$',views.login,name='login'), url(r'accounts/logout/$',views.logout,name='logout',kwargs= {'next_page':'/'}), ] -
How do I call a function when I make a post request at Python?
I programmed using the django rest framework. Since DRF is CRUD automatic, I created a view as shown below. class PostViewSet(viewsets.ModelViewSet): permission_classes = [permissions.IsAuthenticatedOrReadOnly] serializer_class = PostSerializer queryset = AllfindPost.objects.all() By the way, I would like to call the following functions when I make a post request. def send_fcm_notification(ids, title, body): url = 'https://fcm.googleapis.com/fcm/send' headers = { 'Authorization': 'key=', 'Content-Type': 'application/json; UTF-8', } content = { 'registration_ids': '', 'notification': { 'title': 'title', 'body': 'body' } } requests.post(url, data=json.dumps(content), headers=headers) What should I do? -
Django redirect preserving subpath
In my urls.py I have: urlpatterns = [ url(r'^admin/', admin.site.urls, name='admin'), url(r'^django-admin/', RedirectView.as_view(pattern_name='admin', permanent=True)), ] So if I go to localhost:8000/django-admin/ it successfully redirects me to localhost:8000/admin/, and if I go to localhost:8000/django-admin/my-app/ it also redirects me to localhost:8000/admin/. How could I make localhost:8000/django-admin/my-app/ go to localhost:8000/admin/my-app/? And the same for every possible subpath e.g. localhost:8000/django-admin/my-app/my-view, localhost:8000/django-admin/another-app/, etc? -
Best place to put a "saveAll" method/function
I have a Model class that is structured as follows: class Item(models.Model): place = models.CharField(max_length=40) item_id = models.IntegerField() # etc. @classmethod def from_obj(cls, **kwargs): i = Item() # populate this from json data # which needs a lot of translations applied # before saving the data So, from the above I have a way to create an Item instance via the from_obj classmethod. Now I want to process a json array that contains about 100 objects to create those 100 Item instances. Where should this be put? The function/method would look something like this: def save_all(): objects = requests.get(...).json() for obj in objects: item = Item.from_obj(obj) item.save() Should this be a staticmethod within Item. A plain function outside it? Or should another class be created to 'manage' the Item. What is usually considered the best practice for something like this pattern?