Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Showing Excel File Data in Editor Using Python Django Framework
I want to show the Excel File Data in Editor using django framework, python. If anybody knows how to do this, please help me. I am new in django framwork -
combining two or more querysets from different models in django
main model class MainCategory(models.Model): title = models.CharField(max_length=120, unique=True) app#1 class Category(models.Model): title = models.CharField(max_length=120, unique=True) main_category = models.ForeignKey(MainCategory, default=1, related_name='car_category') app#2 class Category(models.Model): title = models.CharField(max_length=120, unique=True) main_category = models.ForeignKey(MainCategory, default=1, related_name='classifieds_category') on home page I want a combined list of both category list items as follows. {% for object in main_cat_list %} {{ object.title }} {% for item in object.car_category %} {{ item.title }} {% endfor %} {% endfor %} How I can insert classifieds category also inside this list. -
Django: Manipulating for loops to render information differently
On Instagram/Facebook underneath a post, you'll see text like 'Person 1, Person 2 & 10 others liked this post'. I was wondering how this same effect may be achieved using Django for a website? Normally, I would use a for loop like so to loop through all of the likers names; {% for UserModel in post.likers.all %} {{ UserModel.userprofile.first_name }} {% endfor %} However, this doesn't allow me to achieve the desired effect as previously mentioned and will certainly be too long when the number of likers gets into the hundreds. Any ideas on how to do this? Thank you! -
How do I get new Database changes since last login using Django and Python?
I need to get database changes for a user, but only the updates of the user since the last time they logged in. I will be passing in just an email. I have looked into session data but none of that looks very helpful to me. I am new to Python and Django and I have no idea where to start, any help would be appreciated. Here are my models: class Device(models.Model): serial = models.CharField(max_length=16, null=False, unique=True) publickey = models.CharField(max_length=44, null=False) def __str__(self): return '%d: %s' % (self.id, self.serial) class Pairing(models.Model): device = models.OneToOneField(Device,on_delete=models.PROTECT,blank=False, null=False) pairingcode = models.CharField(max_length=10, blank=False, null=False, unique=True) def __str__(self): return '%s: %s' % (self.device_id, self.pairingcode) class UserDevice(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT, null=False) device = models.ForeignKey(Device, on_delete=models.PROTECT, null=False) activation_date = models.DateTimeField(default=timezone.now, null=False) friendly_name = models.CharField(max_length=20, null=True, blank=True) is_owner = models.BooleanField(null=False, default=False) is_admin = models.BooleanField(null=False, default=True) is_alerts_enabled = models.BooleanField(null=False, default=True) class Meta: unique_together = ('user', 'device',) def __str__(self): return '%s => %s on %s' % (self.user.email, self.device.serial, str(self.activation_date)) class Schedule(models.Model): device = models.ForeignKey(Device, on_delete=models.PROTECT, null=False) time = models.TimeField(null=False) class Meta: unique_together = ('device', 'time') class PendingSchedule(models.Model): device = models.ForeignKey(Device, on_delete=models.PROTECT, null=False) user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.PROTECT, null=False) time = models.TimeField(null=False) class Meta: unique_together = ('device', 'time') class Tray(models.Model): device = … -
dajngo 'AnonymousUser' object has no attribute '_meta'
I am using social login in my django app. So, I have added additional backends in my settings.py file. AUTHENTICATION_BACKENDS = [ 'django.contrib.auth.backends.ModelBackend', 'social_core.backends.open_id.OpenIdAuth', 'social_core.backends.google.GoogleOpenId', 'social_core.backends.google.GoogleOAuth2', 'social_core.backends.google.GoogleOAuth', 'social_core.backends.twitter.TwitterOAuth', 'social_core.backends.facebook.FacebookOAuth2', 'social_core.backends.github.GithubOAuth2', ] I have also used UserCreationForm for signup, class SignupForm(UserCreationForm): first_name = forms.CharField(max_length=30, required=True, help_text='Required.') last_name = forms.CharField(max_length=30, required=True, help_text='Required.') 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' ) This is the views file, def signup(request): if request.method == 'POST': form = SignupForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') raw_pass = form.cleaned_data.get('password') user = authenticate(request, username=username,password=raw_pass) login(request,user,backend='django.contrib.auth.backends.ModelBackend') url = reverse('location:get_location') print("location_url ", url) return HttpResponseRedirect(url) else: form = SignupForm() return render(request, 'signup.html', {'form':form}) Now, I get this error when i click signup button on my form, 'AnonymousUser' object has no attribute '_meta' at the line, login(request,user,backend='django.contrib.auth.backends.ModelBackend') Why so ? I can see in my admin panel that user has been saved. What is causing this error ? and how to solve it ? -
How to bound data (for one to many relationship) to a modelForm of the base class
I am a java developer new to python and Django and can't get my head around Django ModelForms in complex cases.I already read the django documentation for Forms Formsets and ModelForms but still can't figure out the following problem. So I have base model let's call it base like so: class Base(models.Model): title = models.CharField(max_length=50) And here I have the relevant ModelForm class BaseForm(ModelForm): class Meta: model = Base fields['title'] An object of this class can contain one or more instances of element and so class Element(models.Model): name = models.CharField(max_length=20) measurement_1 = models.DecimalField(max_digits=15, decimal_places=4) measurement_2 = models.DecimalField(max_digits=20, decimal_places=10) base = models.ForeignKey(Base, on_delete=models.CASCADE) and here is the corresponding ModelForm class ElementForm(ModelForm): class Meta: model = Element fields=['name','measurement_1','measurement_2','base'] In my view I have some unstructured data as a result of web scraping and I would like to generate a bounded Form out of those data so the user can review the result and approve(save in database) or decline the validity of the data. So what I ended up doing was something like the following def parse(request, index): if request.method == "POST": return else : base = Base() base.title=scraped_title base.element_list= list_of_elements baseForm = BaseForm(instance=base) return render(request, 'reviewer/template.html', {'form': baseForm}) now in the resulting … -
django.db.utils.OperationalError: (2026, 'SSL connection error: Unable to get certificate')
I am trying to get run some tasks in a Django application on Jenkins. Django is failing to connect to the MySQL database on Jenkins(which is on a mac). I should note everything works fine locally. I am going to share some of my settings: Databases From Settings DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'HOST': '<myhost>', 'NAME': '<myname>', 'USER': '<myuser>', 'OPTIONS': { 'ssl': { 'ca': os.environ.get('SSL_CA_CERT_PATH'), 'cert': os.environ.get('SSL_CLIENT_CERT_PATH'), 'key': os.environ.get('SSL_CLIENT_KEY_PATH') } } } } The environment variables for the cert paths do actually seem to work which I find odd. I have debugged with the following python commands in my settings and it does print out the expected results (file paths and file contents): print(os.environ.get('SSL_CA_CERT_PATH')) txt_opn = open(str(os.environ.get('SSL_CA_CERT_PATH'))) print(txt_opn.read()) print(os.environ.get('SSL_CLIENT_CERT_PATH')) txt_opn = open(str(os.environ.get('SSL_CLIENT_CERT_PATH'))) print(txt_opn.read()) print(os.environ.get('SSL_CLIENT_KEY_PATH')) txt_opn = open(str(os.environ.get('SSL_CLIENT_KEY_PATH'))) print(txt_opn.read()) Error Message django.db.utils.OperationalError: (2026, 'SSL connection error: Unable to get certificate') I have the certs in a Shared folder and chmod 777 everything. I do not have permission to chown to mysql:mysql however, even with sudo: Sorry, user <myuser> is not allowed to execute '/usr/sbin/chown mysql:mysql client-cert.pem' as root on <myhost>. Lastly, in case is it is relevant, here is what I am running as a jenkins shell script to … -
I need a book for learning Django。 [on hold]
I want to learn Django, so I am looking at official documents for a few days. However, until today, I see are some basic concepts. I understand these concepts, but do not know how to practice and master these knowledge points. Because of this problem, when I look at the official documents, I always feel very confused and uncomfortable. Who can recommend a book on Django entry, that I would like to study with official documents together? -
Memex explorer:ImportError: cannot import name RemovedInDjango19Warning
I am working on memex-explorer repo cloned from git-hub. It is a web app built on Django 1.7.3. I have searched a lot on this error but to no avail. I have tried pip uninstall and install too but it is still showing error. enter image description here. I have put up this issue on the github page but there is been no response. -
Django Haystack: Filtering by object properties
I'm trying to build a page that renders searched Oscar products and filters them by their Category using GET attributes. I'm overriding get_queryset and building my object list from there class ProductSearchView(ListView): model = Product template_name = "productsearch/product_list.html" queryset = Product.objects.none() def get_queryset(self): word_query_attr = self.request.GET.get('q', None) # word query sqs = SearchQuerySet().models(Product).filter(Q(title__icontains=word_query_attr) | Q(category__name__icontains=word_query_attr) | Q(upc__icontains=word_query_attr) | Q(description__icontains=word_query_attr)) qs = Product.objects.all() if self.request.GET.get('cat', None): cat_attr = self.request.GET.get('cat', None) category = Category.objects.get(name=cat_attr) qs = qs.filter(categories__in=category.get_children()) My question is, can I use SearchQuerySet() to filter through fields from result objects? (in this case, categories from Product objects) If not, is there an effective way I can create a Product queryset using SearchQuerySet() results? I've tried filtering through IDs object_ids = [result.object.id for result in sqs] qs = qs.filter(id__in=object_ids).distinct() But there are two problems: it isn't scalable (as noted here) and some queries are very slow when I'm dealing with ~900 results. -
Django return and redirect in same function?
I want that it is necessary to toggle the checkbox before submitting the form, and then say "thank you"... I followed a web tutorial, because i didnt know how to integrate stripe, so there was no forms.py file... I am really confused and dont know how to solve this... I dont really care about the solution, I just want This is my views.py file: from django.conf import settings from django.shortcuts import render from django.contrib.auth.decorators import login_required import stripe from django.http import HttpResponseRedirect stripe.api_key = settings.STRIPE_SECRET_KEY ## Create your views here. @login_required def checkoutlight(request): publishKey = settings.STRIPE_PUBLISHABLE_KEY customer_id = request.user.userstripe.stripe_id if request.method == 'POST': token = request.POST['stripeToken'] try: customer = stripe.Customer.retrieve(customer_id) customer.sources.create(card=token) charge = stripe.Charge.create( amount=1999, #in cents currency="eur", description="Example charge", customer=customer ) except stripe.error.CardError as e: pass context = {'publishKey': publishKey} return render(request, 'checkout/checkoutlight.html', context) And this is my checkoutlight.html: {% extends "startseite/anmeldung.html" %} {% block script %} <script type="text/javascript"> // This identifies your website in the createToken call below Stripe.setPublishableKey('{{ publishKey }}'); function stripeResponseHandler(status, response) { var $form = $('#payment-form'); if (response.error) { // Show the errors on the form $form.find('.payment-errors').text(response.error.message); $form.find('button').prop('disabled', false); } else { // response contains id and card, which contains additional card details var token … -
Set attribute of all fields in Django ModelForm in init method
I have a Django ModelForm where I set certain form attributes in the form __init__() method. class MyForm(forms.ModelForm): class Meta: model = MyModel exclude = ['datecreated', 'datemodified'] def __init__(self, *args, **kwargs): super(MyForm, self).__init__(*args, **kwargs) self.fields['field1'].widget.attrs['class'] = 'class1' self.fields['field2'].widget.attrs['class'] = 'class1' self.fields['field3'].widget.attrs['class'] = 'class1' # override Google Chrome field error issues making form unfocusable self.fields['field1'].required = False self.fields['field2'].required = False self.fields['field3'].required = False Is there away to set attributes of all fields included in the form without writing self.fields for each one individually? -
Display form fields depending on user
So I have a social network where users can post thinks. I would like to incorporate a blog system into the same feed app instead of making blog its own app. I was thinking that if I (or someone with adequate permissions) wanted to make a blog post they could use the same form used by everyone to make a post, however since they have higher permissions they would be shown an extra option on the form that allows them to make it a blog post. and on the blog page I would just filter out to only have posts with blog_post set to true to be shown. I tried to do this with a simple if statement in the forms.py however I get an error: Traceback (most recent call last): File "/anaconda/envs/test/lib/python3.6/site-packages/django/utils/autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "/anaconda/envs/test/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 125, in inner_run self.check(display_num_errors=True) File "/anaconda/envs/test/lib/python3.6/site-packages/django/core/management/base.py", line 359, in check include_deployment_checks=include_deployment_checks, File "/anaconda/envs/test/lib/python3.6/site-packages/django/core/management/base.py", line 346, in _run_checks return checks.run_checks(**kwargs) File "/anaconda/envs/test/lib/python3.6/site-packages/django/core/checks/registry.py", line 81, in run_checks new_errors = check(app_configs=app_configs) File "/anaconda/envs/test/lib/python3.6/site-packages/django/core/checks/urls.py", line 16, in check_url_config return check_resolver(resolver) File "/anaconda/envs/test/lib/python3.6/site-packages/django/core/checks/urls.py", line 26, in check_resolver return check_method() File "/anaconda/envs/test/lib/python3.6/site-packages/django/urls/resolvers.py", line 254, in check for pattern in self.url_patterns: File "/anaconda/envs/test/lib/python3.6/site-packages/django/utils/functional.py", line 35, … -
Django - can't get list_display to work
Here is my code: from django.contrib import admin from django.contrib.admin import ModelAdmin from .models import Feedback from django import forms class FeedbackForm(forms.ModelForm): class Meta: model = Feedback fields = '__all__' class FeedbackAdmin(ModelAdmin): form = FeedbackForm search_fields = ('name', 'category', 'email', 'subject') list_display = ('name', 'category', 'email', 'subject', 'is_read') list_editable = ('is_read', ) admin.site.register(Feedback) When i run it i don't see the search_fields, list_display, or list_editable. I also don't get any error messages when i run the server. What am i doing wrong? -
'User' object has no attribute 'get' with formset (passing user to get a queryset)
I am trying to display a formset for a particular User. If the user is on the 'medical tab', then it should display a tiny form (a checkbox and a text box) for each dependent of the user. In my views.py I have this: def get_dep_form(benefit_tab, user): if benefit_tab == 'medical': DepMedFormSet = formset_factory(DependentMedicalBenefitForm) link_formset = DepMedFormSet(user) else: return None return link_formset In my forms.py I have this: class DependentMedicalBenefitForm(forms.ModelForm): has_medical = forms.BooleanField() med_group_id = forms.CharField(max_length=10) class Meta: model = Dependent fields = [ 'has_medical', 'med_group_id' ] def __init__(self, *args, **kwargs): self.user = kwargs.pop('user') queryset = Dependent.objects.filter(employee=self.user) super(DependentMedicalBenefitForm, self).__init__(*args, **kwargs) self.fields['has_medical'].queryset = queryset self.fields['med_group_id'].queryset = queryset In my views.py I'm getting the form like this: def index(request, benefit_tab=None): #stuff if benefit_tab: link_formset = get_dep_form(benefit_tab, request.user) return render(request, 'benefits/index.html', { #stuff 'link_formset': link_formset, }) I am running into the error: 'User' object has no attribute 'get' If I don't pass a user, and comment out the init function, then it displays a single checkbox and textbox as expected - but I can't figure out why passing the user this way is not working. Bonus points: if you know how to prepopulate the formset with the respective data - that is next … -
Django Rest Framework block GET requests from external origin
I have a Django Rest Framework API with a requirement of blocking GET requests from external sources, kind of similar to how CORS blocks all non-safe verbs. What I need to do is when a GET request comes in from somewhere other than my domain I need to return a 403 Response. From what I've read about CORS, it can't block GET requests, and I'm not seeing any other built-in options for DRF. I've tried looking at the request object to check for an origin but am not seeing that either. Any suggestions? -
python3 django gitignore project/bin and project/include?
I have a django project called sibs. I'm currently upgrading it to use python3. I noticed that there is a bin and include folder inside my projects folder (~/projects/sibs/sibs) where all the settings and url_confs go. Should these be in the gitignore? I looked at some examples and they weren't but I find it hard to believe that the bin should be tracked by git. I just want to double check. I assume these will be regenerated upon run-time. -
Django best practice for extending User model
I want to extend the build-in User model in Django. I do this by just creating a subclass inherited from User. The main problem is that when I retrieve user = request.user, this user is the built-in User type instead of the new subclass I create. So I wonder what's the best practice to do this? -
ValueError: Empty module name
I have error ValueError: Empty module name. Why? I think i have some errors with my urls. urls.py url(r'^news/', include('school9.urls', namespace='school')) template.html <h4> <a href="{% url 'school:detail' news.id %}">{{ news.news_title }}</a> </h4> Project: urls.py url(r'^news/(?P<pk>[0-9]+)/$', views.DetailView.as_view(), name='detail'), Thank you in advance. And sorry that i am asking a question that already was answered -
Hide drop-down menus in using id number
I passed a list [object1, object2, ...] to a drop-down menu. When I pressed on F12 with the desire of knowing the id of object1 which is Total number of clients in the following HTML code. I want to use that id in a JS file. How could I generate one id for each item of the list. Otherwise, what can I use in the JS file instead of an id number for Total number of clients? <div class="select-wrapper select initialized"><span class="caret">▼</span><input type="text" class="select-dropdown" readonly="true" data-activates="select-options-655bff26-fb5b-1642-ddeb-41bd1b4ab105" value="Total number of clients"> <ul id="select-options-655bff26-fb5b-1642-ddeb-41bd1b4ab105" class="dropdown-content select-dropdown" style="width: 100px; position: absolute; top: 1px; left: 0px; opacity: 1; display: none;"> <li class="active selected"><span>Total number of clients</span></li> <li class=""><span>Total new loans</span></li> <li class=""><span>Total renewals</span></li> <li class=""><span>Total debit fees</span></li> <li class=""><span>Total brokerage fees</span></li> <li class=""><span>Total interest</span></li> <li class=""><span>Total accounts receivable</span></li> <li class=""><span>Total active accounts receivable</span></li> <li class=""><span>Total special accounts receivable</span></li> <li class=""><span>Total accounts loss</span></li> <li class=""><span>Total completed loans</span></li> <li class=""><span>Total terminated loans</span></li> <li class=""><span>Total suspended loans</span></li> <li class=""><span>Total delayed fees</span></li> <li class=""><span>Total denied fees</span></li> </ul> <select class="select initialized" id="id_type_choice" name="type_choice"> <option value="0" selected="selected">Total number of clients</option> <option value="1">Total new loans</option> <option value="2">Total renewals</option> <option value="3">Total debit fees</option> <option value="4">Total brokerage fees</option> <option value="5">Total interest</option> <option value="6">Total … -
Field permission in django
I'm using drf and I wanna add permission per field. For example We have a 'budget' field in User model and a boolean field 'display_budget_public' which indicates that, the user wants to show this field to the public or to only a group of users like investors. I mean we want to hide restricted fields from non-investors. class User(AbstractBaseUser, PermissionsMixin): ... budget = model.IntegerField() display_budget_public = model.BooleanField() (Indeed we have many groups of fields and each one of them has its related permission field in a separate model and we have many user groups.) I handled this by manipulating 'to_representation' method and '_readable_fields' property in the rest of ModelSerializer class and excluding fields that don't have a permission. class PermissionFieldSerializer(serializers.ModelSerializer): @property def _readable_fields(self): return [ field for field in self.fields.values() if not field.write_only and self.check_permission(field) ] It's actually a bit more complicated. But there are two problems: by increasing the size of the project, we may forget to handle this permission logic in new serializers (because we have a lot of models and fields and serializers in different api versions). I mean I think it's better to handle it in model manager but I don’t know how. We have a … -
Django Ordering by property field
I'm using 'OrderingFilter' to allow ordering. According to Django documentation, when not specifying 'ordering_fields' you can order by any field that mentioned in the view serializer. I have a field which is basically a @property field in the serializer. But when trying to order by that field, I get the following error: Cannot resolve keyword 'spec_identifier' into field. Choices are:.... This is part of the model view: class ItemViewSet(BaseViewMixin, MyModelView): permission_classes = [MyItemViewPermissions] serializer_class = ItemSerializer filter_backends = (ItemFilter, OrderingFilter,) and this is the property definition I want to order by: @property def spec_identifier(self): return self.spec.identifier if self.spec else None Is it possible to order by it? -
Celery: Make Django formset validation asynchronously
It is necessary to validate the formset asynchronously, using Celery. # forms.py class OrderItem(forms.Form): contract = forms.CharField() amount = forms.DecimalField() def clean(self): # This should run asynchronously OrderItems = forms.formset_factory( OrderItem, extra=0, max_num=10, validate_max=True, min_num=1, validate_min=True, can_delete=True ) # views.py # url: /create_order def create_order(request): if request.method == 'POST': # Create order task_result = create_order_task.delay(request.POST) return HttpRedirect('/create_order/?tid={}'.format(task_result.task_id)) context = {} task_id = request.GET.get('tid', None) if task_id: task_result = celery_app.AsyncResult(task_id) if task_result.ready(): if task_result.successful(): data = task_result.get() if data.get('order_id', None): return HttpRedirect('/order/{}'.format(data.get('order_id'))) if data.get('invalid', None): order_items = ???? # Restore order ivalid OrderItems if task_result.failded(): context['task_failed'] = True # Show message else: # Show some animated indicator and reload page after timeout context['show_indicator'] = True context['reload_timeout'] = 5 else: order_items = OrderItems() context['order_items'] = order_items return TemplateResponse('create_order.html', context) # tasks.py @task() def create_order(data): order_items = OrderItems(data) if not order_items.is_valid(): return {'invalid': ????} # What????? # Create order here and return order.id return {'order_id': order.id} So the problem is: how to return invalid formset? With data and error messages and with minimum manipulations with template? What i already trying: Return formset "as-is" At first it doesn't works because pickle unable to serialize OrderItems with error PicklingError: Can't pickle <class 'django.forms.formsets.OrderItemsFormSet'>: it's not … -
Heroku disconnect MQTT Client every day
Some months ago I started a project with Django + MQTT. First of some problems using this was that Django runs two processes that creating two MQTT clients. I followed this topic and resolved my problem, putting this trick in my code. def on_disconnect(client, userdata, rc): client.loop_stop(force=False) if rc != 0: print("Unexpected disconnection.") else: print("Disconnected") But, every day, my client disconnect exactly at 20:15. To resolve this problem, I have to deploy my project again. Anyone knows what happens with Heroku Server at 20:15? Close all connections in specific port? Thanks! -
Why cannot I use a string variable of Django in Javascript?
I'm currently learning Django/Python. I'm trying to use Django variables in html or javascript, which doesn't work as I desire. My models.py, and views.py files look like class Student(models.Model): name = models.CharField(max_length=200) password = models.CharField(max_length=200) Students' name is a string variable, like "Tanaka" or "Yoshida", and password is an integer variable, 1234 or something like this. views.py def index(request): all_students = Student.objects.all() context = {'all_students': all_students} template = loader.get_template('aaa/LogIn.html') return render(request,'aaa/LogIn.html', context) the script code in LogIn.html file looks like <script> {% for student in all_students %} alert({{student.name}}) {% endfor %} </script> I want to use student.name in this code, but this doesn't work. If I change student.name to student.password, it works as expected. The question is why student.password appears in an alert message while student.name doesn't. I think the problem may be related to the variable type of name and password. How can I use Django variable in this case? Thank you, in advance.