Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to get value of field select in django admin save_model
I have the following model: class Guest(models.Model): first_name = models.CharField(max_length=128) last_name = models.CharField(max_length=128) category = models.ForeignKey(Category) player_achievement = models.ForeignKey(PlayerAchievement, related_name="guest_achievements") player = models.ForeignKey(Player) I want to get the player selected in the form to use in my save_model method: def save_model(self, request, obj, form, change): player = ??? how do i get this from the admin form? obj.player = player obj.save() -
How does Elastic Beanstalk work behind the scenes for Django?
For running django applications locally I can do django-admin startproject djangotest python djangotest/manage.py runserver and the sample webpage shows up at http://127.0.0.1:8000/ However, when I deploy this to EB with eb deploy It just magically works. My question is does EB runs the command python djangotest/manage.py runserver on the EC2 server after eb deploy by default? What are the list of commands that EB executes to get the webpage working? What if I want it to run with different flags like python djangotest/manage.py runserver --nostatic is that possible? -
Show like button in django template tags
I want to show like button in html use django template tags Models.py class Post(models.Model): user = models.ForeignKey(User) text = models.TextField(blank=True) likes = models.ManyToManyField(User,related_name="likes") created_date = models.DateTimeField( default=timezone.now) published_date = models.DateTimeField( blank=True, null=True) Posts.py @login_required() def post_list(request): posts = Post.objects.order_by('-created_date') comments = Comment.objects.all() likes_active = [] for post in posts: for like in post.likes.all(): if like == request.user: likes_active.append({'post_id':post.pk,'like':True}) else: likes_active.append({'post_id':post.pk,'like':False}) return render(request, 'youtube/post_list.html', locals()) post_list.html {% for post in posts %} {% for like_active in likes_active %} {% if like_active.post_id == post.pk and like_active.like == True %} <i id="like" class="big red link heart icon"></i> {% endif %} {% if like_active.post_id == post.pk and like_active.like == False %} <i id="like" class="big link heart icon"></i> {% endif %} {% endfor %} {% endfor %} it can work but just someone post's like button disappear I don't know How show click/clicked like button is the best way in different user -
convert string to other type in python
Hi everyone I have a simple problem but I don't find the solution, I have a function that returns something like that [[4, 'adr', 0, 0, 1, '2016-04-05T13:00:01'], [115, 'adr', 0, 0, 1, '2016-04-05T14:00:01'], [226, 'adr', 0, 0, 1, '2016-04-05T15:00:01'], [337, 'adr', 0, 0, 1, '2016-04-05T16:00:01']] when I check de type of this variable type(data)say that is a string <type 'str'> I want to create a loop to get each element like this item 1 [4, 'adr', 0, 0, 1, '2016-04-05T13:00:01'] item 2 [115, 'adr', 0, 0, 1, '2016-04-05T14:00:01'] I try to convert the string in a list, a tuple... but nothing work, any idea how to change the string to any type that I can do a loop and get the items when I try to convert in a tuple or string I have this result ('[', '[', '4', ',', ' ', "'", 'a', 'd', 'r', "'", ',', ' ', '0', ',', ' ', '0', ',', ' ', '1', ',', ' ', "'", '2', '0', '1', '6', '-', '0', '4', '-', '0', '5', 'T', '1', '3', ':', '0', '0', ':', '0', '1', "'", ']', ',', ' ', '[', '1', '1', '5', ',', ' ', "'", 'a', 'd', 'r', "'", β¦ -
Django migrate getting OperationalError
I'm fairly new to Django, am using 1.10. I reached a point where I was unable to migrate because of an error, and so backed up to an earlier migration using ./manage.py migrate myapp 0003_auto_20160426_2022 and deleted the later migration files. I then repaired my models.py and ran makemigrations, which worked fine. But when I attempted to migrate, I received the following error (only showing last few lines) File "/Users/wahhab/Sites/rts/env/lib/python3.5/site-packages/MySQLdb/connections.py", line 280, in query _mysql.connection.query(self, query) django.db.utils.OperationalError: (1022, "Can't write; duplicate key in table '#sql-72_4a6'") I don't know how to move forward from this point so that I can continue working on my project. I have data in other apps but only a little test data in this new app so far, so I have considered deleting all migrations and the mySQL tables for this app and starting over, but I don't want to create a worse mess than I have and don't know what is causing this error. Any advice is welcome. Thanks! -
limited number of user-initiated background processes
I need to allow users to submit requests for very, very large jobs. We are talking 100 gigabytes of memory and 20 hours of computing time. This costs our company a lot of money, so it was stipulated that only 2 jobs could be running at any time, and requests for new jobs when 2 are already running would be rejected (and the user notified that the server is busy). My current solution uses an Executor from concurrent.futures, and requires setting the Apache server to run only one process, reducing responsiveness (current user count is very low, so it's okay for now). If possible I would like to use Celery for this, but I did not see in the documentation any way to accomplish this particular setting. How can I run up to a limited number of jobs in the background in a Django application, and notify users when jobs are rejected because the server is busy? -
Prevent serializer creating duplicate items
I would like my serializer to stop duplicated creation of tags if they are the same. I tried adding "unique" to the model field of "name" in the class Tag but this did not work- it wouldn't allow me to create other Movie's that linked to a tag which exists. Check if the field "name" already exists (case insensitive). If the tag "name" exists, just create the FK relationship with the existing tag name & the new movie If the tag "name" doesn't exist, create it Models.py class Tag(models.Model): name = models.CharField("Name", max_length=5000, blank=True) def __str__(self): return self.name class Movie(models.Model): title = models.CharField("Whats happening?", max_length=100, blank=True) tag = models.ManyToManyField('Tag', blank=True) def __str__(self): return self.title Serializers.py class TagSerializer(serializers.ModelSerializer): taglevel = filters.CharFilter(taglevel="taglevel") class Meta: model = Tag fields = ('name', 'taglevel', 'id') class MovieSerializer(serializers.ModelSerializer): tag = TagSerializer(many=True, read_only=False) info = InfoSerializer(many=True, read_only=True) class Meta: model = Movie fields = ('title', 'tag') def create(self, validated_data): tags_data = validated_data.pop('tag') movie = Movie.objects.create(**validated_data) for tag_data in tags_data: movie.tag.create(**tag_data) return movie -
Same code, works in runserver but not in apache
views.py def create_reply(request, topic_id): if request.method == 'POST': t = topic.objects.get(id=topic_id) past_time = int(time.time() - t.locktime) r = post() r.topic = t if request.POST['content']: r.content = request.POST['content'] else: return error(request, 'δΈθ½η©Ίη') # messages.add_message(request, messages.WARNING, _('content cannot be empty')) # return HttpResponseRedirect(reverse('topic_view', kwargs={'topic_id': topic_id})) if past_time > 300: messages.add_message(request, messages.WARNING, _('overtime')) return HttpResponseRedirect(reverse('topic_view', kwargs={'topic_id': topic_id})) r.user = request.user # when success to reply ,unlock the topic. t.locker = '0' t.locked = False t.last_replier = request.user.username r.floor = t.reply_count + 1 r.keyword = t.keyword if t.keyword == "keywordwrite": t.keyword = rand_key() elif t.keyword == "freewrite": t.keyword = None user_has_subscribed = t.subscriber.filter( username=request.user.username ) if not user_has_subscribed: t.subscriber.add(request.user) t.save() r.save() sendemail.after_response(t.subscriber.all(),t) sendemail(t.subscriber.all(), t) return HttpResponseRedirect(reverse('topic_view', kwargs={'topic_id': t.id})) elif request.method == 'GET': return error(request, 'don\'t get') sendemail is from django.core.mail import EmailMessage import after_response @after_response.enable def sendemail(users_list,topic): def get_mail_list(users_list): def getmail(user): return user.email mail_list = map(getmail,users_list) return mail_list link ='http://www.gushijielong.cn/topic/'+str(topic.id) mail_list=get_mail_list(users_list) mailtitle =u'δ½ ε ³ζ³¨ηδΈ»ι’οΌ'+ topic.title + u'ζζ°ηζ₯η»δΊ' mailcontent = u'ηΉε»ζ₯η'+ topic.title + u'ηζ°ζ₯η»' + "<a href='" + link + u"'>ηΉε»</a>" email = EmailMessage(mailtitle, mailcontent, to=mail_list) email.content_subtype = "html" print mailcontent email.send() This code is for sending email to the subscribers when a topic has a new reply. It works( I can receive the emails ) β¦ -
How to exclude a part of a Django template file from processing?
I have a Django template file that has a couple of enormous strings in it (images encoded in Base64). When I use the Django templating engine, it chokes and takes 5 minutes to render the template. Is there a way to exclude a part of a template, with something like: {% ignore %} <img src='....'> {% endignore %} Does this exist? -
can't upload image in django admin on deployment
I just tried to change(upload) the picture of one of my records in django admin, and when i submit the "save" button, it said that it has changed successfully but nothing is uploaded and also the path of the image_field didnt change!!! I have exactly the same project on my computer and i can upload files without problem, the only thing that is different in my computer and the server that i deployed my project is the mysql driver, i used "python-mysqldb" on my computer and "mysqlclient" on the server.(and it was weird that i couldnt install "python-mysqldb" on the server, it had been installed on the python2, while i wanted to install it on python3) note: i have apache2.4 installed on both server and my computer. so, what is the problem ?! -
How can I prevent a logged in user from accessing a 'Log In' or 'Sign Up' page in Django version 1.9?
I'm pretty new to Python. My problem is that I want to restrict users who are already logged in from being able to visit the log in and sign up pages. Essentially, what I'm looking for is something like the @login_required decorator, that will allow access to these pages for users who are not logged in. So far, I have Looked at other SO questions such as Django-Registration: How to prevent logged in user from registering?, however I've tried the solution here, and it does not work for me. I've searched through the Django Documentation, Django Girls and other websites that offer tutorials for learning Django. Here's my views.py for the log in: def login_view(request): # Login View to begin user session print(request.user.is_authenticated()) if request.method == 'POST': form = UserLogInForm(request.POST) if form.is_valid(): username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') user = authenticate(username=username, password=password) if user is not None: login(request, user) print(request.user.is_authenticated()) return HttpResponseRedirect('/') else: form = UserLogInForm() return render(request, 'login.html', {'form': form}) else: form = UserLogInForm() return render(request, 'login.html', {'form': form}) and the sign up: class signup_view(View): form_class = UserSignUpForm template_name = 'signup.html' # Blank form is requested def get(self, request): form = self.form_class(None) return render(request, self.template_name, {'form': form}) # Form β¦ -
Django Rest Create with a Writable Nested Serializer
I'm trying to perform a create in Django Rest Framework using a writable nested serializer. With the code bellow I can create a ScriptQuestion but I can't add a RecordedInterview into it. Django says OrderedDict is None. What am I doing wrong? Thanks in advance #models.py class ScriptQuestion(models.Model): interview = models.ManyToManyField(RecordedInterview) ... class RecordedInterview(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) ... The serializers #serializers.py class InterviewTitleSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = RecordedInterview fields = ('id', 'title') extra_kwargs = { 'title': { 'read_only': True } } class QuestionDetailSerializer(serializers.HyperlinkedModelSerializer): interview = InterviewTitleSerializer(many=True) class Meta: model = ScriptQuestion fields = ('id', 'title', 'prep_time', 'answer_time', 'interview') depth = 1 def create(self, validated_data): interview_data = validated_data.pop('interview') question = ScriptQuestion.objects.create(**validated_data) for item in interview_data: item = interview_data['id'] question.interview.add(item) return question Here is my view #views.py class CreateQuestion(generics.CreateAPIView): queryset = ScriptQuestion.objects.all() serializer_class = QuestionDetailSerializer And the json { "title": "Question Test Json", "prep_time": "1", "answer_time":"1", "interview": [ { "id": "a450aeb0-8446-47b0-95bd-5accbb8b4afa" } ] } If I do manually, I can add the RecordedInterview into the ScriptQuestion: #serializers.py def create(self, validated_data): interview_data = validated_data.pop('interview') question = ScriptQuestion.objects.create(**validated_data) item = 'a450aeb0-8446-47b0-95bd-5accbb8b4afa' question.interview.add(item) return question -
django class based view multiple form validatiton
I'm currently trying to have two forms on a single page. I'm using Class Based Views. class TaskDetailView(FormMixin, generic.DetailView): model = Task template_name="tasks/detail.html" form_class = NoteForm form_class2 = DurationForm def get_context_data(self, **kwargs): context = super(TaskDetailView, self).get_context_data(**kwargs) context['note_form'] = self.get_form() context['notes'] = Note.objects.filter(task__slug=self.kwargs['slug']) context['duration_form'] = self.form_class2() context['duration'] = Duration.objects.all() return context def get_success_url(self): return reverse('task_detail', kwargs={'slug': self.kwargs['slug']}) def post(self, request, *args, **kwargs): if not request.user.is_authenticated: return HttpResponseForbidden self.object = self.get_object() form = self.get_form() if form.is_valid(): return self.form_valid(form) else: return self.form_invalid(form) def form_valid(self, form): current_task = get_object_or_404(Task, slug=self.kwargs['slug']) self.object = form.save(commit=False) self.object.task = current_task self.object.save() return HttpResponse(self.get_success_url()) My current status is that I'm able to display all the forms and save ONLY the Notes form. I'm not able to save the Duration Form despite there's a 200 status POST, the data is not being saved to the database. I think my mistake is that I'm not validating it but I'm really not sure how to, and there isn't much information on multiple forms on CBVs in Django. I would really appreciate some guidance and assistance. Thanks -
Adding javascript to a Django redirect (HttpResponse)
I am using a redirect in Django from django.shortcuts import redirect What I want, is for the user to be displayed a Javascript alert message before being redirected. Here is what I've got so far: response = redirect("someUrl") response.write('<script>alert(\'You must remove an item before adding another\');</script>') response['location'] += "?active=" + "all" return response The redirect works, but the Javascript does not. I also tried response = HttpResponse('<script>alert(\'You must remove an item before adding another\');</script>') return response This triggers the alert window, but I'm not sure how to add an equivalent redirect as the method above. -
Difference between storing objects in django session(pickle) and in django-redis session?
What is the difference between storing objects in django session and django-redis session ? can anyone give me a detailed explanation -
PyOpenSSL, PyCrypto related Issue on Google Compute Engine Debian8
I made few changes in requirements.txt file of my django App hosted on Google Compute Engine with Debian8 running on Apache mod_wsgi. But I got this Long Error Trace which I am not able to resolve. I know this is related to cryptography/OpenSSL and similar packages but don't know how to resolve it exactly. Error Trace: File "/usr/local/lib/python2.7/dist-packages/gcloud/datastore/query.py", line 434, in next_page transaction_id=transaction and transaction.id, File "/usr/local/lib/python2.7/dist-packages/gcloud/datastore/connection.py", line 286, in run_query _datastore_pb2.RunQueryResponse) File "/usr/local/lib/python2.7/dist-packages/gcloud/datastore/connection.py", line 124, in _rpc data=request_pb.SerializeToString()) File "/usr/local/lib/python2.7/dist-packages/gcloud/datastore/connection.py", line 93, in _request method='POST', headers=headers, body=data) File "/usr/local/lib/python2.7/dist-packages/oauth2client/transport.py", line 153, in new_request credentials._refresh(orig_request_method) File "/usr/local/lib/python2.7/dist-packages/oauth2client/client.py", line 765, in _refresh self._do_refresh_request(http_request) File "/usr/local/lib/python2.7/dist-packages/oauth2client/client.py", line 792, in _do_refresh_request body = self._generate_refresh_request_body() File "/usr/local/lib/python2.7/dist-packages/oauth2client/client.py", line 1501, in _generate_refresh_request_body assertion = self._generate_assertion() File "/usr/local/lib/python2.7/dist-packages/oauth2client/service_account.py", line 386, in _generate_assertion key_id=self._private_key_id) File "/usr/local/lib/python2.7/dist-packages/oauth2client/crypt.py", line 97, in make_signed_jwt signature = signer.sign(signing_input) File "/usr/local/lib/python2.7/dist-packages/oauth2client/_openssl_crypt.py", line 97, in sign return crypto.sign(self._key, message, 'sha256') File "/usr/local/lib/python2.7/dist-packages/OpenSSL/crypto.py", line 2645, in sign md_ctx = _lib.Cryptography_EVP_MD_CTX_new() AttributeError: 'module' object has no attribute 'Cryptography_EVP_MD_CTX_new' Can someone please suggest some solution to resolve this issue ? Thanks, -
builtins.ValueError when redirect with 2 kwargs
I want to perform a redirect in one of my view, and I'm facing an error with not many details. My urls.py: urlpatterns = [ url( regex=r'^(?P<pk>[0-9]+)/$', view=views.SheetDetailView.as_view(), name='detail' ), url( regex=r'^(?P<pk>[0-9]+)/branch/(?P<branch_slug>[a-zA-Z0-9-]+)/$', view=views.SheetDetailView.as_view(), name='detail' ), ] My view class SheetDetailView(LoginRequiredMixin, UserIsLinkedToSheetMixin, UserPassesTestMixin, DetailView): model = Sheet def get_context_data(self, **kwargs): context = super(SheetDetailView, self).get_context_data(**kwargs) #if no branch is requested, show the master if 'branch_slug' in self.kwargs: branch = self.get_object().get_branch(self.kwargs['branch_slug']) context['branch']=branch return context else: # redirect to master sheet_id = self.get_object().pk branch_slug = self.get_object().get_master().slug return redirect(reverse('sheets:detail', kwargs={'pk':sheet_id, 'branch_slug':branch_slug}), permanent=False) And my error message: Traceback (most recent call last): File "/usr/local/lib/python3.5/site-packages/django/contrib/staticfiles/handlers.py", line 63, in __call__ return self.application(environ, start_response) File "/usr/local/lib/python3.5/site-packages/django/core/handlers/wsgi.py", line 177, in __call__ response = self.get_response(request) File "/usr/local/lib/python3.5/site-packages/django/core/handlers/base.py", line 230, in get_response response = self.handle_uncaught_exception(request, resolver, sys.exc_info()) File "/usr/local/lib/python3.5/site-packages/django/core/handlers/base.py", line 289, in handle_uncaught_exception return debug.technical_500_response(request, *exc_info) File "/usr/local/lib/python3.5/site-packages/django_extensions/management/technical_response.py", line 6, in null_technical_500_response six.reraise(exc_type, exc_value, tb) File "/usr/local/lib/python3.5/site-packages/six.py", line 686, in reraise raise value File "/usr/local/lib/python3.5/site-packages/django/core/handlers/base.py", line 174, in get_response response = self.process_exception_by_middleware(e, request) File "/usr/local/lib/python3.5/site-packages/django/core/handlers/base.py", line 172, in get_response response = response.render() File "/usr/local/lib/python3.5/site-packages/django/template/response.py", line 160, in render self.content = self.rendered_content File "/usr/local/lib/python3.5/site-packages/django/template/response.py", line 137, in rendered_content content = template.render(context, self._request) File "/usr/local/lib/python3.5/site-packages/django/template/backends/django.py", line 92, in render context = make_context(context, request) File β¦ -
Django, Bower. Organization of work with third-party js-libraries in Django-project
I need advice about organization of work in Django-project with Bower. Simple project structure: src βββ apps βββ base βββ common β βββ static β β βββ css β β βββ img β β βββ js β βββ templates β βββ views βββ manage.py βββ requirements.txt βββ utils The current scripts are stored in the directory common/static/js where is storage js-library downloaded with bower? (about file-manifest and dowloading on server i know, but I want to include the js-libraries in repository) Can i change default folder in bower setting bower_components/ on common/script/js (so js-libraries were stored in the same directory)? Or this structure incorrect? Please share your comments and advice on project structure -
Django IOError 13 - permission denied when trying to write to static file
I've spent long hours trying to make Django open and write content into a remote file. This post can be considered as second part of the previously asked question on the same topic. However, this time I managed to make Django see the file, and the error changed from 'IOError - such file or directory does not exist' to IOError at /my_view/[Errno 13] Permission denied: '/var/www/test/djprj/djprj/static/media/my_target_file.xml The view (located in \\10.8.0.1\share\djprj\djprj\djprj\egais): def my_view (request) #... with open(os.path.join(settings.MEDIA_ROOT, 'my_target_file.xml'), 'w') as f: f.write(html_content.encode('utf8')) f.close; settings.py (only relevant part of it) import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) INSTALLED_APPS = [ ... 'django.contrib.staticfiles', ... ROOT_URLCONF = 'supermarket_project.urls' WSGI_APPLICATION = 'supermarket_project.wsgi.application' PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__)) AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] STATIC_URL = '/static/' if DEBUG: MEDIA_URL = '/media/' STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR),"static","static-only") #STATIC_ROOT = [os.path.join(BASE_DIR,"static-only")] MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR),"static","media") #MEDIA_ROOT = [os.path.join(BASE_DIR,"media")] STATICFILES_DIRS = ( os.path.join(os.path.dirname(BASE_DIR),"static","static"), ) Previously, my file was located in the static folder or the folder of the app itself, and Django could not find the file and/or folder for some reason. After moving it to Media, the error changed from "no such file or folder" to "permission denied". MOST β¦ -
Expected type 'Union[str, unicode]', got 'CharField' instead
I'm working on django using mysql. When I try to load data from AWS mysql server I'm getting an error: django.db.utils.DataError: (1406, "Data too long for column 'key' at row 1") My thinking is it has to do with an error in my models.py file. PyCharm is showing this message in my code - highlighted in yellow, not from running the file -: Expected type 'Union[str, unicode]', got 'CharField' instead This is the class I wrote, edited for putting up here: class ClassName(models.Model): item1 = models.ForeignKey("Another_class") item2 = models.CharField(max_length=2000) item3 = models.IntegerField(default=1) def __str__(self): return self.item2 def get_classname_url(self, parameter1, parameter2, parameter3=1): return "http://website.com/" + str(parameter1) + "_" + str(parameter2) + "_" + str(parameter3) + "a_defining_string" + self.item2 My guess on how to load the data is to correct this Union/CharField issue. As you can see, I've tried to increase the CharField(max_length) to 2000 even, though I understand why this wouldn't work. I've also tried to change it to a TextField, and also understand why this wouldn't work. But worth a shot I suppose. What do you all think would be a solid work around this? Also, why is PyCharm expecting unicode? -
Allow only one instance of a model in Django
I would like to control some configuration settings for my project using a database model. For example: class JuicerBaseSettings(models.Model): max_rpm = model.IntegerField(default=10) min_rpm = model.IntegerField(default=0) There should only be one instance of this model: juicer_base = JuicerBaseSettings() juicer_base.save() Of course, if someone accidentally creates a new instances, it's not the end of the world. I could just do JuicerBaseSettings.objects.all().first(). However, is there a way to lock it down such that it's impossible to create more than 1 instance? I found two related questions on SO. This answer suggests using 3rd party apps like django-singletons, which doesn't seem to be actively maintained (last update to the git repo is 5 years ago). Another answer suggests using a combination of either permissions or OneToOneField. Both answers are from 2010-2011. Given that Django has changed a lot since then, are there any standard ways to solve this problem? Or should I just use .first() and accept that there may be duplicates? -
Django internationalization: inheritance of existing .po file
Is there a parameter in gettext to create a .po file inheriting another .po file's strings? E.g. I have an English (en) file containing all translations to English and I would like to create an Australian English (en-au) file with just some minor changes (related to my en file), is it possible to, somehow, inherit all English string so I wouldn't need to translate everything again? -
Filter Using Checkboxes w. Jquery
I am trying to create checkbox filters that show or hide boxes on my pagebased on their id. I'm very new to jquery, but have been playing around with this for a while and cannot seem to get the boxes to hide / show. Please see my code below. Thanks! Sport model class Sport(models.Model): name = models.CharField(max_length=128) Snippet of HTML to filter {% for game in game_list %} {% if game.sport = sport %} <div class="col-xs-12 col-sm-12 col-lg-12"> <section id="{{ sport.name }}" class="box pick-game"> <div class="box box-content"> <div class="game-bet-header"> <div class="row"> <div class="col-md-3"> <h4 class="game-date"> {{ game.time|time }} - {{ game.time|date:"M-d" }}</h4> </div> <div class="col-md-6"> <h4 class="game-title">{{ game.team1 }} vs {{ game.team2 }} </h4> </div> </div> </div> HTML Checkboxes to Use as Filters <div class="sport-sidebar"> <section class="sports-box"> {% for sport in sports %} <div id="sport-filter" class="sport-name"> <label for="filter-{{ sport.name }}"><input type="checkbox" class="sport" value="{{ sport.name }}" id="filter-{{ sport.name }}">{{ sport.name }}</label> </div> {% endfor %} </section> </div> Jquery $('#sport-filter input:checkbox').click(function() { $('#sport-filter input:checkbox:checked').each(function() { $("#" +$(this).val()).show() }); }); -
Why should I use __init__ in models, and how to change '---' selected? django
I have two questions - (1) I see many times that people use __init__ in there code. Why is that and how it can hellp? Can i build a web without using it? (2) I have '---' in my Select field and i really dont know how to change it. here is my code i speaking about: class LogInForm(forms.ModelForm): class Meta: model = UserModel widgets = { 'password': forms.PasswordInput, 'full_name': forms.TextInput(attrs={'class': 'form-field form-control'}), 'password': forms.TextInput(attrs={'class': 'form-field form-control'}), 'gender': forms.Select(attrs={'class': 'form-control'}), 'email': forms.TextInput(attrs={'class': 'form-field form-control'}), 'about': forms.TextInput(attrs={'class': 'form-field form-control'}), } ^ speaking about the row "gender" -
Why I am getting django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet?
Since I had same abstract model in every app model I have To avoid redundancy I just moved my common abstract model into new app I created and called it common Common Models.py now is from django.db import models LANGUAGE_CHOICES = ( ('E','ENGLISH'), ('F','FRENCH'), ('S','SPANISH'), ) class CommonInfo(models.Model): created = models.DateTimeField("creation date", auto_now_add=True) modified = models.DateTimeField("modification date", auto_now=True) description = models.TextField() class Meta: abstract = True then I added my common app to settings.py And finally, in all my apps I added from common.models import CommonInfo from common.models import LANGUAGE_CHOICES After running the local server this is the error I am getting in terminal (full trace) Traceback (most recent call last): File "manage.py", line 10, in execute_from_command_line(sys.argv) File "C:\Users\Boris\dev\rentout\virtrentout\lib\site-packages\django\core\m anagement__init__.py", line 338, in execute_from_command_line utility.execute() File "C:\Users\Boris\dev\rentout\virtrentout\lib\site-packages\django\core\m anagement__init__.py", line 312, in execute django.setup() File "C:\Users\Boris\dev\rentout\virtrentout\lib\site-packages\django__init .py", line 18, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\Boris\dev\rentout\virtrentout\lib\site-packages\django\apps\r egistry.py", line 108, in populate app_config.import_models(all_models) File "C:\Users\Boris\dev\rentout\virtrentout\lib\site-packages\django\apps\c onfig.py", line 198, in import_models self.models_module = import_module(models_module_name) File "c:\python27\Lib\importlib__init.py", line 37, in import_module import(name) File "C:\Users\Boris\dev\rentout\rentout\lease\models.py", line 94, in class LeaseFilter(django_filters.FilterSet): File "C:\Users\Boris\dev\rentout\virtrentout\lib\site-packages\django_filter s\filterset.py", line 181, in new filters = new_class.filters_for_model(opts.model, opts) File "C:\Users\Boris\dev\rentout\virtrentout\lib\site-packages\django_filter s\filterset.py", line 456, in filters_for_model cls.filter_for_reverse_field File "C:\Users\Boris\dev\rentout\virtrentout\lib\site-packages\django_filter s\filterset.py", line 104, in filters_for_model filter_ β¦