Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to set up a callable for Django Imagefield's >> default << parameter
So I have a Model that contains a couple hundred instances and I now added an imagefield logo. As I don't want to upload each and every logo via the admin manually, I want to set up a callable that returns the correct file path so I can just push all logos to media/company_logos. # models.py def logo_directory_path(instance, filename): # file will be uploaded to MEDIA_ROOT/user_<id>/<filename> return f'company_logos/{instance.symbol}' class Company(models.Model): symbol = models.CharField(max_length=50) logo = models.ImageField(upload_to='company_logos/', default=logo_directory_path(instance=symbol, filename=f'{symbol}.png')) This returns an error at instance=symbol saying Type 'str' doesn't have expected attribute 'symbol' Another approach was logo = models.ImageField(upload_to='company_logos/', default=f'company_logos/{symbol}') which returns a URL as src="/media/company_logos/<django.db.models.fields.CharField>" I am not quiet sure how to set this up as I cant fully understand the official docs. My desired outcome is to have a URL for default like so: company_logos/IBM.png with field symbol being the corresponding part (I tried it via f-string). -
Django How to retrieve data based on their pk
I want a staff Dashboard which can see all user data and also CRUD it. how can I dynamically filter for the pk of the user data. If I use objects.all I get everything but cant edit specific values from django.contrib.auth.mixins import UserPassesTestMixin class AdminStaffRequiredMixin(LoginRequiredMixin, UserPassesTestMixin): def test_func(self): return self.request.user.is_superuser or self.request.user.is_staff class Dashboard (AdminStaffRequiredMixin, LoginRequiredMixin, ListView): model = SchulverzeichnisTabelle template_name = 'SCHUK/Dashboard.html' context_object_name = 'Dashboard' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['Schulverzeichnis'] = SchulverzeichnisTabelle.objects.all() return context -
Django migrate ValueError: too many values to unpack
Calling python manage.py migrate results in the following error for the auth table. I've tried deleting my DB and all migrations to start from scratch, not sure where the issue is coming from. Django version is 4.1 $ python manage.py migrate Operations to perform: Apply all migrations: admin, auth, contenttypes, generator, sessions Running migrations: Applying auth.0001_initial...Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "<redacted>/venv/lib/python3.8/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_lin e utility.execute() File "<redacted>/venv/lib/python3.8/site-packages/django/core/management/__init__.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "<redacted>/venv/lib/python3.8/site-packages/django/core/management/base.py", line 402, in run_from_argv self.execute(*args, **cmd_options) File "<redacted>/venv/lib/python3.8/site-packages/django/core/management/base.py", line 448, in execute output = self.handle(*args, **options) File "<redacted>/venv/lib/python3.8/site-packages/django/core/management/base.py", line 96, in wrapped res = handle_func(*args, **kwargs) File "<redacted>/venv/lib/python3.8/site-packages/django/core/management/commands/migrate.py", line 349, in handle post_migrate_state = executor.migrate( File "<redacted>/venv/lib/python3.8/site-packages/django/db/migrations/executor.py", line 135, in migrate state = self._migrate_all_forwards( File "<redacted>/venv/lib/python3.8/site-packages/django/db/migrations/executor.py", line 167, in _migrate_all_forwards state = self.apply_migration( File "<redacted>/venv/lib/python3.8/site-packages/django/db/migrations/executor.py", line 255, in apply_migration migration_recorded = True File "<redacted>/venv/lib/python3.8/site-packages/django/db/backends/sqlite3/schema.py", line 39, in __exit__ self.connection.check_constraints() File "<redacted>/venv/lib/python3.8/site-packages/django/db/backends/sqlite3/base.py", line 289, in check_constraints for column_name, ( ValueError: too many values to unpack (expected 2) Any help is appreciated! -
import module in Django
I have a project with structure like on this picture. Folders structure Where 'backend' folder is Django project folder. I need to import module from another folder 'main' inside Django app file, i.e. import main.Text_Generator in backend.app.views file. I tried: from ...main.Text_Generator import *. This raise an error: "attempted relative import beyond top-level package" And from main.Text_Generator import *, also error "No module named 'main'" What is the correct way to do such import? -
How save edit form in multilanguage project
I'm studying Django from the book Django 2 by Examples. I'm trying to improve a project which starts in chapter 10. Now, I'm trying to add multilingualism with the help of "django-parler". In general I did it, but it seems to me that there are better ways. Views are implemented as classes that are inherited from mixins. If a language other than the default language is selected on the page, the form still comes with the value of laguage_code field equal to default. I tried unsuccessfully to change this field in the form_valid method. The form was still saved with the default language. The only option that works for me is this, by it looks like kludge: def form_valid(self, form): language = translation.get_language() _course = form.save(commit=False) try: course = Course.objects.get(pk=_course.id) except Course.DoesNotExist: course = Course() course.owner = self.request.user course.set_current_language(language) cd = form.cleaned_data course.subject = cd['subject'] course.title = cd['title'] course.slug = cd['slug'] course.overview = cd['overview'] course.save() return redirect(reverse('courses:manage_list')) Maybe someone knows a more elegant way to implement this? I will be grateful. -
POST from Python file to Database in Django
I am developing an application in Django which uses machine learning. For now, I have trained the model and have created a list in views.py . However, I would like to POST the prediction from the file to the database. I've checked many tutorials and even StackOverflow, but I haven't got a satisfactory answer. Here is my views.py: from django.shortcuts import render from django.views.decorators.csrf import csrf_exempt from rest_framework.parsers import JSONParser from core.models import Churn from core.serializers import ChurnSerializer from django.http.response import JsonResponse import pickle # Create your views here. #GET, POST, PUSH, DELETE methods defined u/csrf_exempt def churnApi(request,id=0): if request.method=='GET': churns = Churn.objects.all() churns_serializer = ChurnSerializer(churns, many=True) return JsonResponse(churns_serializer.data, safe=False) elif request.method=='POST': churn_data=JSONParser().parse(request) churns_serializer = ChurnSerializer(data=churn_data) if churns_serializer.is_valid(): churns_serializer.save() return JsonResponse("Added Successfully!", safe = False) return JsonResponse("Failed to Add", safe=False) elif request.method=='PUT': churn_data = JSONParser().parse(request) churn=churns.objects.get(ModelPred=churn_data['ModelPred']) churns_serializer=ChurnSerializer(churn,data=churn_data) if churns_serializer.is_valid(): churns_serializer.save() return JsonResponse("Updated successfully", safe=False) return JsonResponse("Failed to update", safe=False) elif request.method=='DELETE': churn=Churn.objects.get(ModelPred=id) churn.delete() return JsonResponse("Deleted successfully", safe=False) #Render frontend from folder def front(request): context = { } return render(request, "index.html", context) #Prediction generated by Machine Learning model def result(request): cls = pickle.load('churn_model.sav') lis = [] lis.append(request.GET['0']) lis.append(request.GET['1']) lis.append(request.GET['29.85']) lis.append(request.GET['29.85']) lis.append(request.GET['0']) lis.append(request.GET['1']) lis.append(request.GET['0']) lis.append(request.GET['0']) lis.append(request.GET['0']) lis.append(request.GET['1']) lis.append(request.GET['1']) lis.append(request.GET['1']) lis.append(request.GET['0']) lis.append(request.GET['0']) lis.append(request.GET['1']) … -
HTMX infinite-scroll cards changing shapes after scrolling
i'm trying to use htmx's infinite scroll but it doesn't work properly <body> <div class="container"> {% block content %} <div {% if products.has_next %} hx-get="?page={{ products.next_page_number }}" hx-trigger="revealed" hx-swap="afterend" {% endif %} > {% include 'includes/cards.html' %} </div> {% include 'includes/sidebar.html' %} {% endblock content %} </div> </body> when i scrolled down product cards sliding to right slightly and gets smaller on mobile like this and this: to this : can you guys help me understand what im doing wrong please? i also tried https://infinite-scroll.com/ its perfectly working. Edit: views.py def shop(request): anabanner = AnaBanner.objects.all() gender = Gender.objects.all() categories = Category.objects.all() colors = Color.objects.all() materials = Material.objects.all() query = request.GET.get('query','') products = Product.objects.all().order_by('-pk') if query: products = products.filter( Q(name__icontains=query)| Q(sub_name__icontains=query) ).distinct() paginator = Paginator(products, 8) page = request.GET.get('page') cards.html {% load static %} {% block content %} <body> {% for product in products %} <div class="product-card"> <a href="{% url 'productpage' product.slug %}"><div class="main-images"> <img id="black" class="black active" loading="lazy" src="{{product.imageURL}}" alt="blue"> </div></a> <div class="shoe-details"> <span class="shoe_name"> <a href="{% url 'productpage' product.slug %}"><p style="display: -webkit-box;-webkit-line-clamp: 1;-webkit-box-orient: vertical;font-size: 16px; font-weight: 500; color: #161616;width: 100%;overflow: hidden;/* white-space: nowrap; */text-overflow: ellipsis;">{{product.name}}</p></a> </span> </div> <div class="price"> <span class="price_num">{{product.price|floatformat:2}}TL</span> </div> </div> {% if product.stock > 0 %} … -
Django View Not Being Called from Template Form
This is my first time using Django (and I'm a beginner in web development in general), so I'm making a very simple project. It's a "daily check-in" app, where every day I click a button to check in, and I can view the history to see days I checked in or missed. The page is very minimal right now: My problem is I can't get the buttons to connect to their functions. Following along the official documentation, my current understanding is that the Django way to handle input is to wrap elements in a <form> that POSTs to a view, which is mapped in urls.py. Snippet of home.html: <div id="buttons-container"> <form action="{% url 'checkin-checkin' %}" method="post" style="display: inline;"> {% csrf_token %} <input type="button" value="Check in"> </form> <form action="{% url 'checkin-history' %}" method="post" style="display: inline;"> {% csrf_token %} <input type="button" value="View history"> </form> </div> Snippet of views.py: def home(request: HttpRequest) -> HttpResponse: # query DB to see if user is checked in... checked_in = True # hard-coded for now return render(request, "checkin/home.html", context={ "title": "Daily Check-in", "checked_in": checked_in, }) def checkin(request: HttpRequest) -> HttpResponse: print("called checkin") return home(request) # temp, just to return something def history(request: HttpRequest) -> HttpResponse: print("called history") … -
Getting None value in views.py from Ajax
I am trying to get the id of a model object of django from the template using ajax. But I cannot get the exact value of data in the views.py.I am getting a None value for id in views. Where I have done wrong? Here is my code Views.py: def is_ajax(request): return request.META.get('HTTP_X_REQUESTED_WITH') == 'XMLHttpRequest' def home(request): return render(request, 'home/home.html') def index(request): # If you have passed any data through the 'data' property #you can get it here, according to the method used. ##if is_ajax(request=request): id = request.GET.get('data') msg = testing.objects.exclude(id = id).first() # Note that we are passing the 'ajax_comments.html' template. #return render(request, 'practice.html', {'text': msg, 'id':id}) ##else: ##msg = testing.objects.last() return render(request, 'practice.html', {'text': msg, 'id': id} ) #comments = Comment.objects.all.first() #return render(request, 'practice.html', {'comments': comments}) Template: {% extends 'base.html'%} {%block head %} {%endblock%} {%block navbar %} {% endblock %} {%block navsmall %} {% endblock %} {% block header%} {% endblock %} {% block firstgrid%} {%endblock%} {%block secondgrid%} <div id = 'myTest'> {{text.text}} <br> {{id}} <button class = "asd" value="{{text.td}}">Button</button> </div> <script> $(".asd").click(function(e){ e.preventDefault(); var id = $(this).val(); $.ajax({ method: 'GET', // defaults to GET. Set POST if you like, but be aware of the CSRF token submission … -
Handle HEAD request method using gunicorn and django
Is there a way to force gunicorn to pass the handling of "HEAD" request method to a drf application? Currently, I have a view which looks similar to the code below :- @api_view(["POST", "GET", "DELETE", "PUT", "PATCH", "HEAD"]) @renderer_classes([ProxyRender]) def my_proxy_view(request, path=""): return proxy_dispatch( urljoin(settings.PROXY["ENDPOINT"], path), request, ) However, when sending a "HEAD" request to the endpoint it seems like gunicorn or Django is the one handling the response, not my view as invoking my view should yield a head result of the service behind. $ curl -I "http://localhost:8000/proxy/some-endpoint" HTTP/1.1 200 OK Server: gunicorn Date: Sat, 20 Aug 2022 15:29:57 GMT Connection: close Content-Type: application/json Allow: HEAD, POST, PUT, DELETE, GET, PATCH, OPTIONS X-Frame-Options: DENY Content-Length: 106 Vary: Cookie X-Content-Type-Options: nosniff Referrer-Policy: same-origin -
Get gzip file from endpoint, extract data and add to database improvements
I currently have a script that fires a request to an API endpoint which returns a csv.gzip file - which roughly contains 75,000 rows and 15 columns. I download this files to the webserver disk storage, unzip the file to .csv and then loop through every row and add the data into my database. Finally deleting the files saved to disk. The process currently takes between 5 and 10 minutes to complete. I'm sure there is areas of improvement but not sure how to implement them. Some of them is: Save csv data to variable rather than on disk. Bulk import the data into my database. I'm sure there are other improvements to be made, so any advice would be appreciated. response = oauth.get(realm) content = ET.fromstring(response.content) coded_string = (content.find('.//pricefile')) decoded_string = base64.b64decode(coded_string.text) with open('test.csv.gzip', 'wb') as f: f.write(decoded_string) with gzip.open('test.csv.gzip', 'rb') as f_in: with open('test.csv', 'wb') as f_out: shutil.copyfileobj(f_in, f_out) with open('test.csv') as f: reader = csv.reader(f) next(reader) for row in reader: pricing.objects.update_or_create( product_id=row[0], date=datetime.now(), defaults={ 'average_price': Decimal(row[1] or 0), 'low_price': Decimal(row[2] or 0), 'high_price': Decimal(row[3] or 0), ... }) os.remove('test.csv') os.remove('test.csv.gzip') -
Adding Labels to Chart In Javascript
I have created this bar chart in Javascript and I am trying to add the data labels into the bars, such that the bar for the count of values in "0.26<.50" displays the "0.26<.50" label. If anyone can help it would be appreciated. for(let i = 0; i < 1; i++) { Array.prototype.zip = function (other, reduce, thisArg) { var i, result = [], args, isfunc = typeof reduce == "function", l = Math.max(this.length, other.length); for (i = 0; i < l; i++) { args = [this[i], other[i]]; result.push(isfunc ? reduce.apply(thisArg, args) : args); } return result; } const debt_outstanding = Array.from(document.querySelectorAll('.debt-outstanding-data')) const total_assets = Array.from(document.querySelectorAll('.total-assets-data')) const A = total_assets.map((element) => element.innerText) const B = debt_outstanding.map((element) => element.innerText) const C = A.zip(B, function (l, r) { return (l / (l - r)) - 1; }); var result = C.reduce(function (agg, item) { var key = "other"; if (item < .25) key = "0<0.25"; if (item > .26 && item < .50) key = "0.26<.50"; if (item > .51 && item < .75) key = "0.51<.75"; if (item > .76 && item < 1) key = "0.76<1"; if (item > 1.01 && item < 1.5) key = "1.01<1.5"; if (item > … -
wsgi : error Failed to exec Python script file
im trying to deploy a Django/React app in a VPS ubuntu server When I'm trying to access site, i receive this error in Apache: [Sat Aug 20 13:55:19.688413 2022] [wsgi:error] [pid 2672328] [remote 197.1.126.187:48890] Traceback (most recent call last): [Sat Aug 20 13:55:19.688510 2022] [wsgi:error] [pid 2672328] [remote 197.1.126.187:48890] File "/home/vshell/cleverSignal/backend/config/wsgi.py", line 12, in <module> [Sat Aug 20 13:55:19.688540 2022] [wsgi:error] [pid 2672328] [remote 197.1.126.187:48890] from django.core.wsgi import get_wsgi_application [Sat Aug 20 13:55:19.688655 2022] [wsgi:error] [pid 2672328] [remote 197.1.126.187:48890] ModuleNotFoundError: No module named 'django' [Sat Aug 20 14:10:32.319045 2022] [mpm_prefork:notice] [pid 2672327] AH00169: caught SIGTERM, shutting down [Sat Aug 20 14:10:32.469913 2022] [mpm_prefork:notice] [pid 2672623] AH00163: Apache/2.4.41 (Ubuntu) mod_wsgi/4.6.8 Python/3.8 configured -- resuming normal operations [Sat Aug 20 14:10:32.469985 2022] [core:notice] [pid 2672623] AH00094: Command line: '/usr/sbin/apache2' [Sat Aug 20 14:27:08.420149 2022] [mpm_prefork:notice] [pid 2672623] AH00169: caught SIGTERM, shutting down [Sat Aug 20 14:27:08.562734 2022] [mpm_prefork:notice] [pid 2672816] AH00163: Apache/2.4.41 (Ubuntu) mod_wsgi/4.6.8 Python/3.8 configured -- resuming normal operations [Sat Aug 20 14:27:08.562796 2022] [core:notice] [pid 2672816] AH00094: Command line: '/usr/sbin/apache2' [Sat Aug 20 14:27:58.149587 2022] [wsgi:error] [pid 2672817] [remote 197.1.126.187:48912] mod_wsgi (pid=2672817): Failed to exec Python script file '/home/vshell/cleverSignal/backend/config/wsgi.py'. [Sat Aug 20 14:27:58.149702 2022] [wsgi:error] [pid 2672817] [remote 197.1.126.187:48912] mod_wsgi … -
How to convert markdown to HTML and use it directly in a HTML file in Python
I'm new in programming and currently taking the CS50W, learning to use Django to build a dynamic website I'm using Python markdown library to convert the markdonw to HTML like below #in views.py import markdown def entry(request, entry): if entry not in util.list_entries(): return render(request, "encyclopedia/error.html", { "entry": entry }) return render(request, "encyclopedia/search.html", { "entry": entry, "content": markdown.markdown(util.get_entry(entry)) }) #in search.html {% extends "encyclopedia/layout.html" %} {% block title %} {{entry}} {%endblock %} {% block body %} {{content}} {% endblock %} but the HTML only display like this(please check the image below) then I use devtool to check the source code, found that there are " " cover my content, is there any way to remove the " "? enter image description here -
How change value in SQL Django without entering in redactor
As an example i have models like this: from django.db import models class Pos(models.Model): POS_TAGS = [ ('NOUN', 'NOUN'), ('ADJ', 'ADJ'), ('NUM', 'NUM'), ('PRON', 'PRON'), ('ADV', 'ADV'), ('VERB', 'VERB'), ('CNJ', 'CNJ'), ('ADP', 'ADP'), ('PRT', 'PRT'), ('INTJ', 'INTJ'), ('MOD', 'MOD'), ('IMIT', 'IMIT'), ('AUX', 'AUX'), ('PPN', 'PPN'), ('PUNC', 'PUNC'), ('SYM', 'SYM') ] token = models.CharField(max_length=150) pos = models.CharField(max_length=150, choices=POS_TAGS, null=True, default='NOUN') and some data in Pos model: then I want to change data without entering in redactor: like this: just change the value in the main page and press ok to save -
Django & Celery: How to start a thread in AppConfig() only once?
I have a Django app iot_app with Celery and Rabbitmq, where in an app called app_users a thread is started in AppConfig(): app_users/apps.py: def start_test_thread(): th = Thread(target=mqtt_test_function, args=(), daemon=True) th.start() class AppUsersConfig(AppConfig): default_auto_field = "django.db.models.BigAutoField" name = "app_users" def ready(self): run_once = os.environ.get('CMDLINERUNNER_RUN_ONCE') print(run_once) if run_once is not None: return os.environ['CMDLINERUNNER_RUN_ONCE'] = 'True' start_test_thread() As you can see, I check if an environment variable is set to start the thread only once. This works. The thread is started only once. The problem is that when I start Celery with the command celery -A iot_app worker -l info, the thread is started twice. How can I make the thread start only once even with Celery? -
CSRF_token is not valid in djnango Ajax multiple request from same page
I'm trying to perform a OTP-based login in my project. So I have a form with email and password field in the login form and when I submit it through AJAX request I check for the email and password in the database, if the values are correct then I will send an OTP through email and display a new OTP field on the same page for Entering the OTP for verifications. Till now everything is working fine but after entering the OTP when I try to re-submit the form, I got an error csrf_token is not valid. As far as I know csrf_token is only generated on page refresh or page load but in my case the first csrf_token that was generated on page load was used in first post request. So now how can I send the second post request with same csrf_token or can I generate the new csrf_token . Code snippets are as follows; <form id="loginForm" method="post" action="send_otp"> <div class="col-12"> <label class="text-16 lh-1 fw-500 text-dark-1 mb-10">Email</label> <input id="email" type="text" name="email" placeholder="Name"> </div> <div class="col-12"> <label class="text-16 lh-1 fw-500 text-dark-1 mb-10">Password</label> <input id="password" type="password" name="password" placeholder="Password"> </div> <div id="otp_field" class="col-12"> </div> <div class="col-12"> <button type="submit" name="submit" id="send_otp" class="button … -
how to save the data using django channel to postgresql
I'm trying to save the data that send using django channel and postgresql. consumers.py async def connect(self): event = eventhubreader.EventReader() async def cb(partition, events): data = events[len(events)-1] await self.send(json.dumps({'value': data.body_as_json()})) now = datetime.now() dataFormat = {"IotData": {"temperature": data.body_as_json()["temperature"], "humidity": data.body_as_json()["humidity"]}, "MessageDate": now.strftime("%d/%m/%Y %H:%M:%S"), "DeviceId": data.body_as_json()['deviceId']} saverecord = Rawdata() saverecord.ref_waterplant = random.randint(20, 25) saverecord.created_at = dataFormat['MessageDate'] saverecord.is_live = True saverecord.save() print(dataFormat) await self.accept() models.py class Rawdata(models.Model): ref_waterplant = models.CharField(max_length=100) created_at = models.DateField() is_live = True class Meta: db_table = "rawdata" error An error occurred while receiving. The exception is SynchronousOnlyOperation('You cannot call this from an async context - use a thread or sync_to_async.'). -
Why all my images, buttons are not the same with the same css in Django and simple site?
I had a Website made previously in Html&CSS and I wanted to make a Django project with this site. I created a django app, uploaded the html & css & some images and set up this static files dir how it's correctly. But Why all my images, buttons and different things are not the same like without Django? Django somehow take the css differently? -
Direct assignment to the forward side of a many-to-many set is prohibited. Use categories.set() instead
This is my model class Post(models.Model): title = models.CharField(max_length=100, blank=False, null=False) description = models.TextField(max_length=1000, blank=True, null=True) created_by = models.ForeignKey(User, on_delete=models.CASCADE, related_name='post_created_by') categories = models.ManyToManyField(to=Category, blank=True, related_name='categories') This is my serializers class CreatePostSerializer(ModelSerializer): categories = serializers.CharField(error_messages={'required': "categories can't be blank"}) title = serializers.CharField(error_messages={'required': "title can't be blank"}) description = serializers.CharField(error_messages={'required': "description can't be blank"}) class Meta: model = Post fields= ['title','description','categories'] def create(self,validated_data): title = validated_data['title'] description = validated_data['description'] categories = validated_data['categories'] user = self.context['request'].user if (title and description): post_obj = Post.objects.create( title=title, description=description, created_by=user, categories=categories) return validated_data This is my views class CreatePostAPIView(APIView): permisssion_classes = (IsAuthenticated,) def post(self,request,*args,**kwargs): user = request.user data = request.data serializer = CreatePostSerializer(data=data, context={'request': request}) if serializer.is_valid(): serializer.save() return Response({'success' :'True','message' : 'Post created successfully','data' : serializer.data},status=200) return Response(serializer.errors,status=400) When I try to hit the API endpoint then it gives me the following error: Direct assignment to the forward side of a many-to-many set is prohibited. Use categories.set() instead Please feel free to ask me anything. Any help please, Would be very appreciated. -
NoReverseMatch at /news/python-is-cool/
im new and i need your help, can anyone tell me what i did wrong? Reverse for 'post_detail' with keyword arguments '{'slug': 'python-is-cool'}' not found. 1 pattern(s) tried: ['(?P<category_slug>[-a-zA-Z0-9_]+)/(?P[-a-zA-Z0-9_]+)/\Z'] -
Python Django - Select Choice is not Valid
When i want to save the form on a new CharFields (with Choices), Django tell me that the Selec choice is not valid. I take another Choice list which work with another models, it's work normally. Models.py: class productsdefinition(models.Model): Products = models.CharField(max_length=Lenght200, default='NA') Status = models.CharField(max_length=Lenght10, choices=Utilities_CSP.PRODENG_CHOICES) Tester = models.ForeignKey(tester, on_delete=models.CASCADE, null=True) Board = models.ForeignKey(board, on_delete=models.CASCADE, null=True) TestProgram = models.CharField(max_length=Lenght200, default='') ProgramLoad = models.ForeignKey(ProgramLoad, on_delete=models.CASCADE, null=True) ListProgramEG = Utilities_CSP.ExtractProgEG() Probecard = models.CharField(verbose_name='Probe Card',max_length=Lenght200, choices=ListProgramEG, null=True) ProgramEG = models.CharField(verbose_name='Program EG',max_length=Lenght200, choices=ListProgramEG, null=True) forms.py: class ProducDefForm(forms.ModelForm): global tempfield i = 0 tempfield = [] for var in list(vars(productsdefinition()).keys()): if i <= 1: pass elif var == "Date_added": pass elif var == "LastModified": pass elif var.find("_id") != -1: var = var.replace("_id","") tempfield.append(str(var)) else: tempfield.append(str(var)) i = i + 1 class Meta: model = productsdefinition fields = tempfield def __init__ (self, *args, **kwargs): super(ProducDefForm, self).__init__(*args, **kwargs) ListProbecard = Utilities_CSP.ExtractProgEG() self.fields['Probecard'].choices = ListProbecard So my field ProgramEG work fine, when i try to put the list (of choice) to ensure that the field Probecard work, it don't work, it tell me "Select Choice in not valid,...." Do you have any idea where can be the erorr ? In the Table of the DB ? -
Django Excell structure
I need to make an webapp that is based on excell. There should be two kind of groups one for the user which can edit and view data and one for staff which can also create data to work for the user. Each of them have restricted view, user should only see their data while staff should see everything what every user had done or other staff member changed. I cant wrap my head around about those restrictions. my login is like that class Einloggen(LoginView): template_name = 'SCHUK/Einloggen.html' fields ='__all__' redirect_authenticated_user = True def get_success_url(self): if self.request.user.groups.filter(name='Personalverwaltung').exists(): return reverse('Dashboard') else: return reverse('Schulverzeichnis', args=[self.request.user.pk]) but when it comes to display data for the staff, there I hit a wall. class Dashboard (LoginRequiredMixin, ListView): model = SchulverzeichnisTabelle template_name = 'SCHUK/Dashboard.html' context_object_name = 'Dashboard' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['Schulverzeichnis'] = SchulverzeichnisTabelle.objects.all() return context while I can list everything with Foreignkeys the data that staff creates is not listed bc a foreignkey only show one entry when I use a mtm field I get this in my template <QuerySet []> reading docs and all you cant read individual entries from a mtm only what mtm has stored How can I show each … -
Django argument type not iterable?
My models.py: from django.db import models # Create your models here. class Day(models.Model): title = models.CharField(max_length=120) items = models.ManyToManyField('Excercise',related_name='days') def __str__(self): return self.title class Excercise(models.Model): name = models.CharField(max_length=200) reps = models.IntegerField(default=0) sets = models.IntegerField(default=0) def __str__(self): return self.name My serialisers.py class ExcerciseSerializer(serializers.ModelSerializer): class Meta: model = Excercise fields = '__all__' class DaySerializer(serializers.ModelSerializer): class Meta: model = Day fields = '__all__' my views.py : class ExcerciseView(ObjectMultipleModelAPIView, viewsets.ModelViewSet): serializer_class = ExcerciseSerializer def get_querylist(self,*args,**kwargs): querylist = Excercise.objects.filter() return querylist class DayView(ObjectMultipleModelAPIView, viewsets.ModelViewSet): serializer_class = DaySerializer def get_querylist(self,*args,**kwargs): querylist = Day.objects.filter() return querylist my urls.py router = DefaultRouter() router.register('Excercise',ExcerciseView,basename='Excercise') router.register('Day',DayView,basename='Day') urlpatterns = [ path('admin/', admin.site.urls), path('', include(router.urls)),] Please try to make it simple I am just starting out learning django so its a bit confusing It displays the error File "C:\Users\User\AppData\Local\Programs\Python\Python39\lib\site-packages\drf_multiple_model\mixins.py", line 37, in check_query_data if key not in query_data: TypeError: argument of type 'Excercise' is not iterable. -
How to change the database name display in django admin site?
How to change the admin name and the database name in django admin site?