Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Overloading changelist_view with no changes causing errors
Overloading changelist_view and calling the super() causes attribute errors. I'm creating a super basic dashboard and I am overriding the changelist_view method of a ModelAdmin class. However, this override is resulting in an error "NoneType object has no attribute 'has_header'." However, I'm literally not doing anything but override the changelist_view and calling the super class - I haven't made any changes yet. In admin.py class SummaryAdmin(admin.ModelAdmin): def changelist_view(self, request, extra_context=None): response = super().changelist_view(request, extra_context) The corresponding model in models.py class Summary(Failure): class Meta: proxy = True verbose_name = 'Failure Summary' verbose_name_plural = 'Failures Summary' This is literally the entire contents of the admin model. When I try to go to the django admin panel, I get the attribute error. As far as I can tell, this should be no different than not overrifing changelist_view at all, but if I delete the override everything functions as normal. -
How do I stay on the same page after submitting a post request and hit another post request?
I'm doing a one page website where I'm wanting to input some text and upload files. Basically, how I want my form to look like at the front end is, first I can type some text in the textarea given, below that I should be able to select multiple files, once the files are selected I'll click on the upload button, the files should be uploaded, and then I'll hit submit and that's how I create a post. I'm attaching my code below. I do have written my broken views.py file but I'm not attaching it for now. models.py : class Post(models.Model): post_body = models.TextField(blank=False, max_length=500) class PostMedia(models.Model): file = models.FileField() body = models.ForeignKey(Post, on_delete=models.CASCADE) forms.py : from django.forms import ClearableFileInput from django.forms import ModelForm from .models import Post, PostMedia class PostModelForm(ModelForm): class Meta: model = Post fields = ['post_body'] class PostMediaModelForm(ModelForm): class Meta: model = PostMedia fields = ['file'] widgets = { 'file': ClearableFileInput(attrs={'multiple': True}), form.html (I was trying to write the jquery function): <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <script> $('text-form').on('submit',upload(e) { e.preventDefault(); $.post( '../create-post', $('form').serialize(), function( data ) { alert( data ); } ); }); </script> <div class="site-form"> <h2>Create a New Post here! … -
Django global filter
Is there a way to filter globally a Django model? We need to set a filter in a single place so that it gets applied in all queries generated by Django ORM including related objects lookups etc. Example: class A(Model): n = IntegerField() class B(Model): a = ForeignKey(A) We want to set on A a global filter id__gte=10 (static to make it simple). The filter must be then automatically applied also when doing related queries, e.g. B.objects.filter(a__n=123) # this code cannot be modified should expand somehow magically to an equivalent of B.objects.filter(a__n=123, a__id__gte=10) We can change models, managers, querysets but we cannot change the code where objects are actually queried (a lot of code, third party apps, generic API). -
Converting raw sql query to Django ORM
I have 3 models in my projec like this: class Model_A(Models.Model): field_a_1 = models.IntegerField() ...other fields... class Model_C(models.Model): field_c_1 = models.IntegerField() field_c_2 = models.IntegerField() ...other fields... class Model_B(Model_C): table_a_fk_id = ChainedForeignKey(Model_A, .... ) ...other fields... Because of that in my database I have the following three tables: Table_A(id, name, field_a_1, ...other fields....) Table_B(id, table_a_fk_id, table_c_fk_id, .....other fields...) Table_C(id, field_c_1, field_c_2, ...other fields....) and I need a query that retrive data like this output: Table_A_id Table_A_name count ------------------------------------------------ 12 Table_A_name_12 138 1 Table_A_name_1 133 13 Table_A_name_13 55 15 Table_A_name_15 38 9 Table_A_name_9 34 7 Table_A_name_7 0 19 Table_A_name_19 0 I have solved the problem with a raw sql query, but I don't know how do the same in Django ORM. This is my SQL code: SELECT `Table_A`.`id` AS 'Table_A_id', `Table_A`.`nome` AS 'Table_A_name', COUNT(`ptr`.`table_a_fk_id`) AS `count` FROM `Table_A` LEFT OUTER JOIN ( SELECT `Table_C`.`id`, `Table_B`.`table_a_fk_id` FROM `Table_B` INNER JOIN `Table_C` ON ( `Table_B`.`table_c_fk_id` =`Table_C`.`id`) WHERE ( `Table_B`.`table_a_fk_id` = xx AND `Table_C`.`field_c_1` = yy AND `Table_C`.`field_c_2` = zz ...other constraints on Table_C fields.... ) ) ptr ON (`Table_A`.`id` = `ptr`.`table_a_fk_id`) WHERE (`Table_A`.`field_a_1` = x ) GROUP BY `Table_A`.`id` ORDER BY `count` DESC, `name` ASC I want translate the above sql in Django ORM … -
NOAUTH Authentication required. Redis settings on docker compose for django
I keep on getting the error message: redis.exceptions.ResponseError: NOAUTH Authentication required.. (I'm using celery to perform background tasks). My settings.py looks like this: CELERY_BROKER_URL = 'redis://user:my_strong_password@'+REDIS_IP+':6379/0' the docker-compose I have: services: redis: image: redis:latest container_name: jh_redis ports: - '6379:6379' command: redis-server --appendonly yes --requirepass my_strong_password you can see that my attempt to provide the password (--requirepass) is exactly as it shown in the settings.py however, while the docker is up and running I still get the subject error message. I have tried different combination such as: --requirepass user:my_strong_password but still didn't work. Note: when I take off the entire command line - it works (but 32 hours after - I get the error message and it stop working). What should be the appropriate settings in docker-compose to have it work smoothly? -
How to add disable password for django users
I have created a tool for my colleagues and i have integrated SSO with this django application as well. Now the way i'm planning to authenticate users are like the following. SSO page is sending the logged in user ID in cookie. If the logged in user have an account in django users, i'll check for a match and i should authenticate the user. The challenge i'm facing here is while creating users i have to provide password and i don't want to validate user password again. Is there a way i can disable the password while we add the user in to django admin itself? I'm using Django 1.11 with python 3.4. Let me know your thoughts. -
How to translate variables in Jinja2/Django
I use i18n in my Jinja2 templates and everything works fine for plain text. But I can't find any info how to use translations with variables, which I can't avoid using. Here is an example: {% set words = ["Hello", "world"] %} {% for word in words %} {{ _(word) }} {% endfor %} What should I do to get "Hello" and "world" in my .po file? -
what to do instead of foreign key for one to many relations?
For one to many relations, we can use a foreign key but it has its own problems. I want to remove the foreign key from my field and define relations between tables using ORM. but I don't know how? -
How does attribute of model only for user.is_staff?
Model "Post" has the boolean attribute "moderation". I need the this attribut was only in user.is_staff on the page "Post update". models.py class Post(models.Model): ... moderation = models.BooleanField(default=True) ... forms.py class PostForm(forms.ModelForm): class Meta: model = Post fields = ['title', 'body', 'logo'] views.py class PostUpdateView(PermissionRequiredMixin, UpdateView): model = Post fields = ['title', 'body', 'logo'] permission_required = 'post.can_mark_returned' post_form.html {% extends "base_generic.html" %} {% block content %} <form action="" method="post" enctype="multipart/form-data"> {% csrf_token %} <table> {{ form.as_table }} </table> <input type="submit" value="Submit" /> </form> {% endblock %} -
Django Select2MultipleWidget not allowing multiple selection
I am trying to implement a Select2 Multi-select box in my Django project where a user can select from a range of interests and choose more than 1. What is instead happening is this Where a user sees a scrollable list and can select one. I am looking for this example from Select2 My code is below, I have omitted code that is not relevant. My scripts for JQuery etc are in my base.html file which include Bootstrap, Js, Popper,js and JQuery forms.py from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from .models import Profile from django_select2.forms import Select2MultipleWidget class ProfileUpdateForm(forms.ModelForm): class Meta: model = Profile fields = ['interests'] widgets = { 'interests': Select2MultipleWidget, } models.py from django.db import models from multiselectfield import MultiSelectField from django.contrib.auth.models import User INTEREST_CHOICES = ( ('FITNESS', 'Fitness'), ('SPIRITUAL', 'Spiritual'), ('VEGANISM', 'Veganism'), ('MOVIES', 'Movies'), ) class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) interests = MultiSelectField(choices = INTEREST_CHOICES) profile.html {% extends 'base.html' %} {% load crispy_forms_tags %} {% load static %} {{ form.media.css }} {% block head %} <title>User profile</title> {% endblock %} {% block body %} <script type="text/javascript"> window.onerror = function (msg) { $("body").attr("JSError", msg); } </script> {{ form.media.js }} <div class="container-fluid … -
How to render the options in a select of a Django form?
I would like to render two selects with Django (one multiple select, the other a simple one) and customize it with Materialize. I manage to code the following: In my forms.py class ZonesForm(forms.Form): zones_options = ( (1, 'Zone 1'), (2, 'Zone 2'), (3, 'Zone 3'), (4, 'Zone 4') ) zones = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple, choices=zones_options) conn_options = ( (1, 'ABCDE'), (2, 'FGHIJ'), ) connections = forms.ChoiceField(choices=conn_options) In my zones.html {% block content %} <div class="container"> <div class="row"> <form method="post"> <div class="input-field col s6"> <select multiple name="{{ form.zones.name }}"> {% for opt in form.zones %} <option value="{{ opt.id }}">{{ opt.label }}</option> {% endfor %} </select> <label>Zones</label> </div> <div class="input-field col s6"> <select name="form.connections.name"> {% for opt in form.connections %} <option value="{{ opt.id }}">{{ opt }}</option> {% endfor %} </select> <label>Connection</label> </div> </form> </div> </div> {% endblock %} My problem is: when the page is rendered, I get 4 checkboxes for the first select (as expected), and no names for it (all options are blank). For the second select I get 4 options (one blank, one with 'ABCDE', one blank, one with 'FGHIJ'). I suspect that the problem is with the attributes. I am not getting the right values for them (I have tried … -
Django Gmail API send EMails
Im already using Gmail API for login in my Django project. Im using social-auth-app-django 2.1.0 SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = 'XXXXXX.apps.googleusercontent.com' SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = 'XXXXXXX' now I want to extend this and also send emails via the Gmail API. This means that the sender of the email is the user's own email and not the one from the project page. I've been looking at the reference here. https://developers.google.com/api-client-library/python/guide/django But it doesn't seem to be up-to-date, already the modules CredentialsField and FlowField can't be imported. So my question is, is it possible to integrate this directly via social-auth-app-django as described? If so, how could this be implemented? Unfortunately I didn't find anything suitable on the internet how I could realize it in Django. Im using Django 2.1.3 on Python 2.5.4 -
How to merge the result of two queries using update
I have to show the name of the category and the quantity of items in each category. The items can change the category, so I save the history of the items in the table items_history To show all the category name I'm running this query: category_total = Category.objects.all() Example of result: <QuerySet [<Category: Drink>, <Category: Food>, <Category: Fun>, <Category: Suplies>]> To get the quantity of items in each category, I have to check in the table items_history: items_history = Category.objects.filter(items_history__current=1).annotate(qtd=Count("items_history__idea_id")) Example of result: <QuerySet [<Category: Food>]> items_history[0].name -> 'Food' items_history[0].qtd -> 5 In this case, I have only items in Food Category. So I can't do just one query in items_history, because I'm not gonna get the quantity of the items in the other categories (0, in this case). I need to get all the categories with their respective quantity, so if a category is not persisted in items_history I should get the category name and the quantity = 0. The result expected: items_history[0].name -> 'Drink' items_history[0].qtd -> 0 items_history[1].name -> 'Food' items_history[1].qtd -> 5 items_history[1].name -> 'Fun' items_history[1].qtd -> 0 items_history[1].name -> 'Suplies' items_history[1].qtd -> 0 I'm trying to use update to merge the result of category_total and items_history … -
registered router url returns 404
I'm using django and rest-framework to develop a website. I have a users app in which the models are shown below: class User(AbstractUser): pass class Comment(models.Model): comment_text = models.TextField() author = models.ForeignKey(settings.AUTH_USER_MODEL,default=DefaultUser,on_delete=models.SET_DEFAULT,related_name='author') # DefaultUser is similar to AnonymousUser in django.contrib.aut.models date = models.DateTimeField(default=now) class User_Comment(Comment): on_user = models.ForeignKey(User,on_delete=models.CASCADE,related_name='on_user',default=DefaultUser) class User_Comment(Comment): on_user = models.ForeignKey(User,on_delete=models.CASCADE,related_name='on_user',default=DefaultUser) so it's basically a comment system where a user can comment on another user. I've used a rest framework serializer for posting comments: class User_CommentSerilizer(serializers.ModelSerializer): comment = User_Comment class Meta: model = User_Comment fields = ('comment_text','on_user') # extra_kwargs = {'password': {'write-only': True}} def create(self, validated_data): comment = User_Comment( author= User.objects.filter(username=self.context['request'].user)[0], on_user= User.objects.filter(username=validated_data["on_user"])[0], validated=False, comment_text= validated_data["comment_text"] ) comment.save() return comment and then using a UserCommentViewSet in views.py: class User_CommentViewSet(viewsets.ViewSet): serializer_class = User_CommentSerilizer queryset = User_Comment.objects.all() and finally in the urls file I've registered the view: router = DefaultRouter() router.register('profile' , views.UserViewSet) router.register('comment' , views.User_CommentViewSet) router.register('login' ,views.LoginViewSet, base_name='login') urlpatterns = [ # path('', views.GetUser.as_view()), path('users/', include(router.urls)), ] the profile and login routers are working fine. however the comment router is not showing at all (and returns 404) without raising any other error. I can't figure out what the problem is Although I did find out that it has something … -
django-compressor CACHE folders are empty when CACHES is set to MemcachedCache
I have the following installed on my project Django==2.1.4 django-compressor==2.1 python-memcached==1.59 with the following settings COMPRESS_ENABLED = True CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache', 'LOCATION': '127.0.0.1:11211', 'TIMEOUT': 3600, } } With this configuration, all css and js files are not loaded due to 404 errors. When I check the static folders, CACHE/css and CACHE/js are empty. This is a project that was upgraded from a lower django version. It was working with the same settings prior to upgrade. Previous working version: Django==1.8.4 django-compressor==1.5 python-memcached==1.57 Am I missing some configuration? -
Error moving SQL query from Postgres to MariaDB
This is part of a query which works fine in PostgreSQL (in a Django app): CASE WHEN abc.name = 'foo bar' AND user.first_login <= (now() - interval '{new_user_interval} day') THEN 0 ELSE COALESCE(abc.rank, 0) END AS interesting_value, However, when I try to run it in a MariaDB database, I get this error: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ') THEN 0\n ELSE COALESCE(abc.rank, 0)\n END AS interesti' at line 13" It seems to follow the MySQL case operator syntax fine. Why is this error occurring? -
RuntimeWarning for DateField in Django
Hello i'm using dates for search queries. But i am getting runtime error. RuntimeWarning: DateTimeField Jobs.job_created_on received a naive datetime (2019-01-17 00:00:00) while time zone support is active. Views.py class JobListView(LoginRequiredMixin, generic.TemplateView): template_name = 'admin/jobs/job.html' def get(self, request, *args, **kwargs): context = super(JobListView, self).get_context_data(**kwargs) if 'status' in request.GET: form = JobSearchForm(request.GET) if form.is_valid(): status = form.cleaned_data['status'] start_date = form.cleaned_data['start_date'] end_date = form.cleaned_data['end_date'] company = self.request.user.userprofile.user_company lookups = (Q(job_company=self.request.user.userprofile.user_company) ) if start_date: lookups = lookups | Q(job_created_on__gte=start_date) if end_date: lookups = lookups | Q(job_created_on__lte=end_date) jobs=Jobs.objects.exclude(job_is_deleted = True).filter(lookups) else: form = JobSearchForm() company_name = self.request.user.userprofile.user_company jobs = Jobs.objects.exclude( job_is_deleted = True ).filter( job_company=self.request.user.userprofile.user_company ) return render(request, self.template_name, {'form': form, 'jobs': jobs}) Forms.py ACTIVE_CHOICES = ( ('AllStatus', 'Select Status'), ('Active', 'Active'), ('InActive', 'Inactive'), ) class JobSearchForm(forms.Form): start_date = forms.DateField(label=False) end_date = forms.DateField(label=False) status = forms.ChoiceField(choices=ACTIVE_CHOICES, label=False, initial="") def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['start_date'].widget.attrs['placeholder'] = 'Start Date' self.fields['end_date'].widget.attrs['placeholder'] = 'End Date' # self.fields['status'].initial = 'Select Status' self.fields['start_date'].widget.attrs['class'] = 'job_date' self.fields['end_date'].widget.attrs['class'] = 'job_date' self.fields['start_date'].required=False self.fields['end_date'].required=False Template.html <form action="" method="GET" id="searchForm"> {% crispy form %} </form> -
edit django form with instance always loads with empty form fields
models.py class summary_model(models.Model): username = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT) summary=models.TextField(unique=False, blank=False, null=False) numberofprojects=models.CharField(max_length=264, unique=False, blank=False, null=False) numberofinternships=models.CharField(max_length=264, unique=False, blank=False, null=False) numberofjobs=models.CharField(max_length=264, unique=False, blank=False, null=False) def __str__(self): return str(self.username) forms.py class summary_form(forms.ModelForm): #fields from model class Meta: model = summary_model fields = ('summary','numberofprojects','numberofinternships','numberofjobs') views.py def summaryview(request): username=request.user if request.method == 'GET': try: summaryform=summary_form(request.GET or None,instance=summary_model.objects.get(username=username)) print(summaryform) except: summaryform=summary_form(request.GET or None) elif request.method == 'POST': form4=summary_form(request.POST or None,instance=summary_model.objects.get(username=username)) if form4.is_valid(): summary_obj = form4.save(commit=False) summary_obj.username = request.user summary_obj.save() return redirect('#anotherview') else: summaryform=summary_form(instance =summary_model.objects.get(username =username)) return render(request,'app/summary.html',{'summaryform':summary_form,}) template/summary.html {% block content %} <form action="" method="post" novalidate> {% csrf_token %} {{ summaryform.non_field_errors }} <div class="row form-row bg-white has-shadow"> <div class="col-12"> <span class="labelspan">{{ summaryform.summary.label }}</span> {{ summaryform.summary.errors }} <span class="inputfieldspan">{{ summaryform.summary}}</span> </div> <div class="col-6"> <span class="labelspan">{{ summaryform.numberofprojects.label }}</span> {{ summaryform.numberofprojects.errors }} <span class="inputfieldspan">{{ summaryform.numberofprojects}}</span> </div> <div class="col-6"> <span class="labelspan">{{ summaryform.numberofinternships.label }}</span> {{ summaryform.numberofinternships.errors }} <span class="inputfieldspan">{{ summaryform.numberofinternships}}</span> </div> <div class="col-6"> <span class="labelspan">{{ summaryform.numberofjobs.label }}</span> {{ summaryform.numberofjobs.errors }} <span class="inputfieldspan">{{ summaryform.numberofjobs}}</span> </div> </div> {{ summaryform.message.help_text }} <button type="submit" class="btn3">Save and Continue</button></form> {% endblock %} i need to take input in summary form and allow user to edit using the same view.when i save the filled data its updating but the main issue is its not populating data in the … -
get_context_data function doesn't return the 'form'
I have the following Django code (django version 1.11) of a form: class MyDocumentUpdateView(UpdateView): """ We extend UpdateView as we need to pass self.object in context as resource """ model = MyDocument def get_context_data(self, **context): context[self.context_object_name] = self.object context['resource'] = self.object #context['form'] = self.get_form() <-- if I uncomment this it works return context class DocumentUpdateView(MyDocumentUpdateView): form_class = MyDocumentForm def form_valid(self, form): doc = form.save(commit=False) doc.owner = self.request.user updateMyDocument(doc, form) return HttpResponseRedirect( reverse( 'mydocs_detail', args=( self.object.slug, ))) When I run this code, I get an error: 'str' object has no attribute 'fields' I realized that this error related with the return of the context variable. For some reason the context dictionary does not include the 'form'. As indicated in the documentation: get_context_data(**kwargs)¶ Calls get_form() and adds the result to the context data with the name ‘form’. But in my case the context dictionary does not include the 'form'. If I use the get_form() def, then everything works: context['form'] = self.get_form() But this seems like an overkill to me and I want to dig deeper on why this doesn't work. Then I have noticed that in my case I use: def get_context_data(self, **context): instead of: def get_context_data(self, **kwargs): So I defined the … -
mail_admin in Django + Apache2 = wsgi:error <3
I use mail_admin in my Django site but whan I call this in view all is good without that message come no, and this error in error.log of apache2 My view: def order(request): name = request.POST.get('name', '') telephone = request.POST.get('telephone', '') mail = request.POST.get('email', '') date = timezone.now() if name and telephone and mail: try: mail_admins( 'Product', '"New client '+name+' with phone: '+telephone+' and email: '+mail+' ...blah blah blah "', ['<I'm>@gmail.com', '<some>@gmail.com'],) except BadHeaderError: return HttpResponse('Invalid header found.') user = SmartLightUser(SmartLightUser_name=name, telephone=telephone, mail=mail, ord_date=date) user.save(); return HttpResponseRedirect(reverse('SmartLight:ordered', args=())) else: return HttpResponse('Make sure all fields are entered and valid.') apache2 error.log: [Thu Jan 17 14:32:53.511971 2019] [wsgi:error] [pid 27941:tid 140191074412288] [remote 195.135.246.161:6669] Content-Type: text/plain; charset="utf-8" [Thu Jan 17 14:32:53.512078 2019] [wsgi:error] [pid 27941:tid 140191074412288] [remote 195.135.246.161:6669] MIME-Version: 1.0 [Thu Jan 17 14:32:53.512094 2019] [wsgi:error] [pid 27941:tid 140191074412288] [remote 195.135.246.161:6669] Content-Transfer-Encoding: 8bit [Thu Jan 17 14:32:53.512110 2019] [wsgi:error] [pid 27941:tid 140191074412288] [remote 195.135.246.161:6669] Subject: =?utf-8?b?W0RqYW5nb10gRml4ZSBNYXQg0LfQsNC80L7QstC70LXQvdC90Y8=?= [Thu Jan 17 14:32:53.512124 2019] [wsgi:error] [pid 27941:tid 140191074412288] [remote 195.135.246.161:6669] From: <site>@gmail.com [Thu Jan 17 14:32:53.512138 2019] [wsgi:error] [pid 27941:tid 140191074412288] [remote 195.135.246.161:6669] To: <i'm>@gmail.com [Thu Jan 17 14:32:53.512151 2019] [wsgi:error] [pid 27941:tid 140191074412288] [remote 195.135.246.161:6669] Date: Thu, 17 Jan 2019 12:32:53 -0000 [Thu Jan 17 … -
Python web service for controlling TCP server
What is the best way to create a web API, that would be able to control TCP server? I've tried to do it the following way: import socket from flask import Flask # tcp server TCP_IP = '0.0.0.0' TCP_PORT = 5001 BUFFER_SIZE = 20 app = Flask(__name__) light_on = False @app.before_first_request def launchServer(): global light_on s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.bind((TCP_IP, TCP_PORT)) s.listen(1) CONN, addr = s.accept() while light_on: data = CONN.recv(1024) # SOME LOGIC HERE CONN.shutdown(socket.SHUT_RDWR) CONN.close() @app.route('/start') def start(): print('starting') global light_on light_on = True launchServer() return "Started" @app.route('/stop') def stop(): global light_on light_on = False return "Stopped" if __name__ == "__main__": app.run(host='0.0.0.0', debug=True, port=5000, use_reloader=False) Also, I've packed this app in docker file, and unfortunately I'm not even able to use /start handler. What is the proper/best way to create such web service (Flask is no strict requirement, I can use any python framework)? Service must be able to start, stop, send data back to TCP connection controlled by endpoints. -
Django Unittest that form field is required
I'm am trying to test the form fields have or don't have the required attribute, but I don't know where to find it. This is what I have tried: form.fields[field].widget.attrs['required'] But I get this error: form.fields[field].widget.attrs['required'] KeyError: 'required' -
Python/Django random DB query results due to "Default argument value is mutable" in method
I encountered a bug in my Django app yesterday and even though I fixed it since, I still do not understand its cause, neither how I resolved it. Well, actually I found the root cause while writing this question, thanks to SO "Questions with similar titles" feature. See "Least Astonishment" and the Mutable Default Argument Buuut, I still don't understand how could that affect my app in the way it affected it. So, let's dig in. I have a web page, which display a list of items. I query those items through the Model.get method, from the views.py file. Nothing out of the ordinary, basically fetching the DB from the model, calling the model from the view and providing a variable with the fetched values to the template. When using the faulty source code, I would refresh the page and the items would randomly either appear, or disappear. I figured the DB query would either return the items, or return an empty list. Here is the faulty source code (model.py): @classmethod def get(cls, school=None, additional_filters={}): if school: additional_filters['school'] = school return MyModel.objects.filter( **additional_filters ) And here is how I fixed it: @classmethod def get(cls, school=None, additional_filters=None): if not additional_filters: additional_filters … -
List index out of range error for loop on Json
I'm trying to request a json object and run through the object with a for loop and take out the data I need and save it to a model in django. I only want the first two attributes of runner_1_name and runner_2_name but in my json object the amount or runners varies inside each list. I keep getting list index out of range error. I have tried to use try and accept but when I try save to the model it's showing my save variables is referenced before assignment What's the best way of ignoring list index out or range error or fixing the list so the indexes are correct? I also want the code to run really fast as I will using this function as a background task to poll every two seconds. @shared_task() def mb_get_events(): mb = APIClient('username' , 'pass') tennis_events = mb.market_data.get_events(sport_ids= [9],states=MarketStates.All, per_page=200, offset=0, include_event_participants=Boolean.T, category_ids=None, price_depth=3, side=Side.All) for data in tennis_events: id = data['id'] event_name = data['name'] sport_id = data['sport-id'] start_time = data['start'] is_ip = data['in-running-flag'] par = data['event-participants'] event_id = par[0]['event-id'] cat_id = data['meta-tags'][0]['id'] cat_name = data['meta-tags'][0]['name'] cat_type = data['meta-tags'][0]['type'] url_name = data['meta-tags'][0]['type'] try: runner_1_name = data['markets'][0]['runners'][0]['name'] except IndexError: pass try: runner_2_name = data['markets'][0]['runners'][1]['name'] … -
Not able to load image in by using .html(text) method of jQuery in django/ChatterBot example
ChatterBot Training data set image_data.yml: categories: - myown conversations: - - Marazzo booking report random test one? - <img src="{% static 'img/Book.png' %}" height="50" width="50"> jQuery code: function createRow(text) { var $row = $('<li class="list-group-item"></li>'); $row.empty().html(text); $chatlog.append($row); } app.html: {% load staticfiles %} //on top of file ... .. ... <ul class="list-group chat-log js-chat-log"> </ul> Error: GET http://127.0.0.1:8000/%7B%%20static%20'img/Book.png'%20%%7D 404 (Not Found) Problem is, it is not considering {% load staticfiles %}. That's why it's not rendering my image. Can any one help me in this? Note: I have also tried to give complete local path, for that it is giving not allowed to load local resource error in chrome console.