Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Rest Framework - Search by query within a particular category of books
in my Django Rest Framework project, I have the following simple model: class Book(models.Model): book_title = models.CharField(max_length=100, blank=False) book_category = models.CharField(max_length=50, blank=False) Now, the user should be able to search for a title within a certain category. Therefore, I use the built-in SearchFilter provided by Django Rest Framework: class SearchBooks(generics.ListAPIView): serializer_class = BookSerializer filter_backends = [filters.SearchFilter] search_fields = ['book_title'] def get_queryset(self): return Book.objects.filter(book_category=self.request.data.get('category')) So, what I want is that the user should type the book title as search query but Django should only search within a certain category. What I do in PostMan: I pass the book title as search query and put the category into the Body section as form-data. For example, let's say I have two Book instances: Book(book_title="My Happy Days", book_category="Horror") Book(book_title="My Happy Days", book_category="Lifestyle") When I type http://127.0.0.1:8000/books/searchBooks?search=My Happy Days with category=Horror in the Body section of the PostMan application as form-data, then I should get only the 1st Book instance. But with the view you have seen above, I get both instances no matter what the category is. With my current solution, it seems that Django only focuses on the search query and that what I implemented in the get_queryset() method is not computed. How … -
How to filter queryset to current user in Django
I have a site that grabs all the records that is listed under the current user. Right now it grabs and filters it to all the available records and then filters it to the current user. Is there a way to make it so it doesn't have to do the initial filtering? class PromiseView(SingleTableView): queryset = Promise.objects.filter(deleted__isnull=True) table_class = PromiseTable template_name = 'promise.html' def get_queryset(self): current_user = str(self.request.user)[10:len(str(self.request.user))] return self.queryset.filter( windows_user=current_user, # There has to be a better way for this one. ) I would want to make it so the initial query set is equal to queryset = Promise.objects.filter(windows_user=current_user,deleted__isnull=True) and get rid of the get_queryset function. It makes no sense to query the entire database first and then query it again to filter it to how I want it. -
django favicon icon does not display
I have the following django project file structure: lecture3/ lecture3/ urls.py tasks/ static/ img/ favicon.ico urls.py my tasks/urls.py file is: from django.urls import path from . import views from django.contrib.staticfiles.storage import staticfiles_storage from django.views.generic.base import RedirectView app_name = 'tasks' urlpatterns = [ path("",views.index, name="index" ), path("add",views.add, name="add" ), path('favicon.ico', RedirectView.as_view(url=staticfiles_storage.url('img/favicon.ico'))), ] but when I run I get a 404 error. How do I fix this? -
Running my LoginView doesn't log me in and writes the csrf-token and the User credentials in the URL
Whenever I try to login using my custom class-based LoginView, my URL updates (writes the csrf token, the password, and the username in it), and nothing else happens. My views.py class LoginView(View): def post(self, request): username = request.Post['username'] password = request.Post['password'] user = authenticate(username=username, password=password) if user is not None: if user.is_active: login(request, user) return redirect('/') else: message.info(request, 'inavalid credentials!') return redirect('login') else: return render(request, 'registration/login.html') def get(self, request): return render(request, 'registration/login.html') My urls.py urlpatterns = [ path('login/', LoginView.as_view(), name='user-login'), ] My login.html <body> <form class="box" action="{% url 'user-login'%}" methode="post"> {% csrf_token %} <h1>Login</h1> <hr class="line"> <input type="text" name="username" placeholder="&#xf007; Username"> <input type="password" name="password" placeholder="&#xf084; Password"> <p>Don't have an Account? <a href="{% url 'register' %}">Sign in!</a></p> <hr class="line"> <input type="submit" name="" value="Login"> <input type="submit" value="Login"> <p>{{ form.errors }}</p> <input class="btn login_btn" type="submit" value="Login"> </form> {% for message in messages %} <p id="messages">{{message}}</p> {% endfor %} The URL that appears after I submitted through the Button on my login.html Does anyone have any ideas? I have spent about 8 hours to make it work and tried a lot of different approches but nothing seems to work. -
Django Query string stay in url during session
I pass the Query string through a form like this: <form action="stockChart" autocomplete="off" method="GET"> <input type="text" required="required" name="Ticker" maxlength="5"> </form> and then it redirects me to the page with all the data corresponding to the input and puts my input in the url /stockChart?Ticker=AAPL views.py def stockChart(request): TICKER = request.GET['Ticker'].upper() But if I go to another tab where I also want to use the same ticker it doesn't work, since the URL doesn't have the query string in it. Right now I'm using TICKER = request.session['Ticker'] but by doing that the URL doesn't contain the query string. Is there a way to keep the string (?Ticker?AAPL) in the url, when navigating to other pages? -
Django get objects that are foreign key of two models
I have the following three models where Budget and Sale both contain a foreign key to Customer: class Customer(models.Model): name = models.CharField(max_length=45) # ... class Budget(models.Model): customer = models.ForeignKey(Customer, on_delete=models.PROTECT) # ... class Sale(models.Model): customer = models.ForeignKey(Customer, on_delete=models.PROTECT) # ... I want to get a queryset of all Customer objects for which both a Budget and Sale exists. I initially tried getting the intersection of the customer field of all Budget and Sale objects: customers = { budget.customer for budget in Budget.objects.all() } & { sale.customer for sale in Sale.objects.all() } This returns the correct objects, but becomes horribly inefficient as the size of my database grows. How can I retrieve these objects in a more efficient way? Thanks for any help! -
Django Foreign Key not getting updated
Hi Guys I'm new to Django and I'm struggling with a problem that should be easy to be solved. This is my UserSerializer: class UserSerializer(serializers.ModelSerializer): role = RoleSerializer(many=False) class Meta: model = User fields = ['id', 'first_name', 'last_name', 'email', 'password', 'role', 'role_id'] extra_kwargs = {'password': {'write_only': True},} This is my GenericAPIView: class UserGenericAPIView(generics.GenericAPIView, mixins.UpdateModelMixin): serializer_class = UserSerializer queryset = User.objects.all() def put(self, request, pk=None): return self.partial_update(request, pk) The request that the frontend sends is this: PUT http://localhost:8000/api/users/1/ Content-Type: application/json { "first_name": "First Name", "last_name": "Last Name", "email": "email@example.com", "role_id": 2 } All the fields change except for the role_id... Any idea what is the best way to update the role_id? -
Why is django not sending mail?
hola estoy tratando de enviar correo atraves de django con smtp.lib library pero a la hora de ejecutar me dice que la libreria no me reconoce los datos de autenticacion este es el codigo que tengo dentro de mi archivostrong text -
How can I create a Django model with days of the week already embeeded?
How can I create a model, just like in this image: That it has the Days of the week already embeeded, PLEASE I don't need neither the date nor a calendar, just a model with every day of the week, so that each new class already has these days and from where i can add additional information (options). What kind of relation or model form should be added to a class so that it looks like this when created? -
Opening database in Pycharm for Django project
I am working on a django project using pycharm. How do I view the data in my sqlite db. From sources I found online, I have to open View-Tools Windows-Database, but I don't have that option. Can anyone help? I barely starting using pycharm today, thanksenter image description here -
How to show a field as list of instead of choicelist on django
Here is an invoice. In this case, it shows lines of products and user can select products on each line from dropdown list. My need is to show all products, each line with one product which i can fill with details as price and quantity as example bellow. Models: class Invoice(models.Model): company = models.ForeignKey(Company, on_delete=models.CASCADE) number = models.CharField(max_length=64, unique=True, default=invoice_number) date = models.DateField(default=timezone.now) client = models.ForeignKey('Client',on_delete=models.CASCADE) class InvoiceItem(models.Model): invoice = models.ForeignKey('Invoice', on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) price = models.DecimalField(max_digits=20, decimal_places=2) quantity = models.DecimalField(default=0, max_digits=20, decimal_places=2) forms: class InvoiceForm(ModelForm): class Meta: model = Invoice fields = "__all__" class InvoiceItemForm(ModelForm): class Meta: model = InvoiceItem fields = "__all__" InvoiceItemFormSet = inlineformset_factory(Invoice, InvoiceItem, form=InvoiceItemForm, extra=3, can_delete=False) View : class InvoiceCreate(CreateView): form_class = InvoiceForm model = Invoice template_name = "sales/invoice_form.html" def get_success_url(self): return reverse_lazy('invoice_details', kwargs={'pk' : self.object.pk}) def get(self, request, *args, **kwargs): company_instance = request.user.company self.object = None form = InvoiceForm(company_instance) formset = InvoiceItemFormSet(form_kwargs={"company":company_instance}) products = list(Product.objects.values()) return self.render_to_response( self.get_context_data(form=form,formset=formset, products=products)) def post(self, request, *args, **kwargs): self.object = None company_instance = request.user.company form = InvoiceForm(company_instance, self.request.POST) formset = InvoiceItemFormSet(self.request.POST, form_kwargs={"company": company_instance}) if (form.is_valid() or formset.is_valid()): return self.form_valid(form, formset) else: return self.form_invalid(form, formset) def form_valid(self, form, formset): self.object = form.save() formset.instance = self.object formset.save() try: … -
Using ForEach in Javascript with a django json response
I have a json response from django and I'm trying to display each item in the json response as its own div using javascript. The json response is as follows: [{"model": "network.posts", "pk": 1, "fields": {"user": 1, "post": "hi", "timestamp": "2020-11-10T21:24:51.118Z"}}, {"model": "network.posts", "pk": 2, "fields": {"user": 1, "post": "My first post!", "timestamp": "2020-11-10T21:25:07.893Z"}}, {"model": "network.posts", "pk": 3, "fields": {"user": 2, "post": "This is my 3rd post :)", "timestamp": "2020-11-10T22:43:23.383Z"}}, {"model": "network.posts", "pk": 4, "fields": {"user": 2, "post": "This is my 3rd post :)", "timestamp": "2020-11-10T22:44:34.421Z"}}, {"model": "network.posts", "pk": 5, "fields": {"user": 2, "post": "This is my 3rd post :)", "timestamp": "2020-11-10T22:47:17.896Z"}}] That comes from a django view which is: def get_posts (request): # Get list of posts posts = Posts.objects.all() if request.method == "GET": return JsonResponse(serializers.serialize('json', posts), safe=False) For now I'm just trying to console log each 'post' using javascript. Here's what I have so far: // Load all posts fetch(`/posts`) .then(response => response.json()) .then(data => { console.log(data); }); That works, but it logs the whole json response. What I want to do is chop it up so each post is logged separately, but I can't work it out! I tried using ForEach like this: // Load all posts … -
What should be the method called with a number field in django
I have created a forms.py file in my Django application to add additional fields to my Registration form. email attribute is added. Now i want to enter an attribute of Student no that every user will have. so instead of forms.EmailField() what field should my Student_No attribute should have from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm class UserRegistrationForm(UserCreationForm): email = forms.EmailField() -
Django, how to have an array in model without M2M?
I want my model to have an array of other model's instances. Let me explain. I have a Company model which has a localizations field which is supposed to be a set/array of addresses. Since one address can only be for one Company, M2M relationship seems wrong here. When Company gets deleted, all of its localizations should also be deleted. How do I accomplish that? (I don't use Postgres) -
Django reverse multiple args
i want to use multiple args in Django sitemaps reverse ,but not working , i mean example.com/title/daily and /title/love def get_absolute_url(self): return reverse("singCategory", args=[self.Title, "Daily" "Love"]) i try but not working args=[self.Title, "Daily" and "Love"]) args=[self.Title, "Daily" or "Love"]) -
Django ORM SELECT with JOIN (and some condisions)
So sorry, I don't have up skills from Django ORM, as so have this question. I have that model: class Calendar(models.Model): start = models.DateField(null=False) end = models.DateField(null=False) user = models.ForeignKey(User, models.CASCADE, related_name='calendars') created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) And I want aggregate all intersections. This not big deal. Then I execute sql query: select a.id, b.id from calendar a join (select * from calendar where user_id = %s) b on ( a.id <> b.id and a.start < b.end and a.end > b.start ) where b.id is not null order by a.id, a.id; But I have no idea how this query translate in ORM presentation. -
How to achieve shared customers across accounts in stripe ? (Clone customers across accounts)
I am working on stripe payments, where i require having a shared customer across different connected accounts, that are connected with the platform, I am using "Express Accounts" in stripe connect for connecting the connected accounts, and all of them are linked with the platform account. On the frontend (client-side) (Angular), using the "Stripe Prebuilt checkout page", for accepting payment and I am verifying the payment in webhooks(checkout.session.completed) at backend using Django Rest Framework. I am using Destination Charges, for handling the payments and separate charges and transfers. (That i am able to achieve using stripe prebuilt checkout page by specifying payment_intent_data.application_fee_amount and payment_intent_data.transfer_data.destination) A destination charge means the charge is processed on the platform and then the funds are immediately and automatically transferred to the connected account’s pending balance. Now I have a requirement where I need to have shared customers and share customers across the connected accounts, Is it even possible to achieve shared customers using a stripe prebuilt checkout page? If yes, how can I achieve it? Or Do I need to go with "Custom payment flow" for accepting a payment? I tried to follow this article Clone customers across accounts but I have not had any … -
How do I can change the default django rest_auth redirection?
hi I'm using django rest_auth package for managing my project's authentication system. when I do register or log in with a user it gives me just a key and doesn't redirect user to any page and for logout as well. how do I can redirect users to my home page after login, logout and register??? -
Django NoReverseMatch at /register
I'm attempting to enable users to register on my Django based website; however I am running into the following error: NoReverseMatch at /register Reverse for 'register' not found. 'register' is not a valid view function or pattern name. I am struggling to see what needs to be changed below, I feel that I have tried tweaking everything to get it working, but nothing seems to. I am using a namespace "Flightfinder" for my application, not sure if this has something to do with it? Full Error: NoReverseMatch at /register Reverse for 'register' not found. 'register' is not a valid view function or pattern name. Request Method: GET Request URL: http://127.0.0.1:8001/register Django Version: 3.1.3 Exception Type: NoReverseMatch Exception Value: Reverse for 'register' not found. 'register' is not a valid view function or pattern name. Exception Location: /mnt/c/Users/tjmce/Desktop/Git/CS50w/Final Project/finalproject/.venv/lib/python3.8/site-packages/django/urls/resolvers.py, line 685, in _reverse_with_prefix Python Executable: /mnt/c/Users/tjmce/Desktop/Git/CS50w/Final Project/finalproject/.venv/bin/python3 Python Version: 3.8.5 Python Path: ['/mnt/c/Users/tjmce/Desktop/Git/CS50w/Final Project/finalproject', '/usr/lib/python38.zip', '/usr/lib/python3.8', '/usr/lib/python3.8/lib-dynload', '/mnt/c/Users/tjmce/Desktop/Git/CS50w/Final ' 'Project/finalproject/.venv/lib/python3.8/site-packages'] Server time: Wed, 11 Nov 2020 20:32:27 +0000 Layout Template: {% load static %} <!doctype html> <html lang="en"> <head> <!-- jQuery & jQuery UI --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css"> <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script> <!-- Bootstrap (includes Popper) --> <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ho+j7jyWK8fNQe+A12Hb8AhRq26LrZ/JpcUGGOn+Y7RsweNrtN/tE3MoK7ZeZDyx" crossorigin="anonymous"></script> <!-- … -
Django (DRF) monitor a database for changes not made via Django
this might be a vague question since it's more about the concept and not knowing what kind of tools are available to me. I am developing a system with React that will consume a Django Rest Framework API, with a MySQL database, just your basic CRUD functions. This database is also updated from an external application. I have no control over the external application, so I can't make it use my API. I want to be able to monitor the database for any changes, from either my end or the other program, and once there is a change I want to perform a set of functions. I am quite new to this so I have no clue how to start with this problem. I could on the frontend compare new and old data and display a notification, but I want to be able to, for example send an email when there is a change in the database (based on the results of the calculations). -
Djano Queryset returned from Manager with Stored Procedure
I have a model.Manager that runs a stored procedure and a model.Model to handle the returned data. However, when the data is returned, it's not returned as a queryset but instead a list of tuples, and I cannot reference them by field name. I would like to have the results returned as a queryset. models.py class DashboardDetailManager(models.Manager): def dashboardDetail(self, from_date, to_date): from django.db import connections # AD 11/10/2020 updated sproc to return multiple sets for easier handling # was only returning the last set of expected results--> raw_sql = f"EXEC dbo.spGetDashDetailData @formFromDate = '{from_date}', @formToDate = '{to_date}'" with connections['ECS3'].cursor() as cursor: cursor.execute(raw_sql) detail_rows = [] for row in cursor.fetchall(): detail_rows.append(row) while cursor.nextset(): for row in cursor.fetchall(): detail_rows.append(row) return detail_rows class DashDetailData(models.Model): occurred = models.DateField(blank=True, null=True); severity = models.CharField(max_length=3, blank=True, null=True) batchid = models.CharField(max_length=255, blank=True, null=True); hrefkey = models.CharField(max_length=255, blank=True, null=True) email = models.EmailField(null=True, blank=True) id_cst = models.IntegerField(null=True, blank=True) docType = models.CharField(max_length=255, blank=True, null=True); tpid = models.CharField(max_length=255, blank=True, null=True); name_cst = models.CharField(max_length=255, blank=True, null=True); message = models.CharField(max_length=255, blank=True, null=True); attachment = models.CharField(max_length=255, blank=True, null=True); bom_status = models.CharField(max_length=255, blank=True, null=True); ack = models.CharField(max_length=255, blank=True, null=True); bom_count = models.IntegerField(null=True, blank=True) objects = DashboardDetailManager() views.py detail_rows = DashDetailData.objects.dashboardDetail('11-10-2020', '11-20-2020') -
How to avoid error while using list_display in django
I need to get view of table in admin. I imported table from Mysql. In models.py code is written: class Stations2(models.Model): id_stations = models.IntegerField(db_column='ID_stations', primary_key=True) # Field name made lowercase. name = models.TextField(db_column='Name', blank=True, null=True) # Field name made lowercase. type = models.TextField(db_column='Type', blank=True, null=True) # Field name made lowercase. country = models.TextField(db_column='Country', blank=True, null=True) # Field name made lowercase. latitude = models.FloatField(db_column='Latitude', blank=True, null=True) # Field name made lowercase. longitude = models.FloatField(db_column='Longitude', blank=True, null=True) # Field name made lowercase. elevation = models.IntegerField(blank=True, null=True) site_gaw_id = models.TextField(blank=True, null=True) stations_id = models.IntegerField(blank=True, null=True) class Meta: managed = False db_table = 'stations_2' I wrote in admin.py: from django.contrib import admin from .models import Stations2 class data_admin(admin.ModelAdmin): model = Stations2 list_display = ('Name', 'Type',) admin.site.register(Stations2,data_admin) and got an error: ERRORS: <class 'scrapping_2.admin.data_admin'>: (admin.E108) The value of 'list_display[0]' refers to 'Name', which is not a callable, an attribute of 'data_admin', or an attribute or method on 'scrapping_2.Stations2'. <class 'scrapping_2.admin.data_admin'>: (admin.E108) The value of 'list_display[1]' refers to 'Type', which is not a callable, an attribute of 'data_admin', or an attribute or method on 'scrapping_2.Stations2'. without data_admin code work well. How Should I solve my problem? -
Django Query Filter and Order Queryset
I'm doing a project that involves handling recipes. It's built on django and postgres. There's a recipe table full of recipes, ingredient table full of ingredients, and a usedby table to handle the many to many relationships. Each entity has an ID in the form of "entityname_id". Full disclosure, this is for a university assignment, so take that into account if you feel uncomfortable with posting code. I'm trying to find recipes similar to another recipe by finding recipes with the largest number of similar ingredients. To do this: I first find a list of the ingredient_ids in the original recipe. (line 1) Go through each usedby, group them by recipe_id, and add one to that recipe_id's count every time one if it's ingredients is in the original recipe's ingredient list. (line 2) Filter down the query to only include the first 20 results ordered by the most similar ingredients. (line 3) Filter the original queryset to only include recipes in the top 20.(line 4) ingredient_ids = Usedby.objects.filter(recipe_id=searchTerm).values("ingredient_id") recipe_counts = Usedby.objects.values("recipe_id").annotate(theCount = Count(Case(When(ingredient_id__in=ingredient_ids, then=1), output_field=IntegerField()))) recipe_counts = recipe_counts.order_by("-theCount").values("recipe_id", "theCount")[0:20] qs = qs.filter(recipe_id__in=recipe_counts.values("recipe_id")) All of this works. The issue I can't seem to figure out is how to sort the 20 … -
Upload and download xlsx files in django
I'm trying to work with a view for file upload (xlsx) to s3. And a celery function that should download this file so that I can perform some actions. My view: class ImportView(APIView): parser_classes = (FileUploadParser, ) def post(self, request, filename): imported = ImportSerializer(data=request.data) fs = FileSystemStorage(tempfile.gettempdir()) file_name = fs.save(content=new_colabs.validated_data["file"], name="import.xlsx") full_path = os.path.join(fs.location, file_name) object_name = file_name s3 = boto3.client("s3") s3.upload_file(full_path, "my_bucket", file_name) # call celery here... return Response(status=status.HTTP_200_OK) My celery task: def example_download_funciont(self): s3 = boto3.client("s3") bucket = s3.Bucket("my_bucket") with open(file_name, 'wb') as data: file = bucket.download_fileobj(object_name, data) workbook = load_workbook(file) # [...] Running this code I can upload it to s3. However, when I try to access it directly through the aws console I get this error: AccessDeniedAccess DeniedAEEF2C5140AF4B82zNYFYcwehn+ZDxm+FuEI8mqrcCCU6BQzDdjd6mzOseMDanA6cPmu2VnbX3KvR978xN9v0QwOa7g=try { Object.defineProperty(screen, "availTop", { value: 0 }); } catch (e) {} try { Object.defineProperty(screen, "availLeft", { value: 0 }); } catch (e) {} try { Object.defineProperty(screen, "availWidth", { value: 2560 }); } catch (e) {} try { Object.defineProperty(screen, "availHeight", { value: 1080 }); } catch (e) {} try { Object.defineProperty(screen, "colorDepth", { value: 24 }); } catch (e) {} try { Object.defineProperty(screen, "pixelDepth", { value: 24 }); } catch (e) {} try { Object.defineProperty(navigator, "hardwareConcurrency", { value: 8 … -
Visual Studio seems to show inconsistent error suggestions
I am not sure why VS code is stating that my 'from' is incorrect within my models.py file. See image. Is there a package or a setting that I should be aware of? Snip of what I am experiencing