Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Admin: How to select Groups roles to display based on active user role?
I have a Django app with multiple levels of admin role and users defined by the django-role-permissions package. I want to apply permissions to users only through groups, defining the permissions for the group roles and assigning the user to the correct group. I want to "hide" the higher level admin roles in Groups when lower level admins create users. A lower level admin should not be able assign a created user to a higher level admin role in Groups. I can do this with Users (lower level admins cannot view / change higher level admins) by overriding get_queryset with code shown below. I want to be able to do something equivalent with the roles in Groups. I would prefer to do this in my admin.py rather than in templates. It would have been nice if the Groups members were also gathered by get_queryset, but that does not seem to be the case. I have searched around without finding anything definitive. I set up django-debug-toolbar to see the context passed into the forms, but I don't see the Groups elements passed in that way to change_form. It's tempting to try overriding FilteredSelectMultiple inside of django.contrib.admin.widgets, but I don't yet see … -
Make Django admin work on a specific port
How to make Django administration URL work on a specific port? I am looking to run it on a unique port and then restrict the access to that port from the AWS security group to my IP. -
How to limit display data based on record value using Django Rest Framework?
I want to limit display data based on record data value. This is my code : models.py class Subcategory(models.Model): subcategory_id = models.BigAutoField(primary_key=True) subcategory = models.CharField(max_length=40) class Question(models.Model): question_id = models.BigAutoField(primary_key=True) subcategory = models.ForeignKey('Subcategory', models.DO_NOTHING, default=None) practice_setting = models.ForeignKey('PracticeSetting', models.DO_NOTHING, default=None) question = models.TextField() answer = models.CharField(max_length=255) class PracticeSetting(models.Model): practice_setting_id = models.BigAutoField(primary_key=True) num_of_question = models.SmallIntegerField() serializers.py class SubcategorySerializer(serializers.ModelSerializer): class Meta: model = Subcategory fields = ('subcategory_id', 'subcategory') class QuestionSerializer(serializers.ModelSerializer): class Meta: model = Question fields = ('question_id', 'subcategory', 'practice_setting', 'question', 'answer') class PracticeSettingSerializer(serializers.ModelSerializer): class Meta: model = PracticeSetting fields = ('practice_setting_id', 'num_of_question') view.py @api_view(['GET']) def subcategory_list(request): # GET list of subcategory if request.method == 'GET': subcategories = Subcategory.objects.all() subcategory = request.GET.get('subcategory', None) if subcategory is not None: subcategories = subcategories.filter(subcategory__icontains=subcategory) subcategories_serializer = SubcategorySerializer(subcategories, many=True) return JsonResponse(subcategories_serializer.data, safe=False) @api_view(['GET']) def question_list(request): # GET list of question if request.method == 'GET': questions = Question.objects.all() subcategory = request.GET.get('subcategory', None) if subcategory is not None: questions = questions.filter(subcategory__subcategory__icontains=subcategory) questions_serializer = QuestionSerializer(questions, many=True) return JsonResponse(questions_serializer.data, safe=False) @api_view(['GET']) def practiceSetting_list(request): # GET list of practiceSetting if request.method == 'GET': practiceSettings = PracticeSetting.objects.all() practiceSetting = request.GET.get('practiceSetting', None) if practiceSetting is not None: practiceSettings = practiceSettings.filter(practiceSetting__icontains=practiceSetting) practiceSettings_serializer = PracticeSettingSerializer(practiceSettings, many=True) return JsonResponse(practiceSettings_serializer.data, safe=False) /api/subcategory [ { subcategory_id: 1, subcategory: … -
Django AWS S3 Buckets: CKEditor gives SignatureDoesNotMatch error
I have put all of my static files in an S3 bucket on AWS. The images, javascript and CSS works fine on the site but the CKEditor rich text editor won't show up and is giving me the following errors: SignatureDoesNotMatch. The request signature we calculated does not match the signature you provided. Check your key and signing method TypeError: c[a] is undefined // I think that this error is only because of the first one There is also a script that didn't load in the console for the CKEditor which I think is also due to the signature error Here are my settings AWS_ACCESS_KEY_ID = id AWS_SECRET_ACCESS_KEY = secret_id AWS_STORAGE_BUCKET_NAME = bucket_name AWS_S3_FILE_OVERWRITE = False AWS_DEFAULT_ACL = None DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' AWS_S3_REGION_NAME = 'eu-west-2' AWS_S3_ADDRESSING_STYLE = "virtual" TEXT_CKEDITOR_BASE_PATH = 'https://bucket_name.s3.amazonaws.com/ckeditor/ckeditor/' Note This error is happening also in the admin page so it's not the javascript that puts in the CKEditor that is causing the error so I haven't shared that javascript here as it is irrelevant -
Way to get custom queryset along with serialized relation response in django-rest-framework
Currently im implementing the django-rest-framework in my project. I want a custom response from my serializer (which is a serialized relation) but at the same time I also want to use custom queryset with query params so i implemented get_queryset()method in my generics.ListAPIView. Using this i cant get my custom serialized relations in my response. Serializer.py class ChainedSerializer(serializers.ModelSerializer): cate = serializers.SerializerMethodField() sub_cate = serializers.SerializerMethodField() class Meta: model = Chained exclude = ('id', 'shop') def get_cate(self, obj): cat = Cate.objects.get(id=obj.cate.id) print(cat) return cat.cate_name def get_sub_cate(self, obj): sub_cats = SubCate.objects.get(id=obj.sub_cate_id).sub_cate_name return sub_cats class ShopSerializer(serializers.ModelSerializer): shop = ChainedSerializer(read_only=True, many=True) class Meta: model = Shop fields = '__all__' Views.py class ShopList(generics.ListAPIView): queryset = Shop.objects.all() serializer_class = ShopSerializer permission_classes = (permissions.AllowAny,) def get_queryset(self): subcate = self.request.query_params.getlist('subcate') subcate_ids = list( SubCate.objects.filter(sub_cate_name__in=subcate).values_list('id', flat=True)) shop_ids = list(Chained.objects.filter(sub_cate_id__in=subcate_ids).values_list( 'shop_id', flat=True)) queryset = Shop.objects.filter(id__in=shop_ids).values() return queryset Response when using the ```get_queryset()``` method [ { "id": 1, "shop_type": "willodale", "shop_name": "first shop", "shop_email": "something@gmail.com", "phone": "1111111111", "area_code": "11111", "area_name": "dummy", "shop_address": "dummy", } ] Response if i dont use the get_queryset() method [ { "id": 2, "shop": [ { "cate": "Serv", "sub_cate": "WI" } ], "shop_type": "type", "shop_name": "dummy2", "shop_email": "something2@gmail.com", "phone": "1111111111", "area_code": "11111", "area_name": "dummy", "shop_address": "dummy", }, { … -
How do I validate input in Django REST framework before creation?
I have a model that represents a shopping item with a "choose-your-own-price" model. The seller can opt in to allow customers to pick from a low, medium, or high price. Thus, I need to validate that the user sends a valid option between these three values for each shopping item. Currently, my model looks like this: class PurchaseItem(models.Model): """ PurchaseItem. "price" should be treated as a suggestion. We allow users to choose their own price, so we need to validate that what comes here is a valid choice from the Listing. Otherwise, a malicious user might be able to charge whatever they want. The Listing model has a ListingPrice with a required 'suggested_cost' field and optional low, medium, high costs. """ id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) item = models.ForeignKey(Listing, on_delete=models.DO_NOTHING) price = models.DecimalField(max_digits=8, decimal_places=2, blank=False, null=False) currency = models.CharField(max_length=30, choices=SUPPORTED_CURRENCIES, default='USD') created_date = models.DateTimeField(auto_now_add=True) purchased_by = models.ForeignKey(User, on_delete=models.CASCADE) def clean(self): listing_price = self.item.price valid_prices = [listing_price.suggested_cost] if listing_price.supports_cost_choice is True: valid_prices = valid_prices + [listing_price.low_cost, listing_price.medium_cost, listing_price.high_cost] if self.price not in valid_prices: raise ValidationError("Selected price is not a valid option.") super(PurchaseItem, self).clean() def save(self, force_insert=False, force_update=False, using=None, update_fields=None): self.clean() # <---- Workaround. I'm trying to remove this. super(PurchaseItem, self).save(force_insert, force_update, … -
Unable to read Django app files when hosting website through AWS using nginx and gunicorn
So I was trying to deploy a Django app through AWS using nginx and gunicorn. For some reason when I go to the ip it says "Welcome to nginx" and does not read my app files. This is the first time I am working with nginx and django, so does anyone have an idea what could be wrong? Is there any changes I need to make to my nginx.conf or django.conf or gunicorn.conf files? My wsgi.py file is in /Main/website/wsgi.py, unlike what you might usually find as /Main/wsgi.py This is my django.conf: listen 80; server_name ec2-18-191-164-253.us-east-2.compute.amazonaws.com; location / { include proxy_params; proxy_pass http://unix:/home/ubuntu/GMMR/app.sock; } } and this is my gunicorn.conf: directory=/home/ubuntu/GMMR/website command=/home/ubuntu/env/bin/gunicorn --workers 3 --bind unix:/home/ubuntu/GMMR/app.sock website.wsgi:application autostart=true autorestart=true stderr_logfile=/var/log/gunicorn/gunicorn.err.log stdout_logfile=/var/log/gunicorn/gunicorn.out.log [group:guni] programs:gunicorn this is my nginx.conf: worker_processes auto; pid /run/nginx.pid; include /etc/nginx/modules-enabled/*.conf; events { worker_connections 768; # multi_accept on; } http { ## # Basic Settings ## server_names_hash_bucket_size 128; sendfile on; tcp_nopush on; tcp_nodelay on; keepalive_timeout 65; types_hash_max_size 2048; # server_tokens off; # server_names_hash_bucket_size 64; # server_name_in_redirect off; include /etc/nginx/mime.types; default_type application/octet-stream; ## # SSL Settings ## ssl_protocols TLSv1 TLSv1.1 TLSv1.2; # Dropping SSLv3, ref: POODLE ssl_prefer_server_ciphers on; ## # Logging Settings ## access_log /var/log/nginx/access.log; error_log /var/log/nginx/error.log; ## # … -
Django/Wagtail - How to create a conditional in template that checks for url path?
I'm struggling to finding a quick and easy solution to show HTML content based on a conditional that checks if the wagtail page is at root, aka '/'. According to the Wagtail docs, I can also make this work using original request object from Django: Additionally request. is available and contains Django’s request object. This is essentially what I want to do. I use the page object here from wagtail but it might be better if I used the request object from Django instead. How can I {% if page.request.path == '/' %} <div> show something </div> {% else %} #show nothing {% endif %} How can I structure a conditional to solve what I'm trying to do? -
Get a value from a JS script and pass it to a HTML Form
I don`t find out how to get the value from the js script input ( phone number that user input , and the country prefix code that the script auto put ) <script src="{% static 'assets/js/intlTelInput.js' %}"></script> <script> var input = document.querySelector("#phone"); window.intlTelInput(input, { initialCountry: "gb", }); </script> and have it saved thru my HTML form under this: <input type="tel" name="phone-number" class="form-control input-style" placeholder="your phone"> <input type="tel" id="phone"> Full code : <form class="submit-form" method="post" action="{% url 'register' %}" enctype="application/json"> {% csrf_token %} <div class="div-block"> <div class="double-fields-step-2-only"> <div class="form-group"> <div class="form-group right"> <input type="tel" name="phone-number" class="form-control input-style" placeholder="your phone"> <input type="tel" id="phone"> <script src="{% static 'assets/js/intlTelInput.js' %}"></script> <script> var input = document.querySelector("#phone"); window.intlTelInput(input, { initialCountry: "gb", }); </script> <div class="icon"></div> </div> </div> <button type="submit" class="btn btn-register" data-title="Loading..."> Register </button> </form></div> </form> -
Django: converting the "date_joined" field on the AbstractUser class to only month and year precision
I have a Django model with a User class that inherits from AbstractUser. class User(AbstractUser): pass In the Django Admin screen, I see that the date_joined field has month, day, year, and time precision. I also have a Django template with the following code: {% block header%} <h2>{{ profile.username }}</h2> <h3>{{ profile.date_joined }}</h3> {% endblock %} Not surprisingly, this renders as follows: Foo Bar July 4, 2021, 6:38 p.m. What I'd like is for it to render as only the month and date, as follows: Foo Bar July 2021 Is is possible to convert the date_joined field on the User class to month and year only? Thanks! -
Choosing a for loop based on if condition in Django
In Django How can I write condition for choosing one of two for loops? {% if type == 'type_one' %} {% for object in type_one_ojects %} {% elif type == 'type_two' %} # this_line {% for object in type_two_ojects %} ... ########## Given error ########## # Invalid block tag on this_line: 'elif', expected 'empty' or 'endfor'. Did you forget to register or load this tag? -
How do I save data to a table in Django?
I am trying to find the average price of each product and I am trying to store this in a table daily to form a price history chart, and all the objects will be data points on the chart. However, I am not able to create objects with the data I have, and I am not sure why. The Error I've gotten is <class 'OSError'> and I suspect it is because I am creating objects in the PriceHistory model incorrectly. class Command(BaseCommand): help = "Loops through each Retailer Product and scrapes their data" def handle(self,*args,**options): # Scrape Code happens here (cycles through all the retailerproduct objects, each object is recognised as 'product' in this script) # prices is just an array of all the prices for a particular product from several retailers mean = find_mean(prices,product) def find_mean(prices,product): mean = 0 for i in prices: mean += float(i) #This is where I am having problems: PriceHistory.objects.create(price=round(float(mean/len(prices)),2),product=int(product.product._id)) This is my PriceHistory Model class PriceHistory(models.Model): price = models.DecimalField(default=0.00,max_digits=8,decimal_places=2) product = models.ForeignKey(Product,on_delete=models.CASCADE,related_name='history') date = models.DateField(default=date.today,blank=True) _id = models.AutoField(primary_key=True,editable=False) This is my Product Model class Product(models.Model): name = models.CharField(max_length=30,null=True,blank=True) brand = models.CharField(max_length=20,null=True,blank=True) image = models.ImageField(null=True,blank=True) _id = models.AutoField(primary_key=True, editable=False) This is a table with all … -
django/react retrieve and play audio file
models.py from django.db import models from datetime import datetime class Song(models.Model): title = models.CharField(max_length=64) audio_file = models.FileField() genre = models.CharField(max_length=64) created_at = models.DateTimeField(default=datetime.utcnow) serializers.py from rest_framework import serializers from . import models class SongSerializer(serializers.ModelSerializer): class Meta: model = models.Song fields = '__all__' views.py from . import models, serializers from rest_framework import viewsets, status from rest_framework.response import Response from rest_framework.views import APIView class SongView(APIView): # get the songs def get(self, request, format=None): serializer = serializers.SongSerializer(models.Song.objects.all(), many=True) return Response(serializer.data) urls.py from django.urls import path from . import views urlpatterns = [ path('songs/', views.SongView.as_view(), name='songs') ] Home.js import React from 'react' import { useState, useEffect } from 'react' import axios from 'axios' const Home = () => { const getSongs = () => { axios.get('http://localhost:8000/api/songs/') .then(res => setSongs(res.data)) // see data below (Response.json) } let [songs, setSongs] = useState([]) useEffect(() => { getSongs() console.log(songs) }, []) return ( <> { songs.map(song => (<div className='music-controller'> <div className="music-controller-body"> <div className="music-controller-header"> <h2>{song.title}</h2> <p><small>{song.genre}</small></p> </div> <div className="controls"> <i className="fas fa-play"></i> <audio src={song.audio_file} autoPlay></audio> // Cannot retrieve url </div> </div> </div>) )} </> ) } export default Home Response.json [ { "id": 1, "title": "Kubbi | Cascade", "audio_file": "/media/Kubbi__Cascade.mp3", "genre": "Instrumental", "created_at": "2021-07-24T10:21:48Z" } ] All I want … -
How to show all fields values of a model from a form in Django?
I'm making a page to edit the user's account. The new values are saving with no problems, but I can't show the current values of the fields in the form (using forms.ModelForm). forms.py: class UserForm(forms.ModelForm): class Meta: model = User fields = ('email', 'first_name', 'last_name') class UsuarioForm(forms.ModelForm): class Meta: model = USUARIO fields = ('cpfCnpj', 'dataNascimento', 'telefone', 'receberNotificacoes', 'tipoUsuario' ) views.py: @login_required @transaction.atomic def modificar_cadastro(request): if request.method == "POST": user_form = UserForm(request.POST, instance=request.user) usuario_form = UsuarioForm(request.POST, instance=request.user.usuario) if usuario_form.is_valid() and user_form.is_valid(): user_form.save() usuario_form.save() return render(request, 'index.html') else: messages.error(request, ('Please correct the error below.')) else: usuario_form = UsuarioForm(instance=request.user) user_form = UserForm(instance=request.user.usuario) return render(request, 'modificar-cadastro.html', { 'usuario_form': usuario_form, 'user_form': user_form, }) template: {% extends 'base.html' %} {% load crispy_forms_tags %} {% block conteudo %} <h2>Modificar cadastro</h2> <form method="POST" class="post-form">{% csrf_token %} {{ user_form|crispy }} {{ usuario_form|crispy }} <button type="submit" class="btn btn-outline-dark">Save</button> </form> {% endblock %} models.py: class USUARIO(models.Model): user = models.OneToOneField(User, on_delete=CASCADE) tipoUsuario = models.IntegerField(choices=TIPOS_USUARIO, default=1) cpfCnpj = models.CharField(max_length=11, blank=False, null=True, verbose_name='CPF') dataNascimento = models.DateField(blank=False, null=True, verbose_name='Data de nascimento') telefone = models.CharField(max_length=11, blank=True, null=True, verbose_name='Número de telefone') pontuacao = models.DecimalField(max_digits=30, decimal_places=15, blank=True, null=True) receberNotificacoes = models.BooleanField(default=False) What do i need to do to the current values to be displayed on my form? -
Django admin site downloading style-sheets but not displayed as styled
I have set up a basic Django system and am testing out the admin app. The admin screen displays with raw styles and not the pretty ones shown in the tutorials and specified in the style-sheets. Following several other questions, I found this is a common problem caused because Django doesn't normally serve static files. However, it does if DEBUG is switched on and I do have debug switched on. I followed all of the suggestions in the answers anyway to collect static files, etc. If I enter the static file URLs directly they get downloaded and I can see the files in the developer mode of the browser (both Chrome and Edge). So I think the static files are being served. Furthermore, if I save the page using the browser, it saves all of the static files and then if I open the main page it is shown with the correct styles. So the styles are working. So it would seem to me that the files are being served and the browser is getting them and it can render them (from a saved file) but it somehow isn't working when served from Django. Can anyone tell me what is … -
How i can show rows that have inputed value in new table?
This is my table : <table id="products"> <thead> <tr> <th>name</th> <th>quantity</th> </tr> </thead> {% for pr in productlist %} <tbody id="t1" class="tbody"> <tr class="test" data-index="pr.productid" style="border: none; border-collapse: collapse;"> <td> {{ pr.productname }} </td> <td> <input class="prqty" id="prinp" type="number" placeholder="0" max="pr.numberqut" min="0" name="mylist"> </td> </tr> </tbody> {% endfor %} </table> and this is result: Here i append to new table: <table id="here"></table> <script> $('#here').html($('#products').clone().attr('id', 'newproducts')); </script> My problem is that i don't know how can filters rows that have input value. i want this: Thanks for any help. -
Post request causes "django.db.models.query_utils.DeferredAttribute" DRF
I'm quite new at this so patiance please. Now what I was trying to do was, create a function that checks if there are any objects in the database, if there are increase the counter, give that value to a model field and then pass that value to a field on another model. I tried do it as best as I could and when I run a post method, it does post the data, so if I were to check it out on the database, the field which I supposedly update gives me the error django.db.models.query_utils.DeferredAttribute Edit: If i run the code once, as I said it does create the object and the field has that error from above, if I try to make another post request, it crashes and gives the error that the field is supposed to be unique but it isn't. This is my simplified code below, if you need to see more just ask. Thanks in advance. class Order(models.Model): code = models.CharField(max_length=10, unique=True) code_year = models.IntegerField def __str__(self): return str(self.code) def save(self, *args, **kwargs): self.code = Counter.name super(Order, self).save(*args, **kwargs) class Counter(models.Model): def count(self): self.value=0 items = Order.objects.all() for item in items.values('code_year'): self.value+=1 return self.value @property … -
fetching data with datatable js django ajax , lose data when searching
i'm trying to fetching data using ajax , and display data into datatable showing data is working fine , but when i try to search or doing some sort into the datatable , it lost the data , and requires to reload the page again ?! class MainGroup(models.Model): admin = models.ForeignKey(User,on_delete=models.CASCADE) main_type = models.CharField(max_length=40,unique=True) date = models.DateTimeField(auto_now_add=True) my views.py def list_maingroup(request): lists = MainGroup.objects.all().order_by('-pk') data = [] for obj in lists: item = { 'id':obj.id, 'admin':obj.admin.username, 'main_type':obj.main_type, 'date':obj.date } data.append(item) return JsonResponse({'data':data}) my templates const form = document.getElementById('main_form') form.addEventListener("submit",submitHandler); function submitHandler(e) { e.preventDefault(); $.ajax({ type: 'POST', url: '{% url 'products:maingroup' %}', data : $('#main_form').serialize(), dataType: 'json', success: successFunction, }); } function successFunction(data) { if (data.success) { form.reset(); alertify.success("added") } else if(data.error_code=='invalid'){ for(var key in data.error_msg){ if(key == 'main_type'){ document.getElementById('main_error').removeAttribute('hidden') document.getElementById('main_error').innerHTML = data.error_msg[key][0] } } } } $.ajax({ type:'GET', url:'{% url 'products:list-maingroup' %}', success:function(response){ console.log(response) data = response.data var k = '<tbody>' for(i = 0;i < data.length; i++){ k+= '<tr>'; k+= '<td>' + data[i]['id'] + '</td>'; k+= '<td>' + data[i]["admin"] + '</td>'; k+= '<td>' + data[i]["main_type"] + '</td>'; k+= '<td>' + data[i]["date"] + '</td>'; k+= '</tr>' } k+='</tbody>' document.getElementById('tableData').innerHTML = k } }) <div class="col-md-12"> <!-- general form elements --> <div … -
Django JsonResponse not returning expected response of JSON
I’m trying to return some json with this: return JsonResponse({"likes": likes}) The response I’m getting is commented in my client.js code, the response doesn’t contain my json and causes an error when trying to parse the response. Why isn't the response json? If json is in the response how do I access it? In views.py: import json from django.http import JsonResponse @csrf_exempt @login_required def like_post(request): if request.method == "POST": data = json.loads(request.body) print("POST request received", data) try: post = Post.objects.get(id=data["post_id"]) except Post.DoesNotExist: pass try: liked = Like.objects.get(user=request.user, post=post) print(liked) except Like.DoesNotExist: print("adding new like") like = Like(user=request.user, post=post) like.save() likes = post.likes.all().count() print("likes", likes) return JsonResponse({"likes": likes}) else: print("like_post accessed via GET") return render(request, "network/index.html") In my client.js: function handleLike(e) { const data = e.target.dataset console.log(e.target, data.post_id, data.post_user, data.user) if (data.post_user !== data.user) { fetch("/posts/like", { method: "POST", body: JSON.stringify({ post_id: data.post_id }) }) .then( res => { console.log(res) /* Response { type: "basic", url: "http://localhost:8000/posts/like", redirected: false, status: 200, ok: true, statusText: "OK", headers: Headers, body: ReadableStream, bodyUsed: false } */ JSON.parse(res) // Error SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data }) .then( res => { e.target.firstElementChild.innerText = `(${res.likes})` }) .catch( err => … -
Working with python and django: my Status is not rendering on my views correctly
So my goal is to show the status of the job application as a drop down with the default to 'applied' but the rest of the selection would be: ('A', 'Applied'), ('B', 'In Progress'), ('C', 'Interview scheduled'), ('D', 'Interview complete'), ('E', 'Job Offer'), ('F', 'Incomplete'), ('G', 'Not Selected'), ('H', 'Unknown'), here are my models class Job_application(models.Model): name = models.CharField(max_length=100) company = models.CharField(max_length=100) location = models.CharField(max_length=250) date = models.DateField('Date Applied') url = models.CharField( max_length=250, blank=True ) requirements = models.TextField( max_length=500, blank=True ) notes = models.TextField( max_length=500, blank=True ) user = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.name def get_absolute_url(self): return reverse('detail', kwargs={'job_id': self.id}) #every model instance has its own method #django will now render the detail page, class Attachment(models.Model): # will implement later with AWS if possible -CO url = models.CharField(max_length=250) job_app = models.ForeignKey(Job_application, on_delete=models.CASCADE) def __str__(self): return f'Attachment for job_id: {self.job_id} @{self.url}' class Status(models.Model): date = models.DateField('Date') STATUS = ( ('A', 'Applied'), ('B', 'In Progress'), ('C', 'Interview scheduled'), ('D', 'Interview complete'), ('E', 'Job Offer'), ('F', 'Incomplete'), ('G', 'Not Selected'), ('H', 'Unknown'), ) status = models.CharField( max_length=1, choices=STATUS, default=STATUS[0][0] ) job_app = models.ForeignKey(Job_application, on_delete=models.CASCADE) def __str__(self): # Nice method for obtaining the friendly value of a Field.choice return f"{self.get_status_display()}" # change the … -
I'm getting an error that I do not understand from Django
I am trying to follow James Bennett example but getting this error: ValueError at /loadtest too many values to unpack (expected 2) Request Method: GET Request URL: http://127.0.0.1:8000/loadtest Django Version: 3.2.5 Exception Type: ValueError Exception Value: too many values to unpack (expected 2) Exception Location: /Users/lowell.dennis/Code/loadtest/env/lib/python3.9/site-packages/django/forms/widgets.py, line 691, in _choice_has_empty_value Python Executable: /Users/lowell.dennis/Code/loadtest/env/bin/python Python Version: 3.9.6 Python Path: ['/Users/lowell.dennis/Code/loadtest', '/Users/lowell.dennis/.vscode/extensions/ms-python.python-2021.7.1053846006/pythonFiles/lib/python/debugpy/_vendored/pydevd', '/usr/local/Cellar/python@3.9/3.9.6/Frameworks/Python.framework/Versions/3.9/lib/python39.zip', '/usr/local/Cellar/python@3.9/3.9.6/Frameworks/Python.framework/Versions/3.9/lib/python3.9', '/usr/local/Cellar/python@3.9/3.9.6/Frameworks/Python.framework/Versions/3.9/lib/python3.9/lib-dynload', '/Users/lowell.dennis/Code/loadtest/env/lib/python3.9/site-packages'] Server time: Sat, 24 Jul 2021 01:52:04 +0000 I am hoping that someone can see the error I am making. Here is my form class code code: class DynamicForm(Form): def __init__(self, *args, **kwargs): dynamic = kwargs.pop('dynamic', 0) super(DynamicForm, self).__init__(*args, **kwargs) for field in dynamic: self.fields[field[0]] = field[1] I am building an array of tuples, (name, field), where name is the name of the field and field is the field type (like CharField, ChoiceField, FloatField, IntegerField, URLField) with the prompt, initial, label, required and where needed choices items filled in). My view function ends with this: return render(request, 'loadtest.html', {'form': DynamicForm(dynamic = fields)}) My loadtest.html contains the following: <form action="" method="post"> {% csrf_token %} <table> {{ form.as_table}} </table> <input type="submit" value="Submit"> </form> -
how do I configure my staticfiles in django?
I followed the procedures to setup staticfiles but I'm not getting what i want when I add an image to the section background it gives a wrong path "staticfiles/css/assets/img/oilcarriage.jpg" instead of "staticfiles/assets/img/oilcarriage.jpg" here's the path to the image: i would be really grateful if you can help me now :) -
how to add a mouse cropping feature to python project?
I am working on a project that allows users to upload their images and I wanted to be able to add a feature for them to crop it using the mouse, Can anyone please point out reliable resources or directions. so far I have to explore pillow, openCV. Also I am beginner developer and I keep running into machine learning sources to crop the image? is that a complicated task to accomplish, my python knowledge is mainly creating simple apps like to do lists, tic tac toe,... appreciate your help -
Heroku deployment of Django application with sqlite
I would like to deploy my Django application to Heroku. It is working perfectly in my localhost but when I tried to deploy, I get this error: ProgrammingError at / relation "myblog_category" does not exist LINE 1: ...g_category"."name", "myblog_category"."name" FROM "myblog_ca... The problem is probably related with my migrations but still can not solve. Is it related with sqlite? Thanks -
WAMP icon turns orange after adding mod_wsgi-express module-config results in httpd file
i am trying to deploy my django app on windows using wamp and mod_wsgi. the probleme is that the icone turns orange once i configure the httpd file and add the following lines resulting from the mod_wsgi-express module-config command : LoadFile "c:/users/zakaria/appdata/local/programs/python/python39/python39.dll" LoadModule wsgi_module "c:/users/zakaria/appdata/local/programs/python/python39/lib/site-packages/mod_wsgi/server/mod_wsgi.cp39-win_amd64.pyd" WSGIPythonHome "c:/users/zakaria/appdata/local/programs/python/python39" the error in the appache error log is stating : Python path configuration: PYTHONHOME = (not set) PYTHONPATH = (not set) program name = 'python' isolated = 0 environment = 1 user site = 1 import site = 1 sys._base_executable = 'C:\\wamp64\\bin\\apache\\apache2.4.46\\bin\\httpd.exe' sys.base_prefix = 'C:\\Users\\ZAKARIA\\AppData\\Local\\Programs\\Python\\Python39' sys.base_exec_prefix = 'C:\\Users\\ZAKARIA\\AppData\\Local\\Programs\\Python\\Python39' sys.platlibdir = 'lib' sys.executable = 'C:\\wamp64\\bin\\apache\\apache2.4.46\\bin\\httpd.exe' sys.prefix = 'C:\\Users\\ZAKARIA\\AppData\\Local\\Programs\\Python\\Python39' sys.exec_prefix = 'C:\\Users\\ZAKARIA\\AppData\\Local\\Programs\\Python\\Python39' sys.path = [ 'C:\\Users\\ZAKARIA\\AppData\\Local\\Programs\\Python\\Python39\\python39.zip', '.\\DLLs', '.\\lib', 'C:\\wamp64\\bin\\apache\\apache2.4.46\\bin', ] Fatal Python error: init_fs_encoding: failed to get the Python codec of the filesystem encoding Python runtime state: core initialized ModuleNotFoundError: No module named 'encodings' Did you guys went trough a similar situation? Thanks in advance.