Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Haystack rebuild Index and update Index
I am getting UnicodeEncodeError: 'ascii' codec can't encode character u'\u2019' in position 26: ordinal not in range(128) while rebuilding index. models.py from django.contrib import admin from django.db import models from haystack import indexes __all__ = ['Events'] class Events(models.Model): ''' Events ''' class Meta: ''' Meta properties for this model ''' app_label = 'admin' verbose_name_plural = 'Events' headLine = models.CharField( max_length=50, default=None, db_index=True, unique=True, ) write_date = models.DateField(auto_now=False) venue = models.CharField(max_length=200, default=None, db_index=True, unique=False) Content = models.TextField(default=None) display_pic = models.FileField(upload_to='Events') def __unicode__(self): ''' Returns object display name ''' return self.headLine class EventsAdmin(admin.ModelAdmin): ''' Events view for admin ''' list_display = ( '__unicode__', ) admin.site.register(Events, EventsAdmin) class EventsIndex(indexes.SearchIndex, indexes.Indexable): """ MasterTrainersIndex Index for Haystack """ text = indexes.CharField(document=True) headLine = indexes.CharField(model_attr='headLine') def get_model(self): "Return model class for current index" return Events def index_queryset(self, using=None): "Used when the entire index for model is updated." return self.get_model().objects.all() def prepare_model_type(self, obj): "Fetch model type" return "Events" def prepare_auth(self, obj): return str(obj.headLine) def prepare_text(self, obj): "Prepare primary document for search" pattern = "{headLine}\n" return pattern.format( headLine=obj.headLine, ) search_index.py I have imported my models in search_index.py from admin.models.events import EventsIndex When I try to ./manage.py rebuild_index from terminal I get following error UnicodeEncodeError: 'ascii' codec can't encode … -
Django-cms: 'Settings' object has no attribute 'SITE_ID'
I would like to enable my django-cms instance to host multiple sites. For that I created two different sites in the admin panel. Unfortunately only one site is shown because I needed to hardcode the SITE_ID in the project settings. According to https://github.com/django/django/pull/2460 this is not a mandatory setting anymore. But my Django 1.10.7 instance shows the following traceback if I delete it: Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/var/www/venv/lib/python3.5/site-packages/django/core/management/__init__.py", line 338, in execute_from_command_line utility.execute() File "/var/www/venv/lib/python3.5/site-packages/django/core/management/__init__.py", line 312, in execute django.setup() File "/var/www/venv/lib/python3.5/site-packages/django/__init__.py", line 18, in setup apps.populate(settings.INSTALLED_APPS) File "/var/www/venv/lib/python3.5/site-packages/django/apps/registry.py", line 115, in populate app_config.ready() File "/var/www/venv/lib/python3.5/site-packages/django/contrib/admin/apps.py", line 22, in ready self.module.autodiscover() File "/var/www/venv/lib/python3.5/site-packages/django/contrib/admin/__init__.py", line 24, in autodiscover autodiscover_modules('admin', register_to=site) File "/var/www/venv/lib/python3.5/site-packages/django/utils/module_loading.py", line 74, in autodiscover_modules import_module('%s.%s' % (app_config.name, module_to_search)) File "/usr/lib/python3.5/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 986, in _gcd_import File "<frozen importlib._bootstrap>", line 969, in _find_and_load File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 673, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 665, in exec_module File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed File "/var/www/venv/lib/python3.5/site-packages/cms/admin/__init__.py", line 2, in <module> import cms.admin.pageadmin File "/var/www/venv/lib/python3.5/site-packages/cms/admin/pageadmin.py", line 39, in <module> from cms.admin.forms import ( File "/var/www/venv/lib/python3.5/site-packages/cms/admin/forms.py", … -
Pre-populating a child models django create form with a parent's ID
I have followed the guidelines from This answer in order to pass Parent pk to the child creation page. At the moment though it is not working and I am seeing the following log. [14/Jul/2017 13:15:37] "POST /catalog/ProductInstance/2/create/ HTTP/1.1" 200 4001 I'm not sure what I'm doing wrong, here is the code I currently have. Models Models.py class Product(models.Model): serial_number = models.CharField(unique=True, max_length=15) class ProductStatus(models.Model): serial_number = models.ForeignKey('Product', on_delete=models.CASCADE, null=True) status = models.CharField(max_length=20, blank=True, default='Stock', help_text='Products status') date = models.DateTimeField(auto_now_add=True) View class ProductStatusCreate(CreateView): model = ProductStatus template_name = 'catalog/productstatus_create.html' form_class = ProductStatusModelForm def form_valid(self, form): productstatus = form.save(commit=False) product_id = form.data['product_id'] product = get_object_or_404(Product, id=product_id) productstatus.product = product return super(ProductStatusCreate, self).form_valid(form) def get_context_data(self, **kwargs): context = super(ProductStatusCreate, self).get_context_data(**kwargs) context['s_id'] = self.kwargs['product_id'] return context def get_success_url(self): if 'product_id' in self.kwargs: product = self.kwargs['product_id'] else: product = self.object.product.pk return reverse_lazy('product_detail', kwargs={'pk': product}) Forms class ProductStatusModelForm(forms.ModelForm): class Meta: model = ProductStatus fields = ['status',] def __init__(self, *args, **kwargs): self.fields["product"] = forms.CharField(widget=forms.HiddenInput()) super(ProductStatusModelForm, self).__init__( *args, **kwargs) templates/myapp/product_detail.html <a href="{% url 'productinstance_create' product_id=product.id %}">New</a> urls.py urlpatterns += [ url(r'^productinstance/(?P<product_id>\d+)/create/$', views.ProductInstanceCreate.as_view(), name='productinstance_create'), ] productstatus_create.html {% extends "base_generic.html" %} {% block content %} <h2>New Product Status</h2> </br> <form action="" method="post"> {% csrf_token %} <table> <input type=hidden id="id_product" … -
Best way to update_or_create an object on Django/Mongoengine
Is there any efficient way to update or create a record? Using Django with a SQL database, just do it. Data = { 'First_name': 'foo', 'Last_name': 'bar' } Person.objects.update_or_create (cod = 1, defaults = data) Is there any similar way of doing this in the mongoengine? I tried using the modify as follows reg = Person.objects.filter(cod=1) Person.objects(cod=1).modify( first_name="foo", last_name="bar", new=False if reg else True ) but it did not work. -
reverse error in django not showing what it cant reverse
I don't think I am reversing '' but still I am getting an error: Reverse for '' not found. '' is not a valid view function or pattern name. Don't know where the source of error is because it is not showing what reverse is not found. urls.py url(r'^search_page/$', views.index, name='search_page'), url(r'^search_customer/$',views.ajax_customer_search,name='search_customer'), template:base.html <!DOCTYPE html> <html> <head> <title>Django/jQuery AJAX Search</title> <script type="text/javascript" src="http://jqueryjs.googlecode.com/files/jquery-1.2.6.js"></script> {% block extra_js %} {% endblock %} </head> <body> <div id="centered"> {% block main %}{% endblock %} </div> </body> </html> template:index.html {% extends "base.html" %} {% block extra_js %} <script type="text/javascript"> $( document ).ready( function() { $( "#searchSubmit" ).click( function() { q = $( "#q" ).val(); $( "#results" ).html( "&nbsp;" ).load( "{% url search_customer %}?q=" + q ); }); }); $( document ).ajaxStart( function() { $("#spinner").show(); }).ajaxStop( function() { $( "#spinner" ).hide(); }); </script> {% endblock %} {% block main %} <div> <input id="q" type="text"/> <input id="searchSubmit" type="submit" value="Search"/> <br/> <span class="hint">Type in a query string to search for users</span> <div class="margin"> <span id="spinner"><img src="http://upload.wikimedia.org/wikipedia/commons/d/de/Ajax-loader.gif"/></span> <div id="results"></div> </div> </div> {% endblock %} {% if results|length %} <table> <tr class="even"> <td colspan="3" class="right"> <strong>Found {{ results|length }} users</strong> </td> </tr> {% for user in results %} <tr class="{% … -
Upload File With Django Via FTP
A quick question has anyone wrote a script or is there package that allows for model uploads to a separate server to store files. I do not want to use Amazon S3 since this application is for a non-profit who has limited funds. I have a server available to store files. I am looking for any suggestions and tips. -
Django.Wsgi.Apache. Error 403 in Apache2
There are two website made on Django. Their config files are same (renamed the names, the paths to the projects). But First is working and Second not working. There are two website made on Django. Their config files are the same (renamed the names, the paths to the projects). But First is working and Second not working. firstweb.conf. <VirtualHost *:80> WSGIScriptAlias / /var/www/firstweb/firstweb/wsgi.py ServerName firstweb.com Alias /static /var/www/firstweb/static <Directory /var/www/firstweb> Order deny,allow Deny from all Allow from all </Directory> ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined </VirtualHost> Now from the second site(twoweb) I have got the error 403 (Forbidden). Access to the projects: drwxrwxrwx 3 andrey andrey 4096 июл 14 14:19 firstweb drwxrwxrwx 3 andrey andrey 4096 июл 14 14:28 twoweb What am I doing wrong?Thank and sorry for my english. -
Excel import to model in Django
Can anyone please refer me to a code to import excel file into django models. I have literally searched all the websites but was not able to find a proper code. -
Workaround for setTimeout issue
HTML <div class="wrapper"> <div id="overlay"></div> <a href="#" title="{% trans "Send email - rejected file(s)" %}" class="btn btn-icon select-another-button" data-url="{% url "messaging:send" request_id=object.pk %}"> <i class="material-icons">assignment_late</i> <div class='alert alert-success' id="show-message" style="display: none;"> <p> The message was sent to the client. Please wait 5 minutes <br> before sending the message again. </p> </div> </a> </div> JavaScript $(function(){ var timeout; $('.select-another-button').each(function(){ $(this).bind('click', function(e) { $(this).attr('disabled','true'); //disables the button $('#overlay').show(); //after disabling show the overlay for hover timeout = setTimeout(function(){ $(this).attr('disabled','false'); //enables after 5mins $('#overlay').hide(); //hide the overlay }, 300000); e.preventDefault(); fileBrowser(this); return false; }); }); }); $("#overlay").hover(function(){ var timeleft = Math.ceil((timeout._idleStart + timeout._idleTimeout - Date.now()) / 1000); $('#show-message').html("Please wait" + timeleft).show(); },function(){ $('#show-message').hide(); }); Django The method is @staff_member_required @csrf_exempt def send(request, request_id=None): req= Request.objects.get(pk=request_id) request_folders = req.folder.all_files.all() context = [] for doc in request_folders: if doc.meta.state == u'rejected': context.append(doc) if context: ctx = {'request': req} EmailFromTemplate('document-refusal', extra_context=ctx)\ .send_to(req.customer.user) return HttpResponse('') The urls.py file is app_name = 'messaging' urlpatterns = [ ... url(r'^send/(?P<request_id>[0-9]+)/$', send, name='send'), ] I've created a button which will send an email. Once it sends, the button will deactivate for five minute and a message is displayed if and only if the cursor is on the button. Actually, when the … -
How to style the imagefied in django forms?
I have a user model and user can upload multiple photos in another model. So, when updatging/creating the user, I have used inline forms to add/update photos also. The default django image upload field rendering is not very good. It displays details like the current image url, remove checkbox, file upload field and other messages(Currently,Change etc). This is not attractive at all. I mean for an admin interface, it is ok; but when it comes to end user interface, I have to say its not good enough. I have found ways to display thumbnail instead of image_url from database. But I still need it to be better. Is there anyway I can render it as below? The drag drop function is not required as for each image i want to display the widget and the image itself as background of widget in edit forms with change option. Is there any way to do this? -
Djano's only() still selects every existing field
I have a Django model consisting of multiple fields. I only wish to select one. I use only() as, according to the documentation it should return only the woodAsked field here. Yet the returned queryset will still contain each and every field in the Painting model. >>> a = Painting.objects.only('woodAsked') >>> serializers.serialize("json",a)[1:200] '{"model": "binaryQuestionApp.painting", "pk": 3, "fields": {"name": "Getty00052501.jpg", "objectNumber": "00052501.jpg", "collection": "Getty", "title": "pretty after al", "woodAsked": 0, "woodYes": ' How can I select ONLY the 'woodAsked' field? -
How to prefetch_related in django rest framework over nested models
Yesterday I installed Silk and examined that each query takes how much time and I realized that I it queries database 108 times which are a lot so I decided to use select_related and prefetch_related but in Django rest framework I got serious problems. As you see in files bellow I have a Like model and When a person get new Posts I want to send a field is_like to show in Ui that person like this post or not ... How can I use pre_fetch to show likes ? models.py class Users(models.Model): id = models.BigAutoField(primary_key=True) user = models.OneToOneField(User, related_name='profile') website = models.URLField() class Post(models.Model): id = models.BigAutoField(primary_key=True) author = models.ForeignKey('Users', related_name="profile") text = models.TextField(max_length=320) created_date = models.DateTimeField(default=timezone.now) class Likes(models.Model): id = models.BigAutoField(primary_key=True) post = models.ForeignKey('Post', related_name='likes') liker = models.ForeignKey('Users', related_name="liker") serializers.py class PostSerializer(ModelSerializer): author = UsersSerializer() is_like = SerializerMethodField() class Meta: model = Post fields = ( 'id', 'author', 'text', 'created_date', 'is_like', ) def get_is_like(self, obj): return obj.likes.filter(post=obj.id, liker=self.context['request'].user.profile).exists() queryset Post.objects.select_related('author','author__user').prefetch_related('likes').order_by('-created_date') but get_is_like get in N+1 loop, How can I get rid of it ? -
django multilinguage website @login_required redirect issue
I'm developing a multilingual website using django 1.11 , 'django.middleware.locale.LocaleMiddleware' middleware and i18n_patterns I use @login_required decorator for my views (for redirecting user to login page when he's not logged in) but it doesn't redirect user based on current language . for example when (not logged in) user goes to /fr/user/profile it will be redirected to /en/accounts/login?next=/fr/user/profile (but it should redirects to /fr/accounts/login?next=/fr/user/profile ) (because default website language is en(english) it always redirects to default language ) -
Passing json data to the html template using d3.js in django
views.py def index(request): fm_ds=Details.objects.filter(Gender='Female',Dept='Software',Shift='Day').count() m_ds=Details.objects.filter(Gender='Male',Dept='Software',Shift='Day').count() details_dict={} details_dict['Male']=m_ds details_dict['Female']=fm_ds print details_dict context = {'data_json': json.dumps(details_dict)} print context return render(request, 'index.html', context=context) gives me output as {'data_json': '{"Male": 0, "Female": 2}'} index.html in templates <!DOCTYPE html> <meta charset="utf-8"> <style> /* set the CSS */ .bar { fill: steelblue; } </style> <body> <script src="//d3js.org/d3.v4.min.js"></script> <script> var margin = {top: 20, right: 20, bottom: 30, left: 40}, width = 960 - margin.left - margin.right, height = 500 - margin.top - margin.bottom; var x = d3.scaleBand() .range([0, width]) .padding(0.1); var y = d3.scaleLinear() .range([height, 0]); var svg = d3.select("body").append("svg") .attr("width", width + margin.left + margin.right) .attr("height", height + margin.top + margin.bottom) .append("g") .attr("transform", "translate(" + margin.left + "," + margin.top + ")"); // get the data var data = {{ data_json|safe }}; x.domain(data.map(function(d) { return d.gender; })); y.domain([0, d3.max(data, function(d) { return d.count; })]); svg.selectAll(".bar") .data(data) .enter().append("rect") .attr("class", "bar") .attr("x", function(d) { return x(d.gender); }) .attr("width", x.bandwidth()) .attr("y", function(d) { return y(d.count); }) .attr("height", function(d) { return height - y(d.count); }); svg.append("g") .attr("transform", "translate(0," + height + ")") .call(d3.axisBottom(x)); svg.append("g") .call(d3.axisLeft(y)); }); </script> </body> Is there anyother way to get the json data. i have a graph for male and female in x and count … -
Styling ModelForms in Django
i wanted to use UserCreationFormin Django but i need to embed Bootstrap Classes in it so i decided to override it and unfortunately it doesn't work for styling! Here is my code forms.py class UserCreationForm(forms.ModelForm): """ A form that creates a user, with no privileges, from the given username and password. """ error_messages = { 'password_mismatch': ("The two password fields didn't match."), } username = forms.CharField(label=("Password"), widget=forms.TextInput(attrs={'class': 'form-control input-lg', 'placeholder':'First Name',})) password1 = forms.CharField(label=("Password"), widget=forms.PasswordInput(attrs={'class': 'form-control input-lg', 'placeholder':'First Name',})) password2 = forms.CharField(label=("Password confirmation"), widget=forms.PasswordInput(attrs={'class': 'form-control input-lg', 'placeholder':'First Name',}), help_text=("Enter the same password as above, for verification.")) class Meta: model = User fields = ("username",) def clean_password2(self): password1 = self.cleaned_data.get("password1") password2 = self.cleaned_data.get("password2") if password1 and password2 and password1 != password2: raise forms.ValidationError( self.error_messages['password_mismatch'], code='password_mismatch', ) return password2 def save(self, commit=True): user = super(UserCreationForm, self).save(commit=False) user.set_password(self.cleaned_data["password1"]) if commit: user.save() return user template.html <div class="container makemargs"><div class="row"><h3 class="col-sm-offset-3 col-sm-6">Signup</h3></div><div class="row"><div class="col-sm-offset-1 col-sm-2"></div><div class="col-sm-6"><form id="signupForm" action="" method="POST" accept-charset="utf-8" class="form" role="form">{% csrf_token %} {{form}}<button id="submitBtn" class="btn btn-block signup-btn" type="submit" disabled>Create my account</button></form></div></div></div></div> -
Django - get_object_or_404() does not work in unit tests
I'm writing unit tests for Django views. It's as simple as it could be, but I've realized that if I call a view function that contains function get_object_or_404(), it does not work properly because it always returns None object. test.py def test_add_ticket(self): ... response = add_ticket(request, self.company.id) ... views.py def add_ticket(request, company_id): company = get_object_or_404(Company, id=company_id) ... there I pass id of an existing company and get company = None -
What is the different between save(), create() and update () in django rest framework?
I m confused when making api on django rest framework using serializers, please tell me exact different between save(), create() and update() methods, my code sample is as follow, View.py class AddUser(views.APIView): serializer_class = UserForAdminSerializer def post(self, request, *args, **kwargs): serializer = UserForAdminSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) serializers.py class UserForAdminSerializer(serializers.ModelSerializer): first_name = serializers.CharField(max_length=30) last_name = serializers.CharField(max_length=30) name = serializers.CharField(max_length=30) password = serializers.CharField(max_length=20, style={'input_type': 'password'}) class Meta: model = User fields = ('id', 'url', 'first_name', 'last_name', 'name', 'username', 'email', 'password', 'total_exp_year', 'total_exp_month', 'voteup_count', 'is_featured', 'is_active', 'headline', 'description', 'profile_picture', ) def create(self, validated_data): password = validated_data.pop('password', None) instance = self.Meta.model(**validated_data) if password is not None: instance.set_password(password) instance.save() return instance on the above code in view.py file i m used save() method and serializers.py using save() or update() method so please explain me how it's working and clear my confusion between save() and create() -
IntegrityError: NOT NULL constraint failed: core_userprofile.user_id
I am trying to make a simple signup/login page through django. I have used UserCreationForm and used a model UserProfile to extend the user model. When I tried to save the post request of signup it is giving the integrity Error. I am new to django so brief explanation would be appreciated. Thanks in advance forms.py from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from mysite.core.models import UserProfile from django.db import models class SignUpForm(UserCreationForm): first_name = forms.CharField(max_length=30, required=False, help_text='Optional.') department = forms.CharField(max_length=30) last_name = forms.CharField(max_length=30, required=False, help_text='Optional.') email = forms.EmailField(max_length=254, help_text='Required. Inform a valid email address.') class Meta: model = User fields = ('username', 'first_name', 'last_name', 'email','password1', 'password2', 'department',) def save(self, commit=True): # Save the provided password in hashed format user = super(SignUpForm, self).save(commit=False) user_profile = UserProfile(user=user, department=self.cleaned_data['department']) user.save() user_profile.save() return user, user_profile views.py from django.contrib.auth.decorators import login_required from django.contrib.auth import login, authenticate from django.shortcuts import render, redirect from mysite.core.forms import SignUpForm @login_required def home(request): return render(request, 'home.html') def signup(request): if request.method == 'POST': form = SignUpForm(request.POST) if form.is_valid(): user,user_profile = form.save(commit=False) username = user.cleaned_data.get('username') raw_password = user.cleaned_data.get('password1') user = authenticate(username=username, password=raw_password) login(request, user) return redirect('home') else: form = SignUpForm() return render(request, 'signup.html', {'form': form}) models.py … -
Django deployment over AWS
I am new to Amazon cloud. I have deployed a django application on AWS EC2. I started the application but unable to see it from the browser. Which IP address will have the access? I tried both private and public but both are not resolved. -
Django DRF or ORM making additional calls when assigning to itself
Utilising the DRF I perform simple update/PATCH, nothing special. class ItemDetailSerializer(serializers.ModelSerializer): class Meta: model = Item def update(self, instance, validated_data): instance.name = validated_data.get('name', instance.name) <- makes db call instance.user = validated_data.get('name', instance.user) <- makes db call # removed for brevity instance.save() return instance It 'appears' that each line actually makes an additional call to the DB i.e. instance.name = validated_data.get('name', instance.name), why? Is this a problem with DRF, Django ORM or something else? I have tried wrapping this in a 'transaction' but that appears to makes little difference because only one save is made anyway. -
Add custom CSS styling to model form django
I am using a bootstrap variant to help style a model form. There is a certain class I would like one of the fields to be and I have read around on the subject and the general consensus is to add a widget to the ModelForm's meta, like I tried below: forms.py class EmailForm(forms.ModelForm): class Meta: model = MarketingEmails fields = ['messageid','subject','body','name','altsubject','utm_source','utm_content','utm_campaign',] widgets = { 'body': Textarea(attrs={'class': 'summernote'}), } However this doesn't seem to render onto my template, which is: <div class="row"> <div class="col-sm-6"> <form method="POST" class="post-form" action =""> {% csrf_token %} <p><label for="id_subject">Subject</label> <input class="form-control" id="id_subject" type="text" name="subject" maxlength="1000" value="{{rows.subject}}"required /></p> <p><label for="id_name">Name</label> <input class="form-control" id="id_name" type="text" name="name" maxlength="1000" value="{{rows.name}}"required /></p> <p><label for="id_body">Body</label> <input class="form-control" id="id_body" type="text" name="body" maxlength="1000" value="{{rows.body}}"required /></p> <p><label for="id_altsubject">Alt Subject</label> <input class="form-control" id="id_altsubject" type="text" name="altsubject" maxlength="1000" value="{{rows.altsubject}}"required /></p> <p><label for="id_utm_source">utm_source</label> <input class="form-control" id="id_utm_source" type="text" name="utm_source" maxlength="1000" value="{{rows.utm_source}}"required /></p> <p><label for="id_utm_content">utm_content</label> <input class="form-control" id="id_utm_content" type="text" name="utm_content" maxlength="1000" value="{{rows.utm_content}}"required /></p> <p><label for="id_utm_campaign">utm_campaign</label> <input class="form-control" id="id_utm_campaign" type="text" name="utm_campaign" maxlength="1000" value="{{rows.utm_campaign}}"required /></p> <button type="submit" class="save btn btn-default">Save</button> </form> </div> Is there another way to do this or is there something I have done wrong in my code? -
Access 'name of a pattern' from a URL, in a Django template
Can I access value of a pattern name (from the URL) in a Django template? Like can I access the value of this_name from the url in the django template? url(r'^area/(?P<this_name>[\w-]+)/$', views.AreaView.as_view(), name="area_list") I could get the whole URL path and break it up but wanted to check if there's a straight forward way to do that, since we are already giving it a name. Passing it down in the context data may be an alternative but not sure if I do need to pass it down since I'd guess the template would already have it somehow? I couldnt find a direct method in the request API. -
dynamic cascading select box in django admin
I have three models: Category, Board, Message class Category(MPTTModel): board = models.ForeignKey('Board', verbose_name=_('Board'), related_name='board') parent = TreeForeignKey('self', verbose_name=_('Parent'), blank=True, null=True, related_name='children', db_index=True) title = models.CharField(verbose_name=_('Title'),max_length=128) class Board(models.Model): title = models.CharField(verbose_name=_('Title'), max_length=250) slug = models.SlugField(verbose_name=_('Slug'), max_length=250, unique=False, allow_unicode=True) class Message(models.Model): board = models.ForeignKey(Board, verbose_name=_('Board'), related_name='board_messages', ) category = TreeForeignKey('Category', verbose_name=_('Category'), null=True, blank=True, db_index=True) title = models.CharField(verbose_name=_('Title'), max_length=250) My scenario is that I choose a board when writing a message, the board-dependent categories will be displayed in a select box not showing all of irrelevant categories. It works only when I edit the existing message with the following code: class MessageAdmin(admin.ModelAdmin): def get_form(self, request, obj=None, **kwargs): request.current_object = obj return super(MessageAdmin, self).get_form(request, obj, **kwargs) def formfield_for_foreignkey(self, db_field, request, **kwargs): instance = request.current_object if db_field.name == 'category': if hasattr(instance, 'board'): kwargs['queryset'] = Category.objects.filter(board=instance.board) return super(MessageAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs) My goal is 'category' is prepopulated on change-event of 'board' selection even when writing a new message. If I change the board field, the previously fetched categories are still stuck. I want to get a list dynamically. I believe that it should be with jquery-ajax call, but I'd like to know Django way. Thank you. -
NoReverseMatch encountered when importing a Django template into another
In a Django project, I have a mini navbar that is common in ~30% of my templates. Instead of including it in my global base.html, I decided to take a different route. I first wrote a separate view for this: from django.template.loader import render_to_string def navbar(origin=None): if origin == '1': locations = get_approved_loc(withscores=True) else: locations = get_approved_loc() obj_count = get_all_obj_count() return render_to_string("mini_navbar.html",{'top_3_locs':locations[:3],\ 'other_cities':len(locations[3:]),'obj_count':obj_count}) I next added it in the templates it needed to be in via: {% include "mini_navbar.html" with origin='1' %} When I run this code, I get a NoReverseMatch error. It seems the view function navbar never runs. So the context variables it was sending in (e.g. top_3_locs or other_cities etc) are never populated. Hence NoReverseMatch. What's wrong with this pattern, and what's the fix for it? An illustrative example would do the trick. -
how can i compare timezone.now and item.deadline
Hi I want service old book sale service for university student I create ItemPost model and when user post their books, ItemPost's deadline saved in deadline from django.db import models from django.conf import settings from django.utils import timezone def localtime(): return timezone.localtime(timezone.now()) class ItemPost(models.Model): title = models.TextField( ) created_at = models.DateTimeField( default=localtime ) is_deleted = models.BooleanField( default=False, verbose_name="삭제된 포스트", ) # 마감날짜를 구하는 함수 def deadline_def(self): year_of_item_created = self.created_at.year if self.created_at.month <= 6: return timezone.datetime(year_of_item_created, 6, 30) else: return timezone.datetime(year_of_item_created, 12, 31) deadline = property(deadline_def) # 등록된 학기가 끝난 포스트인지 확인 def is_ended_semester_def(self): now = timezone.now() if now > self.deadline: return True return False is_ended_semester = property(is_ended_semester_def) def __str__(self): return self.title I want compare item's deadline, timezone.now() and return True or False but I can't if I command item.is_ended_semester TypeError: can't compare offset-naive and offset-aware datetimes how can i solved this problem? item.deadline > datetime.datetime(2017, 6, 30, 0, 0) timezone.now() > datetime.datetime(2017, 7, 14, 8, 50, 57, 91304, tzinfo=<UTC>)