Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Fetch multiple rows from multiple models Django
I have this project where, I need to fetch multiple objects from multiple models in a view. I could do that by for loop but I think I shouldn't hit database in each loop. Should I use prefetch_related. or Should I know some other way to retrieve them. for example: class A(models.Model): title_name=models.CharField(...) id=models.AutoField(pk=True) class B(models.Model): user=models.ForeignKey(User,models.ON_CASCADE=True) user_status=models.CharField(...) id=models.ForeignKey(A, models.ON_CASCADE=True) I need to display user_status, user and associated title_name. I get multiple objects, select_related will not be useful. Any suggestions. -
how can change the border radius of the the input text filed created by django forms class?
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <div class="design" style="border-radius:5px; border-color: darkgoldenrod; color: aquamarine; "> <form action="/form/2" method="post"> {% csrf_token %} {{ form }} <input type="submit" value="Submit" /> </form> </div> <input type="text" style="border-color: darkgoldenrod; border-radius: 10px;" /> </body> </html> the text filed created using the takes the css command but the textfiled generated using {{form}} is not taking css command. -
Django how to make ul li hierachy from a self reference model
i have a model like this class Unit(models.ModelForm): Name = models.CharField(max_length = 100) Parent = models.ForeignKey('self' , on_delete=models.CASCADE , related_name = 'SubUnits') i want to show hierarchy tree with ul and li in the template. first of all in the views.py i passed all Units with no parent which considered as Root Objects and then with a custom filter tag i want to generate hierarchy ul li tree object1 ----|object 1.1 |object 1.2------| object 1.2.1 |object 1.3 objecte 2 object 3 ---| object 3.1 | object 3.2---| object 3.2.1 in my custom tag i looks for a function that can generate infinite parent and child ul li for my root object. -
Configure Nginx for aws s3 static and media files
I am using aws s3 for static and media files for my django app. Gunicorn and Nginx are being used for application and proxy server. Nginx setup: server { listen 80; server_name sitename.com; location / { include proxy_params; proxy_pass http://unix:/home/SiteNameDjango/myproject/myproject.sock; } } Since I am using aws s3 for my static and media files, how should I configure Nginx for my static location? Or there's no need to configure for the static and media files? If it helps, here is the Django project settings for aws s3: STATICFILES_LOCATION = 'static' MEDIAFILES_LOCATION = 'media' STATICFILES_STORAGE = 'myproject.custom_storages.StaticStorage' DEFAULT_FILE_STORAGE = 'myproject.custom_storages.MediaStorage' AWS_STORAGE_BUCKET_NAME = "django-bucket" AWS_S3_CUSTOM_DOMAIN = AWS_STORAGE_BUCKET_NAME + ".s3.amazonaws.com" STATIC_URL = "https://" + AWS_STORAGE_BUCKET_NAME + ".s3.amazonaws.com/" MEDIA_URL = STATIC_URL + "media/" ADMIN_MEDIA_PREFIX = STATIC_URL + "admin/" Eg url: https://django-bucket.s3.amazonaws.com/media/user_image/1497598249_49.jpeg -
Django AttributeError: 'str' object has no attribute 'iter'
On Django admin when I tried to update the existing data I’m getting an error, AttributeError: 'str' object has no attribute 'iter' models.py class SSPDrive(models.Model): drive_year = models.DateField(verbose_name='Drive year', null=True, blank=True, help_text="Enter drive year.") class Meta: verbose_name = "SSP Drive" verbose_name_plural = "SSP Drives" def __str__(self): return str('SSP'+str(self.drive_year.year)[-2:]+'T'+str(self.drive_year.year+1)[-2:]) class SSPDriveAdmin(admin.ModelAdmin): save_as = True class Meta: model = SSPDrive admin.site.register(SSPDrive, SSPDriveAdmin) Can someone help me out, why am I getting this error… -
What is the proper way to sanitize raw MIME email in Django?
I'm building an app that stores received raw email. However, I can't seem to figure out what the proper way to sanitize and store them are? class IncomingEmail(forms.Form) ... mime_body = forms.CharField() Is doing form.is_valid() + form.cleanded_data['mime_body'] sufficient here? -
Django Editable Text Field
I've been able to easily create a list of editable items and manage them through the Django admin panel. That seems pretty simple and I have a good idea of how models work from other frameworks. Although, I'm curious to know to know how I can make something as simple as editing a text area on a static site. Basically, I don't need to "add post" or anything of the sort. I just want to be able to edit a text area on a static site. Any docs or examples? -
How to build a query that will help me filter objects
I have problem with a filter that I have to build. i have model state with field move (a1-h8) and field chessman (black_knight etc) I want to display a chessman object field that has a state field equal h7 I read https://docs.djangoproject.com/en/1.11/ref/templates/builtins/ but That did not help me. It did not work. {% for state in states %} {% if state.move|stringformat:"s" == "h7" %} {{ state.chessman }} {% endif %} -
The usual tricks aren't solving "expected string or bytes-like object" in Django
I'm working on a Django Webapp, and I have a pesky error message. It is "TypeError: expected string or bytes-like object". Relevant code follows, analysis below. Full traceback Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/core/handlers/exception.py", line 39, in inner response = get_response(request) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/core/handlers/base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/core/handlers/base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/contrib/auth/decorators.py", line 23, in _wrapped_view return view_func(request, *args, **kwargs) File "/Users/Philip/Code/GrammieGram/grams/views.py", line 83, in gramsindex grams_list = grams_list.filter(display_until=[start_time, end_time]) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site- packages/django/db/models/query.py", line 796, in filter return self._filter_or_exclude(False, *args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/db/models/query.py", line 814, in _filter_or_exclude clone.query.add_q(Q(*args, **kwargs)) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/db/models/sql/query.py", line 1227, in add_q clause, _ = self._add_q(q_object, self.used_aliases) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/db/models/sql/query.py", line 1253, in _add_q allow_joins=allow_joins, split_subq=split_subq, File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/db/models/sql/query.py", line 1187, in build_filter condition = self.build_lookup(lookups, col, value) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/db/models/sql/query.py", line 1083, in build_lookup return final_lookup(lhs, rhs) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/db/models/lookups.py", line 19, in __init__ self.rhs = self.get_prep_lookup() File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/db/models/lookups.py", line 59, in get_prep_lookup return self.lhs.output_field.get_prep_value(self.rhs) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/db/models/fields/__init__.py", line 1417, in get_prep_value value = super(DateTimeField, self).get_prep_value(value) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/db/models/fields/__init__.py", line 1275, in get_prep_value return self.to_python(value) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/db/models/fields/__init__.py", line 1378, in to_python parsed = parse_datetime(value) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/utils/dateparse.py", line 93, in parse_datetime match = datetime_re.match(value) TypeError: expected string or bytes-like object … -
how to prevent user from accessing a webpage without login
I have a page called jobboard.html that I only want the super user to access. Right now I have created up to the point where the user can go to url /login/, enter their username and password, and then they are redirected to /activejobs/. However, anyone can manually type in /activejobs/ into the browser and be directed there. I am not sure how to redirect someone (who does not have permissions) that types in /activejobs/ into the browser to the login page. I have some idea of using the POST data and getting the username and password to authenticate it with the inbuilt user database Django provides but I am not sure how to do it with my current set up. urls.py: from django.conf.urls import url, include from django.contrib import admin from django.contrib.auth import views as auth_views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^login/$', auth_views.login, {'template_name': 'activejobs/login.html'}, name='login'), url(r'^logout/$', auth_views.logout, {'template_name': url(r'^activejobs/', include('activejobs.urls')), ] login.html: {% extends 'activejobs/base.html' %} {% block content %} <h2>Login</h2> <form method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">Login</button> </form> {% endblock %} settings.py contains this line to make it redirect to activejobs url: LOGIN_REDIRECT_URL = '/activejobs/' activejobs/urls.py: from django.conf.urls import url from . import views … -
Excel file corrupted after download with python
I able to save the excel file using python in a folder and able to view it, but create the download function in javascript to download the excel file that I created and save by python , the file was downloaded but corrupted, anyone can help me on this? -
I removed __init__.py by mistake
I have deleted init.py by mistake along with the migrations folder in my django project What should i do now? -
Passing variable to a django queryset
So I have this urlset below. And in the urlset there are two urls that take paramters into the url and passes it into the apiviw. urlpatterns = [ url(r'^([0-9]{4})/([0-9]{1,2})/test/$', views.DuperView.as_view()), url(r'^test/([0-9]{4})/([0-9]{2})/$', views.SuperView.as_view()), url(r'^test/', views.TestView.as_view()), ] Here is the APIView that everything is passed into. class DuperView(APIView): queryset = models.DuperModel.dupers.duperdeduper() def get(self, request, year, month, format=None): an_apiview = [ year, month, ] return Response({'http_method': 'GET', 'api_view': an_apiview}) the first parameter that is defined in the url as ([0-9]{4}) is passed into the get method as year and the second defined as ([0-9]{1,2}) is passed as month. Here is my model, model manager and model queryset for the model this all corresponds to. class DuperQuerySet(models.QuerySet): def duperdeduper(self): return self.filter(year='2000') class DuperModelManager(models.Manager): def get_queryset(self): return DuperQuerySet(self.model, using=self._db) def duperdeduper(self): return self.get_queryset().authors() class DuperModel(models.Model): year = models.ForeignKey(YearModel) month = models.ForeignKey(MonthModel) name = models.CharField(max_length=255) dupers = DuperModelManager() I was wondering if there is a way to pass the year and month method that we pass into the get method into the backend logic in the models. I want to be able to do a join query like the one below. SELECT * FROM dupertable, yeartable WHERE year='variablevaluepassedon' Is this kind of functionality possible? I … -
Not all words are translated
I use ugettext_lazy to make some translations in program. Actually, there are many words that are well translated. However, there are still words that resists being translated. In my django.po file, there is #: formlayouts.py:70 msgid "Personal informations" msgstr "Informations personnelles" #: formlayouts.py:105 msgid "Financial informations" msgstr "Informations financiaires" #: formlayouts.py:136 models.py:500 msgid "Income source" msgstr "Source de revenu" For instance, Personal informations is never shown correctly if I use the following structure HTML('<h5 class="form-title black-text">%s</h5>' % _('Personal informations')) Knowing that _ is the alias of ugettext_lazy. -
Custom ContextProcessor with ListView - not showing in template
I am back to django after a few years and I have adopted Class Based Views - definitely a fan, BUT for some reason, I cannot get my custom content processor to show its data. I am using mostly Generic Views on my application, and from what I understand they should automatically serve the context to the view. This is my context processor (context_processors.py) from models import Alert def context_alerts(request): alert_list = {} alerts = Alert.objects.filter(to_user=request.user) alert_list['alerts'] = alerts alert_list['unread_count'] = len([a for a in alerts if a.unread == True]) # printing to console - this works print alert_list return alert_list Note that when I print the dictionary - it shows in my console, so I know it is firing. It is setup in my settings as so TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'part_iq.context_processors.context_alerts' ], }, }, ] Finally, this is an example view - I have about 20 or so, all standard class based views: class BuyerRfqList(ListView): context_object_name = "rfqs" template_name = "dashboard/buyer/rfq-list.html" def get_queryset(self): user = self.request.user rfqs = Rfq.objects.filter(from_user=user, hidden=False).order_by("created_at") return rfqs I am simply outputting the alerts in the template as so (trying … -
tensorflow serving python model
I have a trained model in python. I want to expose REST API for clients to consume the model. I am debating using Django framework with Python vs Tensorflow serving.Can someone give me suggestions on which would be better choice? -
How Python rules' predicates get its parameters?
I have a predicate like this: @rules.predicate def is_owner_of_book(user, book): ... It's used for a View. My question is how this predicate gets those parameters(i.e., user, book)? -
Final FormWizard redirects to first step
I basically used the django-formtool form wizard to handle saving of my form. User enters the "username" and "repository" on first step. repository is cloned User enters "inventory" and "user" on second step. I'm expecting that after the final submit, it will just save the data I'm having trouble when I try to save on the final step of the wizard, I returns me to the first step. With the expected ValidationError that the repository exists, because on my views.py execute the clone_repository() method. Below are the relevant code I currently have. views.py class PlaybookWizard(SessionWizardView): def process_step(self, form): if self.steps.current == '0': form.clone_repository() if self.steps.current == '1': form.save() return super(PlaybookWizard, self).process_step(form) def done(self, form_list, form_dict, **kwargs): return HttpResponseRedirect('/playbooks') forms.py def check_path_exists(repository, host_inventory=None): if host_inventory: os.chdir(settings.PLAYBOOK_DIR + repository) current_dir = os.getcwd() return os.path.exists(os.path.join(current_dir, host_inventory)) return os.path.exists(os.path.join(settings.PLAYBOOK_DIR, repository)) def get_dir_name(repository): return os.path.join(settings.PLAYBOOK_DIR, repository) def get_remote_repo_url(username, repository): return "https://github.com/{0}/{1}.git".format( username, repository ) class AnsibleForm1(ModelForm): class Meta: model = Playbook fields = ['repository', 'username'] def clean_repository(self): if check_path_exists(self.cleaned_data['repository']): raise ValidationError("Repository already exists") return self.cleaned_data['repository'] def clone_repository(self): repository = self.cleaned_data['repository'] username = self.cleaned_data['username'] dir_name = get_dir_name(repository) remote_url = get_remote_repo_url(username, repository) os.mkdir(os.path.join(dir_name)) repo = git.Repo.init(dir_name) origin = repo.create_remote('origin', remote_url) origin.fetch() origin.pull(origin.refs[0].remote_head) class AnsibleForm2(ModelForm): class Meta: model … -
Creating django pagination using generic view
Hello fellows since i am pretty knew to programming ,I am facing a slight problem in django pagination using generic views ,passing multiple models to a template with one of the models that has to paginated .The pager does not show next pages on my template,but produces just a single page .Bellow is my code : views.py class homeView(generic.ListView): template_name = 'success/home_page.html' context_object_name="articles" paginate_by = 3 def get_queryset(self): articles =Articles.objects.order_by('article_title') paginator = Paginator(articles,self.paginate_by) page = self.request.GET.get('page') try: articles = paginator.page(page) except PageNotAnInteger: articles = paginator.page(1) except EmptPage: articles = paginator.page(paginator.num_pages) return articles def get_context_data(self,**kwargs): contex = super(homeView,self).get_context_data(**kwargs) contex['quote']=Quotes.objects.order_by('quote') return contex hmtl template {% for article in articles %} {{ article.article_title}} {{ article.aticle_hit}} {% endfor % %} <div class="pagination"> {% if articles.has_previous %} <a class="navlink" href="?page={{articles.previous_page_number}}">Prev</a> {% endif %} page{{articles.number}} of {{articles.paginator.num_pages}} <span> {% if articles.has_next %} <a class="navlink" href="?page={{articles.next_page_number}}">next</a> {% endif %} Just page one of my paginated page shows.Next and previous does not work at all .Please help me with a better way to do pagination using generic view and passing multiple models in to a single html template -
Run Django Celery Nohup in Crontab
I want to run some tasks in django. I'm using Celery to do this. Usually, I run this command to execute the tasks: source myvirtualenvpath/bin/activate nohup python manage.py celeryd -E -B --loglevel=DEBUG < /dev/null &>/dev/null & I want to do this each time the machine reboot with a crontab. How can I do this? Thanks -
Django RawSql query to do filter on nested json
My Models looks like this class Foo(): payload = JSONField() Payload looks something like this [{ "id": 12, "names": [{"location": "New York"}, ]{"location": "Philly"}] }, { "id": 15, "names": [{"location": "Paris"}, ]{"location": "Cannes"}] }] queryset = Foo.objects.all() queryset = queryset.filter(payload__names__contains=[{"name": "Paris"}]) #this works!! queryset = queryset.filter(payload__names__contains=[{"name": "Par"}]) #does not work The second statement does not work - it returns 0 results. In the first case it works because the full text is provided. What is the best way to do this in rawSql? [I am assuming it is not possible in Django] I went thorough this but cannot find what to use to do like on a nested array json field. -
Django model - how to define foreign key refer to another table?
I'm working with a legay database so I have to set managed = False, which means I cannot update the database schema. What I'm trying to do is select branches based on project id. Ideally in branches table it should have a project_id as foreign key but the previous system design is another table (branches_projects) stores this relationship. I have been able to get around some problems using https://docs.djangoproject.com/en/1.11/topics/db/sql/#django.db.models.Manager.raw. raw() would return an RawQuerySet, which is not ideal. I wonder if there's a way for me to define a foreign key in my branches table, which is the project_id, but refer/link that to the branches_projects table? class Branches(models.Model): name = models.CharField(max_length=128) branchpoint_str = models.CharField(max_length=255) dev_lead_id = models.IntegerField(blank=True, null=True) source = models.CharField(max_length=255) state = models.CharField(max_length=255) kind = models.CharField(max_length=255) desc = models.TextField(blank=True, null=True) approved = models.IntegerField() for_customer = models.IntegerField() deactivated_at = models.DateTimeField(blank=True, null=True) created_at = models.DateTimeField(blank=True, null=True) updated_at = models.DateTimeField(blank=True, null=True) codb_id = models.IntegerField(blank=True, null=True) pm_lead_id = models.IntegerField(blank=True, null=True) version = models.CharField(max_length=20, blank=True, null=True) path_id = models.IntegerField(blank=True, null=True) branchpoint_type = models.CharField(max_length=255, blank=True, null=True) branchpoint_id = models.IntegerField(blank=True, null=True) class Meta: managed = False db_table = 'branches' verbose_name_plural = 'Branches' class Projects(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=40, primary_key=True) status = models.CharField(max_length=255) platform = … -
Django Attribute Error - form object has no attribute is_valid error
I keep getting an error saying that my BundleForm has no attribute is_valid. I double and triple checked and my BundleForm is associated with a model, specifically my Bundle model. I can't figure out why else I would be getting this error. Any comments/input greatly welcomed! models.py class Bundle(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) user_profile = models.ForeignKey(UserProfile, on_delete=models.CASCADE) name = models.CharField(max_length=100) def __str__(self): return self.name forms.py class BundleForm(forms.ModelForm): name = forms.CharField( help_text='Enter mission name. Change to hidden unless mouse over. ', initial='bundle_name', required=True, max_length=50, ) class Meta: model = Bundle fields = ('name',) views.py def new_bundle(request): form1 = BundleForm() if request.method == 'POST': form1 = BundleForm(request.POST) if form1.is_vaild(): bundle = form1.save(commit=True) return render(request, 'build_a_bundle/new_bundle.html', {'bundle':bundle}) else: return HttpResponse('Form 1 Error') return render(request, 'build_a_bundle/new_bundle.html', {'form1':form1}) -
Not caching view in Django LocMemCache
I am trying to cache a class based view like so urls.py from django.views.decorators.cache import cache_page from django.conf.urls import url urlpatterns = [ url(r'^/awesome-url$', cache_page(60 * 60)(TemplateView.as_view(template_name="awesome.html")), name="awesome"), ] settings.py CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', 'LOCATION': 'unique-snowflake' } } My hope was to have my views cached and I wanted to verify that this was happening by inspecting it with: from django.core.cache.backends import locmem print locmem._caches >{} Source: Contents of locmem cache in django? Sadly the backend is empty. So I am doubtful that the view is being cached, can anyone help? -
Correct url pattern for django verion1.11
I'm currently running django version 1.11 and I want to create a blog. I am at the process where I create a function based view to display html content. I keep running into this error. File "/Users/Fanonx/Desktop/xventureblog/src/xventureblog/urls.py", line 21, in <module> url(r'^admin/', include(admin.site.urls)), NameError: name 'include' is not defined Here is my code for views.py # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.http import HttpResponse from django.shortcuts import render # Create your views here. def post_home(request): return HttpResponse("<h1>Hello<h1>") here is my code for urls.py from django.conf.urls import url from django.contrib import admin from posts.views import post_home urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'^posts/$', post_home), ]