Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
adding css to django checkbox multiselect
I managed to add css classes to my forms with attrs={'class': 'form-control'} For example in a Multiple Choice Field: CHOICES_NAT = (('None', 'None'),('Deutschland', 'Deutschland'), ('Amerika', 'Amerika'), ('Türkei','Türkei'), ('Frankreich', 'Frankreich')) Nationality = forms.ChoiceField(widget = forms.Select(attrs={'class': 'form-control'}), choices = CHOICES_NAT) But i still fail to display the checkboxes of a Multiple Choice Field. The Choices are displayed only the Chechboxes are missing. Heres my code for the Ceckboxes: CHOICES_AGE = (('0-8', '0-8'),('8-14', '8-14'), ('14-21', '14-21'), ('21-60','21-60'), ('60-90', '60-90')) Target_Age = forms.MultipleChoiceField(widget = forms.CheckboxSelectMultiple(attrs={'class':'form-group', 'type':'checkbox',}), choices = CHOICES_AGE, ) As far as i can see the type is not added to the html - i might need to pass multiple attrs differently. Thanks for your help! =) -
Django - Catch Exception before view rendering
I have a OperationalError exception throw during view rendering. So I tried to catch it before the rendering in views.py try: dossiersdb = Person.objects.using('dbn').all() print(dossiersdb) except OperationalError as exp : logger.warning("Got %s", exp) return HttpResponse('<h1>OperationalError</h1>') But I need to put a print(dossiersdb) because whitout it, there is no Exception here but again in the index.html What is the proper way to catch this exception ? -
how to make a delete button work. im using python, django, and bootstrap for the delete button
I am creating a todo app with python and Django and I have a delete button that I want to delete tasks out of a task list but I am very new to this and I have no idea how to make the delete button actually delete lol. I would really appreciate some help. thanks in advance. -
Django, JavaScript: When passing 'null' to front end, JS turns it into &39;null&39;
I have a view that is passing a 2D array to my front end: return render(request, self.template_name, {'runs': runs, 'graph_data': graph_data}) Where graph_data contains arrays of [x, y] coordinates, and occasionally it needs arrays of [null, null] to mark breaks in my line graph (using flot.js) graph_data = [ [1, 7], [2, 9], [null, null], [5, 2], [6, 4] ] When building this 2D array in my view, I insert breaks like this: other stuff happens else: graph_data_total += array graph_data_total += ['break'] Basically, when I need to insert a line break in my graph, I insert the graph array, followed with the string 'break' with string concatenation (+=). Then, I need to convert datetime.datetime objects to milliseconds (the X coordinate in each individual array), so I go over each point and do that, unless it's a "break", in which case I need to insert [null, null], without quotes: for point in z_scores_total: if point != 'break': time = point.time graph_data.append([unix_time_millis(time), point.parameter_value]) else: graph_data.append([json.dumps(None), json.dumps(None)]) The JSON documentation states that json.dumps(None) would insert null, without quotes, as seen here. Except I'm seeing ['null', 'null'] if I print(graph_data), which ends up in my front end as described in the title, [&39;null&39;, … -
issue with the redis delete in python
i have a problem in my current project that i can't manage to solve. I use redis with django / python, it's not the first project where i use redis and i never got that kind of problem before. My script create two differents type of keys, filled with multiple variable. They both have pretty much the same variable, the first one 'GMO' has 10 more viarable than second one 'PLI'. i have a situation where the user press cancel on the app, and i'm supposed to delete the key once he does. For the 'GMO' key i have no trouble to delete it everytime i try. The other one, 'PLI' seem to be a bit more tricky because on some occasion (can't find the reason why it seem totaly random) it doesn't delete the entire key. For example i just tried to create / delete keys, i managed to create and delete 5 key before the last one 'failed' and didn't delete the whole key. Sometimes it happend after i create 2 keys, sometimes 10. I was using the delete(key) function, then i tried hdelete but i doesn't seem to work any better. If anyone had this kind of … -
How can I stucture my django code for a webpage with suppose 4 different divisions of data
I am constructing a webpage in django which will parse data and show it all on a single webpage which is divided into 4 sections. So, I need help in organizing the code so that the backend processing code for different sections can be kept seperate(maybe into seperate methods?), but everything needs to be called and rendered on a single request. Thanks. :) -
Where to start building a internet speed testing Web Application in python?
everyone. I have spent some time learning to code in python then while surfing i came across Speedtest_cli. So began wondering if integrate it in simple html front-end from where i'll run the python script and see my internet speed like this website. Which would be nice. So my question to you all is speedtest-cli works with front-end or should i follow framework such as django/flask to implement something like this. A head-start about where to begin or any links to some tutorial would be appreciated. TIA -
Django rest framework redirect if permission denied
I am new in Django-rest-framework. I am learning about authentication and permissions. I am getting stuck at one point. I have created custom permission for selected users. So if some user doesn't have the correct permission for some view class, it returns HTTP status-403. In the browser it has message "403 Forbidden". Instead of this, I want to redirect the user to some other page. Any help would be appreciated. Thanks -
django2.0 international not work in my server environment
I trapped in a problem for a while. I do as the documentation and i get the result as i want in the local environment. Not only using python3 manage runserver but also uwsgi --http :8000 xxx.uwsgi. But after i upload my files into my server, i can not get the same result as the local environment. Here is the configuration: LOCALE_PATHS = [os.path.join(BASE_DIR, 'locale')] # print(LOCALE_PATHS) LANGUAGE_CODE = 'en-us' LANGUAGES = [ ('en-us', t_l('English')), ('zh-hans', t_l('Chinese')) ] USE_TZ = True TIME_ZONE = 'Asia/Shanghai' USE_I18N = True USE_L10N = True MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'util.middleware.MultipleDomainMiddleware', 'util.middleware.VisitHistoryMiddleware', 'django.middleware.gzip.GZipMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', # 'debug_toolbar.middleware.DebugToolbarMiddleware', ] And the url of .mo, .po file is '/project/locale/zh_hans/LC_MESSAGES/xxx.po', '/project/locale/zh_hans/LC_MESSAGES/xxx.mo' Of course, i add {% load i18n %} to the top of my web page. The function works fine in my local environment, but not working in my server environment. I use nginx + uwsgi + django to deploy my server. And i can make sure that the server get the actually request.LANGUAGE_CODE. I tried to use python3 manage runserver and uwsgi --http to run my code on the server to see if the translation works. The answer is no! The system version … -
GenericForeignKey gets wrong id when used with model with UUIDField
When using GenericForeignKey together with UUIDField, what is the recommended way to get a queryset of the "real model" from a queryset of generic objects? Here are the models I'm testing with: import uuid from django.contrib.contenttypes.fields import GenericForeignKey from django.contrib.contenttypes.models import ContentType from django.db import models class Foo(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4) class Generic(models.Model): content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.CharField(max_length=255) content_object = GenericForeignKey() and this is what I've tried so far: >>> from django.db.models import Subquery >>> from foo.models import Foo, Generic >>> f = Foo.objects.create() >>> g = Generic.objects.create(content_object=f) >>> Foo.objects.filter(id__in=Subquery(Generic.objects.all().values('object_id'))) <QuerySet []> >>> Generic.objects.get().object_id '997eaf64-a115-4f48-b3ac-8cbcc21274a8' >>> Foo.objects.get().pk UUID('997eaf64-a115-4f48-b3ac-8cbcc21274a8') I'm guessing this has to do with the UUIDs being saved without the hyphens for the UUIDField. I can't make object_id into a UUIDField either since I need other models that have integers and strings as primary keys. I'm using Django 1.11 but I've also tested Django 2.0 which has the same problem. -
How to get the running time in the Pylint of each file
I am using the pylint in my project and it runs over 1min which is too long for me .How can I get the specific running time of each file in my project? Here is my research: The issue on the github How to speed up pylint Can you give me some advice about the issue and how to speed up the pylint ? thanks in advance !!!! -
Form validation issue in django
I am new to django. Here,I want to create login for my django app.When I am trying to create user a account,I have been facing form validation problem. While creating user account, I want to add username,email,mobile no,password and organisation name.If email or mobile no already exist it should give the error message And here is my code forms.py User=get_user_model() class UserLoginForm(forms.Form): email=forms.EmailField(label='Email address') password = forms.CharField(label='Password', widget=forms.PasswordInput()) def clean(self,*args,**kwargs): email=self.cleaned_data.get("email") password=self.cleaned_data.get("password") if email and password: user=authenticate(email=email,password=password) if not user: raise forms.ValidationError("This email id is not registered") if not user.check_password(password): raise forms.ValidationError("Incorrect password") return super(UserLoginForm,self).clean(*args,**kwargs) class RegistrationForm(forms.ModelForm): username= forms.CharField(label='Username') #email = forms.EmailField(label='Email address') mobile =forms.CharField(label='Mobile No') #password = forms.CharField(label='Password') org_name = forms.CharField(label='Organisation Name') class Meta: model = User fields = ['username', 'email', 'mobile', 'password','org_name'] def clean_email(self): email = self.cleaned_data.get('email') check_duplicate_email = User.objects.filter (email=email).exists() if check_duplicate_email: raise forms.ValidationError( "This email id is already registered" ) return email def clean_mobile(self): mobile=self.cleaned_data.get('mobile') check_duplicate_mobile=User.objects.filter(mobile=mobile).exists() if check_duplicate_mobile: raise forms.ValidationError( "This mobile no is already registered" ) return mobile models.py class UserRegForm(models.Model): email=models.OneToOneField(User,unique=True) mobile =models.CharField(max_length=10) org_name = models.CharField(max_length=254) views.py def login(request): title="Login" form=UserLoginForm(request.POST or None) if form.is_valid(): email=form.cleaned_data.get("email") password = form.cleaned_data.get("password") user=authenticate(email=email,password=password) login(request,user) return render(request,"userRegistration/login.html",{"form":form,"title":title}) def signup(request): title="Signup" if request.method=="POST": form = RegistrationForm()#request.POST) print form print … -
Using a related by relation ship in a serializer
I currently have these two simple models with their associated serializers class modelChat(models.Model): employer = models.ForeignKey(modelEmployer,on_delete=models.CASCADE,null=True,default=None,blank=True) job = models.ForeignKey(modelJob,on_delete=models.CASCADE,null=True,default=None,blank=True) employee = models.ForeignKey(modelEmployee,on_delete=models.CASCADE,null=True,default=None,blank=True) and its related serializer is this class Serializer_ChatHistory_TX(serializers.ModelSerializer): employer = Serializer_Employer_TX() employee = Serializer_Employee_TX() class Meta: model = modelChat fields = [ 'employer', 'employee', ] Then I have this model which is associated with modelChat using the following relationship class modelChatContent(models.Model): chat = models.ForeignKey(modelChat, on_delete=models.CASCADE, null=True, default=None, blank=True) content = models.CharField(max_length=400, unique=False, blank=False, null=True) The serializer of above is this class Serializer_ChatContent_TX(serializers.ModelSerializer): chat = Serializer_ChatHistory_TX() class Meta: model = modelChatContent fields = [ 'chat', 'content', ] Now every modelChat will have multiple modelChatContent associated with it. The modelChatContent basically contains the messages exchanged b/w two users What I would like to do is to add an extra field to Serializer_ChatHistory_TX that will display all the associated Serializer_ChatContent_TX as an array. so something like this class Serializer_ChatHistory_TX(serializers.ModelSerializer): employer = Serializer_Employer_TX() employee = Serializer_Employee_TX() class Meta: model = modelChat fields = [ 'employer', 'employee', 'conversations', #<----This should return back array of all associated modelChatContent. How do I do that ? ] How do I add an extra field conversations in the Serializer_ChatHistory_TX ? -
django FilterSet for end of day
How to make the query take correct date from start date and end end of the day for FilterSet. Now if you type start_filter_date = 2018.05.23 and end_filter_date = 2018.05.25. Then start_filter_date=2018.05.23T00:00 and end_filter_date=2018.05.25T00:00. Time is taken 00:00, but need to be 23:59? My class is following: class TaskFilterSet(django_filters.rest_framework.FilterSet): id = django_filters.NumberFilter(name="pk") start_filter_date = django_filters.DateFilter(name="date_added", lookup_expr="gte") end_filter_date = django_filters.DateFilter(name="date_added", lookup_expr="lte") -
Django inheritance and polymorphism with proxy models
I'm working on a Django project that I did not start and I am facing a problem of inheritance. I have a big model (simplified in the example) called MyModel that is supposed to represents different kind of items. All the instance objects of MyModel should have the same fields but the methods behaviours varies a lot depending on the item type. Up to this moment this has been designed using a single MyModel field called item_type. Then methods defined in MyModel check for this field and perform different logic using multiple if: def example_method(self): if self.item_type == TYPE_A: do_this() if self.item_type == TYPE_B1: do_that() Even more, some of the sub-types have many things in common, so let's say the subtypes B and C represents a 1st level of inheritance. Then these types have sub-types being for example B1, B2, C1, C2 (better explained in the example code below). I would say that's not the best approach to perform polymorphism. Now I want to change these models to use real inheritance. Since all submodels have the same fields I think multi-table inheritance is not necessary. I was thinking to use proxy models because only their behaviour should change depending on … -
splitting models files into multiple separate models give field abstraction error
My code is as shown below: holidayRequest.py from django.db import models from enum import Enum class HolidayRequests(models.Model): class Meta: db_table = 'holidays_requests' app_label = 'dashboard' name = models.CharField(max_length = 255,null= False) email = models.CharField(max_length = 255,null=False) ph_no = models.CharField(max_length =255,null=False) holiday = models.ForeignKey('holidays',on_delete=models.CASCADE) holiday.py from django.db import models from enum import Enum class Holiday (models.Model): class Meta: db_table = 'holidays' app_label = 'dashboard' holiday_price = models.CharField(max_length = 255,null =False) holiday_title = models.CharField(max_length=255,null=False) init.py (inside models folder) from holidayRequest import HolidayRequests from holiday import Holiday the moment I run migrations, I get the following error: dashboard.HolidayRequests.holiday: (fields.E300) Field defines a relation with model 'holidays', which is either not installed, or is abstract. dashboard.HolidayRequests.holiday: (fields.E307) The field dashboard.HolidayRequests.holiday was declared with a lazy reference to 'dashboard.holidays', but app 'dashboard' doesn't provide model 'holidays'. -
Active CMS Menu on apphooked object
I have an site with Django CMS 3.5.1 and Django 1.11.11 and it has a menu built with CMS. One of its pages is an apphooked list of events. When I click on an event detail, the menu loses its active class. Here's my menu: {% for child in children %} <li class="js-submenuParent {% if child.selected or child.ancestor %}active{% endif %}"> <a href="{% if child.children %}javascript:void(0);{% else %}{{ child.attr.redirect_url|default:child.get_absolute_url }}{% endif %}" class="{% if child.children %}submenu-btn js-openSubmenu{% endif %}">{{ child.get_menu_title }}</a> {% if child.children %} <ul class="submenu js-submenu"> {% show_menu from_level to_level extra_inactive extra_active template "" "" child %} </ul> {% endif %} </li> {% endfor %} I thought child.ancestor could solve the problem (or even child.selected as it seems I can access the parent's title using {% page_attribute "page_title" %}) but it doesn't. Do I have to make a custom apphook menu just to do that or is there a simpler solution? -
Getting TypeError when makemigration to a model when using Django
I am currently learning Python from the book "Python Crash Course" by Eric Matthes. I am trying one of the assignments and am currently stuck. Can't figure out why this error appears. from django.db import models # Create your models here. class Pizza(models.Model): """List of pizzas""" name = models.CharField(max_length=50) def __str__(self): """Return a string representation of the model""" return self.name class Topping(models.Model): """Toppings""" pizza = models.ForeignKey(Pizza) name = models.CharField(max_length=50) def __str__(self): """Return a string representation of the model""" return self.name Getting the error when I add the model Topping to the code. Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "C:\Users\Samuel Tee\Desktop\pizzeria\pp_env\lib\site-packages\django\core\management\__init__.py", line 371, in execute_from_command_line utility.execute() File "C:\Users\Samuel Tee\Desktop\pizzeria\pp_env\lib\site-packages\django\core\management\__init__.py", line 347, in execute django.setup() File "C:\Users\Samuel Tee\Desktop\pizzeria\pp_env\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\Samuel Tee\Desktop\pizzeria\pp_env\lib\site-packages\django\apps\registry.py", line 112, in populate app_config.import_models() File "C:\Users\Samuel Tee\Desktop\pizzeria\pp_env\lib\site-packages\django\apps\config.py", line 198, in import_models self.models_module = import_module(models_module_name) File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python36_64\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_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 219, … -
Django Many-to-Many related_name
enter image description here class Profile(models.Model): user = models.OneToOneField(User) followers = models.ManyToManyField(User, related_name='is_following', blank=True) activation_key = models.CharField(max_length=120, blank=True, null=True) activated = models.BooleanField(default=False) timestamp = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) objects = ProfileManager() def __str__(self): return self.user.username Guys-girls i really need your help)) i am struggling with this thing for 5 hours can't solve this mystery... in shell when i type User.profile.followers.all() and when i type User.is_following.all() i receive different result. Why?))) -
TinyMCE, Django and python-docx
I'm looking into using a rich text editor in my Django project. TinyMCE looks like the obvious solution, however i see that the output format is html (here). Goal is to store user input and then serve it inside a word document using python-docx( which is not html). Do you know of any solution for this? Either a feature of tinyMCE or a html to word-format converter which keeps styles, or maybe another rich text editor similar to tinymce? -
How to create a dynamic RAW Queryset
I want to create a dynamic Raw Queryset. By default a raw queryset looks like: qs = self.raw( 'SELECT DISTINCT ON(P.slug) P.id, P.slug, P.company_id, I.image, 'FROM product AS P ' .... It is possible to create the queryset using conditions. I'm not referring to database conditions like Where, but python conditions like if Something like: 'SELECT DISTINCT ON(P.slug) P.id, P.slug, P.company_id, I.image, 'FROM product AS P ' # if var_a Limit 20 else where P.id = var_b -
Is it required to add custom views in admin page in ModelAdmin class when we can do it normally by adding views in views.py and urls in urls.py?
According to django docs: class MyModelAdmin(admin.ModelAdmin): def get_urls(self): urls = super(MyModelAdmin, self).get_urls() my_urls = [ url(r'^my_view/$', self.my_view), ] return my_urls + urls def my_view(self, request): # ... context = dict( # Include common variables for rendering the admin template. self.admin_site.each_context(request), # Anything else you want in the context... key=value, ) return TemplateResponse(request, "sometemplate.html", context) If I am not wrong, we can do the same thing by adding url in urls.py and the views in views.py as it is normally done then, what is the use of introducing this method? I am a newbie to django and I may be missing something here. Can you please provide an example where we cannot do it in views.py and we must use the above method? Any guidance/help would be appreciated. -
How to filter the data use equal or greater than condition in the url?
I can use the bellow link to filter the id=16's data: http://localhost:8000/api/physicalservertask/list_for_home_workpanel/?id=16 this is my list api view: class PhysicalServerTaskListAPIView(ListAPIView): serializer_class = PhysicalServerTaskListSerializer permission_classes = [IsAdminUser] def get_queryset(self): query_params = self.request.query_params filters = {'{}__contains'.format(key): value for key, value in query_params.items() } return PhysicalServerTask.objects.filter(**filters) I have a question, how can I query the id>= 16's data list through the url? I mean whether I can through the: http://localhost:8000/api/physicalservertask/list_for_home_workpanel/?id__gte=16 to filter the data. I know I can in the ListAPIView query like this: id_gte = self.request.query_params.copy().get('id_gte') ... qs = PhysicalServerTask.objects.filter(**filters) qs.filter(Q(id__gte=id__gte)) but whether there is a more convenient way to realize this? -
How to efficiently structure dynamic forms in Django?
I am using Django.2x for my website. I have 15+ forms to be shown dynamically to the user based on the option he chooses from a dropdown. I have kept all the form-div's in one single html page and i am using JQuery to Show() and Hide() the forms based on the user's selection. Is there any better way where i can structure this flow of showing forms efficiently since my forms could increase soon ? -
While upgrading wagtail-2 with Django-2 without effecting old migrations file. I am getting this 'NoneType' object has no attribute 'is_relation'
I am trying to upgrade wagtail-1.9 to wagtail-2.0, and Django-1.10.6 to Django-2.0 but I am getting this error. delay = not old_field.is_relation AttributeError: 'NoneType' object has no attribute 'is_relation' I don't want to delete or reset my old migrations file because if I delete the old migrations file or reset it I will be lost my data.