Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django 3 | UpdateView Movie matching query does not exist, when using 2 models
I'm hoping this is a very simple issue and I'm over complicating it. Lets say I have two models (movie and checkin). When updating a checkin object, I receive an error "Movie matching query does not exist", however creating works perfectly fine. Models class Movie(models.Model): title = models.CharField(max_length=150) genre = models.CharField(max_length=25) description = models.TextField() slug = models.SlugField() class Meta: ordering = ["title"] def get_absolute_url(self): return reverse("movie_detail", args=[str(self.slug)]) def __str__(self): return self.title class Checkin(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) movies = models.ForeignKey( Movie, on_delete=models.CASCADE, related_name="checkins", ) notes = models.TextField(max_length=255, blank=True) user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="checkins", null=True, blank=True, ) class Meta: ordering = ["-added_date"] def __str__(self): return f"{self.user} checked into {self.movies.title} on {self.added_date}" def get_absolute_url(self): return reverse("checkin_detail", args=[str(self.id)]) The goal for my checkin views is to create a checkin based on the slug from the details page of the movie object. This way the user does not have to scroll through hundreds of movie objects just to find the one they are interested in. I am using get_form_kwargs() to accomplish this (which could be the problem but couldn't figure out a better way to accomplish this). class CheckinCreateView(CreateView): model = Checkin template_name = "checkin/checkin_create.html" context_object_name = "checkin_create" form_class = CheckinForm success_url … -
Autofill Django signup page with automatically generated password
I created a simple page for staff members that adds users by entering a username and password, very similar to the way users are added in the admin page. How can the password field be automatically filled with a random password instead of staff members having to manually enter one in? I have seen a method that sends the user a password-reset email, allowing them to enter their own password. This method however doesn't suit our needs. Please take it step by step as I am still new to this language. Any help is much appreciated! -
React - Django page is blank on refresh
Hello I am using Django as my backend and React as frontend. I have an issue when I refresh page and I am not on root page '/' the page goes blank. Also If Ill try to go instantly somewhere else then the home page such as /contact it is blank also. I know it is because the backend server was not contacted as it is said here. I tried to fix it with useHistory but it did not work showing useContext error. What is the best way to fix this issue with Django - React stack? main urls.py: urlpatterns = [ ... path('', TemplateView.as_view(template_name='index.html')) ] app urls.py: router = routers.DefaultRouter() router.register('frontpage', FrontpageViewSet, 'frontpage') router.register('gallery', GalleryViewSet, 'gallery') urlpatterns = router.urls React index.js: import {BrowserRouter} from "react-router-dom"; ReactDOM.render( <React.StrictMode> <BrowserRouter> <App/> </BrowserRouter> </React.StrictMode>, document.getElementById('root') ); App.js: const location = useLocation(); return ( <div className="App"> <GlobalStyle/> <Nav/> <Switch location={location} key={location.pathname}> <Route exact path='/'> <HomePage/> </Route> <Route exact path='/gallery'> <GalleryPage/> </Route> <Route exact path='/contact'> <ContactPage/> </Route> </Switch> </div> ); -
How to automatically count length of total items in Django ArrayField?
I'm trying to create a column called stock_count that counts the total number of items in an ArrayField, in my case the ArrayField is called stock_list. I've created a function in my model class that doesn't seem to do anything. class Bucket(models.Model): class BucketObjects(models.Manager): def get_queryset(self): return super().get_queryset() ... stock_count = models.IntegerField(blank=True, null=True) stock_list = ArrayField(models.CharField(max_length=6,null=True),size=30,null=True) objects = models.Manager() bucketobjects = BucketObjects() class Meta: ordering = ('-created',) def total_stocks_calc(self): self.stock_count = Bucket.objects.aggregate(Sum('stock_list', distinct=True)) self.save() I would like this column to be automated, meaning whenever an item is added to an ArrayField, the stock_count automatically increments by 1. Am I on the right track to create this? -
How to resize/compress or Set default height width / stylesheet classes of Images Upload by django Ckeditor
I'm Using Django-Ckeditor for RichTextUploadField, However, some images are pretty large and I need to resize/compress before sending it to server or If i can set default width and height or Stylesheet classes I tried this but no luck: CKEDITOR_CONFIGS = { 'default': { 'stylesSet': [ { 'name': 'Image-Fluid', 'element': 'img', 'attributes': {'class': 'img-fluid'}, }, ], }, } Need your help community. Any Idea How to make this possible. My CKeditor config: gist -
How to create Django formset from jquery dynamically form?
After user fill a basic form, the data will be showed in table, dynamically created via jquery. index.html <form> <div class="row"> <div class="col-md-6 mb-3"> <label for="sourceip">Source IP:<span> *</span></label> <input type="text" class="form-control" id="sourceip" placeholder="_._._._ , _._._._ , _._._._" value="" > <span class="error_form" id="sourceip_error_message"></span> </div> <div class="col-md-6 mb-3"> <label for="destip">Destination IP:<span> *</span></label> <input type="text" class="form-control" id="destip" placeholder="_._._._ , _._._._ , _._._._" value="" > <span class="error_form" id="destip_error_message"></span> </div> </div> <div class="mb-3"> <label for="service">Service:<span> *</span></label> <div class="input-group"> <input type="text" class="form-control" id="service" placeholder="" > <span class="error_form" id="service_error_message"></span> </div> </div> <div class="mb-3"> <label for="comment">Comment: </label> <textarea type="text" class="form-control" id="comment" placeholder="Add comment"> </textarea> </div> <hr class="mb-4"> <input type="button" class="btn btn-primary btn-lg btn-block add" value="Add rule"> </form> <div id="tabulka" class="table col-md-10"> <form method="POST" action="#" enctype="multipart/form-data"> {% csrf_token %} <!--{{ formset.management_form }}--> <table > <thead class="thead-dark"> <th scope="col">Source IP</th> <th scope="col">Destination IP</th> <th scope="col">Service</th> <th scope="col">Comment</th> <th scope="col" colspan="2">Action</th> </thead> <tbody id="tbody"> </tbody> </table> <input type="submit" value="insert record"> </form> </div> script.js $(".add").click(function () { var SourceIP = CheckIPAdresses($("#sourceip").val()); var DestIP = CheckIPAdresses($("#destip").val()); var Service = CheckService($("#service").val()); var Comment = $("#comment").val(); for (sadd in SourceIP ){ for (dadd in DestIP){ for (srv in Service){ var markup = "<tr class='table-row' > <td class='SourceIP'> <input name='sip' type='text' class='sip' readonly value='"+SourceIP[sadd] + "'> … -
How to change the default error messages displayed by Django forms
I have created a form in Django which has a charfield with max_length=255 as follows: task = models.CharField(max_length= 255) Now I want to let the user know how many characters he has typed if he exceeds the 255 characters limit, so I did the following if form.is_valid(): #some code else: messages.info(request,(form.errors.get("item").as_text())) now consider two scenarios (1) I am leaving the field blank (2) type 445 characters in the form field and submit then by default I am getting the following error messages: Scenario 1: * This field is required. Scenario 2: * Ensure this value has at most 255 characters (it has 445). but instead, I want to change these messages to: Scenario 1: No task added! Scenario 2: Error: maximum length limit is 255 characters (it has 445). So I tried the following: class ListForm(ModelForm): class Meta: model = ListModel fields = ["task", "status"] error_messages = { 'task': { "required": ("No task added!") 'max_length': ("Error: maximum length limit is 255 characters"), }, } Now the messages have been changed to: Scenario 1: * No task added! Scenario 2: * Error: maximum length limit is 255 characters. My Problem: I don't want the * which is being displayed in front … -
raise Http404 returns 500 page instead of 404 custom page
In my app urls.py I have: handler404 = 'app.views.page_not_found' In my views.py I have: def page_not_found(request, exception): return render(request, '404.html', status=404) Entering invalid url will display the custom 404 page as should be. But when I raise 404, in views.py of some module of the Django app, it return 500 page instead of 404 page (I use raise Http404). Do I need to add something in the urls.py of that module? Why it does not show the 404 page? -
DoesNotExist at /adminpanel/ Inspector matching query does not exist
I am trying to fetch some data from the database by satisfying a particular field's value true. my models.py: class Inspector(models.Model): user = models.OneToOneField(myCustomeUser, on_delete=models.CASCADE, related_name='inspector_releted_user') name = models.CharField(max_length=200, blank=False, null=True) gmail = models.EmailField(null=True, blank=False, unique=True) nid = models.IntegerField(blank=False, unique=True) rank = models.CharField(max_length=20, blank=False, null=True) inspector_varified = models.BooleanField(default=False, blank=True, null=True) def __str__(self): return self.name Now I try to fetch only those data which case inspector_varified 's value is True. my views.py: def adminpanel(request): adminpanel_dict = { 'inspector' : Inspector.objects.get(inspector_varified=True) } return render(request, 'app/adminpanel.html', adminpanel_dict) but it shows error like: Inspector matching query does not exist. How can I fix it? -
Reason for Serializer not working in Django Project
I am working on a Django Project and added a Theme Selection Functionality. The user can select the theme either Light or Dark and it reflects in the backend by the CSS file under the setting.value. I create a mode app and it has the current attributes: class Setting(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name="mode",null=True,blank=True) name = models.CharField(max_length=200, null=True) value = models.CharField(max_length=200) def __str__(self): return self.name In the views the user setting is not reflecting properly as it is always showing User don't have a setting., however the updateTheme is working perfectly fine. This is the first time I configure rest_framework to my app. from .serializers import UserSerailizer def userSettings(request): user, created = User.objects.get_or_create(id=1) setting = getattr(user, 'setting', None) if setting: seralizer = UserSerailizer(setting, many=False) return JsonResponse(seralizer.data, safe=False) else: return JsonResponse({'message': "User don't have a setting."}, safe=False) def updateTheme(request): data = json.loads(request.body) theme = data['theme'] user = request.user setting = Setting.objects.update_or_create( user=user, defaults={'value': theme}, name='theme') print('Request:', theme) return JsonResponse('Updated..', safe=False) serializer.py from rest_framework import serializers from .models import * class UserSerailizer(serializers.ModelSerializer): class Meta: model = Setting fields = '__all__' Everytime a User logs in in the console I am receiving the error Data: {message: "User don't have a setting."} In the … -
django - adding new Inline form using smart-selects nothing happens
I have a code below. class Evaluation(models.Model): person = models.ForeignKey(Person, on_delete=models.CASCADE) class EvaluationDisability(models.Model): disability = models.ForeignKey(Disability, on_delete=models.CASCADE) disability_details = ChainedManyToManyField( DisabiltiyDetail, horizontal=True, chained_field="disability", chained_model_field="disability") # evaluation = models.ManyToManyField(Evaluation,blank=False) evaluation = models.ForeignKey(Evaluation, on_delete=models.CASCADE) class EvaluationDisabilityForm(forms.ModelForm): model = EvaluationDisability class EvaluationDisabilityInline(admin.TabularInline): model = EvaluationDisability form = EvaluationDisabilityForm extra = 1 # autocomplete_fields = ['disability_details'] @admin.register(Evaluation) class EvaluationAdmin(admin.ModelAdmin): model = Evaluation inlines = [EvaluationDisabilityInline] right there is says extra=1 So on the admin page the smart-selects is workin fine just for only 1 row. But adding new row.. smart-selects not working anymore. Same thing if i change the extra to any number. for example extra=5. smart-selects works for the first 5 rows but adding a new one will do nothing. Please help been looking for the resolution on this for weeks now -
Django - How get IP of request in a custom receiver?
I have following code: @receiver(user_logged_in) def user_logged_in_callback(sender, request, user, **kwargs): ip = request.META.get('REMOTE_ADDR') AuditEntry.objects.create(action='User logged in', ip=ip, username=user.username) It works great. In views.py I have a custom receiver: @receiver(pre_save, sender=User) def user_updated(sender, **kwargs): user = kwargs.get('instance', None) ip = request.META['REMOTE_ADDR'] if user: new_password = user.password try: old_password = User.objects.get(pk=user.pk).password except User.DoesNotExist: old_password = None if new_password != old_password: AuditEntry.objects.create(action='Password has changed', ip="127.0.0.1", username=user.username) For sure it falls with "no request found" error. I can't figure out how to extract IP. Thank you. -
Django migration error when database has custom views
Django 3.1. app folder : stocks project folder with settings inside: main I have this model: class Bar(models.Model): stock = models.CharField(max_length=10) timestamp = models.DateTimeField() date = models.DateField() time = models.TimeField() open = models.DecimalField(max_digits=6, decimal_places=2) high = models.DecimalField(max_digits=6, decimal_places=2) low = models.DecimalField(max_digits=6, decimal_places=2) close = models.DecimalField(max_digits=6, decimal_places=2) is_regular = models.BooleanField() change = models.DecimalField(max_digits=10, decimal_places=4) In the SQLite database I have created view daily_bottoms from that model using SQliteStudio. Now I am trying to migrate because added another field. makemigrations works fine, but when trying to migrate I get an error: django.db.utils.OperationalError: error in view daily_bottoms: no such table: main.stocks_bar If I delete the view then it will migrate , but I would like to avoid that every time. How to make it work? -
Django admin 'pk' attribute error in main site
I am using the default admin site with the following config: urls.py: urlpatterns = [ path('admin/', admin.site.urls) ] settings.py: INSTALLED_APPS = [ 'django.contrib.admin' ] admin.py admin.site.register(Student) I removed everything unrelated to admin. The error AttributeError: 'NoneType' object has no attribute 'pk' occurs ONLY when accessing localhost/admin. In other words, accessing the database directly like localhost/admin/school/student doesn't throw an exception. Full Traceback: Traceback (most recent call last): File "C:\Users\**\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\**\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\base.py", line 202, in _get_response response = response.render() File "C:\Users\**\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\template\response.py", line 105, in render self.content = self.rendered_content File "C:\Users\**\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\template\response.py", line 83, in rendered_content return template.render(context, self._request) File "C:\Users\**\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\template\backends\django.py", line 61, in render return self.template.render(context) File "C:\Users\**\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\template\base.py", line 170, in render return self._render(context) File "C:\Users\**\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\template\base.py", line 162, in _render return self.nodelist.render(context) File "C:\Users\**\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\template\base.py", line 938, in render bit = node.render_annotated(context) File "C:\Users\**\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\template\base.py", line 905, in render_annotated return self.render(context) File "C:\Users\**\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\template\loader_tags.py", line 150, in render return compiled_parent._render(context) File "C:\Users\**\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\template\base.py", line 162, in _render return self.nodelist.render(context) File "C:\Users\**\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\template\base.py", line 938, in render bit = node.render_annotated(context) File "C:\Users\**\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\template\base.py", line 905, in render_annotated return self.render(context) File "C:\Users\**\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\template\loader_tags.py", line 150, in render return compiled_parent._render(context) File "C:\Users\**\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\template\base.py", line 162, in _render return self.nodelist.render(context) File "C:\Users\**\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\template\base.py", line 938, in render bit = … -
Django How to convert image to base64 then make a post request with the result
I'm trying to make a form with an image upload field then I convert this image to base64 and make a post request to an API with the base64 in the body my forms.py: class FridgeForm(forms.ModelForm): class Meta(forms.ModelForm): model = Fridge fields = [ 'name', 'date', 'picture' ] widgets = { 'date': forms.DateTimeInput } I tried to do it with jquery using val() but I get the image path string not the image $(document).on('submit', function(e){ e.preventDefault(); }) function canvasBase64(image) { const canvas = document.createElement('canvas'); const ctx = canvas.getContext('2d'); canvas.width = image.width; canvas.height = image.hight; ctx.drawImage(image, 0, 0) return canvas.toDataURL('image/jpeg') } $("button.encode").on("click", function(){ const image = $("input[name=picture]").val() console.log(typeof image) console.log(image) canvasBase64(image, function(base64) { console.log('RESULT: ', base64) fetch(url, { method: 'POST', headers: { "X-CSRFToken": csrftoken, }, body: (base64) }) .then(response => response.json()) .then(data => { console.log('data: ', data) }) }) }) -
Django CMS in Django
I am building a django app that would allow users to create html content (to be used as an email template), but keep getting TemplateSyntaxError. I am trying to use the django-cms plugins in my own view and templates any ideas. {% extends 'admin/merchant/base.html' %} {% load cache %} {% load cms_tags %} {% block extra_head %} {% placeholder "css" %} {% endblock extra_head %} {% block content %} <body> {% cms_toolbar %} {% placeholder "content" or %} Nothing is coming through... {% endplaceholder %} </body> {% endblock content %} but i get this error: Template error: In template /home/joel/Projects/Vendora Deploy/src/templates/admin/merchant/newsletter/create-page.html, error at line 15 Invalid block tag on line 15: 'endblock'. Did you forget to register or load this tag? 5 : {% block extra_head %} 6 : {% placeholder "css" %} 7 : {% endblock extra_head %} 8 : 9 : {% block content %} 10 : <body> 11 : {% cms_toolbar %} 12 : 13 : {% placeholder "content" or %} Nothing is coming through... {% endplaceholder %} 14 : </body> 15 : {% endblock content %} 16 : 17 : 18 : ``` [1]:[Traceback Image][1] https://i.stack.imgur.com/PkHi9.png -
How do I write a rest framework serializer to create an instance of a model containing both foreign key relations and generic relations?
I'm trying to create instances of a model using a POST method on django rest framework. I need a serializer method which can handle the logic behind this. In my models I have two instances of a foreign key and one instance of a generic relation foreign key. Here are my models: class UserModel(models.Model): MEMBERSHIP_TYPE = [ ('NM', 'NORMAL'), ('PT', 'PLATA'), ('OR', 'ORO'), ('PL', 'PLATINO'), ] id = models.AutoField(primary_key=True) username = models.CharField(max_length=100) photo = models.ImageField(upload_to='images/', blank=True) address = models.TextField() client_type = models.CharField(max_length=2, choices=MEMBERSHIP_TYPE, default= 'NM') def __str__(self): return self.username class ArticleModel(models.Model): id = models.AutoField(primary_key=True) code = models.IntegerField() description = models.TextField() def __str__(self): return self.code class OrderModel(models.Model): id = models.AutoField(primary_key=True) client = models.ForeignKey('UserModel', on_delete=models.CASCADE) gen_time = models.DateTimeField(auto_now_add=True) gen_supplied = models.DateTimeField() urgent = models.BooleanField() order_to = GenericForeignKey() article = models.ForeignKey('ArticleModel', on_delete=models.CASCADE) quantity= models.IntegerField() object_id = models.BigIntegerField(default=None, null=True) content_type = models.ForeignKey( ContentType, default=None, null=True, on_delete=models.SET_NULL) class WarehouseModel(models.Model): id = models.AutoField(primary_key=True) warehouse_num = models.IntegerField() order_rel = GenericRelation(OrderModel) class StoreModel(models.Model): id = models.AutoField(primary_key=True) reference = models.IntegerField() store_num = models.IntegerField() order_rel = GenericRelation(OrderModel) class BusinessModel(models.Model): id = models.AutoField(primary_key=True) reference = models.IntegerField() store_num = models.IntegerField() order_rel = GenericRelation(OrderModel) class DetailModel(models.Model): id = models.AutoField(primary_key=True) detail = models.TextField() order = models.ForeignKey('OrderModel', on_delete=models.CASCADE) and here's my serializer so far: class … -
See how many orders he has on his profile page. Django
When I enter my user profile page, I want it to see the total number of orders until today. i tried aggregate and annonate but it's not work. I hope so i use filter method but i don't know how to do it. Orders count = adet in model I added ""if siparis.bayi_id == user.id"" so that the user entering can take action on his orders. Temp Html {% for siparis in siparis %} {% if siparis.bayi_id == user.id %} <strong>{{ a }}</strong><br><small>Siparişler Toplamı</small> {% endif %} {% endfor %} Model Siparis means order class Siparis(models.Model): bayi = models.ForeignKey('auth.User', verbose_name='bayi', on_delete=models.CASCADE, related_name='bayi',limit_choices_to={'groups__name': "BayiGrubu"}) urun = models.ForeignKey(Urun, on_delete=models.CASCADE) adet = models.IntegerField() tarih = models.DateTimeField() status = models.BooleanField() @property def miktar(self): return (self.adet * self.urun.fiyat) @property def fiyat(self): return self.urun.fiyat class Meta: verbose_name = 'Bayi Sipariş' verbose_name_plural = 'Bayi Siparişleri' views def bayi_bayidetay(request): siparis = Siparis.objects.all() urunler = Urun.objects.all() bayiler = bayi_bilgi.objects.all() a = Siparis.objects.aggregate(Sum("adet")) return render(request,'bayi/bayi_detay.html',{'bayiler':bayiler,'siparis':siparis,'urunler':urunler, 'a': a}) Thank you -
how to trigger AWS Lambda function with Django framework?
I need to create a Button with Django Framework and connect to trigger lambda function (aws), click to button to should trigger the function. Also, another page to upload files to S3 Bucket with django from local. Should I work on REST API or there is a way around this. how to get started on this or execute the idea? also helpful if you could share resources on this. -
CkEditor image works in localhost but in production it doesn't preview image and save image in Django framework
Here is my settings.py file. BASE_DIR = Path(__file__).resolve().parent.parent TEMPLATE_DIR = os.path.join(BASE_DIR, 'templates') MEDIA_DIR = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' MEDIA_ROOT = MEDIA_DIR CKEDITOR_JQUERY_URL = 'https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js' CKEDITOR_UPLOAD_PATH = 'uploads/' CKEDITOR_CONFIGS = { 'default': { 'extraPlugins': 'codesnippet', 'toolbar': 'full', 'height': 300, 'width': '100%', 'contentsCss': 'img {max-width: 100%;height: auto! important;}', }, } I have kept CKEditor folder under the static folder. Uploading images using RichTextUploadingField works correctly in localhost. In Production server (cPanel) after DEBUG = False it is not previewing any images clicking "Send it to the Server" and not saving the images. Please help regarding the issue. -
Field 'id' expected a number but got <QuerySet [<Example: 9NjKaWHB3q6SVSq>]>
I wish you a good years, I got an issue. I'd like to get resa_exemple == exemple But I got an issue with this Field 'id' expected a number but got <QuerySet [<Example: 9NjKaWHB3q6SVSq>]> I don't really understand why? class RerservationOrder(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE) exemple = models.ManyToManyField('Example',blank=True, related_name='reservation_order_exemple') ... class Reservation(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE) resa_order = models.ManyToManyField('RerservationOrder',blank=True, related_name='resa_order_reservation') resa_exemple = models.ManyToManyField('Example',blank=True, related_name='resa_order_example') def AddResaOrder(request, slug, pk): current_reservation = get_object_or_404(Reservation, slug=slug) cuisine = get_object_or_404(Cuisine, id=pk) resa = current_reservation.resa_exemple.all() if request.method == "POST": #this work create_resa_order = current_reservation.resa_order.create(user=request.user, ...) #this does not work create_resa_order.exemple.add(resa) #this work current_reservation.resa_order.add(create_resa_order) return HttpResponseRedirect(request.META.get('HTTP_REFERER')) -
Handling text files Heroku's ephemeral file-system to upgrade Python
My Python runtime for one of my first Django projects which I am working on that I am deploying to Heroku is out of date. It’s Python version 3.6.7. My build log tells me I should be using a more recent version - - v3.6.12. When I Google, ‘how to upgrade python heroku’, the first search result is the official Heroku doc which identifies supported run times. The doc explains to view your current run time, you can use: $ python --version or in the project root use $ cat runtime.txt and to select a run time, you can change the contents of runtime.txt. I found the file and I can view its contents with cat. It’s Python v3.6.7 for sure, which is out of date and needs to be changed. The two problems I have encountered are: Viewing the file is easy. What I can’t figure out is how to open/edit runtime.txt. My first instinct is to try CLI interface text editors such as vim, vi, pico, nano, all of which are not installed. My question is: How do I edit text files for my Django project on Heroku? Even once I find that out, my next problem is … -
How can I dynamically define forms.IntegerField's min_value parameter?
I am working with Django and its Forms classes. I have created a Form with a single forms.IntegerField and I want to define its min_value parameter dynamically: class BiddingForm(forms.Form): bidding_form = forms.IntegerField(min_value=1, help_text="€", label="Bid") Right now, it is statically set to 1. I have tried to overwrite the __init__() function and pass in a min_value there. But since bidding_form is a class variable, I cannot use the resulting instance variable min_value on it: class BiddingForm(forms.Form): min_value = 1 def __init__(self, min_value): super().__init__() self.min_value = min_value bidding_form = forms.IntegerField(min_value=min_value, help_text="€", label="Bid") As of my understanding, above class creates an instance variable min_value inside of __init__() which just shadows the class variable min_value and it ultimately results in min_value being 1 in the bidding_form's declaration. Since I have little understanding of Python and Django, I have not yet found a solution to this. So, how can I dynamically define forms.IntegerField's min_value parameter? -
Explanation on Django's request processing - Why does it select one urlpattern from another
So I am doing an free online course that involves Django and have run into something that is rather confusing regarding how Django processes requests. My Django application has a single module and within this module I have essentially two pages that I am generating both of which inherit from a layout template. There is an index page (which contains links to individual entries) and an entry page which displays the content of each individual entry. There are two ways to get to an entry page. You could either directly click on the link that is present on the index page or you could type in the search bar that is present on index page. If the name matches the entry in the search bar it will take you to that entry page. Each method of reaching an entry page has its own url pattern in the urls.py file and each one has its own route function in the views.py file. What was happening was that regardless of what was typed into the search bar, it would only use the route that was meant for directly clicking on the entry link from the index page rather than the route that … -
Could not setup django-oauth-toolkit authentication
I'm going to restrict my working rest_framework.views.APIView inherited class, to be visible only by authenticated users. I made these modifications: Added authentication_classes and permission_classes to my class: class TestView(APIView): authentication_classes = (OAuth2Authentication,) permission_classes = (IsAuthenticated,) return Response("Hey there...") Got an access_token from django-oauth-toolkit: curl -XPOST "http://172.18.0.1:8000/oauth2/token/" \ -d 'grant_type=client_credentials&client_id=MY-CLIENT-ID&client_secret=MY-CLIENT-SECRET' {"access_token": "Haje1ZTrc7VH4rRkTbJCIkX5u83Tm6", "expires_in": 36000, "token_type": "Bearer", "scope": "read write groups"} Tried requesting the view without setting the access_token: curl -XGET "http://172.18.0.1:8000/api/v1/test/" {"detail":"Authentication credentials were not provided."} Tried a new request with the access_token: {"detail":"You do not have permission to perform this action."} Should I do anything more to enable access_token authentication? Note: I have installed these libraries in the environment: Django==2.2.17 djangorestframework==3.12.2 django-oauth-toolkit==1.3.3