Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django makemessages not detecting translatable strings
In a package 'purchase', there is a file reports.py. In this package I'm generating some pdf-reports that sometimes I want to translate to the Czech language. Unfortunately the makemessages script doesn't detect to see the translatable strings. Running the following shows that reports.py is being processed. But no files are added. .././manage.py makemessages -l cs_CZ -v 2 processing file reports.py in . processing locale cs_CZ This is a snippet from the reports.py file: from django.utils.translation import ugettext as trans def purchase_order_report(purchase_order, language='en'): ... doc.add_text(trans('Items requested'), 'Heading2') ... The Locale folder is setup like this: LOCALE_PATHS = ( os.path.join(BASE_DIR, "locale"), ) -
getting get_list to display the list on multiple rows instead of one
I'm struggling to get my templatetag to work. I believe it's the syntax or the way i'm calling app_filters. Forgive me i'm learning web application development so if my logic is off please correct me. My goal is to pass a collection of check boxes on one template to a new one filtered at a different level. I have an array in my view from my GET.getlist call below checkedlist = request.GET.getlist('report_id') reportlist = QvReportList.objects.filter(report_id__in= checkedlist, active = 1).values_list('report_name_sc',flat = True) print (checkedlist) print (reportlist) args = {'retreivecheckbox': checkedlist} return render(request,'accounts/requestaccess.html', args) When I print my array the console displays it correctly, this example is if there was two check boxes selected: ['88', '89'] <QuerySet ['Common Data Model Reconciliation Load', 'LEJR BPCI IV - ICS Baseline']> I've created the following templatetag called app_filters defined as: from django import template register = template.Library() @register.filter def get_list(querydict, itemToGet ): return querydict.getlist(itemToGet) Now i'm trying to get my template to display what's in my console but as individual rows/indexes dependent upon user selections. I'm told get_list will do that for me. I've also tried get_at_index. I.E. I want to see retreivecheckbox as 88 89 and not [88,89] Using the following template my app … -
How do I place a template variable within a template tag?
I'd like the form to submit not to the request.user, but the {{views.kwargs.username}}. I currently have the form action like so: <form enctype="multipart/form-data" method="POST" action="{% url 'profile:make_request' username=request.user %}"> This is a form belonging on user-b's page, filled out by user-a, and submitted to user-b. For username, I'd like to put in {{view.kwargs.username}}, but it does not work. What's the proper way of passing this into the action? -
creating a UserProfile in django
i'm trying to create a UserProfile that is connected to a specific User on creation, however it does not seem to create a UserProfile when i register a user. how come is that? Model.py class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) avatar = models.ImageField(upload_to = 'static/img/avatars', default = 'static/imgs/avatars/avatar.jpeg') views.py def register(request): context = {} if request.user.is_authenticated(): return redirect('/account/') if request.method == "POST": form = SignUpForm(data=request.POST) if form.is_valid(): form.save() profile = UserProfile(user=form) profile.save() username = form.cleaned_data.get('username') raw_password = form.cleaned_data.get('password1') user = authenticate(username=username, password=raw_password) auth_login(request, user) context['success'] = True return HttpResponse(json.dumps(context), content_type="application/json") else: form = SignUpForm() return render(request, 'register.html', {'form': form}) -
Best way to specify one of the existing ManyToMany through relationships?
I have these models for a database of a library: class Author(models.Model): ... class Task(models.Model): ... class BookTask(models.Model): book = models.ForeignKey(Book) author = models.ForeignKey(Author) task = models.ForeignKey(Task) class Book(models.Model): authors = models.ManyToManyField(Author, through='BookTask'...) Everything there works fine, but I would like to specify one of the existing BookTask relationships as the main one. Think of one book where 3 authors have worked in. I would like to assign all 3 to the book and then set 1 of them as the main one. I've tried this: class Book(models.Model): authors = models.ManyToManyField(Author, through='BookTask'...) author_main = models.ForeignKey(BookTask...) But then the generated admin webpage doesn't show the expected choice widget. Any ideas? -
CSS file not loading (Django, python)
Here's the code I have: In the HTML file: link rel="stylesheet" href={% static 'css.css' %}" (Of course there is <> around it but it wasn't loading here for some reason) In settings.py: STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'),) The css.css file is located in the static directory which is in the same directory as manage.py , So why isn't the css file loading? There is also a js file which doesn't seem to be loading either, and it's in the same directory as the CSS file and I'm loading it in with the same method as the CSS file. Also, my pc isn't currently connected to WiFi, in case it makes a difference. I'm working with localhost. -
multiple openpyxl xlsx workbooks into one .zip file for download
I am trying to get some xlsx files from a form, i load them using openpyxl and do some data processing.. and finally i need to download all processed xlsx files zipped to the user. here is an example of what i did so far if form.is_valid(): s = StringIO.StringIO() zf = zipfile.ZipFile(s, mode="w") for xlsx in request.FILES.getlist('xlsxs'): element_column = "G" element_row = 16 massar_column = "C" massar_row_start = 18 loop = column_index_from_string(element_column) while (loop <= ws.max_column): for i in range(massar_row_start, ws.max_row+1): # ... ws["%s%s" % (element_column,i)] = 0 # ... loop+=2 element_column = get_column_letter(loop) buf = save_virtual_workbook(wb) zf.write(buf) # or zf.write(wb) zf.close() response = HttpResponse(s.getvalue(), content_type="application/x-zip-compressed") response['Content-Disposition'] = "attachment; filename=notes.zip" return response I get the error stat() argument 1 must be encoded string without null bytes, not str Thanks in advance for any help you can offer. -
Django form with spotipy not updating on Apache2
I've made a Django website with this form.py to populate a template html with a dropdown list with all my current spotify playlists: from django import forms import spotipy import spotipy.util as util def getplaylists(): #credentials CLIENT_ID='xxxxx' CLIENT_SECRET='xxxxx' USER='xxxxxx' # token krijgen token = util.oauth2.SpotifyClientCredentials(client_id=CLIENT_ID, client_secret=CLIENT_SECRET) cache_token = token.get_access_token() sp = spotipy.Spotify(cache_token) # playlists opvragen results = sp.user_playlists(USER,limit=50) namenlijst = [] idlijst = [] for i, item in enumerate(results['items']): namenlijst.append(item['name']) idlijst.append(item['id']) #samenvoegen dropdowndata = zip(idlijst, namenlijst) #dropdowndata = zip(namenlijst, idlijst) return dropdowndata class SpotiForm(forms.Form): LIJSTEN = getplaylists() lijstje = forms.ChoiceField(choices=LIJSTEN, required=True) I'm running two versions of this Django website on my VPS (with exactly the same code): A) a version on Apache2 (with mod_wsgi) B) a test version ('python ./manage.py runserver x.x.x.x:xxx') When I add or delete a playlist in Spotify the dropdown list in version A gets updated, but the dropdown list of version B does not. Can someone explain to me why this is happening? -
Angular 4 HTTP requests to Django Rest Framework
I'm having issues finding the answer anywhere to an issue I'm having related to the (I think) Authorization header in an HTTP request I'm sending from Angular 4 to the Django Rest Framework API I've created. Lets get down to it: In settings.py, I've made sure that both a permission class and authentication class have been made available. REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.BasicAuthentication', ], 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAdminUser' ], In views.py, this is perhaps where my fault is since the console error I get when trying to send the request from Angular -> Rest API is that 'No 'Access-Control-Allow-Origin' header is present on the requested resource.' which is untrue since it does NOT complain about this when I remove the authentication need. class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all().order_by('-date_joined') serializer_class = UserSerializer permission_classes = (IsAdminUser, ) authentication_classes = (BasicAuthentication, ) def list(self, request): queryset = User.objects.all().order_by('-date_joined') serializer = UserSerializer(queryset, many=True, context={'request': request}) return Response(serializer.data, headers={'Access-Control-Allow-Origin': 'http://localhost:4200'}, status=200) The Angular dev server is running on localhost:4200 while django is left on its default of localhost:8000. I'll include the urls.py for good measure: from django.conf.urls import url, include from rest_framework import routers from backend.api import views from django.contrib import admin router = routers.DefaultRouter() router.register(r'users', … -
Where does Django store the objects?
I have definied a class from django.db import models class Album(models.Model): artist = models.CharField(max_length=20) title = models.CharField(max_length=50) but when I try to create an object in the shell it it says: >>> a = Album() Traceback (most recent call last): File "<console>", line 1, in <module> NameError: name 'Album' is not defined I tried to re-migrate models to the database file (this code was working fine in past), but it says there are no migrations to apply. So where am I suppose to "define" an object if not in models file nor database? -
Class based view - get function is not being called
Trying to use Django-filter class based view FilterView but I have problems with rendering filter in the template. It seems the filter is not in contex. DOCS: https://django-filter.readthedocs.io/en/master/guide/usage.html#generic-view-configuration EDIT: It seems that the get(self...) function of the view is never being called. I've set breakpoints in get method and it didn't stopped there. filters.py class UserProfileFilter(django_filters.FilterSet): class Meta: model = UserProfile fields = ['budget','looking_for','user'] views.py class UserFilterView(FilterView): filterset_class = UserProfileFilter template_name = 'frontend/userprofile_filter.html' userprofile_filter.html {% extends "frontend/base.html" %} {% block content %} <div class="filter"> {{ filter.form.as_p }} </div> <hr> <div class="results"> </div> {% endblock %} But in browser, I see: ... <div class="filter"> </div> ... urls.py url('^search/$',views.UserFilterView.as_view(), name="user_filter") Can't figure out where is the problem. Do you have any ideas? -
Django load script from another app into an html file
I'm having trouble using a script from a file in App1 in a page in app2. My project structure looks like this: I want to use the following file in home/static/scripts/scripts.py Inside an html file in project/templates/project/s3.html My scripts.py file looks like this: import boto3 def listS3(): s3 = boto3.resource('s3') for bucket in s3.buckets.all(): print(bucket.name) My s3.html file looks like this: {% include "home/_header.html" %} {% block content %} {% load staticfiles %} <div class="s3"> </div> {% endblock content %} To be frank I'm not even sure how to load that script and how to call it afterwards as this is my first project in django. Do I use: {% load script.py %} Or something like that? How do I later call function listS3 in the html file? Like this? {% listS3() %} ? I appreciate your help. -
django server is not running due to change in admin.py file in app directory of project
django server is not running whenever i put some code in admin.py file , which is in app directory of main django project. if i commented the code of admin.py file then the server run fine, but if i run the code it show an error in powershell and server doesn't work here is code of admin.py from django.contrib import admin from .models import Entry @admin.register(Entry) class EntryAdmin(admin.ModelAdmin): fieldsets = [ ('Regular Expression', {'fileds':['pattern','test_string']}), ('Other Information', {'fields':['user','date_added']}) ] list_display = ('pattern','test_string','user') list_filter = ['user'] search_fields = ['test_string'] and the error in powershell is .. ERRORS: <class 'entries.admin.EntryAdmin'>: (admin.E011) The value of 'fieldsets[0] [1]' must contain the key 'fields'. any help will be appreciated -
django pandas pd.ExcelFile() throws error no such file
I am using the pynthon3 and Django framework and wanted to read the excel file with the help of pandas, my excel file is present at the level of view file directory. I am doing the following code snap for reading the file, but its throw the error "FileNotFoundError: [Errno 2] No such file or directory: 'formate.xlsx'" df = pd.ExcelFile("formate.xlsx", sheetname=sname) What should I do? -
Docker with Django
someone can help me please? I must run my django application in docker, so I have dowload ubuntu image, apache image, python image, mysql. Can I run ubuntu image first in container, after that can I run apache in container ubuntu? How can I do? Thanks for your answers. -
Django class-based views: Method Not Allowed (POST)
I'm trying to submit some form. Here is my views.py, urls.py and main.html. Every time I get the same error: Method Not Allowed (POST): /contact/ Tell me anybody what is wrong here? Thanks in advance! views.py from django.views.generic import CreateView from django.http import HttpResponseRedirect class Contact(CreateView): def post(self, request, **kwargs): print(request) return HttpResponseRedirect('/') urls.py from .views import Contact urlpatterns = [ url(r'^contact/$', Contact.as_view(), name='contact'), ] main.html <form role="form" method="post" action="{% url 'main:contact' %}"> {% csrf_token %} <div class="form-group"> <label for="Name">Your Name</label> <input type="email" class="form-control" id="Name" placeholder="Enter name"> <label for="Email">Email address</label> <input type="email" class="form-control" id="Email" placeholder="Enter email"> <label for="Text">Message</label> <textarea class="form-control" id="Text" rows="3"></textarea> </div> <button class="btn btn-default">Submit</button> </form> -
Django REST Swagger how to process response and save imagefield POST api (function based)
I am trying to accept a image file that has been post using my Django REST function based POST API. This is based on https://github.com/m-haziq/django-rest-swagger-docs I am getting this error screenshot (https://imgur.com/a/ECq5y) Object of type 'TypeError' is not JSON serializable for doing this face_image = request.data.get('face_image') and whats the right step to save it to the model, would it be something like this employee.face_image = face_image Here is how I define the API https://gitlab.com/firdausmah/railercom/blob/master/railercomapp/api.py @api_view(['POST']) def update_employee_image(request): # ----- YAML below for Swagger ----- """ description: This API deletes/uninstalls a device. parameters: - name: employee_id type: integer required: true location: form - name: face_image type: file required: true location: form """ employee_id = request.POST.get('employee_id') face_image = request.data.get('face_image') <--- this causes the error try: employee = Employee.objects.get(id = employee_id) logging.debug(f"API employee username {employee.username}") employee.face_image = face_image <-- is this how to save the image ? employee.save() return Response("Employee Updated!", status=status.HTTP_200_OK) except Exception as ex: return Response(ex, status=status.HTTP_400_BAD_REQUEST) Here is the model with the imagefield https://gitlab.com/firdausmah/railercom/blob/master/railercomapp/models.py class Employee(models.Model): .... face_image = models.ImageField(upload_to='face_image/', blank=True) Can someone let me know the right way to do this ? process the image from the post and save it to the model. My full source code is … -
How to process Iframe javascript functioncall
I found out javascript function call in iframe is transmitted to view.py or url.py ... therefore if function is not defined in parent page.. it shows "function is undefined...." How can I process javascript function call in its own javascript function. the result of explorer is "date function is undefined..." Thnks in advance. ref. -
Pushing default value of form through Django to Flask
so I am trying to let the user select a question to answer after iterating through all of the questions in the database. I want the ID of the question they choose to be placed into the session['select_q'] variable to be used on another page. The current code I have is throwing a 400 Bad Request: The browser (or proxy) sent a request that this server could not understand. error and I think I am not passing the value to the session properly. What would be the best way to pass the value of the choice to the session so I can use that value on the separate page room.html. Perhaps there is even a better way to do all this other than sessions, but let me know! pending.html code: {% for r in result %} <div class="uk-card uk-card-default uk-width-1-2@m"> <div class="uk-card-header"> <div class="uk-grid-small uk-flex-middle" uk-grid> <div class="uk-width-auto"> <img class="uk-border-circle" width="40" height="40" src="{{ url_for('static', filename='images/user_avatar.jpg')}}"> </div> <div class="uk-width-expand"> <h3 class="uk-card-title uk-margin-remove-bottom">{{ r[9] }}</h3> <p class="uk-text-meta uk-margin-remove-top">{{ r[4] }}</p> <li><u>Time Submitted</u>: {{ r[5] }}</li> <!--<li><u>Question ID</u>: {{ r[0] }}</li>--> <!--GET TECH INFO<li><u>TECH ID</u>: {{ r[0] }}</li>--> </div> </div> </div> <div class="uk-card-footer"> <form action="/room/" method="post"> <!-- POST to session which set they … -
KeyError: 'locations' in Django app
I'm working on a Django application which fetches JSON data from an API and stores it in PostgreSQL database. But while migrating the app I'm getting this error: KeyError: 'locations' Here's the traceback: Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 363, in execute_from_command_line utility.execute() File "/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 355, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/python/lib/python3.6/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/python/lib/python3.6/site-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/app/aggregator/WorldBank/management/commands/fetch_wb.py", line 23, in handle locations = data['locations'], KeyError: 'locations' How to fix this problem? Here's my code for models.py: from django.db import models from django.contrib.postgres.fields import JSONField class Projects(models.Model): data = JSONField(null=True) project_id=models.CharField(max_length=255) project_name=models.CharField(max_length=255) status=models.CharField(max_length=255) country=models.CharField(max_length=255) locations=JSONField() mjtheme=models.CharField(max_length=255) project_docs=JSONField() source=models.CharField(max_length=255) mjtheme_namecode=models.CharField(max_length=255) docty=models.TextField() countryname=models.CharField(max_length=255) countrycode=models.CharField(max_length=255) themecode=models.CharField(max_length=255) theme_namecode=models.CharField(max_length=255) project_url=models.TextField() totalcommamt=models.CharField(max_length=255) mjthemecode=models.CharField(max_length=255) sector1=models.CharField(max_length=255) theme1=models.CharField(max_length=255) theme2=models.CharField(max_length=255) theme3=models.CharField(max_length=255) projectinfo=models.TextField() country_namecode=models.CharField(max_length=255) p2a_updated_date=models.CharField(max_length=255) p2a_flag=models.CharField(max_length=255) project_abstract=JSONField() And here's the code for fetch.py file which is stored under /management/commands/fetch.py: import requests from django.core.management.base import BaseCommand from aggregator.WorldBank.models import Projects class Command(BaseCommand): def handle(self, **options): response = requests.get("https://search.worldbank.org/api/v2/projects?format=json&countryshortname_exact=India&source=IBRD&kw=N&rows=776") data = response.json() projects = data['projects'] for project in projects: print(projects[project]) print("\n\n") data = projects[project] Projects.objects.create( project_id = data['id'], project_name = data['project_name'], status = data['status'], country = data['countryshortname'], locations = data['locations'], mjtheme = … -
django widget.type is incorrect in custom widget
I'm new to django. I'm going to use a custom widget for the check box. Here is my form.py: class SupervisorForm(forms.Form): is_manager = forms.BooleanField(label=_("manager"), required=False) I searched through whole project and realized that this forms is rendered from this file: (forms/widgets/input.html) the code is: <input type="{{ widget.type }}" name="{{ widget.name }}"{% if widget.value != None %} value="{{ widget.value|stringformat:'s' }}"{% endif %}{% include "django/forms/widgets/attrs.html" %} /> now I have created a custom widget called SwitchWidgetCheckboxInput class SwitchWidgetCheckboxInput(ClearableFileInput): template_name = 'utils/SwitchWidgetCheckboxInput.html' @property def media(self): js = ("utils/switch_widget_checkbox_input/SwitchWidgetCheckboxInput.js",) css = {'all': ("utils/switch_widget_checkbox_input/SwitchWidgetCheckboxInput.css",)} return forms.Media(js=js, css=css) def render(self, name, value, attrs=None, renderer=None): """ Returns this Widget rendered as HTML, as a Unicode string. """ context = self.get_context(name, value, attrs) return self._render(self.template_name, context, renderer) my js and css are blank at the moment. and changed the form.py in this way: class SupervisorForm(forms.Form): is_manager = forms.BooleanField(label=_("manager"), required=False, widget=SwitchWidgetCheckboxInput) and copied the same input.html content to my widget html but surprisingly the checkbox turned into a file input! I used a breakpoint in my widget html and realized that widget.type is file, while i used breakpoint in input.html before applying my custom widet the widget.type was checkbox. another point is that in my widget html I changed … -
django template url does not call django rest api
I have following django rest api end point url(r'^api/email-verification/(?P<pk>[0-9]+)/$', EmailVerificationApiView.as_view(), name="email-verified") and following is the html template where i am applying this api to verify a user, i.e after clicking the following Activate link, the above mentioned api endpoint will be called and in back end the user will be flaged verified, but with the click of the html button it doesn't call the api, in fact nothing is happening <body> <tr> <td class="button"> <div><!--[if mso]> <v:roundrect xmlns:v="urn:schemas-microsoft-com:vml" xmlns:w="urn:schemas-microsoft-com:office:word" href="http://" style="height:45px;v-text-anchor:middle;width:155px;" arcsize="15%" strokecolor="#ffffff" fillcolor="#ff6f6f"> <w:anchorlock/> <center style="color:#ffffff;font-family:Helvetica, Arial, sans-serif;font-size:14px;font-weight:regular;">My Account</center> </v:roundrect> <a href="{% url 'email-verified' user_id %}"> Activate </a> </div> </td> </tr> <body> no error given, just not calling the api.I am relatively new in django and django rest api.Is there any other special way to call a django rest api in django template url tag? In mention, the above given html template is a email template. -
Django-rest-framework: have different orderingfilter for different fields
I have a simple model below: class Ingredient(models.Model): name = models.CharField(max_length=30) I am using django rest framework for api endpoints. class IngredientListAPIView(ListAPIView): queryset = Ingredient.objects.all() serializer_class = IngredientListSerializer filter_backends = [OrderingFilter] I wanted my two end points to output as: ?ordering=name -- i want the ordering to be case-insensitive ?ordering=-name -- i want the ordering to be case-insensitive the only way to achieve this is create class CaseInsensitiveOrderingFilter(OrderingFilter): def filter_queryset(self, request, queryset, view): ordering = self.get_ordering(request, queryset, view) if ordering: new_ordering = [] for field in ordering: if field.startswith('-'): new_ordering.append(Lower(field[1:]).desc()) else: new_ordering.append(Lower(field).asc()) return queryset.order_by(*new_ordering) return queryset and then class IngredientListAPIView(ListAPIView): queryset = Ingredient.objects.all().order_by(Lower('name')) serializer_class = IngredientListSerializer filter_backends = [CaseInsensitiveOrderingFilter] But now when i access the following endpoints ?ordering=id -- it shows 1,10,11,12 ?ordering=-id -- it shows 99,98 ..100.. If i use filter_backends = [OrderingFilter] instead of filter_backends = [CaseInsensitiveOrderingFilter] ?ordering=id -- it shows 1,2,3,4, ?ordering=-id -- it shows 220,221,220 so how to tell Django to use filter_backends = [CaseInsensitiveOrderingFilter] for name field and filter_backends = [OrderingFilter] for id field -
Django Login with preset single Username and Password
I am trying to create a simple login page, for anyone who has the username and password should be able access to some specific links. I found some tutorials which teach registration, login, logout using auth templates, but they need me to do user registration first. I could not find any basic tutorial, which can just help me set a default username and password, without creating a signup page. I know this question is not specific, but any heads up will be very helpful! -
From the View, how do I pass custom "choices" into a form's ChoiceField?
According to Django docs., the ChoiceField accepts an iterable of two tuples, "or a callable that returns such an iterable" to use as choices for the field. I've defined ChoiceFields within my forms: class PairRequestForm(forms.Form): favorite_choices = forms.ChoiceField(choices=[], widget=RadioSelect, required=False) Here is the view where I'm attempting to pass a tuple of custom choices: class PairRequestView(FormView): form_class = PairRequestForm def get_initial(self): requester_obj = Profile.objects.get(user__username=self.request.user) accepter_obj = Profile.objects.get(user__username=self.kwargs.get("username")) # `get_favorites()` is the object's method which returns a tuple. favorites_set = requester_obj.get_favorites() initial = super(PairRequestView, self).get_initial() initial['favorite_choices'] = favorites_set return initial Within my models.py, here is the method used above that returns a tuple: def get_favorites(self): return (('a', self.fave1), ('b', self.fave2), ('c', self.fave3)) From my understanding, if I want to pre-populate the form, I pass data in by overriding get_initial(). I attempt to set the initial data of the form's favorite_choices with a callable. The callable being favorites_set. With the current code, I am given an error of 'tuple' object is not callable How can I pre-populate the RadioSelect ChoiceField with my own choices? edit: I've also tried setting initial['favorite_choices'].choices = favorites_set