Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django DRF how to validate captcha response for server side
I amusing nextjs as my frontend. I am struggling to validate server site captcha response. I want data will be not inserted in my database until captcha verification sucess. I tried drf-recaptcha package. Here is my code: settings.py INSTALLED_APPS = ['rest_framework_recaptcha',] #included in my installed app DRF_RECAPTCHA_SECRET_KEY = '< my_secrect key>' serializers.py from rest_framework_recaptcha import ReCaptchaField class ContactSerializer(serializers.ModelSerializer): recaptcha = ReCaptchaField() class Meta: model = Contact fields = '__all__' my API views.py @api_view(['POST', 'GET']) def contact_forms_api(request): if request.method == 'POST': ''' Begin reCAPTCHA validation ''' recaptcha_response = request.POST.get('g-recaptcha-response') url = 'https://www.google.com/recaptcha/api/siteverify' values = { 'secret': settings.GOOGLE_RECAPTCHA_SECRET_KEY, 'response': recaptcha_response } data = urllib.urlencode(values) req = urllib2.Request(url, data) response = urllib2.urlopen(req) result = json.load(response) ''' End reCAPTCHA validation ''' if result['success']: data = request.data serializer = ContactSerializer(data=data) if serializer.is_valid(): serializer.save() print(serializer.data) return Response({ 'status': True, 'message': 'sucess' }) return Response({ 'status': False, 'message': serializer.errors }) here is my nexjs code: I am using this package in my frontend application. here my code sometings look like: <form onSubmit={SubmitContact}> <input type="text"/> <ReCAPTCHA sitekey="my_captcha site ke=y" onChange={handleRecaptcha} /> <form> here is my SubmitContact function look like this: const res = await axios.post(url,data,{headers: headers} ) -
Django - Async views (api requests) and AJAX
I've used this code right here to speed up the api response of IEX. iex_var2 and iex_var1 and result are imported. I've also a form for the user where he searches for the ticker (input_ticker) The response works fine and is quit fast. async def api_test2(request): start_time = time.time() async with aiohttp.ClientSession() as session: input_ticker = request.POST['ticker'] for i in iex_var2: var2 = i url = f"{iex_var1}{input_ticker}{var2}" async with session.get(url) as res: url = await res.json() result.append(url) total = time.time() - start_time print(total) return HttpResponse(result) Now I've got two important questions about my code. How do I avoid, that each reload runs that code again? When I reload the HttpResponse, the view runs again and so on there is duplicated data in "result". Can I use a Cache herefor? I am still a beginner, probably mixing something up here? My question nr.2 is how to print this result into a template? Render does not work along with an async view, so I think AJAX is the solution, but I have neither experience with JS nor with AJAX. So I am not sure how I can the connect the "result" of my view with a template. I#ve also tried to use … -
Django redis docker
I want to make a chat app with django channels and I follow the steps from the docs. To enable the redis server you need to run docker run -p 6379:6379 -d redis:5 but when I run it I get: Unable to find image 'redis:5' locally docker: Error response from daemon: Head "https://registry-1.docker.io/v2/library/redis/manifests/5": Get "https://auth.docker.io/token?scope=repository%3Alibrary%2Fredis%3Apull&service=registry.docker.io": net/http: request canceled (Client.Timeout exceeded while awaiting headers). See 'docker run --help'. What should I do? Thanks,. -
Django get request divide to 3 branches?
I have an article list class (class ArticleListView(View):) In that class I want to have 1 get function with 3 different request. First one use for search articles Second one use for returning a random article link Third one return list of article I can do 2 different get request (all and search one) but I can not add third one. Is this technically possible and if yes who do I like to random page and what part of my get function is wrong? my code : class ArticleListView(View): template_name = "wiki/article_list.html" def get(self, request) : strval = request.GET.keys() if request.GET.get('search') : # Simple title-only search # objects = Post.objects.filter(title__contains=strval).select_related().order_by('-updated_at')[:10] # Multi-field search # __icontains for case-insensitive search query = Q(title__icontains=strval) query.add(Q(text__icontains=strval), Q.OR) article_list = Article.objects.filter(query).select_related().order_by('-updated_at')[:10] elif request.GET.get('random'): # find the number of article abject numberOfArticle = Article.objects.all().count() # find a random number from 1 to number of articles randomPK = random.randint(1, numberOfArticle) # filter article list object base on primary key ( pass that random number) #Item.objects.all()[0].type_id article_list = Article.objects.get(pk=randomPK) else : article_list = Article.objects.all().order_by('-updated_at')[:10] # Augment the article_list for obj in article_list: obj.natural_updated = naturaltime(obj.updated_at) ctx = {'article_list' : article_list, 'search': strval, 'random':strval} return render(request, self.template_name, ctx) my … -
How to properly display all inline fields associated with its parent model fields when paginating in Django template?
I'm a student and a Django newbie, and we have a project that we're trying to build using Django. In my journey to building the project I stumbled upon a problem and got stuck for weeks now. I want to display all the inline fields associated with its parent field on one page as I paginate. When I tried to paginate a model with 2 additional models that have foreign keys to it I got a weird result in my template. I can't seem to figure out how to fix it. I tried several methods on the Internet and have read numerous forums and discussions but to no avail, none has worked so far. Below are my files and a few Images: (models.py) from django.db import models class History(models.Model): BARANGAY = ( ('Alegria','Alegria'), ('Bagacay','Bagacay'), ('Baluntay','Baluntay'), ('Datal Anggas','Datal Anggas'), ('Domolok','Domolok'), ('Kawas','Kawas'), ('Ladol','Ladol'), ('Maribulan','Maribulan'), ('Pag-Asa','Pag-Asa'), ('Paraiso','Paraiso'), ('Poblacion','Poblacion'), ('Spring','Spring'), ('Tokawal','Tokawal') ) barangay_name = models.CharField(max_length=100,choices=BARANGAY,default='Alegria') barangay_img = models.ImageField(upload_to='history_imgs',blank=True) barangay_info = models.TextField() class GeoHazard(models.Model): history = models.ForeignKey(History,related_name='geohazards',on_delete=models.CASCADE) geohazard_img = models.ImageField(upload_to='history_imgs',blank=True) date_published = models.CharField(max_length=100, null=True) geohazard_info = models.TextField() class Assessment(models.Model): RATINGS = ( ('HIGH','HIGH'), ('HIGH (Mitigated)','HIGH (Mitigated)'), ('MODERATE','MODERATE'), ('MODERATE (Mitigated)','MODERATE (Mitigated)'), ('LOW','LOW'), ('UNKNOWN','UNKNOWN'), ) history = models.ForeignKey(History,related_name='assessment',on_delete=models.CASCADE) purok_name = models.CharField(max_length=50) purok_coordinates = models.CharField(max_length=100,default='unknown') flood_rating = models.CharField(max_length=100,choices=RATINGS,default='UNKNOWN') … -
How to get variable from POST method in Modelchoicefield
#forms class ChoiceAddressForm(forms.Form): choice_address = forms.ModelChoiceField(queryset=Address.objects.none(), empty_label='') #views def packing_create(request): if request.method == 'POST': choice_address_form = ChoiceAddressForm(request.POST) choice_address = choice_address_form.fields['choice_address'] return render(request, 'shop/packingcreate.html', {'choice_address': choice_address}) address = Address.objects.filter(usr_adr=request.user).values('adr_no', 'custom_name').order_by('adr_no') address = [tuple(i.values()) for i in address] choice_address_form = ChoiceAddressForm() choice_address_form.fields['choice_address'].choices = address return render(request, 'shop/packingcreate.html', {'choice_address_form': choice_address_form}) This is what I get: <django.forms.models.ModelChoiceField object at 0x7f1f2e6e1460> Also is_valid and cleaned_date not working. -
How to pass "self" or Page.id to a custom admin Panel in the Wagtail CMS?
More generally speaking I want add a custom admin Panel to list some related content. To lookup this related content I need to pass the current instance of the model or at least its ID to this panel. How can I do that within these lists in which these admin panels are noted? Here is my specific example of an ArtistPage. In the editor I would like to add a panel to list WorkPages that are related to this ArtistPage: from wagtail.models import Page class ArtistPage(Page): # ... content_panels = [ # ... ListWorksPanel(artist=self), # This doesn’t work ] The panel itself is defined like that, mostly copied from the HelpPanel: from wagtail.admin.panels import Panel class ListWorksPanel(Panel): def __init__(self, artist="", template="admin/list_works_panel.html", **kwargs,): super().__init__(**kwargs) self.artist = artist self.template = template def clone_kwargs(self): kwargs = super().clone_kwargs() del kwargs["help_text"] kwargs.update( artist=self.artist, template=self.template, ) return kwargs class BoundPanel(Panel.BoundPanel): def __init__(self, panel, instance, request, form): super().__init__(panel, instance, request, form) self.template_name = self.panel.template self.artist = self.panel.artist This is more a general Python question, I think. I know how to pass "self" in functions. But how does that work here with this class as element of a list? I reckon that the __init__() method of the ArtistPage … -
Database content doesn show on production
I am struggling to understand what is missing on my application, sorry it seems a little silly question, I am sure is something quite simple that I am not actually looking to. I have created an API, using REST-FRAMEWORK on my machine and upload it to production, but the content of my database didn't come through. If you see in the picture the product list appers as empty But on my machine it actually has some information -
Ajax post request fails without showing an error, it just prints an empty error
I am trying to create An ajax request in the Django template .. it fails and returns an empty error so am not even able to debug it. Here is what I tried to do : HTML template ..... kml_layer.addListener('click', (kmlEvent) => { setMapOnAll(null); var clickedPoint = kmlEvent.latLng; newPoint.postMessage(clickedPoint.lat() + "," + clickedPoint.lng()); $.ajax({ type: "POST", url: "https://www.{{domain}}{% url 'get_km_from_source' %}", data: { csrfmiddlewaretoken: '{% csrf_token %}', layer_id: "{{ single_layer.id }}", the_element_string_id: kmlEvent.featureData.id, clicked_lat: kmlEvent.latLng.lat, clicked_lng: kmlEvent.latLng.lng }, /* Passing the text data */ success: function (response) { alert("Thankyou for reaching us out " + response); }, error: function (jqXHR, textStatus, errorThrown) { // alert the error if any error occured console.log(textStatus, errorThrown); } }); }); ..... And here is the URL that is being called. path('get_km_from_source/', get_km_from_source, name='get_km_from_source'), Using print debugging in the python function that is being called.. it never reaches this point. but it always fails before starting the request .. and it returns an empty based on the lin console.log(textStatus, errorThrown); .. here is how the error looks like : console output: "error " -
Django Rest Framework: while using generics APIview I'm not able to set permissions
I want the admin user to access every user detail and the non-admin user to get access to its own detail only but Instead of this non-admin user is showing the full list of every user same as the admin user while implementing this. As I've shared my views.py, permissions.py, and models.py for the same. I'm not sure whether the problem is in permisions.py or models.py as I'm new to Django. I'm using Postman for API testing and this is working fine for the admin user but for an individual user, it's not working. views.py class UserListCreateAPIView(generics.ListCreateAPIView): permission_classes = [IsStaffOrTargetUser] queryset = User.objects.all() serializer_class = UserSerializer class UserRetrtieveUpdateDestroyAPIView(generics.RetrieveUpdateDestroyAPIView): permission_classes = [IsStaffOrTargetUser] queryset = User.objects.all() serializer_class = UserSerializer permissions.py class IsStaffOrTargetUser(BasePermission): def has_permission(self, request, view): # allow user to list all users if logged in user is staff return request.user or request.user.is_staff def has_object_permission(self, request, view, obj): # allow logged in user to view own details, allows staff to view all records return request.user.is_staff or obj == request.user models.py class User(AbstractBaseUser): email = models.EmailField(verbose_name='Email',max_length=255,unique=True) name = models.CharField(max_length=200) contact_number= models.IntegerField() gender = models.IntegerField(choices=GENDER_CHOICES) address= models.CharField(max_length=100) state=models.CharField(max_length=100) city=models.CharField(max_length=100) country=models.CharField(max_length=100) pincode= models.IntegerField() dob = models.DateField(null= True) # is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_admin … -
Adding a range price filter
I'm trying to add a range price filter for a list of products with django and I'm having some trouble with how to proceed Here's the code for the template : ( produits.html ) <div class="mb-4"> <h3 class="mb-3 h6 text-uppercase text-black d-block">Filter by Price</h3> <div id="slider-range" class="border-primary"></div> <input type="text" name="PRICE" id="amount" class="form-control border-0 pl-0 bg-white" disabled="" /> Here's the model code for products : class Product(models.Model): nom = models.CharField(max_length=200,null= True, blank=True) prix = models.DecimalField(max_digits=7,decimal_places=2,null=True,blank=True) description = models.TextField(null=True,blank=True) nbr_stock = models.IntegerField(null=True,blank=True,default=0) image= models.ImageField(null=True,blank=True) taille= models.CharField(max_length=5,null=True,blank=True) categorie=models.CharField(max_length=200,null= True, blank=True) @property def imageURL(self): try : url = self.image.url except : url = '' return url def __str__(self): return self.nom My question is how can I "retrieve" the value from the range slider and then show the products according to the price? thank you in advance -
Field 'id' expected a number but got 'category.id'
I'm trying to make a category in the DB, but when I try to access the category with the model that entered. it showing me this Error: ValueError at /category/Django/ Django is category I entered with the model I made using a ForeignKey. I tried a different method for the category but it didn't work either. so I think the problem is in the db.sqlite3 file or in the migrations files. I can't delete the sql3 db file, I have data that I can't easy replaces. I don't think the problem is in the settings.py, I tried to change it before and got the same outcome. the full Error: \Python39\site-packages\django\db\models\lookups.py", line 25, in __init__ self.rhs = self.get_prep_lookup() File "C:\Users\HPi5\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\django\db\models\fields\related_lookups.py", line 117, in get_prep_lookup self.rhs = target_field.get_prep_value(self.rhs) File "C:\Users\HPi5\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\django\db\models\fields\__init__.py", line 1825, in get_prep_value raise e.__class__( ValueError: Field 'id' expected a number but got 'published'. here is the views.py for the category class CatListView(ListView): template_name = "Blog/category.html" context_object_name = 'catlist' def get_queryset(self): content = { 'cat': self.kwargs['category'], 'posts': Post.objects.filter(category__name=self.kwargs['category']).filter(category='published') } return content def category_list(request): category_list = Category.objects.exclude(name='default') context = { "category_list": category_list, } the urls.py from django.urls import path from . import views urlpatterns = [ path("category/<category>/", views.CatListView.as_view(), name="category"), ] and for … -
saving the data with user logout signal
I am using the logout signal for saving the logout time of user as follows class StaffLogData(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='staff_log_data', on_delete=models.CASCADE) log_in_time = models.DateTimeField(verbose_name='Log In Time', blank=True, null=True) log_out_time = models.DateTimeField(verbose_name='Log Out Time', blank=True, null=True) active_time = models.DateTimeField(verbose_name='Active Time', blank=True, null=True) active_log_time = models.TimeField(verbose_name='Active Log Time', blank=True, null=True) timestamp = models.DateTimeField(verbose_name='Timestamp', default=timezone.now) def duration(self): if self.log_out_time: return self.log_out_time.replace(microsecond=0) - self.log_in_time.replace(microsecond=0) else: return None def staff_log_in_data(sender, user, **kwargs): if user: StaffLogData.objects.create(user=user, log_in_time=timezone.now()) user_logged_in.connect(staff_log_in_data) def staff_log_out_data(sender, user, **kwargs): last_log_data = StaffLogData.objects.filter(user=user).last() if last_log_data: last_log_data.log_out_time = timezone.now() print('last logout', last_log_data.log_out_time) last_log_data.save() user_logged_out.connect(staff_log_out_data) It prints the output but not saving it, any help is appreciated. -
django debug toolbar problem with the failed to load module script
I have been installing djang-debug-toolbar, but it is not showing but in the chrome developer console, it shows following error. Failed to load module script: Expected a JavaScript module script but the server responded with a MIME type of "text/plain". Strict MIME type checking is enforced for module scripts per HTML spec. I have installed pip django debug toolbar using pip in pycharm I have changed the setting in the settings.py Also I have changed the urls.py in the project folder I went in the registry of the windows to check on the HKEY_CLASSES_ROOT\.js\Content Type from text/plain to but there is no Content Type folder under the folder .js Any hints? -
How can I create a basic Soap server with spyne in django
I want to create a server which uses Django and make and take response as SOAP, so I try to use spyne for this reason but I can't run the given code class HelloWorldService(ServiceBase): @rpc(Unicode, Integer, _returns=Iterable(Unicode)) def say_hello(ctx, name, times): """Docstrings for service methods appear as documentation in the wsdl. <b>What fun!</b> @param name the name to say hello to @param times the number of times to say hello @return the completed array """ for i in range(times): yield u'Hello, %s' % name application = Application([HelloWorldService], 'spyne.examples.hello.soap', in_protocol=Soap11(validator='lxml'), out_protocol=Soap11()) wsgi_application = WsgiApplication(application) if __name__ == '__main__': import logging from wsgiref.simple_server import make_server logging.basicConfig(level=logging.DEBUG) logging.getLogger('spyne.protocol.xml').setLevel(logging.DEBUG) logging.info("listening to http://127.0.0.1:8000") logging.info("wsdl is at: http://localhost:8000/?wsdl") server = make_server('127.0.0.1', 8000, wsgi_application) server.serve_forever() -
pass a value from bootstrap to django modal
Here i am trying to pass the value outside for loop modal using ajax here is my template.html {% for compliance in compliance %} {% complience_category compliance request.user as compliances %} {% for qualification in compliances %} ..... ..... <td> <button data-id="{{ qualification.id }}" type="button" class="btn btn-warning margin-bottom edit-qualification"> edit </button> </td> .... ..... {% endfor %} {% csrf_token %} <div class="modal hid fade" id="modal-default"> <form class="form-horizontal" method="POST" enctype="multipart/form-data" action=" {% url 'update_qualifications' qualification.id %}"> {% csrf_token %} <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button> <h3>Update Compliance</h3> </div> <div class="modal-body"> <div class="control-group"> <label class="control-label" for="inputdate_{{qualification.id}}">Expiry Date</label> <div class="controls"> <input type="date" id="inputdate_{{qualification.id}}" name="expiry_date" value="{{qualification.expiry_date|date:'Y-m-d'}}"> </div> </div> </div> <div class="modal-footer"> <button class="btn" data-dismiss="modal">Close</button> <button class="btn btn-primary" type="submit">Save</button> </div> </form> </div> {% endfor %} This is my AJAX $(document).on('click','.edit-qualification',function(){ var id = $(this).data('id'); $.ajax({ url:'', type:'POST', data:{ 'id':id, 'csrfmiddlewaretoken': $('input[name=csrfmiddlewaretoken]').val(), }, success:function(data){ $('#edit_modal .modal-dialog').html($('#edit_modal .modal-dialog',data)); $('#edit_modal').modal('show'); }, error:function(){ console.log('error') }, }); }); </script> Here my modal is outside of for loop Here my problem is when i click the edit button my modal popup is not working (it means when clicking the edit button nothing works for me ) -
how to transfer list from django view to django forms?
I have AppointmentCreateView, which performs the function of booking, and I have hours(), which returns a list of hours the worker has received from his individual schedule, i need to return this list to forms class AppointmentCreateView(CreateView): model = Appointment form_class = AppointmentForm template_name = 'appointment/booking.html' success_url = reverse_lazy('workers') def hours(self, pk): worker = User.objects.get(id=pk) schedule = Schedule.objects.get(id=worker.id) HOUR_CHOICES = [] from_hour = schedule.from_hour to_hour = schedule.to_hour while from_hour <= to_hour: HOUR_CHOICES.append(from_hour) from_hour = time(from_hour.hour + 1, from_hour.minute) return HOUR_CHOICES def form_valid(self, form): form.instance.worker = User.objects.get(pk=self.kwargs['pk']) return super(AppointmentCreateView, self).form_valid(form) i need the user to select the desired time from the list but i don't know how to transfer transfer this list here class AppointmentForm(forms.ModelForm): time = forms.TimeField(widget=forms.Select(choices=HOUR_CHOICES)) class Meta: model = Appointment fields = ('location', 'time') def __init__(self, *args, **kwargs): super(AppointmentForm, self).__init__(*args, **kwargs) self.fields['location'].empty_label = 'Select' -
Wie kann ich meiner Web Anwendung sagen, dass sie auf gespeicherte Datei zugreifen und diese ausgeben soll? [closed]
Ich stehe vor folgendem Problem und hoffe ihr könnt mir weiterhelfen: Für meine Arbeit muss ich Daten aus einer Website auf meine eigenentwickelten Webanwendung exportieren und anhand dieser Daten ein Gantt Diagramm zeichnen. Für das Exportieren gibt es schon eine Funktion auf der Website. Die Daten können als html Datei oder XML Datei exportiert werden. Doch wie sag ich meiner Web Anwendung, dass diese auf die gespeicherten Daten zugreifen und auslesen soll? Auf was muss ich hierbei achten? Ist JS dafür eine geeignete Sprache oder empfehlt ihr mir mit einer anderen Programmiersprache zu arbeiten wie z.B Python? Oder sogar vllt. dass Framework Django nutzen? Ich bin für jeden Tipp dankbar! Lg -
Setting callback domain in django allauth
I have fargate containers , the one has django and the other has nginx. And django use allauth for login. https://django-allauth.readthedocs.io/en/latest/installation.html In this case, when accessing OAuth allauth makes the callback url such as, 127.0.0.1/callback/something However, Of course it doesn't work. Callback url should be example.com/callback/something. How can I set the callback domain? -
AttributeError at / 'AnonymousUser' object has no attribute '_meta'
I was trying to use signin page but this error shows up. Image of error while running in Mozilla web browser localhost I had tried the solution using this link and ended up mixing auth model to the chatbot model. this is the link of my whole views.py file of chatbot app. https://pastebin.com/2E7mgyuR def get(self, request): return render(request, 'chatbot/signin.html') def post(self, request): context = { 'data': request.POST, 'has_error': False } username = request.POST.get('username') password = request.POST.get('pass1') if username == '': messages.add_message(request, messages.ERROR, 'Username is required') context['has_error'] = True if password == '': messages.add_message(request, messages.ERROR, 'Password is required') context['has_error'] = True user = authenticate(request, username=username, password=password) # if not user and not context['has_error']: # messages.add_message(request, messages.ERROR, 'Invalid login') # context['has_error'] = True if context['has_error']: return render(request, 'chatbot/signin.html', status=401, context=context) login(request, user) return redirect('chatpage') and This is my models.py of chatbot from django.db import models from django.contrib.auth import get_user_model # Create your models here. Mod = get_user_model() class User(Mod): is_email_verified = models.BooleanField(default=False) def __str__(self): return self.email and this is what it is showing in terminal Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). June 27, 2022 - 09:27:56 Django version 4.0.5, using settings 'Eva_Chatbot.settings' … -
category and paginator connections django html
I have a problem when I select one category and in this category when I want to go to another page it sends me just to a different page and I need it to send me to for example category=pk {{ page=2 }} or like this but now it sends to {{ page=2}} enter image description here -
How to Get queryset not dict django aggregate
i'm using this queryset for my requirements invoices = Invoice.objects.aggregate(total_amount=Sum('order__order_items__amount'),number_of_invoices=Count('pk', distinct=True)) which returns dict---> {'total_amount': Decimal('17700.00'), 'number_of_invoices': 2} but I want queryset how can i do that.. Thanks for any help -
Django differentiate between fetch requests
I have 2 different fetch request coming to the same view in Django. How do I differentiate between them? The first fetch request is loading new content and the second is used for a different purpose altogether but they both come from the same url and to the same view. I have the following code in my view: if request.headers.get('X-Requested-With') == 'XMLHttpRequest': return async_response(request, post) And what I need is something similar to: if request.headers.get('X-Requested-With') == 'XMLHttpRequest': if fetch function 1: django function 1 if fetch function 2: django function 2 Do i need to add some custom headers? -
No such file or directory when python manage.py runserver
I have function to upload the document in folder, after it i want to execute methods to transform this file. I wrote another functions where i am calling this methods, but after pyrhon manage.py runserver i receive No such file or directory: 'beeline/media/docs/assignment.xlsx' But if i execute python file with methods everyrhing is working fine class UploadView(generic.TemplateView): def get(self, request): form = ExcelForm return render(request, 'index.html', {'form': form}) def injection(self): post_team() post_db_service() post_database() post_db_schema() post_db_table() return "Everything is created" def post(self, request): if request.method == 'POST': form = ExcelForm(request.POST, request.FILES) if form.is_valid(): upload = request.FILES['file'] fss = FileSystemStorage('media/docs') fss.save(upload.name, upload) self.injection() return render(request, 'ty.html') return render(request, 'index.html') -
Django calculated fields on custom queryset
This seems like a basic question but for the life of me I cannot seem to figure this out. I have a Recipe model that uses a custom RecipeQueryset as a manager. Now I've been doing a lot of reading on where to put business logic of the application some people suggest a "services" layer others say to put it in a custom queryset which is what I am trying to accomplish now. None of them really give an example of doing calculations though only CRUD functionality. At the moment I have a property of total_cost defined on the Recipe model but according to a lot of articles/discussions I should be moving this "business logic" to elsewhere to the custom queryset for example? Is there a way to do the calculation in a custom queryset method for a queryset of Recipe objects and calculate that total_cost for each Recipe and return that queryset with the extra total_cost field? How would I then add this so it can be used in my serializer? Model class RecipeQueryset(models.QuerySet): """Custom queryset for Recipe Model""" def all_for_user(self, user): return self.filter(user=user) # this is where I think I should put it? def total_cost(self, recipe): return # …