Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to filter an object with choice filed values in django_filter
I have following choice field in my model IPInfo class IPInfoModel(models.Model): TYPE_INTRANET = 1 TYPE_INTERNET = 2 IP_TYPES = ( (TYPE_INTRANET, u'INTRANET'), (TYPE_INTERNET, u'INTERNET'), ) ip = models.GenericIPAddressField("IP", unique=True) ip_type = models.SmallIntegerField(choices=IP_TYPES) and I use django_filters to filter IPInfo. from django_filters import rest_framework as django_filters class IPInfoFilter(django_filters.FilterSet): ip_type = django_filters.ChoiceFilter(choices=IPInfoModel.IP_TYPES) class Meta: model = IPInfoModel fields = ["ip_type",] class IPInfoViewSet(mixins.ListModelMixin, viewsets.GenericViewSet): queryset = IPInfoModel.objects.all() serializer_class = IPInfoSerializer filter_class = IPInfoFilter I want to filter IPInfo on ip_type. How can I filter IPInfo by either "INTRANET" or "INTERNET". not use "1" or "2". -
Mock an entire python module for django testcases
I'm currently trying to mock a credentials.py module which is not available during the tests when running them with Gitlab Runner in the pipeline (credentials are on .gitignore). My test_views.py looks like this: @patch('battery_upgrade_web.views.BatteryUpgradeView.credentials', new=credentials_example) class IndexViewTest(TestCase): @patch('battery_upgrade_web.views.BatteryUpgradeView.credentials', new=credentials_example) def setUp(self): # A client simulates a user interacting with the code at the view level # Lot of working mocks self.c = Client() @patch('battery_upgrade_web.views.credentials', new=credentials_example) def test_valid_data(self): resp = self.c.post('/', data={'parameter': 324}) My views.py: from battery_upgrade_web import credentials class BatteryUpgradeView(generic.TemplateView): def post(self, request, *args, **kwargs): #lot of code to execute My problem is, that I can't only patch the variables in credentials.py but I have to patch the whole module and replace it with credentials_example.py. My solution above works locally with existing credentials.py, it also mocks the credentials.py and replaces it with my credentials_example.py during tests. But when I delete credentials.py, the test throws following error message when running >python web/manage.py test battery_upgrade_web: Creating test database for alias 'default'... Traceback (most recent call last): File "web/manage.py", line 16, in <module> execute_from_command_line(sys.argv) # lot of tracebacks File "C:\Users\e\AppData\Local\Continuum\anaconda2\envs\BatteryUpgrade36\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_loal File … -
Django design model - when a data of status field changes, remaining models status change with it
Its my first time trying django as my first programming project. I have a hierarchy structure of Company -> Business -> Outlets using foreign key. I would like to know is there anyway to structured it in a way where the Company status is saved as inactive status, the remaining business, outlets models that will be triggered as inactive status. from django.db import models from django.contrib.auth.models import User # Create your models here. class Common_Info(models.Model): """(Common description)""" name = models.CharField(blank=True, max_length=100) slug = models.SlugField(unique=True, max_length=120) address_1 = models.CharField(max_length=50, null=True) address_2 = models.CharField(max_length=50, null=True) address_3 = models.CharField(max_length=50, null=True) post_code = models.CharField(max_length=6, null=False) registration_no. = models.CharField(max_length=15,null=False) gst_no. = models.CharField(max_length=15,null=True) telphone_no. = models.CharField(max_legth=15, null=False) fax_no. = models.CharField(max_legth=15, null=True) email_address = models.EmailField(max_length=254,null=False) """(Status choice)""" Active_Status = 1 Inactive_Status = 0 STATUS_CHOICES = ( (Active_Status, 'Active'), (Inactive_Status, 'Inactive'), ) status = models.IntegerField(choices=STATUS_CHOICES, default=Active_Status) create_date = models.DateTimeField(auto_now_add=True) create_user = models.ForeignKey(settings.AUTH_USER_MODEL) modified_date = models.DateTimeField(auto_now_add=True) modified_user = models.ForeignKey(settings.AUTH_USER_MODEL) class Meta: abstract = True class Company(Common_Info): """(Company additional description)""" gst_no. = models.CharField(max_length=15,null=True) class Meta: verbose_name ='Company' verbose_name_plural = "Companies" def __unicode__(self): return u"Company" class Business(Common_Info): """(Business description)""" parent=models.ForeignKey(Company, on_delete=models.CASCADE) gst_no. = models.CharField(max_length=15,null=True) class Meta: verbose_name ='Business' verbose_name_plural = "Businesses" def __unicode__(self): return u"Business" class Outlet(Common_Info): outlet_code = models.CharField(max_length=3, unique=True) … -
'QuerySet' object does not support item assignment
class PostDetailView(DetailView): model = Post template_name = 'detail.html' def get_context_data(self, **kwargs): context = super(PostDetailView, self).get_context_data(**kwargs) instance = Post.objects.get(pk=self.kwargs.get('pk')) user = instance.post_user context['comments'] = Comment.objects.filter(comment_post=instance.pk) context['comments']['profile'] = Profile.objects.get(user=user) return context This is my view so far. When i use that code i get this error 'QuerySet' object does not support item assignment. How do i attach the line below correctly? context['comments']['profile'] = Profile.objects.get(user=user) -
Querying objects from 1:M related Models DRF
Designed a Django Model with multi-level 1:M relations, able to get the json response writing Serializers in DRF. It looks easy to perform CRUD operations but only particular to that table, I am expecting response something similar to the response below , then came across a term called Nested Serializers, As I am not much aware of that, can any one suggest me to have one for the below model { "Blocks": [ { "id": 1, "name": "A", "Floor": [ { "id": 1, "name": 0, "books": [ { "id": 1, "name": "White Tiger" }, { "id": 1, "name": "The Alchemist" } ] }, { "id": 2, "name": 1, "books": [ { "id": 1, "name": "Facebook" }, { "id": 1, "name": "The Master Blaster" } ] } ] }, { "id": "2", "name": "B", "Floor": [ { "id": 1, "name": 0, "books": [ { "id": 1, "name": "Know Your self" }, { "id": 1, "name": "The Naga" } ] }, { "id": 2, "name": 1, "books": [ { "id": 1, "name": "The Data Analyics" }, { "id": 1, "name": "Become Master of R" } ] } ] } ] } -
Error fetching data through database in django
from django.shortcuts import render from django.http import HttpResponse def index(request): all_employee = employee.objects.all() html = '' for employee in all_employee: url = 'mainpage/' + str(employee.id) + '/' html += '' + url + '' return HttpResponse(html) def details(request, id): return HttpResponse("This is the details for" + str(id) + " ") the line all_employee = employee.objects.all() is giving the error and when I use this command in shell it is giving this [, , ] instead of each row data -
Cannot get dictionary values in jinja2 templates (Django)
I am trying to access the value of the class dictionary in jinja2 template. I have structure like this: class ClassName: ... return {'key_name': 'value1', 'key_name2': {'inside_key':'inside_value'} def get_data_from_dictionary(request): data = ClassName() return render(request, 'data.html', {'data' :data}) My data.html page looks like this: <!DOCTYPE html> <html> <body> <h1>{{ data.key_name }}</h1> <h2>{{ data.key_name2.inside_key }} </body> </html> I do not get any error and I see a blank page in browser. I have allready tried to call class like this: {{ data[key_name] }} But when I do this, I get an error: django.template.exceptions.TemplateSyntaxError: Could not parse the remainder: '[key_name]' from'pres_key[key_name]' What I am doing wrong?? -
Migrating to Bokeh >1.0: Missing 'arguments' parameter in server_session
Background: I have legacy production code which embeds Bokeh applications inside Django. The purpose is to serve user-specific dashboards. The Bokeh code accesses username arguments from the request, per the documentation. The applications were built using bokeh 0.13. On the Django side, the username argument is passed as in the example below: Example snippet from views.py: from bokeh.util import session_id from bokeh.embed import server_session def get_bokeh_script(user, url_suffix): bokeh_session_id = session_id.generate_session_id() bokeh_url = "https://" + settings.BOKEH_HOST + ":" + settings.BOKEH_PORT + url_suffix script = server_session(url=bokeh_url, session_id=bokeh_session_id, resources=None, arguments={"username":user.username}) return script def my_view1(request): url_suffix = "/my_suffix" script = get_bokeh_script(request.user, url_suffix) return render(request,'dashboard/index.html',{'script':script}) Current scenario: I need to migrate the code to bokeh >1.0, particularly for the on_session_destroyed method of the Document() object. However, it appears that the arguments parameter of server_session has been removed, per the migration guide (see also discussion here). Question: Is there a workaround that will enable me to pass username as an argument from Django to Bokeh, in version 1.0.* ? -
How to add a custom boolean action button in Django Admin?
I have a model which is registered with the admin. models.py class Post(models.Model): title = models.CharField(max_length=100) tag = models.CharField(max_length=3) is_enabled = models.BooleanField(default=False) Now, I want that the admin can only enable or disable the Post by interacting with is_enabled field of the model. admin.py class PostAdmin(admin.ModelAdmin): list_display = ['id', 'title', 'tag', 'is_enabled'] list_display_links = None readonly_fields = ['id', 'title', 'tag'] actions = ['enable_selected', 'disable_selected'] def enable_selected(self,requst,queryset): queryset.update(is_enabled=True) def disable_selected(self,requst,queryset): queryset.update(is_enabled=False) enable_selected.short_description = "Enable the selected Post" disable_selected.short_description = "Disable the selected Post" I have successfully added these actions on the dropdown, however I need to add this in the form of a button on the list, also I need to know how can I call a function when the button is hit to update the is_enabled field. -
How to use Django-filters with large data?
I am using Django-filter with django_filters.ModelChoiceFilter. I am facing the issue that the website is very slow if I have large data in Suburb table. class PDetailFilter(django_filters.FilterSet): class Meta: model = PDetail fields = { # 'code': ['icontains'], # 'bu_name': ['icontains'], # 'bc_effect_date' : ['year__gt', 'year__lt', ], } # Filter by Suburb suburb = django_filters.ModelChoiceFilter(label="Suburb", queryset=Suburb.objects.all()) -
serializer call is showing an TypeError: Object of type 'ListSerializer' is not JSON serializable?
Iam trying to call a serializer in django GET request But it shows up an TypeError: Object of type 'ListSerializer' is not JSON serializable Please help me if i went wrong somewhere. Thanks in Advance. class Member(MemberMixin, APIView): serializer_class = MemberSerializers def get(self, request, format=None): objects = MemberSerializers(Members.objects.all(), many=True) self.meta_data = "GET" self.module = "Member" self.data = objects if objects is None: self.error = "datas are not found" return Response(self.response_obj, status=status.HTTP_404_NOT_FOUND) else: return Response(self.response_obj, status=status.HTTP_200_OK) pass -
Changing BoundField value after initializing and validating form
I am trying to manually change the name of a form field after it initialized in a CBV. You could do this after initializing: form = self.get_form() # it is initialized here form.cleaned_data['name'] = form.instance.name + ' (new)' But I need to change the value after validating, so form.cleaned_data is no longer involved. I need to directly change the value of the BoundField. How can I do that? Or how can I do what I am trying to do in any other way? -
Django - csv.reader and save()/update
I am trying to update a field or multiple fields from my DB by reuploading a CSV-File with a changed value. I tried this: views.py def file_upload(request): if request.method == "POST": form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): id = 0 das2 = CSV3.objects.all().values_list() csv_file = request.FILES['file'] with open(str(csv_file)) as file: reader = csv.reader(file) for row in reader: id += 1 try: _, p = CSV3.objects.get_or_create(id = id, defaults = {'gebaeudebereich' : row[0], 'gebaeudenummer' : row[1], 'ebene' : row[2], 'raum' : row[3], 'dose' : row[4], 'switch_ip' : row[5], 'switch_port' : row[6], 'datum' : row[7], 'akteur' : row[8]}) except IntegrityError: for i in das2: i[1] = row[0] i.save() return redirect('appp:index') form = UploadFileForm() return render( request, "appp/file_upload.html", {"form": form} ) I looped through the values and set value 'gebaeudebereich' to the gebaeudebereich value in the CSV-File (I would do this with the other fields too but this is the idea I tried). It is not saving anything and it does not give me an error, just doesn't do anything. The try clause works just fine. my models.py class CSV3(models.Model): gebaeudebereich = models.CharField(max_length=100) gebaeudenummer = models.CharField(max_length=100) ebene = models.CharField(max_length=100) raum = models.CharField(max_length=100) dose = models.CharField(max_length=100) switch_ip = models.CharField(max_length=100) switch_port = models.CharField(max_length=100) datum = … -
How to export inline text fields into xlsx (or csv)?
I am currently capable of exporting one of the models into xlsx files with the variables that are added in the models.py. However, one of the models that I have has an inline with a text field - and I wish to add this text field into the xlsx export. Does anybody have a previous experience with this? Thanks in advance! -
How to specify help text in a Django Cloudinary Field
How do I include a help_text in CloudinaryField() options in django models I've tried setting it by extending CloudinaryField and passing options. class CloudinaryField(BaseCloudinaryField): def upload_options(self, model_instance): return { 'public_id': pid, 'unique_filename': False, 'overwrite': True, 'resource_type': 'image', 'tags': ['user', 'avatar'], 'invalidate': True, 'quality': 'auto:eco', } -
Django Formset: multichoice queryset filter is not working for my formset after many attempts
I have Contestant model that has many-to-one relationship with Category. I want the creator of the award to only have access to last 15 categories of the award he has created in instantiating contestant model. That's, the multichoice queryset in the Contestant field(category) will only show the list of the last 15 categories being created in the Category Model. I have made different efforts, but the code is either not working or giving '['ManagementForm data is missing or has been tampered with']' error. I have made countless re-factorization of codes and I have tried to adopt solutions I found on internet. But they didn't work. # MY CATEGORY MODEL class Category(models.Model): award = models.ForeignKey(Award, on_delete=models.CASCADE) award_category = models.CharField(max_length=150, blank=True, null=True) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) def __str__(self): return self.award_category # MY CONTESTANT MODEL class Category(models.Model): award = models.ForeignKey(Award, on_delete=models.CASCADE) award_category = models.CharField(max_length=150, blank=True, null=True) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) def __str__(self): return self.award_category #MY VIEW def get_award(request, pk): new_award = get_object_or_404(Award, pk=pk) Contest_Formset = modelformset_factory(Contestant, fields('contestant_name', 'category',), extra=15) formset = Contest_Formset(request.POST) for form in formset: form.fields['category'].queryset = Category.objects.filter(user=request.user)[1:15] if request.method == 'POST' and form.is_valid(): myform = form.save(commit=False) myform.award_name = new_award myform.save() return redirect('award_details', pk=new_award.pk) else: formset = Contest_Formset() context = { 'new_award': … -
How to deploy a djanho backend and react frontennd app to same domain
So I googled around for the answer to this question and found a way to deploy just a react app to github pages using this medium article. The issue is my react app has a django back end. So github pages won't work. I also know how to deploy a django site to heroku. I also know you can deploy a react app to heroku. But deploying them separately makes them have different domains. Now is there a way to deploy a fullstack django and react app to heroku so both has same domain? -
Addig form fields to a custom user model in django admin panel
I'm going through the django for beginners book, testing the code from the chapter 8 about the Custom user model. The goal is to add the field age in the auth user model by subclassing the AbstractUser model. First we create out CustomUser in models.py from django.db import models from django.contrib.auth.models import AbstractUser class CustomUser(AbstractUser): age = models.PositiveIntegerField(null=True, blank=True) Then creating CustomUserCreationFrom and CustomUserChangeFrom in forms.py: from django import forms from django.contrib.auth.forms import UserCreationForm, UserChangeForm from .models import CustomUser class CustomUserCreationFrom(UserCreationForm): class Meta(UserCreationForm.Meta): model = CustomUser fields = UserCreationForm.Meta.fields + ('age',) class CustomUserChangeFrom(UserChangeForm): class Meta(UserChangeForm.Meta): model = CustomUser fields = UserCreationForm.Meta.fields And finally, the CustomUserAdmin in admin.py: from django.contrib import admin from django.contrib.auth.admin import UserAdmin from .forms import CustomUserCreationFrom, CustomUserChangeFrom from .models import CustomUser class CustomUserAdmin(UserAdmin): add_form = CustomUserCreationFrom form = CustomUserChangeFrom model = CustomUser list_display = ['username', 'email', 'age', 'is_staff',] admin.site.register(CustomUser, CustomUserAdmin) And of course telling django about our custom auth model in settings.py: AUTH_USER_MODEL = 'users.CustomUser' Logged as a super user, and when trying to add a new user, there is no field age in the creation form. Am I missing something? -
Django - logout users on browser close or after timeout
I have added my own login/logout page. I want to make session expires either on browser close or when timeout is reached. I found 2 parameters which I have included in setting.py: SESSION_EXPIRE_AT_BROWSER_CLOSE SESSION_COOKIE_AGE But it seems that they are only working for admin panel, nor for my own. Should I have done something more? -
Django admin, how to trigger a function only once?
I have a model let's name it A. I have registered this model with the Admin, now this model needs to have some prefilled data, which is supplied by a third party rest call, the only action an admin can do is to enable or disable something. Now I need the filler function to be called only once, since initially the Table A won't have any data. How can I acieve this? -
enum python how to response
are there any way to display status_choices in model.py type string in postman???? my model.py class Transaction(models.Model): user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE) address = models.TextField() status_choices = ( (1, 'in processing'), (2, 'in delivery'), (3, 'done'), (4, 'cancel'), ) status = models.CharField(max_length=1, choices=status_choices) total = models.BigIntegerField() phone_number = models.CharField(max_length=10) variants = models.ManyToManyField(Variant, through='TransactionVariant') created_at = models.DateTimeField(auto_now_add=True, blank=True) updated_at = models.DateTimeField(auto_now_add=True, blank=True) deleted_at = models.DateTimeField(null=True, blank=True) class Meta: db_table = "transaction" serializer.py class TransactionSerializer(serializers.Serializer): # status = StatusSerializer(many=False, read_only=True) user_id = serializers.IntegerField() transaction_id = serializers.IntegerField(source='id') product = serializers.CharField(source='name') status = serializers.CharField() address = serializers.CharField() total = serializers.IntegerField() phone_number = serializers.IntegerField() created_at = serializers.DateTimeField(format='%H:%M %d %b %Y') my response in postman: "user_id": 5, "transaction_id": 1, "product": "product1", "status": "3",----------> I want this field return what exactly in my model designer "address": "trung nu vuong 3", "total": 123, "phone_number": 1234567890, "created_at": "09:35 21 Jan 2019" want response return { status: done } -
My django blog isnt detecting the HTML/CSS files i added
Edit 1: I am building a blog with django and i recently added some html/css files to a template folder but its not loading. These are my html codes base.html: {% load static %} <!DOCTYPE html> <html> <head> <title>{% block title %}{% endblock %}</title> <link href="{% static "css/blog.css" %}" rel="stylesheet"> </head> <body> <div id="content"> {% block content %} {% endblock %} </div> <div id="sidebar"> <h2>My blog</h2> <p>This is my blog.</p> </div> </body> </html> list.html > {% extends "blog/base.html" %} {% block title %}My Blog{% endblock > %} {% block content %} <h1>My Blog</h1> {% for post in posts %} > <h2> > <a href="{{ post.get_absolute_url }}"> > {{ post.title }} > </a> > </h2> > <p class="date"> > Published {{ post.publish }} by {{ post.author }} > </p> > {{ post.body|truncatewords:30|linebreaks }} {% endfor %} {% endblock %} i could be wrong but i think the issue might be from the views and urls below views.py > from django.shortcuts import render, get_object_or_404 from .models > import Post > > def post_list(request): posts = Post.published.all() return > render(request, > 'blog/post/list.html', > {'posts': posts}) > > def post_detail(request, year, month, day, post): post = > get_object_or_404(Post, slug=post, > status='published', > publish__year=year, > … -
Django import-export name 'name' is not defined
hello guys i need import excel file in django admin i found this this video and I applied the steps but i have Line number: 1 - name 'name' is not defined error how can i solved models.py from django.db import models class Ekle(models.Model): name = models.CharField(max_length = 50, blank = False) lastname = models.CharField(max_length = 50) price = models.CharField(max_length = 50) def __str__(self): return name admin.py from django.contrib import admin from .models import * from import_export.admin import ImportExportModelAdmin @admin.register(Ekle) class ViewAdmin(ImportExportModelAdmin): pass -
How to send a JSON request from JAVASCRIPT to PYTHON script in Django?
I'm writing a django application, and I want to pass JSON data from a python file to a JAVASCRIPT file included in a view. All are on the same server. I tried to simply request the .py script via javascript using AJAX over the same server. The current code" ==)JAVASCRIPT: $.ajax({ type: 'GET', url: 'location_json.py', data: returned_from_json, dataType: 'jsonp', success: function(returned_from_json) { alert(returned_from_json); }, error: function() { alert('Error loading '); } }); ==)PYTHON: #!/bin/python3 import json import urllib.request print(---------------python----------------) #JSON PARAMETERS url = "http://127.0.0.1/my/url" #url to my server body = {'lat':12112,'lng': 5333324} request = urllib.request.Request(url) request.add_header('Content-Type','application/json; charset=utf-8') jsonData = json.dumps(body) jsonDataBytes = jsonData.encode('utf-8') request.add_header('Content-Length',len(jsonDataBytes)) print("json data:"+jsonDataBytes) response = urllib.request.urlopen(request, jsonDataBytes) if(!response) { response = urllib.request.urlopen(request, jsonDataBytes) } print("json sent") Output should be the content of : body = {'lat':12112,'lng': 5333324} lat and lng here have arbitrary for test reasons values. -
How Can I be make django orm with raw sql query?
I am working on a project and also new in django. I have the sql raw query having some joins in it. But my requirement is to make the django orm. I have tried to make it but not able to make the exact orm for that query. I have tried this to make the django orm but dont find exact result: model_data = Model.objects.prefetch_related( 'modelapi', 'modelauth', 'modelapiconfig').filter( modelauth__retrieval_id='XXYY',modelauth__is_active=True).values( 'model_name', 'modelauth__retrieval_id', 'modelapi__api_endpoint_name', 'modelapi__modelapiconfig__api_config') Here is my models.py: class Model(models.Model): model_name = models.CharField(max_length=40, blank=False, verbose_name='Name', unique=True) def __str__(self): return self.model_name class Meta: db_table = 'connector_model' class ModelApi(models.Model): model_id = models.ForeignKey(Model, on_delete=models.CASCADE, verbose_name='MODEL Name', related_name='modelapi') model_description = models.CharField(max_length=150, verbose_name='API Description') api_endpoint_name = models.CharField(max_length=100, blank=False, verbose_name='API endpoint name', default='') def __str__(self): return self.model_id.model_name + "_" + self.api_endpoint_name class Meta: db_table = "connector_model_api" class ModelAuthentication(models.Model): model_id = models.ForeignKey(Model, on_delete=models.CASCADE, verbose_name='MODEL Name', related_name='modelauth') email = models.EmailField(max_length=70) retrieval_id = models.CharField(max_length=30, blank=False, unique=True) def __str__(self): return self.model_id.model_name + "_" + self.retrieval_id class Meta: db_table = "connector_model_authentication" class ModelApiConfig(models.Model): model_auth = models.ForeignKey(ModelAuthentication, on_delete=models.CASCADE, verbose_name='MODEL Customer Name') model_api = models.ForeignKey(ModelApi, on_delete=models.CASCADE, verbose_name='MODEL API', related_name='modelapiconfig') api_config = models.TextField(default={}) def __str__(self): return self.model_auth.model_id.model_name + str("'s ") \ + self.model_api.api_endpoint_name + str(" endpoint") class Meta: unique_together = ('model_auth', 'model_api',) db_table = "connector_model_api_config" …