Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Understanding Django lazy querysets and how they work with function borrowing and Casting columns to integers
I have created a function that I use to apply filters sent from the frontend to query django's database. I include it in the get_queryset method of various ViewSet's. The main issue that arises is when I try to cast one of my model fields to an int to allow me to apply __gt queries to it. The field can contain normal character strings and string representations of integers, but I can easily filter non integer strings based on another field. I thought this would allow me to cast each item in a queryset without reciving an 'is not a valid integer' error when casting the field. But this isn't the case, and I believe the reason has to do with lazy querysets/queryset function borrowing rules. Example Viewset def get_queryset(self): queryset = MyModel.objects.all() # ... # ... other queries # ... filter_model = self.request.query_params.get('filter') if filter_model: queryset = apply_filter(queryset, filter_model) return queryset apply_filter def apply_filter(queryset, filter_model): for _filter in filter_model: # filter models to ensure only instances with valid integer strings are in the queryset field_qs = RelatedChildModel.objects.filter(data_field__name=_filter['name']) # cast integer field field_qs = field_qs.annotate("value_int"=Cast("value", output_field=IntegerField())) # solely to double check that every instance in the queryset has cast an … -
How would I customize a Buefy (or Bulma if easier) implementation with a custom theme/vars/colors in a Django project?
I have a Django web app with Vue on the frontend. I installed Buefy to get easy-to-use components. I'd like to create a theme file to customize some of the colors (things like is-info, primary, etc.) The Buefy and Bulma documentation basically just says "create a SCSS file and then you can specify variables"...but it doesn't explain WHERE this file would go, and how to ensure it gets converted to css, or integrated with webpack, etc. How would I integrate a custom .scss file into my project so it compiles and loads in my app? -
TypeError: wrapper() missing 1 required positional argument: 'backend' happens while tryting to do Oauth2 login
this is my views.py @api_view(http_method_names=['POST']) @permission_classes([AllowAny]) @psa() def exchange_token(request, backend): serializer = UserSerializer(data=request.data) if serializer.is_valid(raise_exception=True): user = request.backend.do_auth(serializer.validated_data['access_token']) if user:#drf built in token authentication?? token, _ = Token.objects.get_or_create(user=user) # drf token authentication return Response({'token':token.key}) else: return Response( {'errors':{'token':'Invalid token'}}, status = status.HTTP_400_BAD_REQUEST, ) https://www.toptal.com/django/integrate-oauth-2-into-django-drf-back-end I'm following this page and trying to request using postman But above error happends. I think I should pass "backend" argument when requesting, but I don't know what to do right now... someone please tell me how can I solve this problem -
Add extra field to django queryset after getting data from some api in graphql's resolver method?
I have a graphql api and there is product resolver method that returns queryset of products. I want to add a new field for every product in the queryset. The new field will be a an index with key of "similarity" and then there would be value. I have tried to use annotate but that does not work in my case. Need guidance on how can I go about this? Thanks in advance. -
Besy way to create records in bulk in django rest framework
I'm a newbie in Django and I'm currently creating my records but I want a more efficient way that can reduce the time and load on the server. Please let me know the best approach to create bulk records with ForeignKeys relations. models.py class Task(models.Model): name = models.CharField(max_length=255, default='') description = models.CharField(max_length=255, null=True, blank=True) project = models.ForeignKey(Project, on_delete=models.CASCADE, null=True) account = models.ForeignKey(User, on_delete=models.CASCADE, null=True) class Meta: db_table = 'tasks' views.py @api_view(['POST']) def create_task(request): # added request JSON below try: response = [] for task in request.data: data = {} data['name'] = task['name'] data['description'] = task['description'] data['project'] = task['project_id'] data['account'] = task['user_id'] serializer = TaskSerializer(data=data) serializer.is_valid() serializer.save() response.append(serializer.data) return Response(response) except Exception as e: return Response(str(e)) serializers.py class TaskSerializer(serializers.ModelSerializer): project = ProjectSerializer(read_only=True) # added to fetch project detail in get request user = UserSerializer(read_only=True) # added to fetch user detail in get request class Meta: model = Task fields = ['id', 'name', 'description', 'project', 'user'] request from client side [ { "name": "foo", "description": "lorem ipsum", "project_id": 1, "user_id": 1 }, { "name": "bar", "description": "lorem ipsum", "project_id": 1, "user_id": 2 }, { "name": "baz", "description": "lorem ipsum", "project_id": 1, "user_id": 3 } ] -
How to filter with a non non-model field?
I have a model with one of its fields is a random generated string as the following from django.utils.crypto import get_random_string class Competition(models.Model): name = models.CharField(verbose_name="challenge name", max_length=256) start_date = models.DateTimeField(verbose_name="start date") end_date = models.DateTimeField(verbose_name="end date") code = get_random_string(length=6) owner = models.ForeignKey(User, related_name="owner", on_delete=models.CASCADE) def __str__(self): return self.name I am trying to have an endpoint like thathttp://192.168.1.2:8000/competitions/?code=${some_string} to access from react frontend. so in order to do so I have some filters from django_filters import rest_framework as filters class CompetitionFilter(filters.FilterSet): class Meta: model = competition fields = { "name": ["exact", "icontains"], "code": ["exact"], "start_date": ["exact", "lte", "gte"], "end_date": ["exact", "lte", "gte"], "owner": ["exact"], } but I have an error saying TypeError: 'Meta.fields' must not contain non-model field names: code So how can I achieve it? -
how to use ajax to update cart items
So, trying to use ajax to update the {{cartItems}} on nav when someone hits the add-to-cart button on template without reloading the page but can't get ajax to work, been at it for quite some time. would really appreciate it if someone can help, thx! views.py def ajax_update(request): data = cartData(request) cartItems = data['cartItems'] context = {"cartItems": cartItems} return render(request, 'store/shop.html', context) urls.py path('ajax_update/', views.ajax_update, name="ajax_update"), cart.js function addCookieItem(productId, action){ console.log('User is not authenticated') if (action == 'add'){ if (cart[productId] == undefined){ cart[productId] = {'quantity':1} }else{ cart[productId]['quantity'] += 1 } } if (action == 'remove'){ cart[productId]['quantity'] -= 1 if (cart[productId]['quantity'] <= 0){ console.log('Item should be deleted') delete cart[productId]; } } console.log('CART:', cart) document.cookie ='cart=' + JSON.stringify(cart) + ";domain=;path=/" /*replacing location.reload() with ajax*/ function updating_cart_ajax(){ $.ajax({ headers:{ 'Content-Type':'application/json', 'X-CSRFToken':csrftoken, }, url: 'ajax_update/', type: 'POST', data : { 'cartItems' : cartItems, }, success: function(data){ console.log('success') console.log(csrftoken) } }) } } template {% for product in products %} <div class="shop-card"> <a href="{{product.slug}}"> <div class="image-card-wrapper"> <img id="store-cart-img" src="{{ product.image_URL }}"> </div> <div class="card-shop-info"> <p>{{product.name}}</p> <p id="styleb">${{product.final_price | floatformat:2}} | <a data-product="{{product.id}}" data-action="add" class="add-to-cart-action update-cart">Add to cart</a></p> </div> </a> </div> {% endfor %} -
Cannot assign "id": "Product.category" must be a "CategoryProduct" instance
i'm working on a django project and i got this error (Cannot assign "'11'": "Product.category" must be a "CategoryProduct" instance.) anyone here can help me please. Model: class Product(models.Model): name = models.CharField("Nombre", max_length=150) category = models.ForeignKey(CategoryProduct, on_delete=models.SET_NULL, null=True, related_name='category') def __str__(self): return self.name View: class ProductCreateView(CreateView): model = Product form_class = ProductForm success_url = '/adminpanel/products/' def post(self, request, *args, **kwargs): form = self.get_form() category = CategoryProduct.objects.get(id=request.POST['category']) if form.is_valid(): product = form.save(commit=False) product.category = category product.save() Form: class ProductForm(forms.ModelForm): name = forms.CharField(max_length=150, label="Nombre") category = forms.ChoiceField(choices=[(obj.id, obj.name) for obj in CategoryProduct.objects.all()], label="Categoría") class Meta: model = Product fields = ['name', 'category'] -
django orm like Wikipedia
imagine we have a model like post: id title->char body->text version or created-at now we nead to retrieve the latest post that grouped by title. latest field can be a veraion thats be a number or maybe a date. how can i write this query. Preferred django-orm query. thanks IF confused can check example: post1: title:test body: old body version:1 post2: title:test body:new body version:2 post3: title:bee body: old version:1 post4: title:bee body:new version:2 post5: title:bee body:newest version:3 post6: title:cow body:cow version:1 now we nead to retrieve posts like this post2, post5, post6 -
Unable to use django-extensions commands
I have created an app and project using django_cookie_cutter. I can run admin_generator, reset_db, makemigrations, migrate. show_urls is not listed in the subcommands dumpdata is and I cannot use dumpdata. Python==3.9 Django==3.2.13 django-extensions==3.1.5 pip3 install django-extensions Added to INSTALLED_APPS django_extensions and my app >>> import django_extensions >>> django_extensions.VERSION (3, 1, 5) manage.py Type 'manage.py help <subcommand>' for help on a specific subcommand. Available subcommands: [django] check compilemessages createcachetable dbshell diffsettings dumpdata flush inspectdb loaddata makemessages makemigrations migrate runserver sendtestemail shell showmigrations sqlflush sqlmigrate sqlsequencereset squashmigrations startapp startproject test testserver -
replace('\n','') does not work for import to .txt format
csv_reader = csv.reader(io_string, delimiter='\t',quotechar="|") for column in csv_reader: column_1 = str(column[1]).replace('\n','') b = Module( user= request.user, a=column_1, b=column[2], ) b.save() ** Here, in column_1 there is such data as an example in the .txt file 'This is a value' and I want to output this data as 'This is a value' after importing it, but I can't. How should I do?** -
Create a minute and hour MultiValueField implementation in django forms
I'm having some troubles to create a form in Django, I don't know if my aproaches are correct soy any help of where I have to read will be appreciated. I want to show a field compose by two fields, one for hours and the other for minutes, reading Django documentation I came out with the idea to use MultiValueField, and I tried this: class CreateEventForm(forms.ModelForm): class TimeField(forms.MultiValueField): def __init__(self, **kwargs): error_messages = { 'incomplete': 'Missing info', } fields = ( forms.CharField(max_length=64, label= "Horas"), forms.CharField(max_length=64, label="Minutos") ) super().__init__( error_messages=error_messages, require_all_fields=False, fields=fields ) journal_start = TimeField() journal_finish = TimeField() class Meta: model = UserEvent fields = ['duration', 'pre_time', 'post_time'] labels = { 'duration': 'Duración', 'pre_time': 'Previo', 'post_time': 'Después: ', } But instead of having two different fields for starting and finishing journey I only have one, this is the picture of the output How can I make a Django form field with two inputs using Model Forms? thanks for reading me! -
How to display ForeignKey fields in a table from inside a DetailView in Django?
I have two models Account and Order and I would like to render a Django table OrderTable will all orders of an account from inside a DetailView. To do that I first select the orders related to the Account instance with self.object and then I build the table into get_context_data, but the problem is that Django throws an error. What is the right way to to do that ? Cannot resolve keyword 'clientid' into field. Choices are: active, email, name [...] models.py class Account(models.Model): name = models.CharField(max_length=100, null=True, blank=False) active = models.BooleanField(null=True, blank=False, default=False) email = models.EmailField(max_length=100, blank=True) class Order(models.Model): account = models.ForeignKey(Account, on_delete=models.CASCADE, related_name='order', null=True) clientid = models.CharField(max_length=150, null=True) dt_update = models.DateTimeField(auto_now=True) dt_create = models.DateTimeField(default=timezone.now, editable=False) tables.py import django_tables2 as tables from myapp.models import Order class OrderTable(tables.Table): class Meta: model = Order fields = ('clientid', 'dt_create', 'dt_update') views.py class AccountDetailView(SingleTableMixin, generic.DetailView): model = Account table_class = OrderTable context_table_name = 'table' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) # Select orders of the account and render a table orders = Order.objects.filter(account=self.object) context['orders'] = OrderTable(orders) return context Template {% extends "base_generic.html" %} {% load static %} {% load django_tables2 %} {% load render_table from django_tables2 %} {% block content %} <h1>{{account.name}}</h1> <p>Orders … -
Question about Django cookie management (API rest) in Flutter application. Is my system robust?
I'm starting in Flutter and I built an api with a login. For authentication I get a cookie from my Django REST API. From my login POST request i store these cookies in my app. cookie sample (1): {set-cookie: csrftoken=7IASHmHBDkqkFxPnYF5rRjEaT0hyd4cxSKHKx2ibnNmmYBBvX68gVKOSDjPZxPAB; expires=Tue, 25 Apr 2023 21:35:15 GMT; Max-Age=31449600; Path=/; SameSite=Lax, sessionid=05yj1bmg5ei7riw8glh13d0gmmw06jbq; expires=Tue, 26 Apr 2022 23:35:15 GMT; HttpOnly; Max-Age=7200; Path=/; SameSite=Lax, date: Tue, 26 Apr 2022 21:35:15 GMT, vary: Accept, Cookie, content-length: 0, referrer-policy: same-origin, cross-origin-opener-policy: same-origin, x-frame-options: DENY, x-content-type-options: nosniff, server: WSGIServer/0.2 CPython/3.10.2, allow: POST, OPTIONS} Then to make a GET request I need to set a cookie of the form bellow. "csrftoken=MZ8YuHN7GaGPId6XEoHOmLJGCj5FrJFU1lElphAxWJVwq366rPoAyI3fOhcEK6ks; sessionid=7cwighx7vbpcoszfl5ltxy2jf32psjeh" To then use it in a Response object from Getx connect package : Response response = await get(appBaseUrl + uri, headers: {"Cookie": COOKIE}); So i manage to transform to the right shape my cookie sample (1) I would have liked to know if my system below is robust because it only needs to change a little bit and nothing will work anymore. Do you have another solution to advise me? Future<ResponseModel> login(String username, String password) async { _isLoading = true; update(); Response response = await authRepo.login(username, password); late ResponseModel responseModel; if (response.statusCode == 202) { print(response.headers); … -
How can I connect my Django Admin panel to Angular
I want help in integrating my Django Admin Panel to my Custom Angular Admin panel, I want to migrate all the functionalities of Django admin in Angular (Front-End). Would appreciate if anyone will share the walkthrough to deal with this problem. If with REST API than how please guide. -
Django : display the content of a PDF or Image on a template
I want to display a pdf/image file on a template. I download the content of the file from a azure blob storage but I do not know how to display it in a template without using the HttpResponse method from Django. Here is my code : function def download_from_blob(file): blob_client = create_blob_client(file) if not blob_client.exists(): return blob_content = blob_client.download_blob() return blob_content views.py def displayFILE(request, file_id): file = UploadFilesAAD.objects.get(pk=file_id) filename = file.Filename file_type, _ = mimetypes.guess_type(filename) url = file.Url blob_name = url.split("/")[-1] blob_content = download_from_blob(blob_name) if blob_content : response = HttpResponse(blob_content.readall(), content_type='application/pdf') response['Content-Disposition'] = 'inline;filename=some_file.pdf' return response This code works but only for pdf and takes the whole page for it. I would like to take this content and insert it in a html tag without using a django method. Because after I want to custom the page to diplay the content in half a page. My idea was to encode the content in 64 bits and then display it in the html code but it does not work. Here is the code : def displayFILE(request, file_id): context = initialize_context(request) file = UploadFilesAAD.objects.get(pk=file_id) filename = file.Filename file_type, _ = mimetypes.guess_type(filename) url = file.Url blob_name = url.split("/")[-1] blob_content = download_from_blob(blob_name) encoded_string = … -
i face Problem while installing swagger in Django
I try to install swager for my Django rest framework project. when I was put this below commend then facing then error. I try too many times. but not success. I follow this below documentation site is. https://drf-yasg.readthedocs.io/en/stable/index.html pip install drf-yasg Collecting drf-yasg Using cached drf_yasg-1.20.0-py2.py3-none-any.whl (1.6 MB) Collecting uritemplate>=3.0.0 Using cached uritemplate-4.1.1-py2.py3-none-any.whl (10 kB) Collecting coreapi>=2.3.3 Using cached coreapi-2.3.3-py2.py3-none-any.whl (25 kB) Collecting inflection>=0.3.1 Using cached inflection-0.5.1-py2.py3-none-any.whl (9.5 kB) Requirement already satisfied: djangorestframework>=3.10.3 in g:\partshouse\venv\lib\site-packages (from drf-yasg) (3.12.4) Collecting ruamel.yaml>=0.15.34 Using cached ruamel.yaml-0.17.21-py3-none-any.whl (109 kB) Requirement already satisfied: Django>=2.2.16 in g:\partshouse\venv\lib\site-packages (from drf-yasg) (3.0.8) Collecting coreschema>=0.0.4 Using cached coreschema-0.0.4.tar.gz (10 kB) Preparing metadata (setup.py) ... error error: subprocess-exited-with-error × python setup.py egg_info did not run successfully. │ exit code: 1 ╰─> [20 lines of output] Traceback (most recent call last): File "<string>", line 36, in <module> File "<pip-setuptools-caller>", line 34, in <module> File "C:\Users\Sony\AppData\Local\Temp\pip-install-zogxxnl5\coreschema_14f317f16044494cb26e7e1e63f7852c\setup.py", line 75, in <module> 'Topic :: Internet :: WWW/HTTP', File "g:\partshouse\venv\lib\site-packages\setuptools\__init__.py", line 87, in setup return distutils.core.setup(**attrs) File "g:\partshouse\venv\lib\site-packages\setuptools\_distutils\core.py", line 109, in setup _setup_distribution = dist = klass(attrs) File "g:\partshouse\venv\lib\site-packages\setuptools\dist.py", line 466, in __init__ for k, v in attrs.items() File "g:\partshouse\venv\lib\site-packages\setuptools\_distutils\dist.py", line 293, in __init__ self.finalize_options() File "g:\partshouse\venv\lib\site-packages\setuptools\dist.py", line 885, in finalize_options for ep in sorted(loaded, … -
Updating field in admin change list
I have a model of products, and want to display the list on the admin site with the possibility of changing the order. class Product(models.Model): name = models.CharField(max_length=500) is_active = models.BooleanField(default=True) category = models.ForeignKey( "categories.Category", on_delete=models.CASCADE, related_name="products" ) description = models.TextField(null=True, blank=True) ingredient = models.TextField(null=True, blank=True) order = models.PositiveIntegerField(default=0) rank = models.PositiveIntegerField(default=0) price = models.DecimalField(max_digits=10, decimal_places=2, default=0) objects = ProductManager() class Meta: verbose_name_plural = _("Products") verbose_name = _("Product") ordering = ["order"] def __str__(self) -> typing.Text: return self.name I decided to order the model by the field order which can't be editable in admin page, so I want to copy it's value to the field rank which I want to make editable in admin page, and when I will save the changes I made to rank I want to override the order values with the new value from rank. This is how I register the model: class ProductAdmin(SortableAdminMixin, TranslationAdmin): inlines = [ImagesInline, NutritionsInline] search_fields = ["name", "description"] autocomplete_fields = ["category", "brand", "manufacturer"] fieldsets = ( ( _("Details"), { "fields": ( "is_active", "name", "price", "category", "description", ), }, ), ( _("Product Info"), { "fields": ("ingredient",), }, ), ) list_display = ("order", "rank", "name", "category") list_editable = ["rank"] I tried to override the … -
Django: Dealing with Username Changes
This might be a silly question, but I thought I'd ask before I continue doing anything. Assume I have two models: the first, some User model, and the second an ImgUpload model which captures the username automatically as the form is submitted and stores it in the database. If I end up updating a username (let's say User1 -> User2) or any other field from the User model, will the ImgUpload model automatically capture this change or do I need some sort of way to handle this? -
Are the names of files uploaded to an HTML multi-file upload input guaranteed to be unique?
Let's say I have a form with a multi-file upload input like this: <form method="POST" enctype="multipart/form-data"> <label for="files">Select files:</label> <input type="file" id="docs" name="docs" multiple><br><br> <input type="submit"> </form> I have a Django backend that is parsing this upload: def view(request): files = request.FILES.getlist("docs") file_names = [f.name for f in files] if len(file_names) != len(set(file_names)): raise Exception("Duplicate file names") Assuming the files are actually uploaded in a mainstream browser (Chrome, Firefox, IE, Edge, Safari, Opera), are the names for the files uploaded in this input guaranteed to be unique? I.e. is there any way for the exception in the backend to get raised? -
CSS files not found when trying to import third party NPM CSS file in django
I am running a django app and I want to import a third-party stylesheet from my node_modules. But my django app is looking in the wrong directory and throws a 404 and I don't understand why. My structure of the static files: static ├── src │ | │ │ │ ├── outputs │ │ ├── example.css │ │ ├── .. │ │ ├── .. │ │ ├── .. │ │ └── .. In my example.css I do the following: @import "~leaflet/dist/leaflet.css"; This should import my leaflet CSS - the ~ represents the path to the node modules- which is in my node_modules directory in my root directory (I also tried the absolute path to node_modules and the same error occurs). I added the node_nodules to the STATIC_DIRS in the django config and my static file settings look like so: STATIC_URL = "/static" STATICFILES_DIRS = [ os.path.join(BASE_DIR, "myproject/static"), os.path.join(BASE_DIR, "node_modules"), ] STATICFILES_FINDERS = ( "django.contrib.staticfiles.finders.FileSystemFinder", "django.contrib.staticfiles.finders.AppDirectoriesFinder", ) With this setting django should look into node_modules for the static files too. Now, with the above settings, when I include my example.css into the head of my template I get the following error: GET http://localhost:8000/static/src/outputs/~leaflet/dist/leaflet.css net::ERR_ABORTED 404 (Not Found) So obviously my app … -
Delete user model
How can I delete the user model? what will be the views? urls.py: path('account_delete/<int:user_delete>', views.account_delete, name="account_delete") views.py: from django.contrib.auth.models import User def account_delete(request,user_delete): return redirect("/") Templates: <a href="{ url 'account_delete' user_delete=user_delete }" class="delete_btn btn"> <i class="far fa-trash-alt"></i> </a> -
can't align list correctly
as you can see my list aligns some kind randomly and i dnot know why. Any ideas? html: {% if shop_name %} <ol> {% for library in shop_name %} <li>Video Library Info</li> <ul> <li>Name : {{library.shop_name}}</li> <li>Adress : {{library.adress}}</li> {% comment %} <button id="btn_goto" onclick="">Select</button> {% endcomment %} </ul> {% endfor %} </ol> {% else %} <p>ERROR</p> {% endif %} css code: body { text-align: center; color: #FFA000; background-color: #911E42; } ol { display: table; text-align: left; margin: 0 auto; margin-bottom: 20px; } ul { display: table; margin: 0 auto; vertical-align: baseline; text-align: left; } so at css i typed that text in list should be aligned on left side but still it does'nt help and it aligns randomly as i think. The thing i need to perfom is to align every li from ul on left side -
In Django, how do I collect the users input from html, use the input with python, and display the console output back to HTML?
I am a student. I am trying to make a simple online ping tester website with Django where the user can type in the IP address on the website, and the backend gives the result of the ping command which can show on the HTML page. Right now I have a problem with correctly collecting the information and getting results back. Views.py from django.http import HttpResponse from django.shortcuts import render import os import cgi import cgitb # Create your views here. def home_view(request, *args, **kwargs): cgitb.enable() form = cgi.FieldStorage() ip_to_check = form.getvalue('ip') result = os.system('ping {}'.format((ip_to_check))) print(result) print(request.user) return render(request, "home.html", {}) def contact_view(request, *args, **kwargs): return render(request, "contact.html", {}) Home.html <html> <head> <title>Ping</title> <meta name="description" content="Ping"> <meta name="keywords" content="Ping"> </head> <body> <h1>ping</h1> <form method="post">{% csrf_token %} <label for="ip">Ip adress:</label><br> <input type="text" id="ip" name="ip" placeholder="8.8.8.8"><br> <input type="submit" name="submit_cmd" value="run"> </form> <h2>Result</h2> <body></body> </body> </html> -
Django retrieve data from multiple tables on 2 levels
enter image description here I have this condition where for each value of table A, I need to recover the values of all connected tables, first (blue tables) and second level (green tables). As far as possible, I would like to adopt a simple solution, which follows Django's directives and doing well, which I obviously have not found. As from suggestions found online, for each foreign key I also set a 'Related Name', even if I am not sure it is useful for the purpose. Python: 3.7 Django: 3.12