Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Purpose of a Django template context object?
In one of our applications (running Django 1.8) we tend to render templates by passing a dictionary into the context parameter of the render() function and returning them as part of a view. For example: from django.views.generic import View class HomePageView(View): def get(self, request, *args, **kwargs): context = {'foo': 'bar', 'foo2': 'bar2'} return render(request, "page.html", context) Now that I've started looking for it, I'm seeing examples of people using Django "context" objects rather than dictionaries. from django.views.generic import View from django.template import Context class HomePageView(View): def get(self, request, *args, **kwargs): context = Context() context['foo'] = 'bar' context['foo2'] = 'bar2' return render(request, "page.html", context) The documentation shows that this Context object can be interacted with in ways similar to a dictionary (pop, copy, key assignment, etc) and has a flatten() method that lets you compare it to a dictionary. https://docs.djangoproject.com/en/1.8/ref/templates/api/#playing-with-context. My question is: Is there any reason why I would ever want to use a Context object rather than a dictionary? I can see how someone might find the subclass of RequestContext useful if they wanted easy access to request variables, but I think I'm missing the context object's utility. -
Order by split string django orm
I have an ID as a reference number and year in this format: 1/17 98/15 2/17 112/17 2345/17 67/17 9/17 8974/16 When i get my IDs out using django orm: obj = MyIDs.objects.filter(run='run_1').order_by('ID') I get them out in the order of the first number: 1/17 112/17 2/17 2345/17 67/17 8974/16 9/17 98/15 However as the number after the / is the year, I would like to order them by the year then number. I am able to do this easily in mySQL (using substring index etc) and also if it was a python list, but as I am now wanting to not process my objects before sending them to my html template - is there a way to do this in the orm? -
Create a sitemap like Flipboard on django
So I'm new to django and would like to know the steps on how to create a sitemap with django which looks something like this. https://flipboard.com/htmlSitemap I have a lot of links on my website. I want them to categorized alphabetically. Also, is this possible in django ? Is there a better way to do it ? Thanks. -
Django Wagtail ajax contact form
I have a contact form that appears at the bottom of every page in the footer. I simply included it in my base.html at the bottom. Now i want to figure out a way to submit it. All the examples wagtail provides is under the assumption i have an entire page dedicated to it and hence submits to itself. This cannot work for me as its not a page. I have written pseudo code of what I think it should look like . def submitContact(request): source_email = request.POST.get('email') name = request.POST.get('name') message = request.POST.get('message') if (source_email is not None) and (name is not None) and (message is not None): body = "sample" send_mail( name, message, source_email, ['test@foobar'], fail_silently=False, ) Then my form would be something like this <form class="form-group" role="form" method="post" action="/submitContact"> ...... </form> Ideally if someone could point to Wagtail resources that show how to create endpoints in models that do not inherit from the Page model and are not snippets that maintain "request" content that would be useful. Ideally what I would prefer is to log this data into contact "table" then send the email after. What should I add to my urls.py to reroute the request with … -
i can't load a img from my instance image
hi im trying load a image from my media folder and is not working, i have as output that my {{ image.image.url }} display /media/products/yo.jpg here is my structure this is my block where i want to load the images that are in the instance of images. also i think my code is not good maybe you can give some advice. {% block content %} <!-- all products--> <section > {% for product in products %} {% for image in images %} <div class="product"> <img src="{% static 'img/vaca.jpg' %}" class="imgpro"> <div class="info"> <p> <h3> Product: </h3> {% if image.product.pk == product.pk %} <img src='{{ image.image.url }}' class="imgpro"> {% endif %} <h3> Offer: </h3> <a href="{% url 'ganagroapp:product_detail' pk=product.pk %}">{{ product.product }}</a> <h3> Description: </h3> {{ product.description }} </p> </div> </div> {% endfor %} {% endfor %} </section> {% endblock content %} this is my view def index(request): images = Image.objects.select_related() category = Category.objects.select_related() products = Product.objects.select_related() return render(request,'ganagroapp/index.html', {'category' : category, 'products' : products, 'images': images} ) -
Mobile device doesn't use cookie
For some reason the mobile authentication detection stoped working. When I access a location containing a form on my page, the form should call (via ajax) for additional information to fill the fields, the server returns depending on user authentification. It worked well for nine months, but stoped working for mobile devices, however it still works for desktop browser access. Mobile and desktop use exactly the same access route, arguments, urls, view function ... everything. The one difference that I noted (after some 8 hours on this issue) when I looked up the request.META, is that desktop sends cookie information, mobile doesn't. However cookies are enabled on mobile and desktop browser. I tested this with Chrome mobile and (a freshly installed) Firefox on mobile, the result is exactly the same. How is this possible? Why does the form when initializing on desktop send the cookie info and when initializing on mobile don't send it? Here is a previous version of this question (written before I noticed the cookie difference and thought it was an api issue) containing technical details that I don't consider to be relevant for the particular question of how does the same functionality behave some differently on … -
How to override Model defaults method of 3rd party installed app, djanog?
I just installed this django-csvimport package. Now I want to override the default values in the Admin area form. I found the code here, which defines the models, and contains the current default text: class CSVImport(models.Model): """ Logging model for importing files """ model_choice = [] model_name = models.CharField(max_length=255, blank=False, default='csvimport.Item', help_text='Please specify the app_label.model_name', choices=get_models()) field_list = models.TextField(blank=True, help_text='''Enter list of fields in order only if you dont have a header row with matching field names, eg. "column1=shared_code,column2=org(Organisation|name)"''') upload_file = models.FileField(upload_to='csv', storage=fs) file_name = models.CharField(max_length=255, blank=True) encoding = models.CharField(max_length=32, blank=True) upload_method = models.CharField(blank=False, max_length=50, default='manual', choices=CHOICES) error_log = models.TextField(help_text='Each line is an import error') import_date = models.DateField(auto_now=True) import_user = models.CharField(max_length=255, default='anonymous', help_text='User id as text', blank=True) def error_log_html(self): return re.sub('\n', '<br/>', self.error_log) error_log_html.allow_tags = True def __unicode__(self): return self.upload_file.name So for example I would like override the model_name field default csvimport.Item with something else. I am a bit at a loss how to override this as I do not have an app folder for csvimport, as its a 3rd part installation. It will be my first time overriding a 3rd party installed app model. Now that I look into it a bit more, not sure if I should override … -
SSLError: [Errno bad handshake]
Traceback (most recent call last): File "/opt/myplex/myplex_service/apps/common/decorators.py", line 63, in decorated return view_func(request, session, *args, **kwargs) File "/opt/myplex/myplex_service/apps/custamization/vfplay/views.py", line 598, in emailmobilesignin response = mobile_validater(url=number_validate_url,Authorization=Authorization) File "/opt/myplex/myplex_service/apps/custamization/vfplay/utils.py", line 524, in mobile_validater resp = requests.get(url,headers=hooq_parameters, timeout=TIME_OUT,verify=False) File "/opt/pyenv/myplex_service/lib/python2.7/site-packages/requests/api.py", line 55, in get return request('get', url, **kwargs) File "/opt/pyenv/myplex_service/lib/python2.7/site-packages/requests/api.py", line 44, in request return session.request(method=method, url=url, **kwargs) File "/opt/pyenv/myplex_service/lib/python2.7/site-packages/requests/sessions.py", line 335, in request resp = self.send(prep, **send_kwargs) File "/opt/pyenv/myplex_service/lib/python2.7/site-packages/requests/sessions.py", line 438, in send r = adapter.send(request, **kwargs) File "/opt/pyenv/myplex_service/lib/python2.7/site-packages/requests/adapters.py", line 331, in send raise SSLError(e) SSLError: [Errno bad handshake] I have used the verify=Flase option to skip the ssl certificate check but still its saying the ssl badhandshake -
how to make visible a certain item on a navigation bar to a certain group of users?
Could anybody please tell me how to make visible a certain item on a navigation bar to a certain group of users? For example I need an item 'Faculty' to be visible just for a certain group and the bar should look like this: Home | Faculty | Student | Admin and for all others it should be: Home | Student | Admin It must be straightforward, but there is a mistake somewhere in my implementation: {% if user.groups.filter(name='Faculty group').exists() %} <li>...</li> ... {% endif %} Could you please correct me. Thank you! -
Redirect to admin after login - Django
I am trying to redirect the user after login to their appropriate login pages according to their policy. If the user is a staff then after login the user should be redirected to admin page so on. I have the following contents. In my settings.py: from django.core.urlresolvers import reverse_lazy LOGIN_URL=reverse_lazy('login') LOGOUT_URL=reverse_lazy('logout') My apps urls.py: url(r'^login/$', authy_views.log_me_in, name="login"), url(r'^logout/$', auth_views.logout, name='logout'), log_me_in is a custom login view that uses AuthenticationForm. My custom login view authy_me.views.py: from django.contrib.auth.views import login as auth_login from django.contrib.auth import authenticate, login def log_me_in(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') user = authenticate(username=username, password=password) if user.is_active: if user.is_staff and not has_2fa(user): logger.info('is staff but does not have 2FA, redirecting to Authy account creator') return redirect('%s?next=/admin/' % settings.LOGIN_URL) elif user.is_staff and has_2fa(user): logger.info("is staff and 2FA enabled redirecting to Authy verification") return redirect('2fa') elif not request.user.is_staff and not has_2fa(user): logger.info('is not staff and does not have 2FA') else: login(request, user) return redirect('/') defaults = { 'authentication_form': AuthenticationForm, 'template_name': 'login.html', } return auth_login(request, **defaults) The problem: Now when I try to login with http://127.0.0.1:8000/login/ I get the custom login screen, after authenticating myself and the conditions for being staff & no 2fa is satisfied the … -
how to fix AttributeError: 'bool' object has no attribute 'strip'?
Error in forms.py and i don't know why my validation doesn't work! help me when i complite register he gives me this error (i don't know what to add, but stackoverflow ask me add more text) I will wait with impatience)! I will wait with impatience)! self.email = self.__class__.objects.normalize_email(self.email) File "C:\Users\PANDEMIC\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\contrib\auth\base_user.py", line 29, in normalize_email email_name, domain_part = email.strip().rsplit('@', 1) AttributeError: 'bool' object has no attribute 'strip' forms.py from django import forms from .models import User class SignUpForm(forms.ModelForm): email = forms.EmailField(required=True) error_messages = {'password_mismatch': "The two password fields didn't match.", 'email_is_exists': "This email already taken! please use another one!", 'username_is_exists': "This usernamt already Taken, use another one!"} password1 = forms.CharField(label="Password", widget=forms.PasswordInput) password2 = forms.CharField(label="Password confirmation", widget=forms.PasswordInput, help_text="Enter the same password as above, for verification.") class Meta: model = User fields = ("username", "first_name", "last_name", "email") def clean_email(self): email = self.cleaned_data.get("email") chekc_email = User.objects.get(email=email) if chekc_email: raise forms.ValidationError( self.error_messages['email_is_exists'], code='email_is_exists', ) return email def clean_username(self): username = self.cleaned_data.get("username") chekc_username = User.objects.get(username=username) if chekc_username: raise forms.ValidationError( self.error_messages['username_is_exists'], code='username_is_exists', ) return email 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(SignUpForm, self).save(commit=False) user.username … -
How can I call Django's manage.py from GNOME Builder?
I have GNOME Builder installed on 3.24.1 installed on Ubuntu 17.04. I have a functional Django project and an associated virtualenv. (Django 1.11, Python 3) How can I configure Builder, so that when I click Run it invokes manage.py runserver in the virtualenv? (Ideally I'd like to be able to run other manage.py functions too, like manage.py collectstatic.) -
Put submit button and input text on same line
I'm using Django and http://forms.viewflow.io/ . HTML: <div> <form method='POST' action='' > <input type='hidden' name='csrfmiddlewaretoken' value='some value' /> <div class="row"> <div class="input-field col s12 required" id="id_email_container"> <input id="id_email" maxlength="254" name="email" type="email"> <label for="id_email">Email</label> </div> </div> <button type="submit" name="_submit" class="btn" value='Sign Up'>Submit</button> </form> </div> How do I put the submit button next to text input? -
Django Tesseract OCR
I want to extract text data from a pdf. By doing some research I found out that Tesseract OCR engine can be used for this, but I have no idea where to start from. Can anyone help me out to use Tesseract OCR with Django by sharing links related to it and give me an overview of things involved? -
Django how to use |yesno to to toggle views
I need to create a toggle inside of my html that allows me to switch between data in two separate models. Below is the line of code in my html I've used to try and do this: HTML: <a class="btn btn-success pull-right" href="{{ url }}{{ seller|yesno:"?seller=true,?seller=false,?seller=test"}}" > View: seller = False def get(self, request, *args, **kwargs): if self.request.GET.get('seller', None) == '?seller=true': self.model = CarSeller self.seller = True elif self.request.GET.get('seller', None) == '?seller=false': self.model = VanSeller self.seller = False return super().get(request, *args, **kwargs) def get_queryset(self): if self.model == CarSeller: com = self.model.objects.filter( carparty=self.vehicle.proff.car_contact.garage, ) else: com = self.model.objects.filter( vanparty=self.vehicle.proff.van_contact, ) return communication def get_context_data(self, **kwargs): context['seller'] = self.seller context['url'] = reverse_lazy( "work:contact:comm_intro", kwargs={'vehicle_id': self.vehicle.id} ) return context To my understanding of reading about use of yesno this should work but instead once i click the button it will swap to true but the value does not change back to false when i press it again. All help appreciated on use of |yesno or any recommendations on how you think i should display this. Any variable you may see missing to do with models and unrelated to question is probably because I've skimmed it out for question. Thanks (Anything else needed let … -
Django distribute filter results
In a Django app, I am doing query like below: Products.objects.filter(category_id=[1, 2, 3])[:6] I am getting back 6 items from category 1. What I want is form each category 2 items. Alternatively I tried with Q like below: Products.objects.filter(Q(category_id=1)|Q(category_id=2)|Q(category_id=3))[:6] I can get all the results and then iterate through the results to filter out and so on. The resulted query set is pretty large. How can I make that query using Django ORM via single query without iterating through the whole queryset? -
How to get the no of times a user visited a shop on each date(activity_date) from the model using a single query
class StoreLog(models.Model): user_id = models.ForeignKey(User, verbose_name=_('User'), related_name='user_analytics_data', null=True, blank=True) store_id = models.IntegerField(verbose_name=_('Store')) device_id = models.TextField( verbose_name=_("Device ID"), db_index=True, help_text=_("ANDROID_ID / TelephonyManager.getDeviceId() (always as hex)") ) device_type = models.TextField(verbose_name=_("Device Info"), blank=True, null=True) activity_date = models.DateTimeField(_('Date'), default=timezone.now) aim: if user visits a shop more than once on a particular date a mail should be send offering some deals -
How to ignore strings from Django's .po files when running `django-admin makemessages`
My Django app uses some strings that are already translated in Django. In custom templates for password reset process I'd like to use some of the original texts, like this one prompting user to log in after completing the reset process. Custom template contains <p>{% trans "Your password has been set. You may go ahead and log in now." %}</p> taken directly from the original form file. After running django-admin makemessages my .po file contains this: #: core/templates/auth/password-reset-complete.html:10 msgid "Your password has been set. You may go ahead and log in now." msgstr "" Translation is working, rendered page already contains the correct translated string. Is it possible to ommit this empty translation from .po file automatically? Simply removing it will only work until I run makemessages again. -
Adding Comment with AJAX POST and displaying it in Django
I have just started to learn ajax. I am implementing it in my Django project where every Discussion (Model) has Comment (Model). I have designed such that the page refreshes after every comment is made. But I don't want to do that, so use AJAX for the same. views.py : def single_discuss(request, slug): discussion = get_object_or_404(Discussion, slug=slug) comments = Comment.objects.filter(discussion=discussion) if request.user.is_authenticated(): if request.method == "POST": comment_form = CommentForm(request.POST) if comment_form.is_valid(): comment_form = comment_form.save(commit=False) comment_form.commenter = request.user comment_form.discussion = discussion comment_form.save() return redirect('single_discuss', slug=discussion.slug) comment_form = CommentForm() else: comment_form = None return render(request, 'single_discuss.html', {'discuss': discussion, 'comments': comments, 'comment_form': comment_form}) single_discuss.html : <div class="single-comment"> <form class="form-inline" method="POST"> {% csrf_token %} {{ comment_form.as_p }} <button type="submit" class="btn btn-primary">Comment!</button> </form> </div> How do I this? I am trying to learn AJAX, so please tell me where should I add what and why? Thanks in advance. I tried understanding this answer which said something else, and this one I don't even think answers completely even though it is marked correct. -
Add Order_by to my django app? Django-Haystack Elasticsearch
I'm trying to add order_by function to my results using Django-Haystack. I've managed faceting but have come stuck with how to implement an order_by button. It's writing the form and button connection within the html I'm struggling with. forms.py if self.location: query = None for location in self.location: if query: query += u' OR ' else: query = u'' query += u'"%s"' % sqs.query.clean(location) sqs = sqs.narrow(u'location_exact:%s' % query) return sqs views.py class FacetedSearchView(BaseFacetedSearchView): form_class = FacetedProductSearchForm facet_fields = ['retailer', 'location'] template_name = 'results.html' paginate_by = 11 context_object_name = 'object_list' results.html <div class="tab-filter"> <select class="selectpicker" data-style="btn-select" data-width="auto"> <option>Sort by</option> <option>Price: Low to High</option> <option>Price: High to Low</option> </select> </div> -
How can I use migrations to move data
I have a scenario where I need to move the data from one model to another model and in turn to another model if necessary.how can I add this process in migration file so,that I can accomplish the requirement with just python manage.py migrate command. -
django.db.migrations.exceptions.InconsistentMigrationHistory
When i run python manage.py migrate on my django project, i gets the following error Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/home/hari/project/env/local/lib/python2.7/site- packages/django/core/management/__init__.py", line 363, in execute_from_command_line utility.execute() File "/home/hari/project/env/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 355, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/hari/project/env/local/lib/python2.7/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/home/hari/project/env/local/lib/python2.7/site-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/home/hari/project/env/local/lib/python2.7/site-packages/django/core/management/commands/migrate.py", line 86, in handle executor.loader.check_consistent_history(connection) File "/home/hari/project/env/local/lib/python2.7/site-packages/django/db/migrations/loader.py", line 298, in check_consistent_history connection.alias, django.db.migrations.exceptions.InconsistentMigrationHistory: Migration admin.0001_initial is applied before its dependency account.0001_initial on database 'default'. I have a user model like below class User(AbstractUser): place = models.CharField(max_length=64, null=True, blank=True) address = models.CharField(max_length=128, null=True, blank=True) So how can i solve this? -
Django CreateView allows resubmission of the data when the form is displayed when hiting the back button
I'm trying to make an app with an upload image. The thing is that I want to limit the possibility of uploading an image to only once per day. Everything is working fine except if the user is using the back button of the browser. He can spam the system. What is the correct way to prevent this? models.py # Admin option to select from PHOTO_STATUS = ( ('ir', 'In Review'), ('ap', 'Approved'), ('tr', 'Trash'), ) def pause(): return timezone.now() + timezone.timedelta(minutes=5) # Main photo upload app class PhotoUpload(models.Model): '''After the user finishes the challenge he can upload a photo using this app''' # The date when a user uploads a photo date_upload = models.DateTimeField(default=timezone.now) # The date when user can upload another photo # pause = date_upload + timezone.timedelta(minutes=20) pause_upload = models.DateTimeField(default=pause) # The status of the photo status = models.CharField(max_length=2, default='ir', choices=PHOTO_STATUS) # The date when the admin aproves the photo date_approved = models.DateTimeField(default=timezone.now, blank=True, null=True) # The date when the admin soft-deletes the photo date_deleted = models.DateTimeField(default=timezone.now, blank=True, null=True) user = models.ForeignKey(User) # A function that defines the path where the photo # will be uploaded and that will change the filename. def path_and_rename(instance, filename): extension = … -
python - add translation to HTML code
This may be a simple question with a simple solution, but I am stumped. I have been given some code that displays some HTML code in a template. However, I am unable to add translation to the title value in the HTML. I have tried inserting the title as a variable (%s), but this does not display in the template. All my attempts have not worked. Does anyone have any ideas? Here is the python class: class BootstrapCheckboxCheckAllFieldRenderer(BootstrapCheckboxFieldRenderer): choice_input_class = BootstrapCheckboxChoiceInput def extra_html(self): return ''' <span class="create_details_buttons"> <div class="create_select_all icon_size12 btn btn-xs btn-default blur-after-click" rel="tooltip" title="To display the details in the order you would like them to appear in your document, you must individually select the details in the required order."> <icon class="fa fa-check-square-o icon_size14"></icon> <span class="spacer"></span> %s </div> <span id="id_spacer" class="spacer"></span> <div class="create_clear_all icon_size12 btn btn-xs btn-default blur-after-click"> <icon class="fa fa-square-o icon_size14"></icon> <span class="spacer"></span> %s </div> </span> ''' % (ugettext('Select All'), ugettext('Clear All')) -
Custom, router-mapped viewset methods not showing in django rest wagger
I'm creating two PUT-mapped functions for my API, one at the list level and the other at the (usual) detail/pk level. Both methods for PUT are exposed properly, so even if django-rest-swagger does not detect show it, it is still working. How do I use / work around the library to show these custom, router-mapped methods (e.g. bulk_update)? I posted the issue in the GitHub repo. # viewsets.py class BookingViewSet(viewsets.GenericViewSet): def list(self, request): pass def retrieve(self, request, pk=None): pass def update(self, request, pk=None): pass def bulk_update(self, request): pass # routers.py class CustomSimpleRouter(SimpleRouter): routes = [ # List route Route( url=r'^{prefix}{trailing_slash}$', mapping={ 'get': 'list', 'post': 'create', 'put': 'bulk_update', }, name='{basename}-list', initkwargs={'suffix': 'List'} ), # Detail route Route( url=r'^{prefix}/{lookup}{trailing_slash}$', mapping={ 'get': 'retrieve', 'put': 'update', 'patch': 'partial_update', 'delete': 'destroy' }, name='{basename}-detail', initkwargs={'suffix': 'Instance'} ), ] # urls.py router = CustomSimpleRouter() router.register(r'bookings', BookingViewSet, base_name='bookings') When both bulk_update and update are present When update is removed from the viewset