Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Kubernetes pod keeps crashing
I have a database service like so in GKE. apiVersion: v1 kind: Service metadata: annotations: kompose.cmd: C:\ProgramData\chocolatey\lib\kubernetes-kompose\tools\kompose.exe convert kompose.version: 1.26.1 (a9d05d509) creationTimestamp: null labels: io.kompose.service: taiga-db name: taiga-db spec: ports: - name: "5472" port: 5472 targetPort: 5472 selector: io.kompose.service: taiga-db This is the DB-Deployment apiVersion: apps/v1 kind: Deployment metadata: annotations: kompose.cmd: kompose convert -f docker-compose.yml kompose.version: 1.26.1 (a9d05d509) creationTimestamp: null labels: io.kompose.service: taiga-db name: taiga-db spec: replicas: 1 selector: matchLabels: io.kompose.service: taiga-db strategy: type: Recreate template: metadata: annotations: kompose.cmd: kompose convert -f docker-compose.yml kompose.version: 1.26.1 (a9d05d509) creationTimestamp: null labels: io.kompose.network/taiga: "true" io.kompose.service: taiga-db spec: containers: - env: - name: POSTGRES_DB value: taiga - name: POSTGRES_PASSOWRD value: taiga - name: POSTGRES_USER value: taiga - name: POSTGRES_HOST_AUTH_METHOD value: trust - name: PGDATA value: /var/lib/postgresql/data/pg-data image: postgres:12.3 name: taiga-db resources: {} volumeMounts: - mountPath: /var/lib/postgresql/data/ name: taigadb-data restartPolicy: Always volumes: - name: taigadb-data persistentVolumeClaim: claimName: taiga-db-data status: {} This is the deployment that connects to it apiVersion: apps/v1 kind: Deployment metadata: annotations: kompose.cmd: kompose convert -f docker-compose.yml kompose.version: 1.26.1 (a9d05d509) creationTimestamp: null labels: io.kompose.service: taiga-back name: taiga-back spec: replicas: 1 selector: matchLabels: io.kompose.service: taiga-back strategy: type: Recreate template: metadata: annotations: kompose.cmd: kompose convert -f docker-compose.yml kompose.version: 1.26.1 (a9d05d509) creationTimestamp: null labels: io.kompose.network/taiga: "true" … -
When i try to query django model by small positive integer field i get error
When i run the following code i get the error "TypeError: Field 'app' expected a number but got <AppChoices.SUK: 1>" class Category(models.Model): class AppChoices(models.Choices): ASK_EMBLA = 0 SUK = 1 --- class RentPostDetailSearializer(serializers.ModelSerializer): --- def get_posted_by_brief(self, obj: RentPost): ----- rating = 0 ratings = list(poster_profile.seller_reviews.filter( app=Category.AppChoices.SUK).values_list("rating", flat=True)) #---> issue here if ratings: rating = sum(ratings)/len(ratings) --- -
Django .py file code changes don't reflect on production server
I made a few changes in two .py files and when I transfer those files through Filezilla to my remote sides the changes in the production server don't reflect. What do I do any suggestions guys? -
i want to post data to Bonus field from a function made from the random choice of list elements
I am trying to make an api for a wheel which rotates and we get a random reward so i am using list and random function. I want to save the data in the Bonus field from the function corresponds to random choice if else condition. I have tried this. models.py class Wallet(models.Model): user = models.ForeignKey(User, null=True, related_name='wallet_mobile', on_delete=models.CASCADE) total_amount = models.FloatField(_('Total amount'), default=10) add_amount = models.FloatField(_('Add amount'), default=0) deposit_cash = models.FloatField(_('Full Add amount'),default=0) win_amount = models.FloatField(default=0) winning_cash = models.FloatField(default=0) withdraw_amount = models.FloatField(default=0) amount = models.DecimalField(_('amount'), max_digits=10, decimal_places=2, default=10) description = models.CharField(max_length=200, null=True, blank=True) Recieved_sreferral = models.CharField(max_length=200, null=True, blank=True) referral_status = models.BooleanField(null=True, blank=True) Bonus = models.FloatField(default=0) serializer.py class Bonusserializer(serializers.ModelSerializer): class Meta: model = Wallet fields = ['Bonus'] views.py @api_view(['POST']) def bonus_money(request, pk): if request.method == 'POST': qs = Wallet.objects.get(pk=pk) serializer = Bonusserializer(qs, data=request.data) if serializer.is_valid(raise_exception=True): Bonus = request.data['Bonus'] li = ['5 Rs. Entry ticket','Get Another Spin','50 Rs Bonus', '10% Discount Coupon','20% Extra Referral Bonus','5 Rs Bonus','Better luck next time','10 Rs Bonus'] x = random.choice(li) if x == li[0]: qs.Bonus = qs.Bonus + 5 qs.save() elif x == li[1]: y = 'Get Another Spin' return y elif x == li[2]: qs.Bonus = qs.Bonus + 50 qs.save() elif x == li[3]: y … -
i am unable to pass data from view.py to html templates django
My name is arslan chaudhry, currently i am working with django. In my django project i have made some filters to filter the product category wise.i have successfully display the category of products. But when i click on the category image i recived an empity page no error is dispalyed. I think data are not passing from view.py to html template.How i can fix this? the code is given below. views.py def collectionsview(request, slug): if(Category.objects.filter(slug=slug, status=0)): products=Product.objects.filter(category__slug=slug) category_name=Category.objects.filter(slug=slug).first() contex={products:"products",category_name:"category_name"} print(products) return render(request, "store/product/index.html", contex) else: return HttpResponse('This is not a valid product') html template {% extends 'store/layouts/main.html' %} {% block title %}Home{% endblock title %} {% block body %} <div class="container mt-3"> <div class="row"> <div class="col-md-12"> <h4>{{category_name}}</h4> <div class="row"> {% for item in products %} <div class="col-md-2"> <div class="card"> <a href="#"> <div class="card-body "> <div class="card-image"> <img src="{{item.imge.url}}" alt="" width="100%" height="100%"> <h4 class="text-center mt-1" style="font-size: medium; font-weight: 600;">{{item.name}}</h4> </div> <span>{{item.original_price}}</span> <span>{{item.selling_price}}</span> </div> </a> </div> </div> {% endfor %} </div> </div> </div> </div> {% endblock body %} -
Django models file field regex?
I want to be able to check if the files that are going to be uploaded through forms contain any sensitive information. Can someone please give me an idea on how I can accomplish this. This is my code. Models.py class File(models.Model): title = models.CharField(max_length=100) author = models.CharField(max_length=100) doc = models.FileField(upload_to='files/docs/', validators=[FileExtensionValidator(allowed_extensions=['pdf','docx'])]) def __str__(self): return self.title My upload code in views.py def upload_file(request): if request.method == 'POST': form = FileForm(request.POST, request.FILES) #request.Files handles file uploads if form.is_valid(): form.save() file_dlp() return redirect('file_list') else: form = FileForm() return render(request, 'upload_file.html', { 'form':form }) -
Why does my Fpl loop not showing up instead, React code not updating
I changed it to FPLLoop, but it still shows the same thing in the typography. Please help. For some reason nothing updates even after I save it. Is there some reason with react.js. import React, { Component } from "react"; import RoomJoinPage from "./RoomJoinPage"; import CreateRoomPage from "./CreateRoomPage"; import Room from "./Room"; import { Grid, Button, ButtonGroup, Typography } from "@material-ui/core"; import { BrowserRouter as Router, Switch, Route, Link, Redirect, } from "react-router-dom"; export default class HomePage extends Component { constructor(props) { super(props); this.state = { roomCode: null, }; this.clearRoomCode = this.clearRoomCode.bind(this); } async componentDidMount() { fetch("/api/user-in-room") .then((response) => response.json()) .then((data) => { this.setState({ roomCode: data.code, }); }); } renderHomePage() { return ( <Grid> <Grid item xs={12} align="center"> <Typography variant="h3" compact="h3"> FPLloop </Typography> </Grid> <Grid item xs={12} align="center"> <ButtonGroup disableElevation variant="contained" color="primary"> <Button color="primary" to="/join" component={Link}> Join a Room </Button> <Button color="secondary" to="/create" component={Link}> Create a Room </Button> </ButtonGroup> </Grid> </Grid> ); } clearRoomCode() { this.setState({ roomCode: null, }); } #Rendered it can't fit as too much code, but the react is the problem It says house party instead -
Why Django can’t update date?
I practiced writing the update function(update)of Pytohn+Django ModelForm. But I have been catching bugs for many days, I still can't think of what went wrong... I came to ask you what is the error? Thank you for your advice. Attach the structure and url of MTV with form writing and pictures Model: `class TaskList(models.Model): task = models.CharField(max_length=200) priority = models.PositiveIntegerField(default=0) status = models.PositiveIntegerField(default=0) user = models.CharField(max_length=50) worker = models.CharField(max_length=50, null=True, blank=True) timestamp = models.DateTimeField(default=timezone.now) start_date = models.DateField(null=True, blank=True) finish_date = models.DateField(null=True, blank=True) def __str__(self): return self.task` Templates: `{% block main %}` `<form action="/edittask/" method="POST">` `{% csrf_token %}` `<table class="table table-striped">` `<tr>` `<td align=right>TaskItem</td>` `<td><input type=text name="task" size=100 value='{{target_edit.task}}' required></td>` `</tr>` `<tr><td> </td><td>` `<input type=submit value="Update" class="btn btn-primary">` `</td></tr>` `</table>` `</form>` `{% endblock %}` Views: `@login_required(login_url='/admin/login/') def edit_task(request,id=1): tasks = TaskList.objects.get(id=id) logged_user = User.objects.get(username=request.user.username) logged_user = UserProfile.objects.get(user=logged_user) form = TaskListEdit(instance=tasks) if request.method=='POST': form = TaskListEdit(request.POST,instance=tasks) print(form) if form.is_valid(): form.save() return redirect("/tasklist/") try: target_edit = TaskList.objects.get(id=id) except: return redirect("/tasklist/") return render(request,"edit_task.html",locals())` Url `urlpatterns = [ path('edittask/',views.edit_task), path('edittask/<int:id>/',views.edit_task), path('', views.index), ]+static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT) forms: class TaskListEdit(ModelForm): class Meta: model = TaskList fields = ['task']` forms `class TaskListEdit(ModelForm): class Meta: model = TaskList fields = ['task']` enter image description here enter image description here enter image … -
Creating slug in my django model gives error: IntegrityError at /admin/blog/post/add/
I have this Django module (below), it creates a field called slug that is a slug of the model name and date: from django.db import models from django.utils.text import slugify class chessed (models.Model): name = models.CharField(max_length=60) type = models.CharField(max_length=20, choices=(('Gemach', 'Gemach'),('Organization', 'Organization'),)) description = models.CharField(max_length=750) picture = models.URLField(max_length=200, default="https://i.ibb.co/0MZ5mFt/download.jpg") slug = models.SlugField(unique=True, default=slugify(name), editable=False) When I try to create a new object from this item in my admin portal, tho, I get this error: IntegrityError at /admin/blog/post/add/ UNIQUE constraint failed: blog_post.slug More: Environment: Request Method: POST Request URL: http://127.0.0.1:8000/admin/blog/post/add/ Django Version: 4.0.1 Python Version: 3.10.1 Installed Applications: ['info.apps.InfoConfig', 'blog.apps.BlogConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "C:\Users\user1\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\backends\utils.py", line 85, in _execute return self.cursor.execute(sql, params) File "C:\Users\user1\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\backends\sqlite3\base.py", line 416, in execute return Database.Cursor.execute(self, query, params) The above exception (UNIQUE constraint failed: blog_post.slug) was the direct cause of the following exception: File "C:\Users\user1\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\user1\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\user1\AppData\Local\Programs\Python\Python310\lib\site-packages\django\contrib\admin\options.py", line 622, in wrapper return self.admin_site.admin_view(view)(*args, **kwargs) File "C:\Users\user1\AppData\Local\Programs\Python\Python310\lib\site-packages\django\utils\decorators.py", line 130, in _wrapped_view response = view_func(request, *args, **kwargs) File "C:\Users\user1\AppData\Local\Programs\Python\Python310\lib\site-packages\django\views\decorators\cache.py", line 57, in _wrapped_view_func response … -
Getting Error while trying to get the value of the many to many field in django
models.py class Organisation(models.Model): """ Organisation model """ org_id = models.AutoField(unique=True, primary_key=True) org_name = models.CharField(max_length=100) org_code = models.CharField(max_length=20) org_mail_id = models.EmailField(max_length=100) org_phone_number = models.CharField(max_length=20) org_address = models.JSONField(max_length=500, null=True) product = models.ManyToManyField(Product, related_name='products') org_logo = models.ImageField(upload_to='org_logo/') created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: db_table = "organisation_master" def __str__(self): return self.org_name serializers.py class Organisation_Serializers(serializers.ModelSerializer): product_name = serializers.CharField(source='product.product_name') class Meta: model = Organisation fields = ('org_id', 'org_name', 'org_address', 'org_phone_number', 'org_mail_id','org_logo','org_code','product','product_name') While i tried to get the value of the product name iam getting an error as "Got AttributeError when attempting to get a value for field product_name on serializer Organisation_Serializers. The serializer field might be named incorrectly and not match any attribute or key on the Organisation instance. Original exception text was: 'ManyRelatedManager' object has no attribute 'product_name'. Can you please help me to fix this issue.Posting the traceback error. Request Method: GET Request URL: http://127.0.0.1:8000/api/onboarding/organisation/ Django Version: 3.2.12 Exception Type: AttributeError Exception Value: Got AttributeError when attempting to get a value for field `product_name` on serializer `Organisation_Serializers`. The serializer field might be named incorrectly and not match any attribute or key on the `Organisation` instance. Original exception text was: 'ManyRelatedManager' object has no attribute 'product_name'. Exception Location: C:\Users\gobs4\AppData\Local\Programs\Python\Python310\lib\site-packages\rest_framework\fields.py, line 490, in get_attribute … -
Django-disqus: manage.py not accepting API key
I'm trying to integrate disqus into my Django app. I got the API key and put it in settings.py, but when I tried to start the local server, it is giving me an error. settings.py INSTALLED APPS = [ ... 'disqus', ] DISQUS_API_KEY = 'key' DISQUS_WEBSITE_SHORTNAME = 'website_shortname' Of course I've put the actual key and shortname. The error I'm getting: NameError: name 'key' is not defined help -
Is there a third-party authentication system for Django?
We are trying to integrate a Django application with an OpenID Connect (OIDC) provider as a Relying Party. The provider isn't a major vendor, and thus doesn't have custom-built packages, so we are leveraging Authlib. This works, but I'm stressed about the amount of custom code we are having to put in to manage the session and redirects and whatnot. I have experience in the Ruby and Node.js worlds, and those communities have the general-purpose authentication tools OmniAuth and Passport, respectively. Is there an equivalent for Django? Closest I've found is mozilla-django-oidc, which I may try — curious if there are others I'm missing. Thanks! -
Bulk import with mptt and Django
I have the following code to take data from a very large csv, import it into a Django model and convert it into nested categories (mptt model). with open(path, "rt") as f: reader = csv.reader(f, dialect="excel") next(reader) for row in reader: if int(row[2]) == 0: obj = Category( cat_id=int(row[0]), cat_name=row[1], cat_parent_id=int(row[2]), cat_level=int(row[3]), cat_link=row[4], ) obj.save() else: parent_id = Category.objects.get(cat_id=int(row[2])) obj = Category( cat_id=int(row[0]), cat_name=row[1], cat_parent_id=int(row[2]), cat_level=int(row[3]), cat_link=row[4], parent=parent_id, ) obj.save() It takes over an hour to run this import. Is there a more efficient way to do this? I tried a bulk_create list comprehension, but found I need parent_id = Category.objects.get(cat_id=int(row[2])) to get mptt to nest correctly. Also, I think I have to save each insertion for mptt to properly update. I'm pretty sure the parent_id query is making the operation so slow as it has to query the database for every row in the CSV (over 27k rows). The upside is this operation will only need to be done sporadically, but this dataset isn't so large that it should take over an hour to run. -
How do I add cropperjs to my django project
I am working on a django project that requires adding a profile picture and that works; but where the problem comes in is that when someone uploads a picture that is quite long or quite wide, the profile image display would look weird. I tried initializing basic cropperjs by adding this to my base.html <link rel="stylesheet" href="{% static 'cropperjs/dist/cropper.min.css' %}"> <script type="module" src="{% static 'cropperjs/dist/cropper.min.js' %}"> and i just wanted to follow the docs and i kept my edit-profile.html {% block content %} <div class="image-box"> <img src="{{ request.user.userprofile.profile_image.url }}" id="image" width="300px"> </div> {% endblock %} and my edit-profile.js console.log('Hello there') var $image = $('#image'); $image.cropper({ aspectRatio: 16 / 9, crop: function(event) { console.log(event.detail.x); console.log(event.detail.y); console.log(event.detail.width); console.log(event.detail.height); console.log(event.detail.rotate); console.log(event.detail.scaleX); console.log(event.detail.scaleY); } }); var cropper = $image.data('cropper'); but then when i runserver and i inspect the page, i see the error edit_profile.js:3 Uncaught ReferenceError: $ is not defined at edit_profile.js:3:14 so i tried creating a normal html file and linked it with a javascript file an then tried to initialize cropper. index.html <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" type="text/css" href="forum/static/cropperjs/dist/cropper.css"> <meta http-equiv="Access-Control-Allow-Origin" content="*"/> <title>Test site</title> </head> <body> <div class="image-box"> <img src="yor.png" id="image" width="300px"> </div> <script type="text/javascript" … -
How to get all manytomany objects in a queryset of objects
I have a model Department which has Roles which Users are linked to. I know the user, but need to get the user.role.department_set.all() (all departments the user's role belong to) and then get all the roles in each of those departments. Models: class User(AbtractUser): role = models.ForeignKey(Role) class Role(models.Model): name = models.CharField() class Department(models.Model): name = models.CharField() roles = models.ManyToManyField() How can I get all the departments which contains the user's role, then get the roles of all those departments? I am doing something like this currently but it is a very expensive lookup: def get_departments(self): """Returns a list of departments the user is in.""" return self.role.department_set.all() def get_users_departments_roles(self): """Returns all the roles of all the departments the user is in.""" departments = self.get_departments() roles = Role.objects.none() for department in departments.iterator(): for role in department.roles.all(): roles |= Role.objects.filter(name=role.name) return roles Side question: After typing all this out, would it be better to just add the a department field to each user? My concern is that if a role changes, I will also have to change the department at the same time and it will add complexity. -
gunicorn.service: Failed execute command: No such file or directory
I change my gunicorn.service from : /var/www/django/myprojectdir/myprojectenv/Scripts/gunicorn \ ... to : /var/www/django/myprojectdir/myprojectenv/bin/gunicorn \ ... then i get this error : gunicorn.service: Failed to execute command: No such file or directory gunicorn.service: Failed at step EXEC spawning /var/www/django/myproject/myprojectenv/Scripts/gunicorn: No such file or directory i already do sudo systemctl daemon-reload sudo systemctl restart gunicorn but, still the same error -
Can I ask for a workaround about Django's static files?
This is a web made from django framework, but I am getting error that static file is not receiving transmission. I followed VScode and Djangoproject's instructions but I still can't fix it Image 1: https://i.stack.imgur.com/l8zRO.png Image 2: https://i.stack.imgur.com/Yh92p.png -
django + postgres return None though Zero
I have column : basic_flg = models.SmallIntegerField('Basix flag', null=True, blank=True) Values in database are Null, 0 or 1. I get one and it return None though in database is 0. Please help me ! Dis i missed configuration ? -
VS Code Auto Import Not Working Dockized Django Application
I have set up a Django Application on a Docker container locally. It runs and can be accessed on the browser on port 8000. However the issue is when I opened the Django Dockerized App in VS Code and tried to write viewsets, serializers and for that I expect VS Code should auto-import them from Django/DRF libraries path, but VS Code neither hints and nor auto-import any of the Django/DRF/Django_Model_Utils. I have tried all the options on this thread but the auto-import doesn't work for dockerized django app when container is opened in VS Code. Even I am able to manually import the Django/DRF modules classes and when ctrl + click, it bring me to the specified class. But when I write like class UserViewSet(serilizers and press ctrl + space, it says not doesn't show in the list. python path on container: /usr/local/bin/python django/drf installed path on container: /usr/local/lib/python3.9/site-packages I use these path in the settings like this: { "python.languageServer": "Default", "python.defaultInterpreterPath": "/usr/local/bin/python", "python.analysis.extraPaths": [ "/usr/local/lib/python3.9/site-packages", ], "python.autoComplete.extraPaths": [ "/usr/local/lib/python3.9/site-packages", ], } The container user is the root, all the packages installed in the above-given path are installed by root and obviously the server process of VS Code will also … -
Templates do not show image. Django
Here is what i tried to do: in my settings.py: TEMPLATES = [ ... 'OPTIONS': { 'context_processors': [ ... 'django.template.context_processors.media', ], }, }, ] MEDIA_ROOT = os.path.join(BASE_DIR, 'img') MEDIA_URL = '/img/' i have also added this in my main urls.py: static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) And here's the code in my template: <img src="{{ product.image.url }}" alt="Not available" height="188px" style="margin: 10px 0" width="188px" /> -
Cant get to remove and add watchlists on an e-commerce site
When i click on the buttons 'Remove watchlist' or 'Add watchlist', the listing goes blank but it does not get deleted or added in my models nor redirects to the url i wrote. I think something is wrong in the watchlist function but idk what. def listing(request, listing_id): listing = Listing.objects.get(pk=listing_id) watchlist = Watchlist.objects.filter(listing=listing_id, user=User.objects.get(id=request.user.id)).first() if watchlist is not None: on_watchlist = True else: on_watchlist = False if request.user.is_authenticated: bids = Bid.objects.filter(listing=listing) max_bid = bids[0].bid for bid in bids: if bid.bid > max_bid: max_bid = bid.bid if listing.price > max_bid: max_bid = listing.price return render(request, "auctions/listing.html", { "listing": listing, "on_watchlist": on_watchlist, "bids": bids, "max_bid": max_bid }) def watchlist(request): if request.method == "POST": listing_id = request.POST.get(int("listing_id")) listing = Listing.objects.get(pk=listing_id) user = User.objects.get(id=request.user.id) if request.POST.get("remove") == "True": watchlist_delete = Watchlist.objects.filter(user=user, listing=listing).first() watchlist_delete.delete() else: watchlist_add = Watchlist(user=user, listing=listing) watchlist_add.save() return HttpResponseRedirect(reverse('listing_id', args=(listing_id,))) This is the HTML form: <form action="{% url 'watchlist' %}" action="POST"> {% csrf_token %} {% if on_watchlist %} <input type="submit" value="Remove from watchlist"> <input type="hidden" name="remove" value="True"> {% else %} <input type="submit" value="Add to watchlist"> <input type="hidden" name="add" value="False"> {% endif %} <input type="hidden" name="listing_id" value="{{ listing.id }}"> </form> -
How do you pass the value of user_type (in CustomUser model) passed to a model form?
I have gone through many Q&As in SO and tried out various solutions. But I'm not sure whether the issue is with the form (CustomUserForm or StaffCreateForm--neither solves this problem), the view, or the way the user_type is set up. Any pointer is greatly appreciated. The CustomUser model lists 3 user_types. The form displays a dropdown menu with the 3 choices. Regardless of my choice, I get an error: Select a valid choice. 2 is not one of the available choices. How do I pass the value to be saved by the form? #models.py class CustomUser(AbstractUser): user_type_data = ((1, "HOD"), (2, "Staff"), (3, "Student")) user_type = models.CharField(default=1, choices=user_type_data, max_length=10) #views.py class StaffCreateView(CreateView): model = Staff form_class = StaffCreateForm context_object_name = 'staff' success_url = reverse_lazy('staff_list') #forms.py class CustomUserCreateForm(UserCreationForm): class Meta: model = CustomUser fields = UserCreationForm.Meta.fields fields = ('user_type', 'username', 'email', 'first_name', 'last_name', 'subject') subject = forms.ModelMultipleChoiceField( queryset=Subject.objects.all(), widget=forms.CheckboxSelectMultiple ) class StaffCreateForm(CustomUserCreateForm): model = Staff def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['subject'].queryset = Subject.objects.all() self.fields['user_type'].initial = "2" When I used "Inspect Elements" in the browser, the choice field looks right: <select name="user_type" class="select" id="id_user_type"> <option value="1">HOD</option> <option value="2" selected="">Staff</option> <option value="3">Student</option> </select> <option value="1">HOD</option> <option value="2" selected="">Staff</option> <option value="3">Student</option> <select name="user_type" … -
Django Building
Do you Think the best way to use DJANGO is to use it to build a REST API and use front-end frameworks like { react vuejs or any js liberary } or build a back-end with Html front-end what is the the famous way in companies -
Query MongoDB to fetch a nested array with skip/limit by nested object key range in Django using pymongo
I am learning Django with pymongo. I have a MongoDB collection where I am storing some words and their year-wise occurrences in some books. The documents are stored in MongoDB in the following format: { "_id":{ "$oid":"625c51eec27c99b793074501" }, "word":"entropy", "occurrence":13, "year":{ "1942":[ { "book":{ "$oid":"625c51eec27c99b7930744f9" }, "number":8, "sentence":[ 1, 288, 322, 1237, 2570, 2585, 2617, 2634 ] } ], "1947":[ { "book":{ "$oid":"625c5280c27c99b793077042" }, "number":5, "sentence":[ 377, 2108, 2771, 3467, 3502 ] } ] } } Now I want to get the list of the sentences with skip and limit (and the respective book id) queried by _id and for specific year range. For example, I want to fetch an array where each row will be a dictionary containing 'year', 'book' and 'sentence'. The array will be queried by the _id and year range. A skip and limit will be applied on the sentence list Is this a possible task using Django and pymongo? If yes, what is the fastest method? So far I have done this: search= {'$and': [{"_id": word_id_obj, "year.1942": {"$exists": 1}}]} datalist= [] word_docs= wordcollec.find(search, {'year': 1, '_id': 0}).skip(1).limit(5) sentlist['recordsFiltered']+= wordcollec.count_documents(search) for b in word_docs: year_data= b['year'][1942] for by in year_data: i= i+1 this_word= {'serial': i, 'year': … -
Django filter objects by Many-To-Many field intersection
Hello, Can some good person give me advice on how to get a queryset of ordered objects by intersecting a many-to-many field with a given one object's many-to-many field? For example I have: class Video(models.Model): tags = models.ManyToManyField(Tag, blank=True) ... class Tag(models.Model): name = models.CharField(max_length=64) ... I select one Video object and would like to have first ten objects that have most similar tags set to show like related videos. Thanks in advance!