Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: is it safe to include secret data in the context dict used to render a template in a view?
Is data that is included in the context dict passed to the render function but is not called in the template accessible to the user or their browser? Is it ok to just pass a QuerySet to the template even when some of the fields of the models must be kept secret from the user? I would appreciate a reference to the official Django documentation or any other reliable sources confirming this is safe, if anyone finds one. Code Example models.py: class Riddle(models.Model): question = models.TextField() # show to user solution = models.TextField() # very secret views.py def riddles_list(request): data = Riddle.objects.all() return render(request, 'riddles.html', {'riddles': data}) riddles.html <ul> {% for riddle in riddles %} <li>{{ riddle.question }}</li> {% endfor %} </ul> Is this safe, or does the user has a way of accessing the solution of the riddle? Is the solution now available anywhere except the Django server? A possible approach would be to change the query to: data = Riddle.objects.values('question') Is this considered better code than just fetching the whole object? (for security, efficiency, readability, maintainability etc.) In the real code there are more calls like filter and annotate in the query, and the models have more fields. -
How to implement pyodbc with Django and storing the password for databases?
I developed a Django application, where a user can change the database dynamically through the UI. I tried using Django's integrated database configurations in settings.py but I had to do some workarounds but still faced some weird errors. Therefore I decided to use pyodbc with a connection string to connect to the database in my views.py. The User inputs his database credentials (table, user, password, host, port), which then get saved on a database. Every time a user needs some data following method gets invoked: con = DatabaseConnection.objects.all().first() conn_str = '{}/{}@{}:{}/{}'.format(con.user, con.password, con.host, con.port, con.name) Everything works fine, but how exactly do I store the password(or the rest of the data) correctly? I thought about encrypting and decrypting the password in my views.py but that wouldn't make sense, would it? -
Javascript: How can I display the total price for the values that are inputted into it?
I am creating a project that will serve as a grocery store. The customer will click on the checkboxes and then click a submit button, prompting an alert to show the values that were clicked and the total price. home.html <form action="{% url 'js' %}" method="POST" id="menuForm"> {% for post in posts %} {% if post.quantity > 0 %} <article class="media content-section"> <div class="media-body"> <div class="article-metadata"> <a class="mr-2">{{ post.category }}</a> </div> <h2><a class="article-title" >{{ post.title }}</a></h2> <p class="article-content"> Price: ${{ post.Price }}</p> <p class="article-content"> Sale: ${{ post.Sale }}</p> <input type="checkbox" id="product_{{ post.id }}" value="{{ post.title }}" form="menuForm" name="products" > Inventory count: {{ post.quantity }} </input> </div> </article> {% else %} {% endif %} {% endfor %} <button id="btn" type="submit" form="menuForm">Confirm Purchase</button> </form> <script src="{% static "JS/javascript.js" %}" type="text/javascript"></script> javascript.js function getSelectedCheckboxValues(name) { const checkboxes = document.querySelectorAll(`input[name="${name}"]:checked`); let values = []; checkboxes.forEach((checkbox) => { values.push(checkbox.value); }); return [values]; console.log(getSelectedCheckboxValues('products')) } console.log(values) var price = 0; var tPrice = 0; for (var i = 0;i<values.length;i++){ if (values[i] == 'Milk'){ var MPrice = 3.99 tPrice = price+MPrice; } if (values[i] == 'Cheese'){ var CPrice = 4.50 tPrice = price + CPrice; } if (values[i] == 'Yogurt'){ var YPrice = 1.99 tPrice = price … -
Django admin - combine two models
I have setup a small support application at my website, but to integrate it and get the full potential out of it I as an administrator should have the opportunity to also reply onto support tickets the user has opened. Otherwise a support application is pretty useless I guess ... So my question is how can I combine these two models at django admin to reply onto a support ticket? I need to get the replies underneath the actuall support ticket plus a form to add a reply at django admin... Can smb. Help: class SupportTicketReplies(models.Model): content_type = models.ForeignKey(ContentType, limit_choices_to=referential_models, on_delete=models.CASCADE) object_id = models.CharField(max_length=36) content_object = GenericForeignKey('content_type', 'object_id') id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='support_ticket_reply_author', verbose_name='Author', blank=True) content = models.TextField(verbose_name="Content", max_length=3000) creation_date = models.DateTimeField(auto_now_add=True, blank=False) class SupportTickets(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False, unique=True) ticket_id = models.IntegerField(default=ticket_id_generator, unique=True, blank=False, null=False, editable=False) requester = models.ForeignKey(User, on_delete=models.CASCADE, null=False, blank=False) category = models.IntegerField(choices=TICKET_CATEGORY, verbose_name='Ticket Category') subject = models.CharField(max_length=40) problem_description = models.TextField(max_length=3000) status = models.IntegerField(choices=STATUS_OF_TICKET, verbose_name='Ticket Status', default=0) reply_relation = GenericRelation(SupportTicketReplies, related_query_name='reply_relation') creation_date = models.DateTimeField(auto_now_add=True, null=True) Thanks in advance -
ValueError: cannot assign "value": "field" must be a "object" instance
i was building a django app for dbms project and i had to write the code to update a row using mysql (i have to use cursor), so i used the below syntax but i am getting a value error cursor.execute("update profiles_author a,address_country c set country_id=%s, about=%s, photo=%s where a.country_id=c.id",[country,about,photo]) Error is as follows... Cannot assign "1": "Author.country" must be a "Country" instance. i tried to switch off and on the foreign key contraint but i believe thats not the problem and it didnt work anyway cursor = connection.cursor() cursor.execute("set foreign key constraint=0;") cursor.execute("update profiles_author a,address_country c set country_id=%s, about=%s, photo=%s where a.country_id=c.id",[country,about,photo]) cursor.execute("set foreign key constraint=1;") Is there anyway to do this by using cursor or something where i can do it using mysql code or saving it using the model object is the only option? pardon my question format if i did some mistakes, Thank you -
Margin Right Auto in bootstrap is not working in Django
I am a bootstrap and Django beginner and I want to know why my margin-right is not working in Django. I was following a YouTube tutorial. Here is that link: https://www.youtube.com/watch?v=qDwdMDQ8oX4 Here is the code I have used; {% load static %} <!DOCTYPE html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- Bootstrap CSS --> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous"> <link rel="stylesheet" href="{% static 'blog/main.css' %}"> {% if title %} <title>Django Blog - {{ title }}</title> {% else %} <title>Django Blog</title> {% endif %} </head> <body> <header class="site-header"> <nav class="navbar navbar-expand-md navbar-dark bg-steel fixed-top d-flex"> <div class="container"> <a class="navbar-brand mr-4" href="{% url 'blog-home' %}">Django Blog</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarToggle" aria-controls="navbarToggle" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarToggle"> <div class="navbar-nav mr-auto"> <a class="nav-item nav-link" href="{% url 'blog-home' %}">Home</a> <a class="nav-item nav-link" href="{% url 'blog-about' %}">About</a> </div> <!-- Navbar Right Side --> <div class="navbar-nav"> <a class="nav-item nav-link" href="#">Login</a> <a class="nav-item nav-link" href="#">Register</a> </div> </div> </div> </nav> </header> <main role="main" class="container"> <div class="row"> <div class="col-md-8"> {% block content %}{% endblock %} </div> <div class="col-md-4"> <div class="content-section"> <h3>Our Sidebar</h3> <p class='text-muted'>You can put any information here you'd like. <ul class="list-group"> <li class="list-group-item list-group-item-light">Latest … -
Google Analytics with local Django Application
I am trying to add Google Analytics (GA) to my Django application and I am a beginner to Django. My application is not deployed to the internet, i.e. I access it through http://127.0.0.1:8000/. According to this tutorial https://pypi.org/project/django-google-analytics-app/, I need a tracking code which I cannot get because GA does not accept http://127.0.0.1:8000/ as a website URL. How can I add GA to my local Django app and get the related analytics on GA. Thanks a lot for your help! -
Updating field value in views
I've a model with name Task with the following attributes: class Task(models.Model): jobid = models.CharField(max_length = 10, null = True) worker = models.ForeignKey(Worker, null = True, on_delete=models.SET_NULL) machine = models.ForeignKey(Machine, null = True, on_delete=models.SET_NULL) production_count = models.IntegerField(default = 0) qc_passed = models.IntegerField(default = 0) target_count = models.IntegerField(null = True) duration = models.IntegerField(default = 0) def __str__(self): return (self.jobid) I want to update the duration field with the time difference. The time difference is the time duration for which the form shows up on the screen. def HMImachine1(request, pk_test): machinevalue = 9 worker = Worker.objects.get(empid = pk_test) totaltask = worker.task_set.all() task = totaltask.filter(production_count = 0, machine = machinevalue) if not task: return redirect('HMI_notauth') start_time = datetime.datetime.now() form = ProductionForm(instance = task[0]) content = {'form': form, 'task': task[0], 'start_time': start_time} if task: if (request.method == 'POST'): form = ProductionForm(request.POST, instance = task[0]) if form.is_valid(): form.save() end_time = datetime.datetime.now() diff = end_time - start_time worktime = divmod(diff.total_seconds(), 60) sec = int(worktime[1]) total_time = sec + task[0].duration task[0].duration = total_time task[0].save(update_fields = ['duration']) return redirect('login') return render(request, 'MachAutomation/HMI_production.html', content) The ProductionForm updates the production_count and qc_passed. I tried the following in the shell: >>> task <QuerySet [<Task: JB1010>, <Task: JB1050>]> >>> start_time = datetime.datetime.now() … -
How do I save data in my Django DB when I am taking Inputs from Modal table Form?
I am trying to make a Profile settings page where when I click on Edit (name or description or others) then it will pop up a modal form and then I want user to edit their name and then that name should be saved in the Django DB and display that changed value in the profile settings page. This is what I have tried, but I'm still not able to save data in Django DB. This is my views.py: def seller_profile_settings(request): data = {} if request.user.is_authenticated: try: details = detail.objects.filter(email=request.user).first() except: return redirect('/userdetail/logout') if details.vendor: data = { "user": details } if request.method == "POST": if request.POST.get('submit'): if form.is_valid(): description = request.POST.get('description') name = request.POST.get('name') contact = int(request.POST.get('email')) mission = request.POST.get('mission') address = request.POST.get('address') t_and_c = request.POST.get('t_and_c') details.description = description details.name = name details.contact = contact details.mission = mission details.t_and_c = t_and_c details.address = address a = customer_address(email=request.user.email, address=addresss, permanent=True) a.save() details.info_update = True details.save() return redirect('userdetail/seller_profile_settings.html') return render(request,'userdetail/seller_profile_settings.html', {"details":details}) and below is my HTML file where I am taking user inputs: <form method="POST" enctype="multipart/form-data" action="{% url 'seller_profile_settings' %}"> <input type="hidden" name="csrfmiddlewaretoken" value="kcu26KY77seywzOvJAc18zISS2zwQO1gCLsDwwHU7dFzHcs4FQcPMg6TQr0MbisQ"> {% csrf_token %} <table class="table table-hover"> <tbody> <tr> <th>Name</th> <td class="font-weight-normal">{{ details.name }}</td> <td data-toggle="modal" data-target="#exampleModalLong"><a href="#"><i … -
Manage requests and optimize server utilization in django
Actually, I need some suggestions for a server-based architecture. So let me explain the whole architecture first. I have two Django servers that are used for multiple operations, but the system which I am talking about is, server(A) calls the server(B) with 4 big JSON files nearly ~10MB, so every request has these 4 files, size may vary. And the sever(B) processes the data which consists of more CPU intensive tasks, multiple IO tasks, DB operations, etc. Now the problem I am facing is: I don't have a proper system to receive all the requests in an optimized manner so that I can reduce the round trip time for the requests. And I need to process all these requests on the server(B) parallelly and utilize all the resources of my server(B). Right now it's not utilizing the resources properly, though I have used multiprocessing. Any suggestion will be helpful. Thank You -
in-place-edit in Django/Python not working
i am looking to use inplaceedit in my django app. I did the installation and it went well : pip install django-inplaceedit==0.77 On top of the base.html i have <!DOCTYPE html> <html lang="en"> <!-- Static assets - Used to load the Favicon --> {% load static %} {% load inplace_edit %} {% inplace_toolbar %} .... I get the following error : Exception Value: Invalid template library specified. ImportError raised when trying to load 'inplaceeditform.templatetags.inplace_edit': No module named 'django.core.urlresolvers' if I keep following the turtorial and add the following to the urls.py, I get : ... File "C:\Users\franky.doul\AppData\Local\Programs\Python\Pyth -packages\inplaceeditform\urls.py", line 20, in <module> from django.conf.urls.defaults import patterns, url ModuleNotFoundError: No module named 'django.conf.urls.defaults' Anything that I am missing or doing wrong please? -
Django - get latest item from get_object_or_404
I want to return an object from my get_object_or_404 method but my query returns multiple objects. Is there a way to get last or first item? This is how I do it: return get_object_or_404(BatchLog, batch_id=self.kwargs["pk"]) I know it is not possible but this is kind of what I need: return get_object_or_404(BatchLog, batch_id=self.kwargs["pk"].last()) -
How do I customize how Django handles successful password resets?
I have sub-classed Django's password reset views and everything works fine, however, when the reset link is invalid it displays a template. I would like it to be a message. So, for example, when the link is valid, it displays the password reset form and then a success message with a redirect (this is how it functions at the moment). When the link is invalid, though, it should display an error message with a different redirect. How would I be able to add that error message and redirect? urls.py from .views import * urlpatterns = [ path('password-reset/', PasswordResetView.as_view(), name='password-reset'), # password reset view re_path(r'^password-reset/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$', PasswordResetConfirmView.as_view(), name='password-reset-confirm'), # password reset confirm view ] views.py class PasswordResetConfirmView(PasswordResetConfirmView): template_name = 'accounts/password-reset-confirm.html' post_reset_login = True post_reset_login_backend = 'django.contrib.auth.backends.ModelBackend' def get_context_data(self, **kwargs): context = super(PasswordResetConfirmView, self).get_context_data(**kwargs) context['title'] = 'Password reset' return context def form_valid(self, form): messages.success(self.request, 'Your password has been successfully reset.') return super().form_valid(form) def get_success_url(self): student = self.request.user return reverse_lazy( 'home') password-reset-confirm.html {% extends 'base.html' %} {% block content %} {% if validlink %} <div class="floating-labels auth"> <div class="container"> <form method="POST" autocomplete="off" class="shadow" novalidate> {% csrf_token %} <div class="mb-4"> <h4 class="mb-3 heading">Reset password</h4> <hr> </div> {% include 'accounts/auth.html' %} <button class="btn btn-lg btn-one btn-block … -
Set Pagination for APIview in Djang
I`ve a view extended by APIview how can I set Pagination for it? my view: class MarketView(APIView): def get(self, request): queryset = Market.objects.filter(is_showing=True) market_serializer = MarketSerializer(queryset, many=True) return Response(market_serializer.data, status=status.HTTP_200_OK) -
How to get single object with Django ORM with lazy evaluation?
I have a wrapper class which I want that some of its fields evaluate lazy, so it hit database when that field called. I use queryset for fields that contain a list. But I don't know how can I achieve this for fields that have single object. Because if I use objects.get() or .first() at the end of queryset it will be evaluated immediately. -
NSQ: how can i check content of deferred or requeued messages in nsq
NSQ deferred or requeued messages How NSQ manage deferred or requeued message and how can I check the actual content of this message is there any way check either with admin UI or with console -
How to modify multiple objects with same values in certain fields?
I have this model: class Connection(models.Model): CONNECTION_CHOICES = [ ('REST-API', 'REST-API'), ('SSH', 'SSH'), ('SFTP', 'SFTP'), ('SOAP-API', 'SOAP-API'), ] endpoint = models.CharField(max_length=240, blank=True, null=True) port = models.IntegerField(blank=True, null=True) connection_type = models.CharField(max_length=240, choices=CONNECTION_CHOICES) source_tool = models.ForeignKey(Tool, on_delete=models.CASCADE, related_name='source-tool+') target_tool = models.ForeignKey(Tool, on_delete=models.CASCADE, related_name='target-tool+') def __str__(self): return self.source_tool.name + " to " + self.target_tool.name def get_absolute_url(self): return reverse('tools:connection-detail', kwargs={'pk': self.pk}) In a view, I am trying to combine objects, where source_tool and target_tool are the same, but the connection_type differs. Currently, I have this view: def api_map_view(request): json = {} nodes = [] links = [] connections = Connection.objects.all() for connection in connections: if {'name': connection.source_tool.name, 'id': connection.source_tool.id} not in nodes: nodes.append({'name': connection.source_tool.name, 'id': connection.source_tool.id}) if {'name': connection.target_tool.name, 'id': connection.target_tool.id} not in nodes: nodes.append({'name': connection.target_tool.name, 'id': connection.target_tool.id}) if {'source': connection.source_tool.id, 'target': connection.target_tool.id} in links: links.replace({'source': connection.source_tool.id, 'target': connection.target_tool.id, 'type': links['type'] + '/' + connection_type}) else: links.append({'source': connection.source_tool.id, 'target': connection.target_tool.id, 'type': connection.connection_type}) json['nodes'] = nodes json['links'] = links print(json) return JsonResponse(data=json) This returns me e.g. { 'nodes': [ {'name': 'Ansible', 'id': 1 }, {'name': 'Terraform', 'id': 2}, {'name': 'Foreman', 'id': 3} ], 'links': [ {'source': 1, 'target': 2, 'type': 'SSH'}, {'source': 2, 'target': 3, 'type': 'REST-API'} {'source': 1, 'target': 2, 'type': 'REST-API'} ] } … -
Is there a way to update an object's specific field using an api in django?
Apologies if my question seems a bit basic, or too complicated, but I'm still learning django. What I'd like to do is somehow update a model object's field, preferably using an api call. I'll try to demonstrate. I have several different model objects that look like this. class Quarterback(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE, null=True) name = models.CharField(max_length=20, blank=True) score = models.IntegerField(blank=True, null=True) I'd like to know if it's possible to populate the "score" field with data pulled via an api url. Of course, I can populate the score manually, or with an event listener like onclick, but because scores are dynamic and change every week, I'd really like to find a way to have the score field populate via the api because their data updates each week. At the moment, I'm displaying individual scores in my html by comparing the player's name in the model shown above with a list of names and scores stored in a variable that gets its info from the api. If I could somehow get the "score" field of this model to get its info from the url/api, I could just iterate through the object and display the score very easily. Even if this is … -
Mapbox Leaflet Marker Cluster in Django
I have used Mapbox for my Django project and I add a Cluster marker to the map, now I want to add more info to the popup for each marker like title form my django database any one have any idea haw i can add information to this code I used my code like this: L.mapbox.accessToken = mapkey; var map = L.mapbox.map('map') .setView([37.82, 22.215], 4) .addLayer(L.mapbox.styleLayer('mapbox://styles/mapbox/streets-v11')); var markers = new L.MarkerClusterGroup(); var addressPoints = [ {% for r in resto %} {{ r.terrain|tuple_to_array }}, {% endfor %} ]; //console.log(addressPoints); for (var i = 0; i < addressPoints.length; i++) { var a = addressPoints[i]; var info = a[2]; var marker = L.marker(new L.LatLng(a[1], a[0]), { icon: L.mapbox.marker.icon({'marker-symbol': 'restaurant', 'marker-color': 'f86767'}), title: info }); marker.bindPopup(info); markers.addLayer(marker); console.log(a) } map.addLayer(markers); -
Appending formdata is not working properly
Here I made an array from the images inside the ul tag and append in the formdata.console.log(files,'files') this data gives me the in this format ["data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEASABIAAD…7uefxPcmWZ5CBgF2LED05rw89q9TDRXsovvr95NS6la+2h//Z", "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEASABIAAD…/qGldWDfsQAKCg/5nKrPVXMM0eq6v/DigKQAKCg//AIr/AP/Z"] I appended this array to the input file with name image[]. Now when I try to get the images in the django view with request.GET.getlist('image[]') it only returns the last selected image. I think the appends is not working here. js var formdata = new FormData($('#form-id')[0]); var imgArray = []; $('#blah li .image #ig').each(function(){ imgArray.push($(this).attr('src')); }); var files = imgArray; for (var i = 0; i < files.length; i++) { formdata.append('image[]', files[i]); } console.log(files,'files') var csrftoken = document.getElementsByName('csrfmiddlewaretoken')[0].value; $.ajax({ url: ' {% url 'add' %}', type: 'POST', beforeSend: function(xhr, settings){ xhr.setRequestHeader("X-CSRFToken", csrftoken); }, data: formdata, cache: false, contentType: false, processData: false, enctype: 'multipart/form-data', success: function(data) { window.location.href = "/" } }); }); html <ul class="list list-inline list--image" id="blah"> <li class="selected"> <div class="image"> <img id="thumbnail" src="" width="83" height="100"/> </div></li> <div class="files--upload"><input class="d-none imgUpload" name="image[]" multiple type="file" id="imgInp" placeholder=""/><label class="upload-label" for="imgInp"> <div class="ic-add"></div> <div class="mt-2">Add Photo</div> -
Getting this error UNIQUE constraint failed: store_order.id
Whenever i try to update an order I get this error, Here is my model: CHOICES = ( ('Pending', 'Pending'), ('Processing', 'Processing'), ('Picked', 'Picked'), ('Shipped', 'Shipped'), ('Completed', 'Completed'), ) class Order(models.Model): product = models.ForeignKey( Product, on_delete=models.CASCADE, related_name="product") customer = models.ForeignKey(Customer, on_delete=models.CASCADE) quantity = models.IntegerField(default=1) fname = models.CharField(max_length=100, null=True) address = models.CharField(max_length=1000, null=True) phone = models.CharField(max_length=12, null=True) price = models.IntegerField() date = models.DateField(datetime.datetime.today, null=True) status = models.CharField( max_length=100, blank=True, null=True, default="Unpaid", unique=True) order_status = models.CharField( max_length=100, choices=CHOICES, null=True, blank=True, default="In Review") payment_method = models.ForeignKey( PaymentMethod, on_delete=models.CASCADE, blank=True, null=True) total = models.IntegerField(null=True) def save(self, *args, **kwargs): self.total = self.quantity * self.price return super().save(self, *args, **kwargs) I don't know why I am getting this kind of error can someone please explain why I am getting its error and how can I solve this issue. Here is my order view: class Checkout(View): def post(self, request): fname = request.POST.get('fname') phone = request.POST.get('phone') address = request.POST.get('address') cart = request.session.get('cart') customer = request.session.get('customer') products = Product.get_products_id(list(cart.keys())) for product in products: order = Order(customer=Customer(id=customer['id']), product=product, fname=fname, price=product.price, phone=phone, address=address, quantity=cart.get(str(product.id))) order.save() request.session['cart'] = {} return redirect('user_orders') -
check if object in ManyToMany field django rest framework
here is my models.py: class Post(models.Model): id = models.AutoField(primary_key=True) body = models.TextField(max_length=10000) date = models.DateTimeField(auto_now_add=True, blank=True) user = models.ForeignKey(User, on_delete=models.CASCADE) liked_by = models.ManyToManyField(User, blank=True, related_name='liked_by') class Meta: ordering = ['-date'] serializers.py: class PostSerializer(serializers.ModelSerializer): user = UserSerializers() total_likes = serializers.SerializerMethodField() total_comments = serializers.SerializerMethodField() class Meta: model = Post fields = ('id','body','date','user','total_likes','total_comments') def get_total_likes(self, instance): return instance.liked_by.count() def get_total_comments(self, instance): return instance.comment_set.count() Q1: how do i check if a user exists in ManyToManyField of a single post? Q2: shouldn't i use ManyToManyField in drf? then which would be better? -
Django - Retrieve all FK as objects
Can I retrieve from my watchlist all the books directly so I can work with them? Like, same as if I did Book.objects.all(). So instead of getting Wachlist querySet (with pk, user, book, date_added) I just get the books. class Watchlist(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) book = models.ForeignKey(Book, on_delete=models.CASCADE) date_added = models.DateTimeField(auto_now_add=True, null=True, blank=True) -
Is there any way to run many functions in a django view?
I have written a view function that converts CSV files as well as count the no of lines in CSV files. views.py def submit(request): csv_form = '' if request.method == 'POST': csv_form = CsvForm(request.POST, request.FILES) if csv_form.is_valid(): csv_file = TextIOWrapper(request.FILES['csv_file'].file, encoding='ascii', errors='replace') def file_conversion(input_file): #conversion work def total_lines(input_file): return sum(1 for line in input_file) file_conversion(csv_file) total = total_lines(csv_file) In this only ,file_conversion is working as while total is returning 0, If I switch the position of the functions, throws exception. Is there any way to run both functions? -
Django changing models field into views
I everyone, I have a problem with a django's view. My goal is to change the 'execute' field into 'True' if newOrder is buy and there is some other sell order with a inferior price. And reverse for sell newOrders. I want to change the 'execute' field for the newOrder and also for the other order (in pairs). That's my code: views.py def order(request): form = OrderForm() if request.method == 'POST': form = OrderForm(request.POST) if form.is_valid(): new_order = form.save() if new_order.buy is True: sellOrder = Order.objects.filter(sell=True, execute=False, price__lte=new_order.price).first().update(execute=True) new_order.execute = True sellOrder.save() else: buyOrder = Order.objects.filter(buy=True, execute=False,price__gte=new_order.price).first().update(execute=True) new_order.execute = True buyOrder.save() new_order.profile = request.user new_order.save() return redirect('home') else: form = OrderForm() contex = {'form': form} return render(request, 'app/new_order.html', contex) models.py class Profile(models.Model): _id = ObjectIdField() user = models.ForeignKey(User, on_delete=models.CASCADE) wallet = models.FloatField() class Order(models.Model): _id = ObjectIdField() profile = models.ForeignKey(User, on_delete=models.CASCADE) datetime = models.DateTimeField(auto_now_add=True) buy = models.BooleanField(blank=True) sell = models.BooleanField(blank=True) price = models.FloatField() quantity = models.FloatField() execute = models.BooleanField(blank=True) But something goes wrong. This is the error: AttributeError at /new_order/ 'NoneType' object has no attribute 'update'