Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django add select2
i try to add the Select2 in my django app but i can't use it. What i do wrong ? Anyone have a solution ? page.html <!----Select2-----> <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" /> <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script> <!----Select2-----> <script> $(document).ready(function() { $('#id_employe').select2(); }); </script> Filter from the form -
How to extract values from Queryset Django
When an output is received in the below form after running the query <QuerySet [<key: value object (ad5bb6b4-8035)>]> I want to get ad5bb6b4-8035 string only for further operations. So I tried course_qs = <QuerySet [<key: value object (ad5bb6b4-8035)>]> for course in course_qs: print(course) which returned value object (ad5bb6b4-8035) How to get only ad5bb6b4-8035.? getting values of QuerySet in django How to extract numerical value from Django queryset? Extracting message from django queryset -
Image not saving to django models when trying to upload from react-native
I am writing my first react-native app with a django backend. In order for my app to function properly, I need to send an image from the react-native to django models. I am trying to send an image and then save it to the model, but when I check the django-admin the image field is empty. heres my code- react-native: const [ sentI, setSentI ] = useState(null) const sendI = async (image) => { const formData = new FormData() image_data = { uri : image.uri, name : "profileImage", type : 'image/jpg' } if (image != null){ await formData.append( 'image', image.uri,) await formData.append( 'name', usern,) setSentI(formData) console.log('recieved') } console.log(formData) } const showImagePicker = async () => { // Ask the user for the permission to access the media library const permissionResult = await ImagePicker.requestMediaLibraryPermissionsAsync(); if (permissionResult.granted === false) { alert("You've refused to allow this appp to access your photos!"); return; } let result = await ImagePicker.launchImageLibraryAsync({ mediaTypes: ImagePicker.MediaTypeOptions.All, allowsEditing: true, aspect: [4, 3], quality: 1, }); // Explore the result console.log(result); if (!result.cancelled) { await setProfileImage(result); console.log(result.uri); sendI(result); } } const image = () => { fetch(`http://192.168.5.234:8000/home/imagetest/`, { method: 'POST', body: { sentI }, }) .then( res => res.json()) .then( res … -
Django: self.model_set not accesible in custom save() function
I'm trying to make a custom save function that calculates some values and will store them in another Model to which a ManyToMany relationship exists. From what I can understand from the documentation, I should have a field_set way of accessing all the related objects. However, when I save here, I get the error 'Game' object has no attribute 'heat_set' I don't see what I'm doing wrong here: class Game(models.Model) heat = models.ManyToManyField(Heat) [...] def save(self, *args, **kwargs): super().save(*args, **kwargs) for heat in self.heat_set.all(): [...] -
Django Rest Framework value id is being sent, but is being received as null
Having an issue where I am trying to set the interest_category. Here is my current code. Serializer class ProjectsSerializer(serializers.ModelSerializer): interest_category = serializers.StringRelatedField() class Meta: model = Project read_only_fields = ( 'created_by', 'created_at', 'updated_at', ), fields = ( 'project_title', 'project_description', 'interest_category', ) Model class Project(models.Model): project_title = models.CharField(max_length=255) project_description = models.TextField(max_length=1500) interest_category = models.ForeignKey(Interests, on_delete=models.CASCADE) created_by = models.ForeignKey(User, related_name='projects', on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now_add=True) Views class ProjectViewSet(viewsets.ModelViewSet): serializer_class = ProjectsSerializer queryset = Project.objects.order_by('-created_at') def perform_create(self, serializer): serializer.save(created_by=self.request.user) Here is the data being sent { "project_title": "Test", "project_description": "Test1", "interest_category": 2 } Here is the data being received (35, Test, Test1, 2022-09-22 02:11:54.342202+00, 2022-09-22 02:11:54.342202+00, 1, null). I can send the data without a null error when I am NOT using the interest_category = serializers.StringRelatedField() in the serializer. Any ideas why the interest_category is showing null and why it is not being sent and/or received correctly when using the serializers.StringRelatedField()? And if it is because of the StringRelatedField is there a better way to get the name while posting the ID? In frontend, I am passing the ID as a value. -
best way to store celery results
I am using celery for my async tasks, however, I am using Redis as backend broker. My current plan is to filter and manipulate data inside the backend and store it into django-db for viewing etc. Is this the recommended way? Or I should use Django DB as backend results db and store all the raw data then filter and manipulate it into different tables? -
Django ORM query for filtering product price between two number is not working properly
class Product(models.Model): product_name = models.CharField(max_length=255,unique=True) slug = models.SlugField(max_length=255) brand = models.CharField(max_length=255) price = models.CharField(max_length=255) product_image_1 = models.ImageField(upload_to = 'photos/product',blank = False) product_image_2 = models.ImageField(upload_to = 'photos/product', blank = False) product_image_3 = models.ImageField(upload_to = 'photos/product', blank = False) product_image_4 = models.ImageField(upload_to = 'photos/product',blank = False) product_description = models.TextField() category_id = models.ForeignKey(Categories,on_delete=models.CASCADE) subcategory_id = models.ForeignKey(SubCategories, on_delete=models.CASCADE) stock = models.IntegerField(default=0) created_at = models.DateTimeField(auto_now_add=True) is_active = models.BooleanField(default=True) def __str__(self): return self.product_name def get_url(self): return reverse('product_detail',args = [self.category_id.slug , self.subcategory_id.slug, self.slug ]) '''view''' val=request.POST.get('value') val = re.findall("\d+", val) # code to get all inigers from string min_price = int(val[0]) max_price = int(val[1]) print(min_price) print(max_price) ***product = Product.objects.filter(category_id = categories,is_active = True,price__gte = min_price, price__lte = max_price)*** when i give value greater than max_value product object returns null object I want all objects between the two min_value and max_value -
Django is not serving my image asset, using rest framework
I am uploading an image file from Flutter to Django, the image is getting saved properly in my backends directory under assets/images, and when I query the database with a get I get the proper path of the file. But when I go to the URL in the browser the image does not appear and I get an error. I am using rest-framework for my app. Model: class Product(models.Model): supplier = models.ForeignKey(Supplier, on_delete=models.CASCADE) name = models.CharField(max_length=200) quantity = models.IntegerField(default=0) barcode = models.CharField(max_length=200) cost_price = models.FloatField(default=0) selling_price = models.FloatField(default=0.0) image = models.ImageField(upload_to='images/', null=True) Settings.py: MEDIA_ROOT = os.path.join(BASE_DIR, 'assets') MEDIA_URL = '/pm/assets/' Urls.py: urlpatterns = [ path('', include(router.urls)), ] urlpatterns += staticfiles_urlpatterns() urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Serializer: class SuppliersSerializer(serializers.ModelSerializer): product_set = ProductsSerializer(read_only=True, many=True) class Meta: model = Supplier fields = ['pk','user','name','email','phone','product_set'] class ProductsSerializer(serializers.ModelSerializer): transactions_set = TransactionsSerializer(read_only=True, many=True) class Meta: model = Product fields = ['pk','name','quantity','barcode','cost_price','image', 'selling_price', 'transactions_set'] JSON response: { "pk": 13, "name": "pi3", "quantity": 3, "barcode": "11111", "cost_price": 10.0, "image": "/pm/assets/images/533a6ac0-f682-4814-9237-89df8e02fda715039130977982609.jpg", "selling_price": 20.0, "transactions_set": [] }, But when visiting: http://localhost:8000/pm/assets/images/533a6ac0-f682-4814-9237-89df8e02fda715039130977982609.jpg I get this error: -
Is there any way with django tables2 to only show data based off any given information
I have looked all over not sure if I am searching to broadly. I want to essentially only show data to a user if that user is linked to the data. Currently it shows all data. Example of similar function. {% for group in request.user.groups.all %} {% if group.name == 'General User' %} {% for project in project_card_list %} {% for u in project.assigned_users.all %} {% if u == user %} This is just a quick example of what I want, I was able to display the data this way but was wanting to clean it up and have it show in a django table2 table instead. Table code: class ProjectTable(tables.Table): class Meta: model = Project template_name = "django_tables2/bootstrap.html" fields = ("name", "project_lead", "start_date", "end_date", "description") exclude = ("project_id", "assigned_users",) View: @login_required(login_url='login_register') def projects_page(request): table = ProjectTable(Project.objects.all()) return render(request, 'projects.html', {'table': table}) -
Tools used to build Stack Overflow
Creating a blog site is difficult what should I use Django and heroki or what ?? What should a blog Site Contain ? Can I create an alternative to Stack Overflow -
hi i have problem with django and front_end
I want to build an online store and I want to enter the number of products that the customer wants to enter in the front and then send it to Django, for example, if he says 6 apples, I will change the number of apples to 6 in Django. -
Having a problem integrating this google calendar keep getting null setting src (Netsuite)
this is my code, and I am trying to be able to switch between different calendars. But it wont let me function googleCalendars(portlet, column) { var calendarSelect; portlet.setTitle("Sportex Calendars"); calendarSelect = portlet.addField("calendar_select", "select", "Select Calendar"); calendarSelect.setHelpText("Select a calendar"); calendarSelect.addSelectOption("humanresources", "Human Resources"); calendarSelect.addSelectOption("vacation", "Vacations"); calendarSelect.addSelectOption("appointments", "Appointments"); portlet.addField("calendar", "inlinehtml", "Some HTML").setLayoutType("outsidebelow", "startrow").setDefaultValue("" + "<div>" + '<<iframe src="https://calendar.google.com/calendar/embed?height=600&wkst=1&bgcolor=%23ffffff&ctz=America%2FPhoenix&showCalendars=0&src=c3BvcnRleGNhbGVuZGFyQGdtYWlsLmNvbQ&src=YWRkcmVzc2Jvb2sjY29udGFjdHNAZ3JvdXAudi5jYWxlbmRhci5nb29nbGUuY29t&src=ZW4udXNhI2hvbGlkYXlAZ3JvdXAudi5jYWxlbmRhci5nb29nbGUuY29t&src=aHQzamxmYWFjNWxmZDYyNjN1bGZoNHRxbDhAZ3JvdXAuY2FsZW5kYXIuZ29vZ2xlLmNvbQ&color=%23039BE5&color=%2333B679&color=%230B8043&color=%23B39DDB" style="border:solid 1px #777" width="1200px" height="600px" frameborder="1" scrolling="no"></iframe>' + "</div>"); portlet.addField("resizer", "inlinehtml", "CSS Overrides for Portlet Content Resizing").setDefaultValue("" + "<style>" + "ns-script-portlet-content-wrapper iframe," + "#main_form table, #cal_frame {" + "width: 100%;" + "}" + "</style>"); portlet.setScript("customscript_googlecalendar_client")} function fieldChange(type, name) { if(name == "calendar_select") { if(nlapiGetFieldValue("calendar_select") == "humanresources") { document.getElementById("cal_frame").src = "https://calendar.google.com/calendar/embed?src=833451c59dcb80fff2263f6cfb17fa5ae246b70d97588f1ef46ffbc04658433b%40group.calendar.google.com&ctz=America/Phoenix" }else { if(nlapiGetFieldValue("calendar_select") == "vacation") { document.getElementById("cal_frame").src = "https://calendar.google.com/calendar/embed?src=f61df42873f6d090babb273c46cd295f12795c08647b8c18088d25691cb653fb%40group.calendar.google.com&ctz=America%2FPhoenix" }else { if(nlapiGetFieldValue("calendar_select") == "appointments") { document.getElementById("cal_frame").src = "https://calendar.google.com/calendar/embed?src=clto48tqq2vmp19sfuqra8oprc%40group.calendar.google.com&ctz=America/Phoenix" } } }}nlapiResizePortlet()}; -
Always Defer a Field in Django
How do I make a field on a Django model deferred for all queries of that model? Research This was requested as a feature in 2014 and rejected in 2022. Baring such a feature, the obvious idea is to make a custom manager like this: class DeferedFieldManager(models.Manager): use_for_related_fields = True def __init__(self, defered_fields=[]): super().__init__() self.defered_fields = defered_fields def get_queryset(self, *args, **kwargs): return super().get_queryset(*args, **kwargs ).defer(*self.defered_fields) class A(models.Model): big_field = models.TextField(null=True) b = models.ForeignKey(B, related_name="a_s") objects = DeferedFieldManager(["big_field"]) class B(models.Model): pass class C(models.Model): a = models.ForeignKey(A) class D(models.Model): a = models.OneToOneField(A) However, while this works for A.objects.first() (direct lookups) and B.objects.first().a_s.all() (one-to-manys), it doesn't work for C.objects.first().a (many-to-ones) or D.objects.first().a (one-to-ones). An easy way to test this is to drop the field that should be deferred from the database, and the code will only error with an OperationalError: no such column if the field is not properly deferred. How do I make this field deferred for all ways this model is loaded (without needing to put a defer call on every query)? -
Django/python retrieving integer value from models.integerfield
class Trainingvalue(models.Model): maximalvalue= models.PositiveIntegerField(null=True,blank=True) How can I retrieve integer from maximal value , in order to use in a views.py function like to create another variable to render it to context dictionary ? -
django-filter IN lookup filter and list of strings
Using Graphene in Django to create Gql schema, now trying to filter Foreign Keys with list of strings. It kinda works, but not exactly. schema.py class CharInFilter(BaseInFilter, CharFilter): pass class ProductFilter(FilterSet): softwares__name = CharInFilter(field_name="softwares__name", lookup_expr="in") class Meta: model = Product fields = {"name": ["exact", "icontains"]} class ProductType(DjangoObjectType): class Meta: model = Product filterset_class = ProductFilter interfaces = (graphene.relay.Node,) query query authorPageProducts { user(slug: "john") { productSet(softwares_Name: "Blender") { edges { node { name softwares { name } } } } } } Here is what works and what not: softwares_Name: "Blender" -> correct softwares_Name: "Houdini" -> correct softwares_Name: "Blender,Houdini" -> empty result, not correct I am passing string separated with comma. Can/should I pass list of strings in Gql query? Im not sure if its possible/necessary. I do have Products that have both Foreign Keys with values "Houdini" and "Blender", so query with "Blender,Houdini" shouldn't be empty. I tried this query in shell, and its correct. Here I used list of strings. u = User.objects.get(id=2) p = u.product_set.filter(softwares__name__in=["Blender", "Houdini"]) Here is some info from Django Debug Toolbar, to see SQL expression for third case. SELECT COUNT(*) AS "__count" FROM "shop_product" INNER JOIN "shop_product_softwares" ON ("shop_product"."id" = "shop_product_softwares"."product_id") INNER JOIN "shop_software" … -
Unable to search from hacker news api django
I would like to search different items (jobs, stories, ask) from the hacker news api but I can't seem to figure out how to do it correctly, please check code below and tell me what I'm doing wrong as I'm unable to run it successfully. def search(request): if 'search' in request.GET: search = request.GET['search'] url = 'https://hacker-news.firebaseio.com/v0/item/{item-id}.json?print=pretty' response = requests.get(url) article_list = response.json() context = {} context['objects'] = [] for each_id in article_list[:10]: # Make a separate API call for each article. url = f"https://hacker-news.firebaseio.com/v0/item/{each_id}.json" # get response for individual articles response = requests.get(url) article_dict = response.json() context['objects'].append(article_dict) return render(request, 'SyncNews/search.html', context) {% for x in objects %} <h3 class="news-subheading">{{ x.title }}</h3> {% endfor %} <form method="GET" action="{% url 'search' %}"> <input type="text" name="item-id" placeholder="Search" /> </form> -
Default task list in new instance of 'To Do' app in Django
I am learning Django and creating ToDo app. I need to get a hint on logic how to implement default task list while user is creating a new record (instance) of ToDo app. Simply, I want to avoid hardcoding of any specific task list into the HTML, rather I want to have pre-populated (based on app specifics) model class (from Django Admin) which will be added to ToDo app instance during CreateView. Also I wish to implement 'add task' feature within the ToDo app instance i.e. add any extra task user wants on top of default tasks. Hope my question is clear. -
DRF return JsonResponse from another function
I am trying to return the JsonResponse from another function but I get the following error from DRF: AssertionError: Expected a Response, HttpResponse or HttpStreamingResponse to be returned from the view, but received a <class 'NoneType'> Here is my code class SignedURL(GenericViewSet): queryset = fileUpload.objects.all() serializer_class = fileUploadSerializer def create(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) function1(request) def function1(request): return JsonResponse( { "message": "Pass", }, status=status.HTTP_400_BAD_REQUEST, How can I return the JsonResponse from another function without writing return JsonResponse in the def create itself? Further clarification: I have ten different functions with ten different Jsonresponses. ie, function2,function3...function10. If for example, function 4 fails, I would like to return the JSON response immediately from that function and not to proceed further with the other functions within the create call. -
Problem while creating a mofelform and editing a particular field in the modelform
I am in a middle of a project. The problem is arising from here : class PatientCreation(forms.ModelForm): class Meta: model = Patient fields = ['user','contact'] dob = forms.DateField(widget=forms.SelectDateWidget(years=range(1960,2022))) Whenever i try to save the form by using the frontend its creating an error. The model for this form is : class Appointments(models.Model): doctor = models.ForeignKey(Doctor, on_delete=models.CASCADE) patient = models.ForeignKey(Patient, on_delete=models.CASCADE) app_time = models.DateTimeField() diognoses = models.TextField(max_length=1000) prescriptions = models.TextField(max_length=250) class Meta: unique_together = ('doctor', 'patient', 'app_time') def __str__(self): st = (str(self.doctor.user.name)+str(self.patient.user.name)).lower().strip() return st I am not sure if i can even define a particular field in a model form or not else the widget is working fine. So how can I implement the logic such that I get the date time widget in dob field. Also how can i default the value of the user field as the currently logged in user. -
django app app crashing when opening on heroku
I'm trying to open my heroku app but i keep getting the 'heroku logs --tail' error. I checked the logs and the only error I can see is: 'ImportError: cannot import name '_sanitize_token' from 'django.middleware.csrf' (/app/.heroku/python/lib/python3.10/site-packages/django/middleware/csrf.py)' FYI, I had some issue with the _sanitize_token when trying to run my server with manage.py before deploying. I had to change some settings in tastypies authentication: original(wouldn't let me run server): from django.middleware.csrf import _sanitize_token amended(this let me run the server): import django.middleware.csrf Now, I don't know wether the error above is actually causing the crash or if i should be looking into this: at=error code=H10 desc="App crashed" TYIA for any help on this -
how to add django-database-size to django project view?
I am trying to use django-database-size to display mysql table sizes to django admin page. The project has very limited docs to how to add the view. Here is the repo: https://github.com/chrisspen/django-database-size All it mentions about adding the view: Install the appropriate view in /sql (currently only PostgreSQL and MySQL supported). -
Does foreign key have to be primary key in Django?
Can we use any other unique column as foreign key in django model? -
Integrity Error NOT NULL constraint failed even though I have set blank=True, null=True in my model
Im getting a NOT NULL constraint error in my code when trying to save my model form, even though the fields I have left empty are optional (have set blank=True, null=True) in models.py Im very confused, what am I doing wrong? The error is popping up when I leave the first optional field blank (description). Filling any of them manually before work.save() pushes the issue to the next field, and passes when all fields are filled. EDIT: this also happens when trying to create a work instance from the admin dashboard. models.py class Work(models.Model): ## core fields creator = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True, default=None) created = models.DateTimeField() modified = models.DateTimeField() work_slug = models.SlugField(max_length=50) # slug -> TBD: find way to assign default value to slug = archival number. archive = models.ForeignKey(Archive, on_delete=models.CASCADE) # superfolder -> replaces category, series etc with dynamic hierarchical database folder = models.ForeignKey(Folder, on_delete=models.CASCADE) # basic metadata fields name = models.CharField(max_length=50) year = models.CharField(max_length=50) medium = models.CharField(max_length=50) description = models.CharField(max_length=1200, blank=True, null=True) # optional metadata authors = models.CharField(max_length=50, blank=True, null=True) classification = models.CharField(max_length=50, blank=True, null=True) location = models.CharField(max_length=50, blank=True, null=True) link = models.URLField(max_length=50, blank=True, null=True) record_creator = models.CharField(max_length=50, blank=True, null=True) # revisit -> # custom descriptors cd1_name … -
Connecting a Django App Deployed to IIS to a Sql Server Database
I'm currently having difficulties connecting my Django app to a SQL Server Database after I've deployed it to IIS. My current setting for the database is: DATABASES = { 'default': { "ENGINE": 'mssql', "NAME": 'databasename', "USER": 'myusername', "PASSWORD": 'mypassword', "HOST": 'host', "PORT": '', "OPTIONS": {"driver": "ODBC Driver 17 for SQL Server", "Trusted_Connection":'yes'}, }, } and with this setting, I keep getting the error message: ('28000', "[28000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Login failed for user 'myusername'. (18456) (SQLDriverConnect); [28000] [Microsoft][ODBC Driver 17 for SQL Server]Invalid connection string attribute (0); I've also tried using sql_server.pyodbc as the engine but also got the same error message. I was just wondering if there's anything else I would need to do for me to be able to connect my app to the database or if there's anything I would need to change in my current setting? -
Why django template not render tag after include tag
i consider that why template not render tag after {% include %}. when i put some tag like something in front of include tag, it work. But it not work if i try to put behind the include tag. :( in index.html <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-gH2yIJqKdNHPEq0n4Mqa/HGKIhSkIHeL5AyhkYV8i59U5AR6csBvApHHNl/vI1Bx" crossorigin="anonymous"> <link rel="stylesheet" href="{% static 'styles/main.css' %}" /> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/js/bootstrap.bundle.min.js" integrity="sha384-A3rJD856KowSb7dwlZdYEkO39Gagi7vIsF0jrRAoQmDKKtQBHUuLZ9AsSv4jD4Xa" crossorigin="anonymous"> </script> </head> <body> <div class="d-flex"> {% include 'navbar.html' %} <div class="content"> <div class="header"> {% include 'header.html' %} </div> <div> {% block subHeader %} {% endblock %} </div> <div> {% block list %} {% endblock %} </div> </div> </div> </body> </html> in list.html <table class="table"> <thead> <tr> <th scope="col">Cardinal Number</th> <th scope="col">ID</th> <th scope="col">Name</th> <th scope="col">Category</th> <th scope="col">Cost</th> <th scope="col">Note</th> <th scope="col">Image</th> <th scope="col">Action</th> </tr> </thead> <tbody> <tr> <th scope="row">1</th> <td>Mark</td> <td>Otto</td> <td>@mdo</td> </tr> <tr> <th scope="row">2</th> <td>Jacob</td> <td>Thornton</td> <td>@fat</td> </tr> <tr> <th scope="row">3</th> <td colspan="2">Larry the Bird</td> <td>@twitter</td> </tr> </tbody> </table> in products.html {% extends 'index.html' %} {% block subHeader %} {% include 'components/subHeader.html' with url="api/add-product" name="product" selectName="product-category" %} {% endblock subHeader%} {% block list %} {% include 'components/list.html' %} {% endblock content%} although i put whatever after include …