Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Using pycharm to debug django application with python3 as docker container within a vagrant instance
I set up an ubuntu vagrant instance as virtual machine and installed docker in it. I also have python as docker container within vagrant instance. Is there anyway to debug django application using pycharm directively with python in this case? Thanks! -
NoReverseMatch Django: can't find pattern
I'm building my first application (guess app) with Django, I've been doing well so far. But I've encountered an error when trying to redirect to a Detail View when a user submits a file through a submit function (similar to a 'post blog' scenario). I've looked up several posts with the same problem and I can not figure out why my code is not working. views.py @login_required def submit(request): if request.method == 'POST': submited_form = SubmitFileForm(request.POST, request.FILES) if submited_form.is_valid(): ... form.save() return HttpResponseRedirect(reverse('result-detail'), kwargs={'pk': form.pk}) else: submited_form = SubmitFileForm() return render(request, 'guess/submit.html', context) class ResultDetailView(LoginRequiredMixin, DetailView): model = Result template_name = 'guess/result_detail.html' context_object_name = 'result' I know I'm mixing class based views with function based views, but for some reason I can not get my submit function to work when I try to implement it as a class based view. Anyway, I think that shouldn't be a problem urls.py url_patterns = [ ... path('result/<int:pk>', guess_views.ResultDetailView.as_view(), name='result-detail'), ... ] result_detail.html {% extends "guess/base.html" %} {% block content %} <article class="media content-section"> <div class="media-body"> <div class="article-metadata"> <a class="mr-2" href="#">{{ result.author }}</a> <small class="text-muted">{{ result.date_posted }}</small> </div> <h2 class="article-title">{{ result.title }}</h2> <p class="article-content">{{ result.statistic }}</p> </div> </article> {% endblock content %} I'd expect … -
eb create: ERROR: PermissionError - [Errno 13] Permission denied: './catroot2\\edb.log'
Hi I'm new to this server set up, let me get to the point, I had this django project I want to deploy on AWS and i follow the document in link: https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create-deploy-python-django.html but when I reach the part on (To create an environment and deploy your Django application) point 3. Create an environment and deploy you application to it with eb create: I had this problems: (FATWebsite) C:\WINDOWS\system32>eb create django-env Creating application version archive "app-190212_105329". ERROR: PermissionError - [Errno 13] Permission denied: './catroot2\\edb.log' form google https://stackoverflow.com/a/31279057/10865416 it seems to me that './catroot2\\edb.log' It is a special file which cannot be written or manipulated. But I do not know of any answer to resolve this issue and I can't submit ticket to AWS for help (because that plan service) Appreciated it if you could help -
access object from angular django endpoint
I have a list of dogs on a django backend that I want to display on an Angular 7 frontend. I am getting objects back from the {{currentDogs}} variable in the browser, but I cannot seem to access the individual dogs.. When i render this the browser displays: browser output This will be the home page dog-list works! [object Object] List of all Dogs api.service export class ApiService { apiURL: string = 'http://127.0.0.1:8000' constructor(private httpClient: HttpClient) { } public getDogs(){ return this.httpClient.get<Dog[]>(`${this.apiURL}/dogs`); } } my dog-list.component export class DogListComponent implements OnInit { currentDogs: Observable<Dog[]>; constructor(private service : ApiService) { } ngOnInit() { this.currentDogs = this.service.getDogs() } } dog-list.html <p> dog-list works! {{currentDogs}} <li *ngFor="let dog of currentDogs"> {{dog.name}} </p> -
When I jumped from the list page to the details page, the url jumped, but the page did not display, and the prompt 'ZiXun' object is not iterable
I tried adding Read More to the html. After clicking Read More, the page shows that the path has jumped. Turned around, but the page does not display information I hope that after clicking Read More, I can jump to the news.html page and display the contents. I hope someone can help me. def news(request,zx_id): try: zixun=ZiXun.objects.get(id=zx_id) print('1------------------>') print(zixun) print(zx_id) except ZiXun.DoesNotExist: raise Http404 return render(request,'news.html',locals()) -
How do I output a DateTime field as milliseconds in my view?
I'm using Python 3.7 and Django. I have this field in my model ... class Article(models.Model): ... created_on = models.DateTimeField(default=datetime.now) Then in my view, I'm trying to output this field in a data attribute as milliseconds, so I tried data-created-on="{{ article.created_on.timestamp() * 1000 }}" However, this is resulting in the error when my view is rendered ... Could not parse the remainder: '() * 1000' from 'article.created_on.timestamp() * 1000' What's the proper way to output my DateTime field as a time in milliseconds? -
Session with Django
In a Home page, i have a form login. in the view.index of the app "Home", after authenticate, i create the ssesion. And after, i call the app "Places" if the authenticate is okey, request.session['user'] = username request.session.set_expiry(900) return HttpResponseRedirect('/places/') in the settings of the project i configure the SESSION_SAVE_EVERY_REQUEST = True. How can i send the session to all others pages of the project, and log out the user when the session is expired ? -
I can not display images with waigtail
I'm trying to use insert images with wagtail cms but accuse the following error: 'QuerySet' object has no attribute 'get_rendition' I have read the documentation but there they use a for to display several images but I want to show only one models: class HomePage(Page): body = RichTextField(blank=True) content_panels = Page.content_panels + [ FieldPanel('body', classname="full"), InlinePanel('gallery_images', label="Gallery images"), ] class BlogPageGalleryImage(Orderable): page = ParentalKey(HomePage, on_delete=models.CASCADE, related_name='gallery_images') image = models.ForeignKey( 'wagtailimages.Image', on_delete=models.CASCADE, related_name='+' ) caption = models.CharField(blank=True, max_length=250) panels = [ ImageChooserPanel('image'), FieldPanel('caption'), ] base.html: {% load wagtailcore_tags wagtailimages_tags %} {% image page.gallery_images.all width-400 as my_image %} I wanted to insert only one image dynamically, it is possible? -
Django - list related instances of class
I have a Projects app with two classes in my models.py (Project, and Deadline). Each Project can have multiple deadlines and my end goal is to list out a Project's deadlines on my web page. class Project(models.model): proj_name = models.CharField(max_length= 100, verbose_name = 'Project Name') class Deadline(models.model): deadline_name = models.CharField(max_length= 100, verbose_name = 'Deadline Name') proj_name = models.ForeignKey(Project, on_delete=models.CASCADE) I'm calling the project's deadlines in my html by {{ deadline.proj_name }} but it returns nothing. I've read through the documentation and I think I should be doing this through querysets? Can anybody lead me in the right direction? I think I should be calling {{ projects.deadlines }} but I don't know how to structure this to make it happen (sorry still learning) -
django-storages + private S3 bucket - How can I make a username the folder name?
I'm using django-storages and a private S3 bucket to store user uploads. I would like the following folder structure: /uploads/someuser321/20190112-123456/ I obviously know how to do the timestamp (2019-01-12 at 12:34:56), but how do I get the user's username into the path? My model currently looks like this: user_file = models.FileField( upload_to="uploads", storage=PrivateMediaStorage(), null=True, blank=True) I can just add an f-string for the datetime/timestamp. I understand that and I know how to do it. But how can I add the user's username as a folder as well? I would need to somehow access this from the view, so that I know who the request.user is, but how would I even do that? Thanks for any help in advance!! -
How To Narrow Down Django DetailView Export To CSV File
I am trying to figure out how to do a simple export of data to a CSV file. I found an example that works.... def export_data(request): response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="users.csv"' writer = csv.writer(response) writer.writerow(['username', 'First name', 'Last name', 'Email address']) users = User.objects.all().values_list('name','userid') for user in users: writer.writerow(user) return response The code above works as you would expect, exporting all of the users from User.objects.all() to the spreadsheet. However, I am trying to do this from a DetailView and only get the data for the user that is being viewed, not the entire model, with the .all(). From what I gather, in order to do this in a DetailView, I believe I need to do something like... class ExportDataDetailView(LoginRequiredMixin,DetailView): model = Author context_object_name = 'author_detail' ....And then perhaps I need to override get_queryset? It seems like overkill though because I'm already in the DetailView... Thanks for any pointers in the right direction in advance. -
Saving Django Form Data to a User field
I'm creating a website for general education uses and one of the features is a calendar section where i would like the user to be able to store their events but then when they login they can view the events they created. I cant seem to get this calendar to link to a user field. I would like each record in the calendar table to have a user_id which will be the same as the current_user. I understand that you can user the django default user auth but i have not done that due to not knowing about it and by the time i realized it was too late as i need to hand this piece of code in ASAP ! So all I really need to do is when the form is valid, i need to assign the value of the current_user id as the value for student in the calendar table. But for some reason i keep getting problems and the form isn't detected as being valid or the program just doesn't assign the value. My Main objective is to have each user view their own calendar. I don't mind changing the current student field to a foreign … -
Running celerybeat causes django to throw ImportError. No module named 'app_name_here'; 'app_name_here' is not a package
Celery works fine with my code and django itself doesn't throw any error. But running celery beat causes ImportError. This is a legacy project and they didn't use virtualenv. I've to install celery and celerybeat to the server for this django site. However running celerybeat with celery -A proj beat causes django to throw ImportError: No module named 'parser.models'; 'parser' is not a package (parser is my app created via manage.py startapp) Running celery -A proj, celery -A proj beat causes this error to be thrown. But if I run python3 -m celery -A proj it works fine. Expected result is to make celery work the way described in its official docs. -
Server Side Encryption with s3Boto - Server Side Encryption with KMS managed key requires HTTP header x-amz-server-side-encryption : aws:kms
I am trying to setup server side encryption on my django app for file uploads. I am using s3Boto3Storage. I can't find clear documentation on how to implement server side encryption, and when trying to upload my file, I get the following error: An error occurred (InvalidArgument) when calling the PutObject operation: Server Side Encryption with KMS managed key requires HTTP header x-amz-server-side-encryption : aws:kms Here is what my settings look like: AWS_ACCESS_KEY_ID = 'XXXX' AWS_SECRET_ACCESS_KEY = 'XXXX' AWS_STORAGE_BUCKET_NAME = 'tickets' AWS_S3_ENDPOINT_URL = 'https://sfo2.digitaloceanspaces.com' AWS_S3_FILE_OVERWRITE = False AWS_S3_OBJECT_PARAMETERS = { 'CacheControl': 'max-age=86400', } AWS_LOCATION = '' AWS_DEFAULT_ACL = None AWS_S3_ENCRYPTION = True STATIC_URL = 'https://%s/%s/' % (AWS_S3_ENDPOINT_URL, AWS_LOCATION) STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' -
Angular 7 formData + file + nested object
I have a django Backend and Angular 7 frontend, everything works fine when sending formData with my params and the file, but when I'm trying to send a nested json it's empty. The nested json is for the nested serializer in my object. example with postman Angular POST let input = new FormData(); var empty = { name: "name" } input.append('username', user.value.username); input.append('password', user.value.password); if(profile_photo){ input.append('profile_photo', profile_photo, profile_photo.name); } input.append('first_name', user.value.first_name); input.append('last_name', user.value.last_name); input.append('email', user.value.email); input.append('role', user.value.role); input.append('active', user.value.active); input.append('address', user.value.address); input.append('job', user.value.job); input.append('phone', user.value.phone); input.append('phone_type', user.value.phone_type); input.append('superadmin_profile', new Blob([JSON.stringify(empty)], {type : 'application/json'})); input.append('general_profile', new Blob([JSON.stringify(empty)], {type : 'application/json'})); input.append('security_profile', new Blob([JSON.stringify(empty)], {type : 'application/json'})); if(user.value.properties){ input.append('properties', user.value.properties); } if(user.value.residentials){ input.append('residentials', user.value.residentials); } const httpOptions = { headers: new HttpHeaders({ 'Authorization': 'token ' + localStorage.getItem('userToken') }) }; return this.http.post(this.Endpoints.getUsers, input, httpOptions); I put required=False so it doesn´t give the "This field is required." but it is still being empty, I also printed the request.data in the django view and the nested json variables are there but are not getting in the serializer. Django Serializer class UserSerializer(serializers.ModelSerializer): superadmin_profile = SuperadminProfileSerializer(required=False) general_profile = GeneralProfileSerializer(required=False) security_profile = SecurityProfileSerializer(required=False) residentials_photo = serializers.SerializerMethodField() password = serializers.CharField(write_only=True) """ Serializer for Department model. """ class Meta: model … -
Many django projects on same localhost & session management
As I am running four Django projects as subdomains of the same apache2 localhost, user sessions get confused and keep signing out. I am using the standard Django authentication system. Is there a solution for this problem? Thanks in advance for your help! -
Django: Required = False Not Working Properly
I have a Django server that I am working on for my company. For my web form, I want the user to be able to check a box, in which if selected, the user will have another document to sign. However, I do not want them to be required to check it. The checkbox that I wish to have checked (or not) is the "callforwarding" field. I have tried setting the acc field as callforwarding=models.BooleanField(default=False, null=True, blank=True) In my forms.py, the field is: callforwarding=forms.BooleanField(required=false, widget=forms.CheckboxInput(attrs={'class' : 'form-control-lg'})) However, if the checkbox isn't checked, the form cannot be submitted. I don't receive any sort of error, the form just won't submit. #forms.py class LOAForm(forms.Form): propertyname = forms.CharField(max_length = 40, widget=forms.TextInput(attrs={'class' : 'form-control', 'placeholder' : 'Name Of Property'})) signdate = forms.DateField(widget=forms.DateInput(attrs={'class' : 'form-control', 'placeholder' : 'yyyy-mm-dd'})) billingaddress = forms.CharField(max_length=20, widget=forms.TextInput(attrs={'class' : 'form-control', 'placeholder' : 'Billing Street Address'})) billingcity = forms.CharField(max_length=15, widget=forms.TextInput(attrs={'class' : 'form-control', 'placeholder' : 'Billing Address City'})) billingzipcode = forms.CharField(widget=forms.TextInput(attrs={'class' : 'form-control', 'placeholder' : 'Billing Address Zip Code'})) billingemail = forms.CharField(widget=forms.EmailInput(attrs={'class' : 'form-control', 'placeholder' : 'Email Address for Billing'})) streetaddress = forms.CharField(max_length=20, widget=forms.TextInput(attrs={'class' : 'form-control', 'placeholder' : 'Property Street Address'})) streetcity = forms.CharField(max_length=15, widget=forms.TextInput(attrs={'class' : 'form-control', 'placeholder' : ' Property City'})) … -
'GenericRelatedObjectManager' is not JSON serializable
I've gone through a bunch of topics with the same problem and I haven't found the solution for me. I have 2 models, these are 2 different types of questions: class Question(models.Model): description = models.CharField(max_length=400) answers_list = GenericRelation(Answer) class SuperQuestion(models.Model): top_description = models.CharField(max_length=200) mid_description = models.CharField(max_length=200) meta_description = models.CharField(max_length=1000) answers_list = GenericRelation(Answer) and I have an Answer model, that can contain answers for both questions and superquestions: class Answer(models.Model): limit = models.Q(app_label='core', model='question') |\ models.Q(app_label='core', model='superquestion') content_type = models.ForeignKey( ContentType, limit_choices_to=limit, on_delete=models.CASCADE ) object_id = models.PositiveIntegerField() question = GenericForeignKey('content_type', 'object_id') answer = models.CharField(max_length=500) additional = models.CharField( max_length=2000, blank=True, null=True, default=None ) My serializers: class AnswerSerializer(serializers.ModelSerializer): class Meta: model = Answer fields = [ 'id', 'question', 'answer', 'created_at' ] class QuestionSerializer(serializers.ModelSerializer): class Meta: model = Question fields = [ 'id', 'description', 'answers_list' ] depth = 1 class SuperQuestionSerializer(serializers.ModelSerializer): class Meta: model = SuperQuestion fields = [ 'id', 'top_description', 'mid_description', 'meta_description', 'answers_list', ] depth = 1 What I'm trying to do in my views is to fetch all questions and every question has to contain all answers to that question. It looks like this: questions = QuestionSerializer( QuestionSession.objects.get( pk=session_id).questions.all(), many=True ) But it all gives me: TypeError: Object of type 'GenericRelatedObjectManager' is … -
Where does my "urls.py" file go in my Django project?
I'm using Django and Python 3.7. I used PyCharm to create a project and it created the following directory structure (some of the custom additions are my own): mainpage __init__.py __pycache__ admin.py apps.py fixtures management migrations models.py services.py templates mainpage trending.html tests.py urls.py views.py mainpage_project __init__.py __pycache__ settings wsgi.py manage.py templates venv The file "urls.py" looks like the below from django.contrib import admin from django.urls import path from . import views urlpatterns = [ path('trending', trending, name='trending'), ] I'm confused about where "urls.py" should go and what it should contain. When I start up my server, it gives me the following error ("ModuleNotFoundError: No module named 'mainpage_project.urls'") ... (venv) localhost:mainpage_project davea$ python manage.py runserver Performing system checks... Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x103096950> Traceback (most recent call last): File "/Users/davea/Documents/workspace/mainpage_project/venv/lib/python3.7/site-packages/django/utils/autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "/Users/davea/Documents/workspace/mainpage_project/venv/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 117, in inner_run self.check(display_num_errors=True) File "/Users/davea/Documents/workspace/mainpage_project/venv/lib/python3.7/site-packages/django/core/management/base.py", line 379, in check include_deployment_checks=include_deployment_checks, File "/Users/davea/Documents/workspace/mainpage_project/venv/lib/python3.7/site-packages/django/core/management/base.py", line 366, in _run_checks return checks.run_checks(**kwargs) File "/Users/davea/Documents/workspace/mainpage_project/venv/lib/python3.7/site-packages/django/core/checks/registry.py", line 71, in run_checks new_errors = check(app_configs=app_configs) File "/Users/davea/Documents/workspace/mainpage_project/venv/lib/python3.7/site-packages/django/core/checks/urls.py", line 40, in check_url_namespaces_unique all_namespaces = _load_all_namespaces(resolver) File "/Users/davea/Documents/workspace/mainpage_project/venv/lib/python3.7/site-packages/django/core/checks/urls.py", line 57, in _load_all_namespaces url_patterns = getattr(resolver, 'url_patterns', []) File "/Users/davea/Documents/workspace/mainpage_project/venv/lib/python3.7/site-packages/django/utils/functional.py", line 37, in __get__ res = instance.__dict__[self.name] … -
Load individual page - Permissions in Django REST framework
I have a site written in django with wagtail as cms similar to web shop. When I go to products you don't have to be logged in to view all products. But when you want to see individual you have to be logged in. I didn't write rest framework part of app. Now I want to turn that off so everyone can see individual product. I don't know what to change, but I know that is REST framework issue. In wagtail the page is public. my settings are: REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), 'DEFAULT_AUTHENTICATION_CLASSES': ( 'oauth2_provider.contrib.rest_framework.OAuth2Authentication', 'rest_framework.authentication.SessionAuthentication', 'rest_framework.authentication.TokenAuthentication', ), } and views.py class ProductViewSet(viewsets.ModelViewSet): authentication_classes = [OAuth2Authentication, authentication.SessionAuthentication, ] permission_classes = [IsAuthenticatedOrTokenHasScope, ] required_scopes = ['read', 'write', ] queryset = Product.objects.live().all() serializer_class = ProductSerializer I don't know what else is required but help will be appreciated. -
How to reuse get_search_results function in multiple classes
I have a custom get_search_results defined for my admin.ModelAdmin classes but they are all doing the same filtering. Is there a way to overwrite get_search_results for multiple admin.ModelAdmins? def get_search_results(self, request, queryset, search_term): queryset, use_distinct = super(MyAdmin, self).get_search_results(request, queryset, search_term) if not (request.GET.get('created_on__gte') or request.GET.get('created_on__lte')): past_date = datetime.date.today() - datetime.timedelta(days=90) queryset = queryset.filter(created_on__gt=past_date) return queryset, use_distinct -
Creating backend for dynamic SAML authentication based on user's configuration
I am currently adding Single Sign On support to an application through the SAML 2.0 protocol. To achieve this I found a useful module: https://github.com/fangli/django-saml2-auth. I set up authentication using Azure AD and it worked flawlessly. This was an excellent starting point, however the module asks that you specify the Metadata and mapping specifications under your settings.py file. My end goal is to have different clients use their own SAML Identity provider to authenticate against my application. Ex) Some clients might use Azure, others ADFS, others Okta. and so on.... I would like users to enter their email, then based on their domain name be redirected to their company's idp, where they would authenticate and be redirected back to my app's SAML endpoint. However, I need to load the correct metadata and mapping details when the SAML assertion is sent back to my endpoint. How can I keep the state of the correct configuration to use since the browser must redirect outside of my app to generate the SAML assertion? Then once its come back, it no longer has reference to the original customer's configuration. My current "solution" involves using mysql database to set the current configuration as active and … -
Why is the Calendar not displaying in the template?
Below is the models, utils and views for my calendaring App. It is quite unfortunate that the calendar is not displaying in the template. Please help me!! models.py I have my models defined as follows, I have my models defined as follows; class Availability(models.Model): title = models.CharField(max_length=200) description = models.TextField(max_length=30, blank=False) start_time = models.DateTimeField() end_time = models.DateTimeField() utils.py I have my utils defined as follows; class Calendar(HTMLCalendar): def __init__(self, year=None, month=None): self.year = year self.month = month super(Calendar, self).__init__() # formats a day as a td # filter events by day def formatday(self, day, events): events_per_day = events.filter(start_time__day=day) d = '' for event in events_per_day: d += f'<li> {event.title} </li>' if day != 0: return f"<td><span class='date'>{day}</span><ul> {d} </ul></td>" return '<td></td>' # formats a week as a tr def formatweek(self, theweek, events): week = '' for d, weekday in theweek: week += self.formatday(d, events) return f'<tr> {week} </tr>' # formats a month as a table # filter events by year and month def formatmonth(self, withyear=True): events = Availability.objects.filter(start_time__year=self.year, start_time__month=self.month) cal = f'<table border="0" cellpadding="0" cellspacing="0" class="calendar">\n' cal += f'{self.formatmonthname(self.year, self.month, withyear=withyear)}\n' cal += f'{self.formatweekheader()}\n' for week in self.monthdays2calendar(self.year, self.month): cal += f'{self.formatweek(week, events)}\n' return cal views.py I have my views … -
Django Queryset many to many
I have an issue with the output of a ManyToMany query in Django I have two classes: Investor and Fund. A Fund can have many Investors, and an Investor can be invested in multiple Funds, hence the Manytomany relationship The objective is to show in HTML (via a template) a list per investor of all the funds in which he/she is invested. Models.py: class Fund(models.Model): name = models.CharField(max_length=100) def __str__ (self): return self.name class Investor(models.Model): first_name = models.CharField(max_length = 100) investments = models.ManyToManyField(Fund) def __str__ (self): return self.first_name view.py: def investors_overview(request): investors = Investor.objects.all() return render(request, 'funds/investors.html', {'investors_overview' : investors }) template: {% for investor in investors_overview %} <p>{{investor.first_name}} </p> <p>{{investor.investments.all}} </p> I would like the have as output the exact names of the various funds the investor is invested in. However, the output in HTML is not "clean" and is as as follows: <QuerySet [<Fund: Fund1>, <Fund: Fund2>]> -
How to put an image with css dynamically with wagtail
I'm using the django cms wagtail, but it has an image that needs to be dynamically placed and needs to be css <header class="masthead" style="background-image: url({% static 'img/home-bg.jpg' %})">