Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how would I allow only registered users to post in the site
I am creating a website where user is posting his information in the site, the problem am facing is that even when I have logged out still I can post. I want only registered and logged in users to be able to post in the site This is for python 3.7.3, django 2.2.3, mysql 5.7.26, I want to post only when am logged in unfortunately I can post in both ways, when am logged in and logged out, which means anybody can post even if he/she not a registered user views.py def PostNew(request): if request.method == "POST": form = PostForm(request.POST) if form.is_valid(): post = form.save(commit=False) post.author = request.user post.save() return redirect('loststuffapp:IndexView') else: form = PostForm() return render(request, 'loststuffapp/form.html', {'form': form}) models.py class Documents(models.Model): docs_name = models.CharField(max_length=200) item_type = models.CharField(default="", max_length=100, help_text='*Enter the item name you found e.g. Marksheet,key,wallet') police_station = models.CharField(max_length=255, help_text='*Enter the police station you sending the docs') phone_no = models.IntegerField(default=0) date = models.DateTimeField(default=timezone.now) Description = models.TextField(blank=True, null=True, help_text='*Enter full description about item') pay_no = models.IntegerField(default=0) publish = models.BooleanField(default=False) image = models.ImageField(default="add Item image", upload_to="DocsImage",blank=False) """docstring for Documents""" def __str__(self): return self.docs_name home.html {% extends "loststuffapp/base.html" %} {% block content %} <a class="waves-effect waves-light btn" href="/PostNew">Add documents</a> {% for … -
Converting comma separated string to list, then display list in Django template
I'm trying to take an input that is a comma separated string value, store those items in a list for temporary display and use in a template. I'm currently having trouble storing each comma separated string value in a list, then displaying that list in a template. I have also tried both of the following in the template: {% for i in formula.inputs_list %} {{ i }} {% endfor %} and {% for i in inputs_list %} {{ i }} {% endfor %} If I'm passing inputs_list through the context, then consequently through render request, why can't I iterate over the inputs_list in the template? I also tried to strip commas then append a blank list which is close, but simply removes the commas without inputting individual items into the list. I do understand why, but I don't understand how to get items out of the input string to a lits: def test_formula(request, formula_id): formula = Formula.objects.get(id=formula_id) inputs_list = [] for inputs in formula.inputs: strip = inputs.strip(",") inputs_list.append(strip) context = {'formula': formula, 'inputs_list': inputs_list} return render(request, 'formulas/test_formula.html', context) views.py def test_formula(request, formula_id): formula = Formula.objects.get(id=formula_id) inputs_list = formula.inputs.split(",") context = {'formula': formula, 'inputs_list': input} return render(request, 'formulas/test_formula.html', context) formulas/test_formula.html {% … -
Django / Redis Paths for Celery + Cache
Do I need multiple Redis paths? I'm using Celery with Redis but also django-redis for caching. Is the right thing to do something like: Celery: redis://127.0.0.1:6379/0 Cache: redis://127.0.0.1:6379/1 Or is it normal that they use the same path? -
Django + RestFramework + twilio: Getitng status call back sid
I am trying something that I believe is so simple and I it works fine when i test my end point with postman, however when the site is up, is when i get "error" These are my current settings: twilio==6.29.1 Django==2.0.7 djangorestframework==3.9.4 Python 3.6.8 After sending an SMS with twilio: client = Client(key1,key2) message = client.api.account.messages.create( body= request.data["Body"], to= request.data["toNumber"], status_callback='https://myurl', from_= request.data["fromNumber"] ) I have set up the call back class SMSCallBack(APIView): parser_classes = (JSONParser,) def post(self, request, format=None): print(request.GET) print(request.GET.getlist('SmsSid')) return Response({'xxx': 'xxx'}) However this is my respond in the logs <QueryDict: {}> [] If I try to do the same in postman I get <QueryDict: {'SmsSid': ['asd']}> ['asd'] Now I am guessing with postman that Ihave set it correctly (POST, and add in params tab a value) as the console log from twilio is indicating that one of the multiple params they are sending is the SmsSid I am pretty new with Django and python, so perhaps is there something i am missing when trying to get the incoming parameters? -
css issues with html template while running in django server
i have bought a social media template from themforest for my django application the html template is perfect without running any server but after integrating and running the server there are some issues with the UI i have tried checking out all the static files but everything seems to be good newsfeed.html <footer id="footer"> <div class="container"> <div class="row"> <div class="footer-wrapper"> <div class="col-md-3 col-sm-3"> <a href=""><img src="{% static 'images/logo-black.png' %}" alt="" class="footer-logo" /></a> <ul class="list-inline social-icons"> <li><a href="#"><i class="icon ion-social-facebook"></i></a></li> <li><a href="#"><i class="icon ion-social-twitter"></i></a></li> <li><a href="#"><i class="icon ion-social-googleplus"></i></a></li> <li><a href="#"><i class="icon ion-social-pinterest"></i></a></li> <li><a href="#"><i class="icon ion-social-linkedin"></i></a></li> </ul> </div> <div class="col-md-2 col-sm-2"> <h5>For individuals</h5> <ul class="footer-links"> <li><a href="">Signup</a></li> <li><a href="">login</a></li> <li><a href="">Explore</a></li> <li><a href="">Finder app</a></li> <li><a href="">Features</a></li> <li><a href="">Language settings</a></li> </ul> </div> <div class="col-md-2 col-sm-2"> <h5>For businesses</h5> <ul class="footer-links"> <li><a href="">Business signup</a></li> <li><a href="">Business login</a></li> <li><a href="">Benefits</a></li> <li><a href="">Resources</a></li> <li><a href="">Advertise</a></li> <li><a href="">Setup</a></li> </ul> </div> <div class="col-md-2 col-sm-2"> <h5>About</h5> <ul class="footer-links"> <li><a href="">About us</a></li> <li><a href="">Contact us</a></li> <li><a href="">Privacy Policy</a></li> <li><a href="">Terms</a></li> <li><a href="">Help</a></li> </ul> </div> <div class="col-md-3 col-sm-3"> <h5>Contact Us</h5> <ul class="contact"> <li><i class="icon ion-ios-telephone-outline"></i>+1 (234) 222 0754</li> <li><i class="icon ion-ios-email-outline"></i>info@thunder-team.com</li> <li><i class="icon ion-ios-location-outline"></i>228 Park Ave S NY, USA</li> </ul> </div> </div> </div> </div> <div class="copyright"> <p>Thunder Team © 2016. All … -
DRF: customize PrimaryRelatedField
DRF renders a foreign key with PrimaryKeyRelatedField by default and it is represented as a single pk. class Foo(models.Model): bar = models.ForeignKey('Bar') def FooSerializer(serializers.ModelSerializer): class Meta: model = Foo fields = [ 'id', 'bar' ] FooSerializer(foo_instance).data looks like { 'id': 3, 'bar': 5, } I'd like it to become { 'id': 3, 'bar': { 'id': 5 }, } Not just for Foo/Bar, but for whole project -
How to fix 'Image Source Url is missing' issue when using Django CkEditor
I installed djnago-ckeditor and followed the installation guide.Using RichTextUpload() for my models which are imported from ckeditor_uploader.When I try to upload an image it is saying that 'Image Source Url is missing'. I'm using python, django latest versions basesettings.py INSTALLED_APPS=[ ...... 'ckeditor', 'ckeditor_uploader', ] CKEDITOR_UPLOAD_PATH = os.path.join(BASE_DIR, MEDIA_ROOT, 'ckeditor_media') CKEDITOR_JQUERY_URL = '//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js' CKEDITOR_IMAGE_BACKEND = 'pillow' CKEDITOR_CONFIGS = { 'default': { 'toolbar': 'full', 'height': 300, 'width': '100%', }, } urls.py path('ckeditor/', include('ckeditor_uploader.urls')), models.py from ckeditor_uploader.fields import RichTextUploadingField ...Model about = RichTextUploadingField() -
Ajax with primary key in url of Django cannot work
all, i am using Django to do a social website and now i am trying to do friend network. The problem i encountered now is when i am using ajax to pass user id in url and it throw url cannot be found error, maybe see code the will be much clearer. the code is as following i tried to take awayid, that is , take away all id in ajax, url, and method, then it can work. but if i add id parameter in, then it cannot work html template <button class="add-friend-btn" id="add-friend"> Add friend <script src="{% static 'account/js/friends.js'%}" type="text/javascript" ></script> <script type="text/javascript"> var userprofilePk = "{{userprofile.pk}}"; // other user's id(primary key) </script> {% endif %} javascript friend.js $(document).ready(function() { var addFriend = document.getElementById('add-friend'); addFriend.addEventListener("click", function (event) { $.ajax({ type: 'POST', headers: { "X-CSRFToken": csrftoken }, url: "ajax/friend-request/send/"+userprofilePk+"/", data: { "test": "test", }, dataType: 'json', success: function (data) { }, error: function (error) { }, }); }); }); Django url urlpatterns = [ re_path("ajax/friend-request/send/<pk>/", views.send_friend_request, name="user_send_request"), ] views.py def send_friend_request(request, id): print("send_friend_request") payload = {"test": "test"} return HttpResponse(json.dumps(payload), content_type='application/json') the error message is: Not Found: /account/profile/sm10547/ajax/friend-request/send/2/ app_1 | HTTP POST /account/profile/sm10547/ajax/friend-request/send/2/ 404 [0.01, 172.18.0.1:38852] -
How to test email confirmation?
I'm trying to make a test for the email confirmation view with django-rest-auth. Here is what I have: def test_verify_email(self): # Verify email address username = 'userTest' payload = { 'email': 'test@example.com', 'password1': 'TestpassUltra1', 'password2': 'TestpassUltra1', 'username': username, } res = self.client.post(REGISTER_USER_URL, payload) self.assertEqual(res.status_code, status.HTTP_201_CREATED) user = get_user_model().objects.get(email='test@example.com') # TODO retrieve the confirmation key from the user resp = self.client.post(VERIFY_USER_URL, {'key': ''}) self.assertEqual(resp.status_code, status.HTTP_200_OK) self.client.post(REGISTER_USER_URL, payload) will send an email with the confirmation code in it and while I know I could retrieve that code with django.core.mail.outbox in the code I rather not do that as I will have to parse the email content to look for the confirmation code (which can kill my test if the email changes). I couldn't find this code stored anywhere in the DB, it seems to really exist only inside the body of the email sent. My question is: Is it possible to recover this verification code in my test without parsing the email? I just want to retrieve it to launch my self.client.post(VERIFY_USER_URL, {'key': ''}) with it. Here is the example of the content of an email: Hello from example.com! You're receiving this e-mail from NomadSpeed because user detro1 has given yours as … -
Neo4j + Django: Where do I write the top-level Driver object?
It is written in the documentation that For general applications, it is recommended to create one top-level Driver object that lives for the lifetime of the application. For example: from neo4j import GraphDatabase class Application(object): def __init__(self, uri, user, password) self.driver = GraphDatabase.driver(uri, auth=(user, password)) def close(self): self.driver.close() Where do I write this code? I want to use neo4j as a database in views.py. -
How do you find the source of a related_name in Django in large codebases?
Take these two models for example (pseudo code) class House(): Pass class Cat(): house = Foreignkey(to=House, related_name=“cats”) Now say if this is a massive codebase that I’m not familiar with with these definitions in different files. I see an instance of House being called with the method “cats” house1.cats And I want to investigate and see where cats came from. But when I go to the definition of House, there is no mention of cats. There is no way I can figure this out just by looking at House, and names are not always as simple to follow as this example(sometimes the related name is not similar to the class name). I do use fuzzy finding and search for related_name=cat In the codebase and that usually works, but it does not work for models where the related_name was generated through an base class such as class Base(models.Model): m2m = models.ManyToManyField( OtherModel, related_name="%(app_label)s_%(class)s_related", related_query_name="%(app_label)s_%(class)ss", ) It’ll be basically impossible to figure out what model is the source of relation other than hunting it down manually by looking at every single file, which is quite difficult in a large codebase My question is, is there a way or workflow to figure this … -
Django @login_required causing issue when submitting forms
I am passing a some information to view function by submitting a form and view requires has @login_required decorator. Here is the template where i'm passing email ID using a from <form action="{% url 'become_booster' %}" method="post"> {% csrf_token %} <input type="hidden" name="email" value="{{ profile_user.email }}" /> <div class="form-group"> <div class="col-md-12 col-sm-12"> <input type="submit" class="btn btn-success btn-sm" value="Become a Booster"> </div> </div> </form> Here is the view function @login_required def become_booster(request): if request.method == "POST": email = request.POST.get('email') user = CustomUser.objects.filter(email= email)[0] tiers = Tiers.objects.filter(user=user) form = SubscriptionForm return render(request,'select_tier.html',{'tiers':tiers,'form':form}) This is working fine when the user logedin already. When user didn't login, @login_required sends them to login and when it comes back request.method is no longer POST. It no longer has that email info. Can someone help me with this. Thanks! -
django-summernote: how to get the created object by django?
I have a django form with a SummernoteInplaceWidget() and the summernote editor is correctly created. But i need to execute the following command to the editor: $('#summernote').summernote('editor.insertText', 'hello world'));, like the documentation (https://summernote.org/deep-dive/#basic-api). But this command doesn't work. I've tried this: $('#id_content').summernote('editor.insertText', 'hello world'); but other editor was created. I need to insert the text in the first editor that was created by django-summernote and don't create anymore. There is my form: class ParagrafoForm(ModelForm): content = forms.CharField(widget=SummernoteInplaceWidget()) There is my settings.py: SUMMERNOTE_CONFIG = { 'iframe': False, 'lang': 'pt-BR', 'toolbar': [ ['style', ['bold', 'italic', 'underline', 'strikethrough']], ['script', ['superscript', 'subscript']], ['clear', ['clear']], ['font', ['fontname', 'color']], ['para', ['ul', 'ol', 'paragraph', 'height']], ['table', ['table']], ['view', ['fullscreen', 'codeview', 'help']], ], 'disable_attachment': True, 'summernote': { 'width': '100%', 'height': '480', }, } In my template I've: {{ form.content|safe }} So, how to insert text in editor without creating anymore? Or how get the element in javascript to do this? Which's the identificator for the django-summernote created object? -
Views function: saving a form field value into the profile model attribute
I am writing a code for my views function in a django app "colortest" and my Profile model is in django app "users". I want to add a form field data into the Profile Model attribute. When I save the variable I get an IntegrityError I have searched every site but I can't understand colortest/views.py from users.models import Profile def testreport(request): if request.method == "POST": test_result = request.POST.get('test_result') p = Profile(user=request.user, test_result=test_result) p.save() messages.success(request, f'Your account has been Updated!') return render(request, 'colortest/test1.html') return render(request, 'colortest/result.html') users/models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='profile_pics') bio = models.TextField(max_length=1000, default="") test_result = models.CharField(max_length=100, default="") def __str__(self): return f'{self.user.username} Profile' def save(self, *args, **kwargs): super(Profile, self).save(*args, **kwargs) img = Image.open(self.image.path) if img.height > 300 or img.width > 300: output_size = (300, 300) img.thumbnail(output_size) img.save(self.image.path) I want data to be saved in the test_result field of the Profile Model but it keep giving the error IntegrityError at /colortest/result/testreport UNIQUE constraint failed: users_profile.user_id Request Method: POST Request URL: http://127.0.0.1:8000/colortest/result/testreport Django Version: 2.2.1 Exception Type: IntegrityError Exception Value: UNIQUE constraint failed: users_profile.user_id C:\Users\Osama E.Khan\Desktop\website\colortest\views.py in testreport p.save() … ▶ Local vars C:\Users\Osama E.Khan\Desktop\website\users\models.py in save super(Profile, self).save(*args, **kwargs) -
How can i send a information in Html to Django(backend)?
How do I send a clicked link in html or selected information in the ComboBox to Django? views.py def musicList(request): musics = Song.objects.filter() print(musics) con = sqlite3.connect(str(request.user)+".db") cursor = con.cursor() cursor.execute("Select name From sqlite_master Where type='table';") tables = list() for i in cursor.fetchall(): tables.append(i[0]) context = { "musics":musics, "tables":tables, } return render(request,"musicList.html",context) musicList.html {% for music in musics %} <tr> <th scope="row">{{music.id}}</th> <td>{{music.artist}}</td> <td>{{music.song_name}}</td> <td>{{music.song_type}}</td> <td>{{music.owner}}</td> <td> <div class="dropdown"> <button type="button" class="btn btn-primary btn-sm dropdown-toggle" data-toggle="dropdown"> Choice a Music List </button> <div class="dropdown-menu"> {% for table in tables %} <a class="dropdown-item" href="add_to_list/{{music.id}}" value="{{table}}">{{table}}</a> {% endfor %} </div> </div> </td> </tr> {% endfor %} What do I do to return the value corresponding to the "value" of the link that the user clicked from the "dropdown-menu" to a different function in views.py -
Pass a element from a query using django filters between two forms
I asked this question, but i got not response probably because is a big problem so i try to figurate with baby steps. I want to pass the variable product between two forms. Like in this from block 1 to block 2. {% extends 'base.html' %} {% block content %} <div class="list-product"></div> <form method="GET"> {{ filter.form }} <button type="submit" class="btn btn-primary">Search</button> </form> <form action="" method="POST"> {% for product in filter.qs %} <input type="radio" name="product" value="{{product.name}}" unchecked> {{product.name}}<br> {% endfor %} <input type="submit" value="Add> </form> </div> <div class = "list-buy"></div> <form method="GET"> <ul> <li>{{product.name} from {{product.brand}} with cost: {{product.price}}</li> </ul> <input type="submit" name="Finish" > </form> </div> {% endblock content %} My product is modeled by: class Product(models.Model): name = models.TextField(blank=False, max_length=25) brand = models.TextField(blank=False, max_length=25) price = models.PositiveSmallIntegerField(default=200) And can be searched by brand and for price. But I get an error that i need to use csrf-token correctly. Why? -
How can I make a Model field value unique (unique=True) but only comparing it to other models from that User?
I have a Tag model, that must have a name field that needs to be unique, but only for that user's tags. So that one user can't create two 'tagname' tags, but many different users can (create a tag with the same name). The field must be unique inside the models that relate to the User. This is the Model. class User(AbstractUser): email = models.EmailField(unique=True) class Tag(models.Model): name = models.CharField(max_length=30, unique=True) user = models.ForeignKey(User, null=True, on_delete=models.CASCADE, related_name='tags') -
Show a leaflet map in a geodjango form added by javascript
I'm using Django, with PostGIS, and I have a Plant.geometry field, declared as django.contrib.gis.db.models.PointField(null=True, blank=True) I'm writing a single-page web client using bootstrap and leaflet, and the user may ask for a form to update a Plant record, this goes in a Bootstrap modal div. The form is automatically generated, based on this ModelForm class: from django import forms from django.contrib.gis import forms as geoforms class PlantForm(geoforms.ModelForm): class Meta: model = Plant fields = '__all__' widgets = { 'geometry': geoforms.OSMWidget(attrs={'map_height': 240}), } the url for this form coming from this line: path("plant/<str:code>/form/", PlantForm.as_view(), name="plant-form"), my javascript client asks for the form, then uses jQuery to put the html into the document: $(modal_form_body).empty(); $.getJSON(form_url, function(data) { $(modal_form_body).append($(data.form)); I'm having two problems, one I which solved brutally, the other for I need help, and it's the reason for my asking here. Comments on the first are welcome, too. 1: media I don't manage to put the form.media into the html, and have it used by my javascript client. So what I did was to inspect what was the value of the form.media, copy it in my static files, and refer to them in my global head element, like this: <link href="{% static … -
In Home component of react+redux app, this.props.posts is undefined after calling action getPosts() on componentdidmount
I am trying to make a blog-style application. I am running a django server and trying to make a react-redux frontend. I am using redux-devtools and when I comment out the error code, redux seems to have the data in the state. Not sure what is going wrong. Also, I am using redux-thunk and axios to communicate with the backend. I am pretty much copying from a youtube tutorial. This is the reducer reducers/posts.js import {GET_POSTS} from "../actions/types"; const initialState = { posts: [] } export default function(state = initialState, action) { switch (action.type) { case GET_POSTS: return { ...state, posts: action.payload } default: return state; } } this is the action actions/posts.js import axios from "axios"; import {GET_POSTS} from "./types"; export const getPosts = () => dispatch => { axios.get('/get/posts/').then(res => { dispatch({ type: GET_POSTS, payload: res.data }) }).catch(error => {console.log(error)}) } this is reducers/index.js import {combineReducers} from 'redux'; import posts from "./posts"; export default combineReducers({ posts }); this is store.js import {createStore, applyMiddleware} from 'redux'; import {composeWithDevTools} from 'redux-devtools-extension'; import thunk from 'redux-thunk'; import rootReducer from './reducers'; const initialState = {}; const middleware = [thunk]; const store = createStore( rootReducer, initialState, composeWithDevTools(applyMiddleware(...middleware)) ); export default store; this is … -
infinite scrolling using django
I am fairly new to web development and I am building a blog style website. I use pagination to split posts into seperate pages but now i want to rather go for infinite scrolling like facebook does. I have watched countless videos and read a whole bunch of docs regarding this but to be honost, I get lost in all of them. I use django and python for my backend and all sources seem to use other languages etc like JS and ajax etc. All these mentioned sources start from the ground up which somehow confuses me as i already have pagination in place. Is there a way i can just tweak my current pagination to enable infinite scrolling instead of rebuilding the whole thing in different languages? or just help me get this done the right way. I've been struggling with this for weeks now so now i come here as a last resort. No point in running straight here if no effort was put in before hand Here is my current pagination code: views.py: from django.shortcuts import render, get_object_or_404 from .models import Post from django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin from django.contrib.auth.models … -
When saving many uploaded files to db save() method only really works for the last file in the query
I am using CreateView and in the template, I am uploading multiple files to store in the database. I get all file from the request by files = self.request.FILES.getlist('file') and loop it to create an object for each one. However, object creation only works for the last object in the list. def form_valid(self, form): files = self.request.FILES.getlist('file') allowed_file_extensions = ['xls', 'xlsx', 'doc', 'docx', 'pdf'] for file in files: file_converted_to_string = str(file) file_regex = re.search(r"([a-zA-Z0-9-_\s]+)[.](\w+?)$", file_converted_to_string) file_name, file_extension = file_regex.group(1), file_regex.group(2) if file_extension in allowed_file_extensions: self.object = form.save(commit=False) self.object.file = file self.object.file_name = file_name self.object.file_extension = file_extension self.object.department_belonged = self.request.user.profile.department print(self.request.user.profile.department) self.object.creator = self.request.user self.object.save() return super().form_valid(form) Even more interesting, when I replace: self.object = form.save(commit=False) self.object.file = file self.object.file_name = file_name self.object.file_extension = file_extension self.object.department_belonged = self.request.user.profile.department self.object.creator = self.request.user self.object.save() with: self.model.objects.create(file=file, file_name=file_name, file_extension=file_extension, department_belonged=self.request.user.profile.department, creator=self.request.user) It create a new object for each file in the list but raise error in upload_to function in models.py. file = models.FileField(upload_to=file_path) def file_path(instance, filename): return f'{instance.creator.profile.department}/user_{instance.creator.id}/{filename}' Error: Exception Value: 'NoneType' object has no attribute 'profile' -
Running manage.py collectstatic with PyCharm running creates Permission Denied errors under windows
When running manage.py collectstatic for my Django project with PyCharm running I get a "Permission Denied" error. This is true whether I run manage.py from within PyCharm or from a command windows. The error goes away if I close PyCharm before I run collectstatic. My question: is there a way to get PyCharm to release its hold on the static files so that I can run collecstatic without closing and opening PyCharm? -
How to create custom django validation for authentication
Hi everyone) I'm new in Django. I need to do a really simple validation for sign in form. In my app can sign in only one user, with a specific username and password, for example, "my_username" and "my_password". And superuser can't sign in. I don't know do I even need a table in a database for only one user? By now I write a simple login form with django.contrib.auth.views LoginView and this work, but for everyone who is in database and superuser. -
Link html page or jsp page to multiple django apps
I am still new to django, and I have spent 2 hours on looking on how to connect html sites and jsp sites to multiple apps. For example, I have index.html, calculator.jsp, login.jsp, register.jsp, and 2 other django apps. The index.html can link to 3 jsp sites, and 2 django apps. The problem is how to run multiple django servers for multiple apps simultaneously. Can sb help me ? I think I should use these: uswgi, nginx or django apache. Nevertheless, I get lost while following the API documentation. Also, there is no youtube video that show how to run multiple django servers. -
How to use variables in ModelChoiceField queryset
I am trying to use a specific list of data in my form with Django. I am using ModelChoiceField to retrieve from the model the data I need to display in the form (to let the users select from a scolldown menu). My query is complicate because need two filters based on variables passed by views I've tried to use the sessions but in form is not possible to import the session (based to my knowledge). form.py def __init__(self, pass_variables, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['initiative'] = forms.ModelChoiceField(queryset=raid_User_Initiative.objects.filter(company=pass_variables[1], username=pass_variables[0]).values_list('initiative', flat=True)) view.py pass_variables = ((str(request.user), companyname)) f = Issue_form(pass_variables) If I don't pass the variable the process works. The problem is with the code above as the form don't provide any error but it doesn't pass the if f.is_valid(): Thanks