Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
UUIDs with django and mssql
I have a mssql schema with the django ORM / pymssql extension. I have some classes build via the inspectdb function. A lot of the Primarykeys in the tables are UUID fields / mssql uniqueidentifier, which the ORM inspected as CharFields with length 36. I am concerned now with possible duplicates for the primary keys since the tables are growing very fast. The tables have a default constraint for any new primary key on the database site. So basically I have two (different) sources of UUID generation (the database server and the application server) How is it possible to insert via the ORM from django performantly? Am I save with generating the UUIDs via pythons uuid module or do I have to ask the database everytime for a new UUID before creating a object with django? -
How to have a choice depending on the instance of a model in Django admin
I am stuck since quiet a few days now. I have a level 1 model, which is in 0 to Many relation with a level 2 model, which is in a 0 to Many relation with a level 3 model: class Level1(models.Model): title = models.CharField(max_length=30) # some fields class Level2(models.Model) title = models.CharField(max_length=30) # some Fields level1 = models.ForeignKey(Level1, on_delete=models.CASCADE) class Level3(models.Model) title = models.CharField(max_length=30) # some Fields level2 = models.ForeignKey(Level2, on_delete=models.CASCADE) choices = # I get stuck here # The field 'choices' must point to one level2 instance proposed through a kind of Choices form field, but maybe I am wrong. By pointing, I think it can be as well a relation or just storing the id of the Model instance. The choices must be limited. Here an example would be the simplier way to explain : Level 1 : objects : A, B Level 2 : objects : A1, A2, A3 : (Parent A); B1, B2 : (Parent B) Level 3 : object A10 : (parent A1) For A10 choices must be limited to A1, A2, A3. And that's it. Thank you in advance for your help. -
Get field from cursor select (mssql) in my template
I have this VIEW below: from django.shortcuts import render from django.db import connections def IndexView(request): con_totvs = connections['totvs'].cursor() with con_totvs as cursor: cursor.execute("SELECT A1_NOME, A1_CGC FROM SA1010 WHERE D_E_L_E_T_ <> '*' ORDER BY A1_NOME") select = cursor.fetchall() # bla bla bla context = {} cursor.close () con_totvs.close () return render(request, "home.html", context) Just like I use when creating models, in my template id like to do something like: {% for i in SELECT %} {{ i.A1_NOME }} {% endfor %} Is this possible? Ive been searching but i failed it -
Convert template html in django to pdf and download it
How I can create a button on my web page using Django to convert the page to PDF and download it ? -
Django Rest API Models Problem an unexpected keyword argument 'is_staff'
i have error ExtendedUser() got an unexpected keyword argument 'is_staff' This is my model.py class ExtendedUser(AbstractBaseUser): objects = UserManager() id = models.AutoField(primary_key=True) first_name = models.CharField(max_length=100) last_name= models.CharField(max_length=100) username = models.CharField(max_length=100) email = models.CharField(max_length=100) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) password = models.CharField(max_length=50) def __str__(self): return str(self.first_name) and this is my serializer class RegisterSerializer(serializers.ModelSerializer): class Meta: model = ExtendedUser fields = ['id','first_name','last_name','password','email'] extra_kwargs = {'password': {'write_only': True}} def create(self, validated_data): user = ExtendedUser.objects.create_user(validated_data['first_name'], validated_data['email'], validated_data['password']) return user What is problem , how to avoid this problem ? i do't want to use is_staff field -
How to compare the value of an input with an object field in django template?
I want to compare the value of an object field to the value of an input that i have set the value with jQuery on a click event. Here is the jQuery function: <script> $(document).ready(function() { $('.position').click( function(){ var id=$(this).attr('id'); alert(id) $('.info-tooltip').toggleClass("hidden"); $('.header').addClass("popup"); $('.section').addClass("popup"); $('#map-value').val(id); }, ) $('.remove-link').click( function(){ $('.info-tooltip').addClass("hidden"); $('.header').removeClass("popup"); $('.section').removeClass("popup"); }, ) }); </script> I want to access the value of the input with the id="map-value" with the id of the object field that I am accessing it with an for cycle like this <form> <input type="text" value="1" id="map-value" name="map-value"> </form> {% for p in points %} {% if p.id == form.input.value %} //i will show sth here {% endif %} {% endfor %} -
Why my own css file is not loading after installation of django-cripsy-form?
I created an website using django (HTML, CSS etc). Everyithing was fine until I wanted to add a login/register form. I used django, templates. But when I installed django-crispy-forms my css was not loading anymore. Only the register form looks good now but the other stuff like logo, menu, etc are ignoring my css. That's how I loaded my css and it worked until django-crispy-forms {% load static %} <link rel="stylesheet" href="{% static 'css/style.css' %}"> <link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}"> Only below form looks good due to the django-crispy-forms package. {% load crispy_forms_tags %} <div class="container pt-5"> <form method="POST" class="form-group"> {% csrf_token %} {{ form|crispy }} <button type="submit" class="btn btn-success">Register </button> </form> </div> -
Dockerfile. Can a CMD read an Argument?
I am new to docke but I am trying to do something like this in the dockerfile ARG ENV CMD echo $ENV CMD [ "manage.py","runserver", "0.0.0.0:8000", "--settings={ENV}" ] And I want to pass the ENV argument from the docker build as build-args. I want to run django based on the environment(staging/production/etc) but looks like CMD is not reading the argument. -
Can I Reorder a LIst Based On User Provided Values Using Only HTMX?
I have HTMX working. The code below is fully functional. The one piece I'd like to incorporate, I can't figure out how to do it. The user is able to provide a number rank...but when they click save, the view returns with the item at the top. Only after they click reload does the list sort itself based on how I defined the attributes with the model. Here's my HTML... <h1 class="title62">Tasks</h1> <button class="button36" hx-get="{% url 'MyTasks:create_task_form' %}" hx-target="#taskforms">Add Task</button> <div id="taskforms"></div> <div id="tblData"> {% if tasks %} {% for task in tasks %} {% include "partials/task_detail.html" %} {% endfor %} </div> {% endif %} <div hx-target="this" hx-swap="outerHTML" hx-headers='{"X-CSRFToken":"{{ csrf_token }}"}' class="" > <form method="POST"> {% csrf_token %} <div class="table22"> <table class="table23"> <thead> <tr> <th class="title67">Number</th> <th class="title67">Task</th> </tr> </thead> <tbody> <button class="button35" hx-post="."> Save </button> <button type="button" class="button33"> Delete </button> <tr> <td class="title73">{{ form.number }}</td> <td class="title73">{{ form.task }}</td> </tr> </tbody> </table> </div> </form> </div> <script> document.body.addEventListener('htmx:configRequest', (event) => { event.detail.headers['X-CSRFToken'] = '{{ csrf_token }}'; }) </script> <div hx-target="this" class=""> <div class="table22"> <table class="table23"> <thead> <tr> <th class="title67">Number</th> <th class="title67">Task</th> </tr> </thead> <tbody> <button class="button35" hx-get="{% url 'MyTasks:update_task' task.id %}" hx-swap="outerHTML"> Update </button> <button class="button34" hx-confirm="Are you sure you … -
pytest how to run tests / django
I'm trying to use pytest for the 1st time in my new created app but i'm facing problems with running it. I still receive 'no tests ran in...' message. My project name is PROJECT, then is my app called diet_app and file tests.py inside the app folder. How to run tests? I tried with: pytest pytest tests pytest diet_app To be more precise - to install pytest i used: pip install pytest pip install pytest-django Maybe I'm missing something obvious but as i said - this is my 1st time using it. I'm working in Pycharm -
comparing value from inputfield with django model data
I have already made an app that allows me to study. It contains multiple test with multiple question with one correct answer each. class Test(models.Model): name = models.CharField(max_length=200) #questions = models.ManyToManyField(Question) author = models.ForeignKey(User, on_delete=models.CASCADE, default=None, null=True, blank=True) date_posted = models.DateTimeField(auto_now_add = True) def get_questions(self): return self.question_set.all() def __str__(self): return self.name class Question(models.Model): text = models.CharField(max_length=200, null=True) test = models.ForeignKey(Test, on_delete=models.CASCADE) created = models.DateTimeField(auto_now_add = True) def get_answer(self): return self.answer_set.all() def __str__(self): return self.text class Answer(models.Model): text = models.CharField(max_length=200) question = models.ForeignKey(Question, on_delete=models.CASCADE, related_name='parent') def __str__(self): return self.text I made JS funtion that compare user answer from input field with correct answer put in html function PointsCounter(){ var points = 0; const elements = document.querySelectorAll('.question-container'); Array.from(elements).forEach((element, index) => { var CorrectAnswer = (((element.querySelector('div form p')).innerHTML).toLowerCase()).trim(); var UserAnswer = (((element.querySelector('div form p input')).value).toLowerCase()).trim(); if(UserAnswer == CorrectAnswer){ points++; }}) document.getElementById("points").innerHTML=points; } Instead of putting correct answer in my html code: <p id="ans" hidden>{{ question.parent.all.last }}</p> I'd like to compare user answer with answer from database, but I do not know how to achieve it. I mean, i'd like to pass correct answer to js function to disallow user to check answer by inspecting html code of page. How can I make it … -
How to update an object with function base views?
Here i'm updating my object with PUT method. When I git the api. It only update those fields which are blank. Those fields which has some text or data already are not updating.. this is data i put : { "email": "main@gmail.com", "first_name": "yes same", //this field has already value and this is not updating "middle_name": null, "last_name": "in", "age": null, "gender": null, "bio": null, "city": null, "street_address": null, "state": "punjab", // this field was null and i gave it some value and it updated "country": "pakistan" // this field was null and i gave it some value and it updated } Object in response : "data": { "id": 1, "email": "main@gmail.com", "first_name": "ma", "middle_name": null, "last_name": "in", "age": null, "gender": null, "bio": null, "city": null, "street_address": null, "state": "punjab", "country": "pakistan" } My code : @api_view(['GET','PUT']) @permission_classes([IsAuthenticated]) @csrf_exempt def update_profile(request,id): profile = UserProfile.objects.if_obj_exists(id) print(profile) if request.method=="GET": serializer = UserProfileSerializer(profile, many=False) return Response({"status":"success","message": "Ok", "data": serializer.data},status=status.HTTP_200_OK) elif request.method=="PUT": serializer = UserProfileSerializer(instance=profile,data=request.data) print(serializer.is_valid()) if serializer.is_valid(): serializer.save() return Response({"data": serializer.data},status=200) return Response({"status":"fail","message": "something went wrong"},status=400) -
How can I check if two objects from differente models equal each other in Django?
I have 2 models, one for Students and another for Faculty. I need to print all Students from one specific Faculty. Model for Faculty class Fakultet (models.Model): fakultet_naziv=models.CharField(max_length=30) fakultet_adresa=models.CharField(max_length=30) fakultet_kontakt_broj=models.CharField(max_length=20) fakultet_email_referade=models.EmailField(default='') fakultet_website=models.URLField() def __str__(self): return self.fakultet_naziv Model for Students class Student (models.Model): student_ime=models.CharField(max_length=30) student_prezime=models.CharField(max_length=30) student_jmbag=models.CharField(max_length=10, primary_key=True) student_adresa=models.CharField(max_length=30, default='') student_email=models.EmailField(default='') student_fakultet=models.ForeignKey(Fakultet, on_delete=models.CASCADE, default='') student_cijepljen=models.BooleanField(default=True) student_cjepivo=models.ForeignKey(Cjepivo, on_delete=models.CASCADE, default='') student_datum_cijepljenja=models.DateTimeField(default=timezone.now) student_datum_isteka_potvrde=models.DateTimeField(default=timezone.now) student_prebolio_covid=models.BooleanField(default=False) def __str__(self): return self.student_jmbag First i tried this method and it didn't work. It didn't show any students at all. def fakultetstudent(request): fakultet = Fakultet.objects.values_list('fakultet_naziv', flat=True) fakultetstudent = Student.objects.filter(student_fakultet__in=fakultet).exists() context = {'fakultetstudent' : fakultetstudent} return render(request, 'main/fakultetstudent.html', context = context) After that i tried this and def fakultetstudent(request): fakultet = Fakultet.objects.values_list('fakultet_naziv') student = Student.objects.values_list('student_fakultet') context = {'faklutet' : fakultet, 'student' : student} if fakultet == student: return render(request, 'main/fakultetstudent.html', context = context) and error is: The view main.views.fakultetstudent didn't return an HttpResponse object. It returned None instead. Pleas help me with this problem. -
Create a JavaScript chart in HTML with a date selector
I used gspread and pandas to convert my google sheet into a list of dictionaries. My google sheet is shown as the following list: (It's a very long list, so I only list a few lines) mylist= [{'Date': '2021-10-02', 'ID': 11773, 'Receiver': Mike}, {'Date': '2021-10-02', 'ID': 15673, 'Receiver': Jane}, {'Date': '2021-10-03', 'ID': 11773, 'Receiver': Mike}, ... {'Date': '2021-12-25', 'ID': 34653, 'Receiver': Jack}] It's a Django project, so my data is defined in views.py: I count the number of records with Mike, Jane and Jack. tsheet2022 = client.open('Return Record 2022') tinstance2022 = tsheet2022.get_worksheet(0) mylist = tinstance2022.get_all_records() mike=len(tuple(d for d in t2022 if d['Receiver'] == 'Mike')) jane=len(tuple(d for d in t2022 if d['Receiver'] == 'Jane')) jack=len(tuple(d for d in t2022 if d['Receiver'] == 'Jack')) count = [mike, jane, jack] I have already drawn a pie chart based on my total counted data in my chart.HTML file : <!-- pie Chart --> <div class="col-xl-4 col-lg-4"> <div class="card shadow mb-4"> <div class="card-header py-3 d-flex flex-row align-items-center justify-content-between"> <h6 class="m-0 font-weight-bold">Team Chart</h6> </div> <!-- Card Body --> <div class="card-body"> <div class="chart-area"> <canvas id="myPieChart"></canvas> <script> var ctx = document.getElementById("myPieChart"); var myPieChart = new Chart(ctx, { type: 'doughnut', data: { labels: ["Mike", "Jane", "Jack"], datasets: [{ data: … -
Cannot run django function
I am following a tutorial on youtube on learning Django.The person i am following is using a macbook and i am on windows.The person run this command in his terminal trying to start a new project and he entered this code django-admin startproject storefront and he was successfull.But when i tried it for windows it gave an error. I googled the error and got a solution python -m django startproject storefront Then the man wanted to run the server using this code manage.py runserver and he was successfull but when i tied on windows it gave this error mange.py' is not recognized as an internal or external command, operable program or batch file. -
App loaded in Django admin, but doesn't showing up
I am trying to add my app to django admin panel. I have 3 apps: users orders advertisements All this applications loaded in settings.INSTALLED_APPS correctly, but django-admin showing up only two apps: users and orders. The most interesting in this situation is that in source code of html file for django-admin panel all apps are loaded, but app advertisements doesn't showing up. As you can see below, code for advertisements app is loaded in html file. When I try to go on links for this app in a tags, i see only white screen on opened page, but source code for page is loaded too. Thanks a lot for any help. <div id="content-main"> <div class="app-advertisements module"> <table> <caption> <a href="/admin/advertisements/" class="section" title="Models in the Advertisements application">Advertisements</a> </caption> <tr class="model-advertisingspacecategory"> <th scope="row"><a href="/admin/advertisements/advertisingspacecategory/">Advertising space categorys</a></th> <td><a href="/admin/advertisements/advertisingspacecategory/add/" class="addlink">Add</a></td> <td><a href="/admin/advertisements/advertisingspacecategory/" class="changelink">Change</a></td> </tr> <tr class="model-advertisingspace"> <th scope="row"><a href="/admin/advertisements/advertisingspace/">Advertising spaces</a></th> <td><a href="/admin/advertisements/advertisingspace/add/" class="addlink">Add</a></td> <td><a href="/admin/advertisements/advertisingspace/" class="changelink">Change</a></td> </tr> </table> </div> <div class="app-auth module"> <table> <caption> <a href="/admin/auth/" class="section" title="Models in the Authentication and Authorization application">Authentication and Authorization</a> </caption> <tr class="model-group"> <th scope="row"><a href="/admin/auth/group/">Groups</a></th> <td><a href="/admin/auth/group/add/" class="addlink">Add</a></td> <td><a href="/admin/auth/group/" class="changelink">Change</a></td> </tr> </table> </div> <div class="app-orders module"> <table> <caption> <a href="/admin/orders/" class="section" title="Models in the Orders … -
Howto Python Request in Django
I am very new to Django, I am trying to request informations from another side to display them on my own. My site works and outside of Django I can request. I have no idea how to request and display the informations in Django neither where to do this in the project. Please help. models.py: from django.db import models class Form(models.Model): ipName = models.CharField(max_length=100) ipAddress = models.CharField(max_length=100) ipKey = models.CharField(max_length=100) ipSecret = models.CharField(max_length=100) ipMask = models.CharField(max_length=100) ipWahrheit = models.BooleanField(default=True) def __str__(self): return self.ipName views.py: from django.shortcuts import render from django.http import HttpResponse from .models import Form import requests def home(request): context = { 'ox': Form.objects.all() } return render(request, 'Ips/home.html', context) home.html: {% extends "Ips/Ips.html" %} {% block content %} {% for ip in ox %} <article class="media content-section"> <div class="media-body"> <div class="article-metadata"> <a class="mr-2" href="#">{{ ip.ipName }}</a> <small class="text-muted">{{ ip.ipAddress }}</small> </div> <p class="article-content">{{ ip.ipName }}</p> </div> </article> {% endfor %} {% endblock content%} With the Informations i get from Form i want to make an request to that Ip address and get back a jason. -
Django contact form sending email back to my own email address
views.py def contact(request): if request.method == "POST": username = request.POST['username'] phone = request.POST['phone'] customer_email = request.POST['customer_email'] subject = request.POST['subject'] message = request.POST['message'] #send Email send_mail(subject, message, customer_email, ['myemail@gmail.com']) return render(request, 'contact.html', {'username': username }) else: return render(request, 'contact.html', {}) This is my html <form method="post" action="{% url 'contact' %}" id="contact-form"> {% csrf_token %} <div class="row clearfix"> <div class="col-lg-6 col-md-6 col-sm-12 form-group"> <input type="text" name="username" placeholder="Name" required=""> </div> <div class="col-lg-6 col-md-6 col-sm-12 form-group"> <input type="text" name="phone" placeholder="Phone" required=""> </div> <div class="col-lg-6 col-md-6 col-sm-12 form-group"> <input type="email" name="customer_email" placeholder="Email" required=""> </div> <div class="col-lg-6 col-md-6 col-sm-12 form-group"> <input type="text" name="subject" placeholder="Subject" required=""> </div> <div class="col-lg-12 col-md-12 col-sm-12 form-group"> <textarea name="message" placeholder="Message"></textarea> </div> <div class="col-lg-12 col-md-12 col-sm-12 form-group"> <button class="theme-btn btn-style-one" type="submit" name="submit-form">Submit Now</button> </div> </div> </form> This is the form I have that should send an email to customer_email, but instead I am getting the email back to me. That is, sender and recipient are both same. What is the issue here. Also is it possible to add the customer's email and phone number in the email message itself. Kindly help. -
'ASGIRequest' object has no attribute 'Get'
Got an error when trying django (4.0.2), the error thrown was: 'AsgiRequest' object has no attribute 'Get' Running with channels 3.0.4, Django 4.0.2, python 3.8 Running via python3 manage.py runserver from django.shortcuts import render,redirect from django.contrib import messages from .models import * # Create your views here. def home(request): if request.method == 'post': username=request.POST.get('username') option=request.POST.get('option') room_code=request.POST.get('room_code') if option=='1': game=Game.objects.filter(room_code=room_code).first() if game is None: messages.success(request, 'Room code not found') return redirect('/') if game.is_over: messages.success(request, 'Game is over') return redirect('/') game.game_opponent=username game.save() else: game=Game(game_creater=username,room_code=room_code) game.save() return redirect('/game/'+room_code+'?username=' + username) return render(request, 'home.html') def game(request, room_code): username=request.Get.get('username') context={'room_code': room_code , 'username' : username} return render(request, 'play.html', context) -
Django Like Button Post not showing on html site
I have followed an online tutorial to add a like button to my website/index html file, but for some reason it is not showing on the site. It must be witht the url or views files, but I can not figure it out. Below is the code. The models that I am trying to pull are migrated and work. If anybody has any tips that I could try I woudl greatly apprechiate it. views file: **from django.shortcuts import render, redirect from django.http import JsonResponse import json import datetime from .models import * from .utils import cookieCart, cartData, guestOrder from .models import Post, Like # Create your views here. def index(request): return render(request, 'index.html', {}) def post_view(request): qs = Post.objects.all() user = request.user context = { 'qs': qs, 'user': user, } return render(request, 'posts/postlike.html', context) def like_post(request): user = request.user if request.method == 'POST': post_id = request.POST.get('post_id') post_obj = Post.objects.get(id=post_id) if user in post_obj.liked.all(): post_obj.liked.remove(user) else: post_obj.liked.add(user) like, created = Like.objects.filter(user=user, post_id=post_id) if not created: if like.value == 'Like': like.value = 'Unlike' else: like.value = 'Like' like.save() return redirect('post-list')** urls file: **from django.urls import path from . import views from .views import post_view, like_post urlpatterns = [ path('', views.index, name='index'), path('store/', … -
collapsing accordion content in django for loop
I am trying to implement for loop in my accordion. Everything seems to be fine except the fact that when I click on 3rd or 4th button then other bodies stay expanded. It should work exactly the same as in the first example in Bootstrap documentation so if you click on Accordion Item #2 then Accordion Item #1 and Accordion Item #3 collapse. I am sure that the issue is with my {% if forloop.first %} but I am not sure how can I dynamically change that so it will collapse all accordion contents except active one. My code: {% for category in top_categories %} <div class="accordion" id="accordionExample"> <div class="accordion-item"> <h2 class="accordion-header" id="heading{{category.id}}"> <button class="accordion-button" type="button" data-bs-toggle="collapse" data-bs-target="#collapse{{category.id}}" aria-expanded="false" aria-controls="collapse{{category.id}}"> {{category.title}} </button> </h2> <div id="collapse{{category.id}}" class="accordion-collapse {% if forloop.first %} show {% else %} collapse {% endif %}" aria-labelledby="heading{{category.id}}" data-bs-parent="#accordionExample"> <div class="accordion-body"> {% for qa in category.qa.all|slice:"0:3" %} <a href="{{ qa.get_absolute_url }}">Q: {{qa}}</a><hr> {% endfor %} </div> </div> </div> </div> {% endfor %} -
"AttributeError: 'list' object has no attribute 'items'" While importing Json
I get the following error when i try to use the "deleted" part of my json file to change one field (ReportedStatusField) for each "Facility" in my Database that matches with the id's inside "deleted": File "C:\users\management\commands\deactivate_facilities.py", line 42, in handle for key, data in data_object.items(): AttributeError: 'list' object has no attribute 'items' It's basically a list of UUID's of Facilities that closed so i change the status this way with a json file that gets imported with a url. import requests import json from users.models import Facility from django.core.management.base import BaseCommand IMPORT_URL = 'https://domain/file.json' class Command(BaseCommand): def import_facility_from_file(self, data): key = data.get('key', None) if Facility.objects.filter(key=UUID): msg = "\n\nFacility closed: {}\n{}".format(key, str()) print(msg) facility, facility_closed = Facility.objects.update_or_create(key=UUID, defaults={ 'ReportedStatusField': 'closed' } ) def handle(self, *args, **options): headers = {'Content-Type': 'application/json'} response = requests.get( url=IMPORT_URL, headers=headers, ) response.raise_for_status() data = response.json() for key, data_object in data.items(): if key in ["deleted"]: for key, data in data_object.items(): self.import_facility_from_file(data) My JSON { "added": {"125hk24h5kjh43k5": { "UUID":"125hk24h5kjh43k5", "Name":"Test Facility 1", "AddressInfo": {"PrimaryAddress":"1234 Drive RD"}, "ImporterLastModifiedTimestamp":1643721420}}, // This is the "list" of deleted Facilities "deleted":["235hk24h5kjh43k5,235hk345789h43k5"], "modified":{"995hk24h5kjh43k5": { "UUID":"995hk24h5kjh43k5", "Name":"Test Facility 2", "AddressInfo": {"PrimaryAddress":"2345 Test RD"}, "ImporterLastModifiedTimestamp":1643721420} } } -
Django advanced model operation
I do have such operation: Contact.objects.filter(contact_code__icontains=my_string[-8:]).exists() I want to find my_string[-8:] not in the beggining, not at the end but strictly on x position in contact_code. Or I want to splite contact_code field, them do MD5 on it and only then look on it? How can I manipulate model query here? I can do it in raw sql and want to do it in model filter - not in code. -
operator does not exist: character varying[] = text[] in django?
models.py from django.contrib.postgres.fields import ArrayField class Product(DateTimeModel): colors = ArrayField(models.CharField(max_length=500),null=True, blank=True) # I am having => black,red views.py def filters(request): color_filters = request.GET.getlist('colors', default=None) # from form ['red'] products = Product.objects.filter(colors__in=l) print(products) When I am performing this I am getting this error ProgrammingError at /product/filter-query/ operator does not exist: character varying[] = text[] HINT: No operator matches the given name and argument types. You might need to add explicit type casts. How to perform this. please needed help. -
Django - modelform + model property
I am trying to solve one issue about saving data in db. This is an example how I think of it: class MyModel(models.Model): id = models.AutoField(primary_key=True) fieldX = models.SomeFieldType() @property: def foo(self): return self._foo @foo.setter def foo(self, var): self._foo=var class MyModelForm(models.Modelform): class Meta: model = models.MyModel fields = '__all__' The thing is I have dict that I am passing to this form (so I am not using view or any provided interaction with user directly. In dict I have some fields and what I want to do is one field that is passed to use it as model property but I do not want it to be saved in db. So I tried something like: form = MyModelForm(data_dict) if form.is_valid(): form.foo = data_dict['data_for_property_not_db'] form.save() Form does not know that my model has this property. So basiclly what I want is to write some parts of my data_dict normaly to form and db as always ->works fine and then I want some data_info pass to that property and use it somewhere in save() as needed without saving it to db itself. Can you help me with this?