Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
AWS Elastic Beanstalk Django configuration file exception
I'm trying to deploy a sample Django (Python 3.6) application to AWS Elastic Beanstalk via the eb CLI tool. I followed this tutorial and all is going good until I get to the YAML Django configuration file. I'm using Sublime 3 for editing, at first I thought it had some problem with the encoding and/or tabs but then I tried with vim, copy-pasting the exact code from the tutorial and got the same error every time. My project structure is / /project /project/wsgi.py ... $ cat .ebextensions/django.config option_settings: aws:elasticbeanstalk:container:python: WSGIPath: project/wsgi.py When I run eb deploy I get the next error: ERROR: InvalidParameterValueError - The configuration file .ebextensions/django.config in application version 2.0.0 contains invalid YAML or JSON. YAML exception: Invalid Yaml: while scanning for the next token found character '\t' that cannot start any token in "<reader>", line 2, column 1: aws:elasticbeanstalk:container: ... ^ , JSON exception: Invalid JSON: Unexpected character (o) at position 0.. Update the configuration file. -
Cleaning up code to show/hide Django objects in template with JavaScript
I have a Django template that lists blog categories and tags in a sidebar and want to limit the results to only show 5 categories and tags by default. I also want to add functionality that toggles (shows/hides) the full list of categories and tags when the user clicks a link at the bottom of the category/tag lists on the sidebar. So far, the code is working. It only shows 5 categories/tags by default and when you hit 'more', it expands to the full list. Then clicking 'hide' will then revert back to hiding the extra elements and only show 5. It also changes the show/hide text to reflect that. However, there is a lot of repeated code and I want to clean it up so I'm only using 1 function and event listener for this. Javascript // Expand sidebar categories and tags let categoryLinks = document.querySelectorAll('.sidebar-categories .sidebar-item-link'); let tagLinks = document.querySelectorAll('.sidebar-tags .sidebar-item-link'); let sidebarMore = document.querySelectorAll('.sidebar-more'); let catMore = sidebarMore[0]; let tagMore = sidebarMore[1]; function truncateCatLinks(links) { for (let i = 0; i < links.length; i++) { if (i > 4) { if (links[i].style.display === 'none') { links[i].style.display = 'block'; catMore.textContent = 'Less...'; } else { links[i].style.display = 'none'; … -
Django's REST framework custom exception handling simply doesn't work
July 2019 - Using latest Django/DRF: in myproj/my_api_app/public_views.py I have: def custom_exception_handler(exc, context): # Call REST framework's default exception handler first, # to get the standard error response. response = exception_handler(exc, context) # Now add the HTTP status code to the response. if response is not None: response.data['status_code'] = response.status_code return response in myproj/myproj/settings.py I have: (Yes, two times myproj/myproj) REST_FRAMEWORK = { # Use Django's standard `django.contrib.auth` permissions, # or allow read-only access for unauthenticated users. 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly' ], 'DEFAULT_THROTTLE_CLASSES': ( 'rest_framework.throttling.ScopedRateThrottle', ), 'DEFAULT_THROTTLE_RATES': { 'public_get': '30/minute', 'user_get': '60/minute' }, 'EXCEPTION_HANDLER': 'myproj.my_api_app.public_views.custom_exception_handler' } I try to hit a non-existing endpoint on purpose and I am still getting the default 404 message (DEBUG=False in settings). I have tried every permutation of the "Path" for the EXCEPTION_HANDLER. Nothing works. The EXCEPTION_HANDLER is ignored. What am I doing wrong? -
Using APIs within Django and how to display the data
I am trying to test how to display API information within a view on my Django project. I know you may have to add some installed APIs into the settings INSTALLED APPS block. This api is a simple geo one. I am new to Django and new to using APIs within it. I have managed to get my app the way I need it using Youtube videos. But now I am on my own. I have many different view classes to display differents of my app. The view below is the view Id like to place the data on. is this how I would potentially do it? Then call { country } within the HTHL to display it? class PostDetailView(DetailView): model = Post template_name = 'clients/post_detail.html' def api_test(request): # This is where the APIs are going to go. response = requests.get( 'http://api.ipstack.com/134.201.250.155?access_key=c30ffa84341bb5b9cb4b3794357d0dfa') geodata = response.json() return render(request, 'clients/post_detail.html', { 'ip': geodata['ip'], 'country': geodata['country_name'] }) I am currently getting no errors within my app, but the country element isnt displaying. -
Django model wont migrate using a OneToOne field
When I try to run migrate my new models using python manage.py migrate, I get this error: AssertionError: OneToOneField(<class 'migratefire.models.Server_DefaultChannel'>) is invalid. First parameter to ForeignKey must be either a model, a model name, or the string 'self' This is how my models.py structure looks (I made sure to declare the inherited models first): class Server_DefaultChannel(): channel_id = models.BigIntegerField(default=0) name = models.CharField(default='undefined', max_length=32) channel_type = models.IntegerField(default='-1') class Server_Inviter(models.Model): avatar = models.CharField(default='undefined', max_length=64) discriminator = models.IntegerField(default=0) inviter_id = models.BigIntegerField(default=0) username = models.CharField(default='undefined', max_length=32) class Server_Guild(models.Model): features = ArrayField(models.CharField(default = 'undefined', max_length = 64)) icon = models.CharField(default = 'undefined', max_length = 64) guild_id = models.BigIntegerField(default=0) name = models.CharField(default = 'undefined', max_length = 128) splash = models.CharField(default = 'undefined', max_length = 64) description = models.CharField(default = 'undefined', max_length = 256) vanity_url = models.CharField(default = 'undefined', max_length = 128) class Discord_Server(models.Model): approximate_member_count = models.IntegerField(default=-1) approximate_presence_count = models.IntegerField(default=-1) server_defaultchannel = models.OneToOneField(Server_DefaultChannel, on_delete=models.PROTECT, null=True) code = models.CharField(max_length=32) server_guild = models.OneToOneField('migratefire.Server_Guild', on_delete=models.PROTECT, null=True) server_inviter = models.OneToOneField('migratefire.Server_Inviter', on_delete=models.PROTECT, null=True) server_tags = ArrayField(models.CharField(default='none', max_length=16)) last_checked = models.DateTimeField(default=0)` I've tried putting the app name in the meta field for each class, I've tried using strings instead and got this error: ERRORS: migratefire.Discord_Server.server_defaultchannel: (fields.E300) Field defines a relation with model 'migratefire.Server_DefaultChannel', … -
DurationField or Timedelta
im having a problem trying to set a duration in my to-do tasks. i've tried with DurationField and some people told me to try the timedelta in your forms.py but im not quite shure how to pass the difference like (6days) from my two model DateField (start and end). Models.py from django.db import models from datetime import datetime, timedelta class To_do (models.Model): task = models.CharField(max_length=150) topic = models.CharField(max_length=150) how = models.TextField(max_length=600) start = models.DateField(default=datetime.today) end = models.DateField(blank=False) duration = models.DurationField(default=timedelta) i'd like to display the difference for the user and after set an alarm for less than 3 days etc. Thanks for your attention. -
Django-allauth - adding additional fields using AbstractUser
I am trying to add additional fields ('test') using AbstractUser. I creates a simple user model. class CustomUser(AbstractUser): test = models.CharField(max_length=100) def __str__(self): return self.email Next i create form: class SimpleSignupForm(SignupForm): first_name = forms.CharField(max_length=30, label='First Name') last_name = forms.CharField(max_length=30, label='Last Name') test = forms.CharField(max_length=100, label='test') def signup(self, request, user): user.first_name = self.cleaned_data['first_name'] user.last_name = self.cleaned_data['last_name'] user.test = self.cleaned_data['test'] user.save() return user Everything is saved outside of my test field. How to save the easiest data from the test field from my forms in my model CustomUser. Why it does not work in my example. Any help will be appreciated. -
How to change django field label text for reset password?
For the reset password, I was wondering if there is any way to customize the field's label tags. Thanks in advance. {% csrf_token %} {% for field in form %} <div class="form-group"> {{ field.label_tag }} <br> {{ field }} </div> {% endfor %} </form>``` -
How to read dicctionaries in Django Templates
I'm working with STRIPE Gateway Payment on Django and I'm facing problems for access to dicctionary on Templates I already do on pure python and work fine. This is my view @login_required def invoice_details(request): customer = stripe.Customer.list(email=request.user) return render(request, 'payment.html', customer) and in template this is my code: <h2>{% trans "User details" %}</h2> {% for actual_customer in customer.data %} ID: {{ actual_customer.id }} {% endfor %} The above code isn't working, any help is appreciated -
Model turns into tuple in django's view. Whata hell?
I am trying to save a string (session hash) into django's model, but something is going wrong.. When I try to update the string, the model turns into a tuple causing AttributeError. At the beginning everything was in a one 'post' function in view and yet not working. I tried to devide that stuff into functions, but it still does not help. Before the assignment type(session) says that 'session' is a model, not tuple. View function code: def post(self, request, *args, **kwargs): data = json.loads(request.body.decode('utf-8')) form = self.form_class(data) if form.is_valid(): phone = form.cleaned_data.get('phone') code = form.cleaned_data.get('code') password = form.cleaned_data.get('password') session = Session.objects.get_or_create(phone=phone, user=request.user.telegramuser) if code and password: return utils.sign_in(session, phone, code, password) elif code: return utils.sign_in(session, phone, code) elif phone: return utils.send_code_request(session, phone) return JsonResponse({'state': 'none'}) utils.send_code_request and sign_in have the same structure def send_code_request(session, phone): result = asyncio.run(_send_code_request(phone)) # result - { # 'state': 'ok', # 'session': 'Hfkdi...AaF24s' # } if result['state'] == 'ok': session.update_session(result.pop('session')) return JsonResponse(result) Manager class DefaultManager(models.Manager): def get_or_create(self, *args, **kwargs): try: return self.get(*args, **kwargs) except ObjectDoesNotExist: return self.create(*args, **kwargs) Error: Internal Server Error: /sessions/add/ Traceback (most recent call last): File "C:\Users\ipyth\Documents\projects\telegram-sendall\.env\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\ipyth\Documents\projects\telegram-sendall\.env\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response … -
Django models problem with foreign keys and relations
I want to make a model with products that will have a subcategory that will fall into its category. Here is an example: outerwear (category) -> t-shirt (subcategory) -> White t-shirt with a pattern (product) But I was faced with the problem that the name of the subcategory is not displayed in the product. My models.py class Global_category(models.Model): Name = models.CharField(max_length=20, verbose_name='Имя') slug = models.SlugField(max_length=20, verbose_name='Slug', unique=True) class Meta: ordering = ['Name'] verbose_name = 'Категория' verbose_name_plural = 'Категории' def __str__(self): return self.Name class SubCategory(models.Model): Name = models.CharField(max_length=20, verbose_name='Имя подкатегории') slug = models.SlugField(max_length=20, verbose_name='Slug', unique=True) Global_category = models.ForeignKey(Global_category, on_delete=models.CASCADE, verbose_name='Имя Категории') class Meta: ordering = ['Name'] verbose_name = 'Подкатегория' verbose_name_plural = 'Подкатегории' class Product(models.Model): Category = models.ForeignKey(SubCategory, on_delete=models.CASCADE, default=None) I will be glad to any help -
Change button wording depending on url
I am looking to change the wording of a button depending on a url path. I have tried to use some {% if blocks %} but unable to get it to work. I have tried to use a if block with a url == '' but nothing has worked. This is my url in my urls.py path('client/<int:pk>/update/', PostUpdateView.as_view(), name="post-update"), {% if url == 'http://localhost:8000/client/{client_ID}/update/' %} -
django iterate over a list that is an item of a queryset
I have a list that is generated by a method on one of my models. On the home page it works wonderfully, however when I go to a detail view of one project I can access all the parts of that project as they are direct fields of the Model, but I can't access the items in the list. Model: class Project(models.Model): date_published = models.DateTimeField(auto_now_add=True) user = models.ForeignKey(User, null=True, on_delete=models.SET_NULL) area = models.ForeignKey(Area, on_delete=models.PROTECT) title = models.CharField(max_length=128, unique=True) slug = models.SlugField(max_length=64) summary = models.CharField(max_length=256) others = models.CharField(max_length=128, blank=True) deadline = models.DateField(null=True, blank=True) priority = models.ForeignKey(Priority, on_delete=models.PROTECT) closed = models.DateTimeField(null=True, blank=True) def save(self, *args, **kwargs): if not self.id: self.slug = slugify(self.title) super(Project, self).save(*args, **kwargs) @property def updates(self): updates = [] sequence_id = 1 categories = set(self.update_set.all().values_list( 'category__id', flat=True)) for cat_id in categories: a = Update.objects.filter( project=self, category__id=cat_id).order_by('added').last() if cat_id == sequence_id: updates.append(a) else: for i in range(cat_id - sequence_id): updates.append('null') updates.append(a) sequence_id = cat_id sequence_id += 1 return updates The view is simple: class ProjectDetailView(DetailView): template_name = 'project_portal/project_detail.html' queryset = Project.objects.all() and here is the dynamic url that I am using: path('project/<int:pk>/', ProjectDetailView.as_view(), name='project_detail'), As for the template, I'm lost, here is one of the things I have tried: <!DOCTYPE html> … -
How to add a checkbox column in django_tables2
I am trying to add a checkbox column so that the users of the interface can select rows and move them. How do I add the checkbox column to a table? I have found the checkboxcolumn.py file in django, but I do not know how to properly implement it into my project. Here is my code for reference. tables.py import django_tables2 as tables from .models import Model60Mm, Model120Mm, Model122Mm class Table60mm(tables.Table): class Meta: model = Model60Mm template_name = 'django_tables2/bootstrap.html' class Table120mm(tables.Table): class Meta: model = Model120Mm template_name = 'django_tables2/bootstrap.html' class Table122mm(tables.Table): class Meta: model = Model122Mm template_name = 'django_tables2/bootstrap.html' class DateTable60mm(tables.Table): shot_time = tables.Column() class Meta: model = Model60Mm order_by = '-shot_name' template_name = 'django_tables2/bootstrap.html' views.py from django.shortcuts import render from django_tables2 import RequestConfig from django_tables2 import SingleTableView from .models import Model60Mm, Model120Mm, Model122Mm from .tables import Table60mm, Table120mm, Table122mm def home(request): return render(request, 'database/home.html') def sixty(request): table = Table60mm(Model60Mm.objects.all()) table.paginate(page=request.GET.get('page', 1), per_page=25) return render(request, 'database/sixty.html', {'table': table}) def onetwenty(request): table = Table120mm(Model120Mm.objects.all()) table.paginate(page=request.GET.get('page', 1), per_page=25) return render(request, 'database/onetwenty.html', {'table': table}) def onetwentytwo(request): table = Table122mm(Model122Mm.objects.all()) table.paginate(page=request.GET.get('page', 1), per_page=25) return render(request, 'database/onetwentytwo.html', {'table': table}) def sixtydate(request): table = Table60mm(Model60Mm.objects.all(), order_by='-shot_time') table.paginate(page=request.GET.get('page', 1), per_page=25) return render(request, 'database/sixtydate.html', {'table': table}) sixty.html template … -
Dynamically Add Form to Django Formset
I want to dynamically add a form to my Django formset. However, on button click nothing happens. I am using form models, but I am defining most elements within the template. I know this is not proper practice, but it was how I originally created my forms and I have not had time to migrate to complete form models. However, could this be causing my issues? I have never used formsets before so any tips would be greatly appreciated! I used Dave's solution here, but I am unsure as to why my implementation does not translate accordingly. template.html <div class="container"> <div id="form_set"> <form action="{% url 'presales' %}" class="presales_formset" data-total-url="{% url 'presales_total' %}" id="presalesForm" method="post" name="presalesForm"> <div class="field"> <label class="label is-large">High Level Task List</label> </div> {% csrf_token %} {{ presales_formset.management_form }} {% for presales_form in presales_formset %} <div class="section"> <div class="field"> <label class="label">Opportunity</label> <div class="select"> <select id="select_opportunity" name="select_opportunity"> <option value="">Opportunity</option> {% for opportunity in my_opportunities %} <option id="selected_opportunity" name="selected_opportunity" value="{{ opportunity.name }}">{{ opportunity.name }} </option> {% endfor %} </select> </div> </div> <label class="label">Task Description:</label> <div class="field"> <div class="control"> <input class="input" id="task_description" name="task_description" placeholder="Task Description"> </div> </div> <label class="label">Hours</label> <div class="field"> <div class="control"> <input class="input" id="hours" name="hours" placeholder="Hours"> </div> </div> <label class="label">Engineer … -
How to save manytomany relationship in Django
Actually am trying to make an social media website in which i have an section of groups in this logged in user can create a group and other user can join it so here is my group model class Groups(models.Model): name = models.CharField(max_length = 255) slug = models.SlugField(blank=True) description = models.TextField() user = models.ManyToManyField(User, related_name='membership') created_at = models.DateTimeField(auto_now=True) def unique_slug(self): slug = slugify(self.name) return slug Here is my views.py def add_group(request): groups = Groups.objects.all() form = forms.add_group() if request.method == 'POST': form = forms.add_group(request.POST) if form.is_valid(): group = Groups() group.name = form.cleaned_data.get('name') group.description = form.cleaned_data.get('desc') groups.user = request.user.id group.slug = group.unique_slug() group.save() # finally save it. return redirect('groups') return render(request,'add_group.html',{'form':form,'groups':groups}) and here is my many to many relation table So How can i save the relationship?? -
The QuerySet value for an exact lookup must be limited to one result using slicing error in django views
please help me out, i would be appreciated!, can anyone explain what my error is? thank you :) ........................................................................................................................................................................................................ def post_detail(request, slug=None): instance = get_object_or_404(Post, slug=slug) if instance.publish > timezone.now().date() or instance.draft: if not request.user.is_staff or not request.user.is_superuser: raise Http404 share_string = quote_plus(instance.content) initial_data = { "content_type": instance.get_content_type, "object_id": instance.id } form = CommentForm(request.POST or None, initial=initial_data) if form.is_valid() and request.user.is_authenticated: c_type = form.cleaned_data.get("content_type") content_type = ContentType.objects.filter(model=c_type) obj_id = form.cleaned_data.get('object_id') content_data = form.cleaned_data.get("content") parent_obj = None try: parent_id = int(request.POST.get("parent_id")) except: parent_id = None if parent_id: parent_qs = Comment.objects.filter(id=parent_id) if parent_qs.exists() and parent_qs.count() == 1: parent_obj = parent_qs.first() new_comment, created = Comment.objects.get_or_create( user = request.user, content_type= content_type, object_id = obj_id, content = content_data, parent = parent_obj, ) return HttpResponseRedirect(new_comment.content_object.get_absolute_url()) comments = instance.comments context = { "title": instance.title, "instance": instance, "share_string": share_string, "comments": comments, "comment_form":form, } return render(request, "post_detail.html", context) -
User is not JSON serializable ee
I have this error raise TypeError(f'Object of type {o.class.name} ' TypeError: Object of type User is not JSON serializable, please help me def get_followers(self, obj): return obj.profile.followers.all() /////serializers.py//////// from django.contrib.auth import get_user_model User = get_user_model() class ProfileRetrieveSerializer(serializers.ModelSerializer): """ Serializer that represents a profile. """ queryset=User.objects.all() followers = serializers.SerializerMethodField() class Meta: model = User fields = [ 'followers', ] def get_followers(self, obj): return obj.profile.followers.all() /////////////models.py///////////////// from django.contrib.auth.models import User from django.db import models class Profile(models.Model): """ Model that represents a profile. """ user = models.OneToOneField(settings.AUTH_USER_MODEL, related_name='profile', on_delete=models.CASCADE) followers = models.ManyToManyField( User, related_name='following', blank=True ) class Meta: ordering = ('-member_since', ) I get this error raise TypeError(f'Object of type {o.class.name} ' TypeError: Object of type User is not JSON serializable [23/Jul/2019 19:16:13] "GET /api/users/profile/ttt/ HTTP/1.1" 500 102886 -
Bad value in primary key field
I am trying to make migrations but this error appear i tried to delete data base file and make migrations but still get this error (https://i.stack.imgur.com/NPnae.jpg) -
Read csv file in django view
I am new to django, I am working of datascience project that need to develop a user interface that interact with user using Django, how I can read csv file in django view in order to some anlysis and send them to template ? -
How to get all users with individual related objects in django?
I want to output all users with their related scores user = User.objects.all() scores = user.myuser.all() Where 'myuser' is a related name of the scores model, I tried the above code but I was getting myuser is not an attribute of the objects error. -
Whats the alternative to base64 encoded images
I am currently serving base64 encoded images via my Django REST API. The URL is something like www.mywebsite.de/api/images/<id> and my Django API is responding with an HTTPResponse. I am doing this because the Images are sensible and the Clients need to authenticate therefore (sending a Token) to get the images. Unfortunately I read that base64 encoded images have a lot of downsides, some are listed here: https://medium.com/snapp-mobile/dont-use-base64-encoded-images-on-mobile-13ddeac89d7c So I am asking myself now, as a beginner: What are the alternatives? How can I serve sensitive Images without Base64 encoding? I would be thankful for any hint into the right direction. Thank you in advance :) -
How do I get a datetime object with offset from a Django ModelForm
I need to capture a date string with users UTC offset. Django returns the error 'Enter a valid date/time' every time. The browser is sending a string like this '2019-07-24 12:45:00 -05:00' I am using bootstrap_datepicker_plus, (https://pypi.org/project/django-bootstrap-datepicker-plus/) to render a DateTimePickerInput field in my Django(2.1) ModelForm. I am trying to get a DateTime value that includes a UTF offset. I can see the date coming through in my is_invalid() method of my view when I print form.data['release_date']. It comes through like this '2019-07-24 12:45:00 -05:00'. Why doesn't' Django like this date format? ModelForm class Meta: model = Post today = datetime.datetime.today() tomorrow =pytz.utc.localize(today + datetime.timedelta(1)) twoWeeks = today + datetime.timedelta(14) dateFmt = '%Y-%m-%d %H:%M:%S %z' datejsFmt = 'YYYY-MM-DD HH:mm:ss Z' fields = ['title', 'body', 'release_date'] widgets = { 'release_at': DateTimePickerInput( format = dateFmt, options={ "format": datejsFmt, 'minDate': datetime.datetime.strftime(tomorrow, dateFmt), 'maxDate': datetime.datetime.strftime(twoWeeks, dateFmt), }) } Settings.py TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True DATETIME_INPUT_FORMATS += ('%Y-%m-/%Y %H:%M:%S %z',) CreateView def form_invalid(self, form): print(form.data['release_at']) print(parse_datetime(form.data['release_at'])) output from CreateView 2019-07-24 12:30:00 -05:00 None -
How to filter a list of displayed elements in django with a dropdown value
Right now I have a list of forms being displayed by Django: {% for form in forms %} <form method="post" class="{{ form.css_class }}"novalidate> {% csrf_token %} {% include 'bs4_form.html' with form=form %} <input type="hidden" name="selected_form" value="{{ forloop.counter0 }}"> <button type="submit" class="btn btn-primary">Submit</button> </form> {% endfor %} I also have a dropdown being rendered above the forms: <label>Choose a component to modify: <select class="rule-component" name="component"> <option value="">Select One …</option> <option value="0">Option 0</option> <option value="1">Option 1</option> <option value="2">Option 2</option> <option value="3">Option 3</option> <option value="4">Option 4</option> </select> </label> My question is, how would I go about displaying no form when the page is entered, and a single form that corresponds with the dropdown value when that is selected? I've attempted something with JavaScript, but I'm not very familiar with it and I'm not sure how to get this to interact with the django templating language. The code below allows me to log the form element I want to display by linking it with the forloop.counter: <script type="text/javascript"> const formElement = document.querySelector(".rule-component") formElement.addEventListener('change', (event) => { const selectElement = document.querySelector("form input[value='" + formElement.value + "']").parentNode; console.log(selectElement) const result = document.querySelector('.result'); result.textContent = `You like ${selectElement.className}`; }); </script>``` -
How do I implement toast messages in Django?
I am trying to implement toastmessage in my django project. I followed this link https://pypi.org/project/django-toast-messages/ and made all the files and did everything mentioned but I cannot get a toastmessage no matter what. Please Help.