Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django how get user(author) of article and transfer it to template
I have simple article model, and I want get user who is author some article. But I can't. I make next: from django.db import models from django.contrib.auth.models import User class Article(models.Model): class Meta(): db_table = 'article' title = models.CharField(max_length=50) text = models.TextField() user = models.ForeignKey(User) in my view we have def articleSingle(request, article_id=1): article = Article.objects.get(id=article_id) return render(request, 'article.html', {'article': article}) and template <h1>{{ article.title }}</h1> <p>{{ article.text }}</p> <p>{{ article.user.username }}</p> But article.user.username or article.user is empty -
cannot access user profile in template from user object
i've created a UserProfile method, which i would like to access with the user, however it does not seem to return anything even though i have set related_name. what am i missing? models.py class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name="profile_user") avatar = models.ImageField(upload_to = 'static/img/avatars', default = 'static/imgs/avatars/avatar.jpeg') def __str__(self): return self.user.username def __unicode__(self): return self.user.username template so far in template i have tried {{ user.profile_user.avatar }}, {{ request.user.profile_user.avatar }} -
Django Social Auth pipline redirect and create
I have implemented Django Social Auth to signup and login using Facebook and Twitter. I was wondering how can I use piplines to specify an action to be done. For example, after creating the profile, I want to check if a field is empty and then redirect the user to another page to complete the profile as Facebook and Twitter don't give you the email address for example. Thank you -
How to prevent FactoryBoy from reusing object of a SubFactory?
I have the following factories: class UserFactory(factory.DjangoModelFactory): class Meta: model = get_user_model() class ProProfileFactory(factory.DjangoModelFactory): user = factory.SubFactory(UserFactory) class Meta: model = ProfessionalProfile class UserProfileFactory(factory.DjangoModelFactory): user = factory.SubFactory(UserFactory) class Meta: model = UserProfile When I inject both pro and user profiles they are associated with the same user: def test_should_create_project(pro_profile, user_profile): assert user_profile.user != pro_profile.user This test fail. How can I make factory boy create a new user for each profile? I'm using Django 1.11, pytest 3.2.2, pytest-django 3.1.2, pytest-factoryboy 1.3.1 -
last activity feature in Django not updating properly
I am trying to implement a lastActive feature but I don't know what values should the null and blank property have for the lastActive field in the User model. With this version of the code, the lastActive fields get a similar time as the created field, but after every login+logout the lastActive field doesn't get updated. Other than that, I am also getting the following error if I try python manage.py migrate, although makemigrations works fine: File "/Library/Python/2.7/site-packages/django/utils/dateparse.py", line 94, in parse_datetime match = datetime_re.match(value) TypeError: expected string or buffer Here's my models.py: class User(models.Model): userID = models.AutoField(primary_key = True) username = models.CharField(max_length = 30, unique = True) first_name = models.CharField(max_length = 30, blank = False) last_name = models.CharField(max_length = 30, blank = False) email = models.EmailField(blank = False, unique = True) password = models.CharField(max_length = 30) class_year = models.IntegerField(validators=[MinValueValidator(4),MaxValueValidator(4),]) created = models.DateTimeField(auto_now = True, editable = False) #this field actually doesn't get updated yet, please debug lastActive = models.DateTimeField(auto_now = True, editable = True) Here's my middleware.py: class LastActiveMiddleware(MiddlewareMixin): def process_response(self, request, response): if request.user.is_authenticated(): User.objects.filter(pk = request.user.pk).update(lastActive=timezone.now()) return response Here's my view.py: def signup(request): if request.method == 'POST': form = SignUpForm(request.POST) if form.is_valid(): form.signup(form, request) username = form.cleaned_data.get('email') … -
AWS broken pipe error when uploading files bigger than 1 MG
I am a django newbie, and I inherited a django back-end with little documentation. I am making a request to said server, which is hosted on AWS. To store the files in the request we use S3. I have found nothing on the django code that limits the size of the file uploads, and I suspect it may be AWS closing the connection because of file size. This is the code I use, and below the error I get whenever the total size of the files is over 1 MG: import requests json_dict = {'key_1':'value_1','video':video,'image':,image} requests.post('https://api.test.whatever.io/v1/register', json=dict_reg) video is a video file ('.mov','.avi','.mp4',etc) with base64 encoding, and image is an image file ('.jpg','.png') with base64 encoding. And this is the trace I get, ONLY when the total size is over 1 MG: /usr/local/lib/python2.7/dist- packages/requests/packages/urllib3/util/ssl_.py:132: InsecurePlatfo rmWarning: A true SSLContext object is not available. This prevents urllib3 from configuring SSL appropriately and may cause certain SSL connections to fail. You can upgrade to a newer version of Python to solve this. For more information, see https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings InsecurePlatformWarningTraceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/local/lib/python2.7/dist-packages/requests/api.py", line 110, in post return request('post', url, data=data, json=json, **kwargs) File "/usr/local/lib/python2.7/dist-packages/requests/api.py", … -
Why the javascript fetch API changes the request from POST to OPTIONS?
I just want to post the data to the API whenever the User clicks on the link or opens a link. Below is the JSON format of the data i'm trying to post, { "username": "somename", "email": "someone@gmail.com", "mobile": "xxxxxxxxxx", "url": "https://www.atatus.com/blog/fetch-api/" } The manifest.json file is below, { "manifest_version": 2, "name": "UserData save to Chrome", "description": "Save the data to the API", "version": "1.0", "browser_action": { "default_icon": "icon.png", "default_popup": "login.html", "defult_title": "UserData save to Chrome" }, "background": { "scripts": ["url.js", "popup.js"] }, "permissions": [ "activeTab", "storage", "history" ] } Below is the HTML file that's used to pop up the form, <form class="form-horizontal" role="form" action="" method="post" enctype="multipart/form-data"> <input class="form-control" autofocus="autofocus" placeholder="Username" id="id_username" type="text" name="username" required/><br> <input class="form-control" autofocus="autofocus" placeholder="Email Address" id="id_email" type="email" name="email" required/><br> <input class="form-control" autofocus="autofocus" placeholder="Mobile" id="id_mobile" type="text" name="mobile" required/><br> <button id="save" type="submit" class="btn btn-success">SAVE</button> </form> <script src="popup.js"></script> The popup.js is the javascript file which i'm using to store the data locally to the chrome storage, function saveChanges() { var user = document.getElementById("id_username").value; var email_id = document.getElementById("id_email").value; var mobile_no = document.getElementById("id_mobile").value; chrome.storage.local.set({ 'username': user, 'email': email_id, 'mobile': mobile_no }, function() { alert("Data Saved Successfully " + user + " - " + email_id + " - " … -
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.