Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Views not cooperating on form submit
I have 3 buttons that should change the behavior of the videos on the page depending on the chosen dropdowns. But the user chooses a choice from the dropdown, the videos don't cooperate. This is the front end. When I choose something on for example language, the videos should change, but it doesn't. The page ends up on http://localhost:8000/?language=EN&level=LEV&category=CAT then the page breaks I tried adding a reverse_url on the views but it still didn't fix the error. def home(request): filter_form = AMLVideoFilterForm(request.GET) videos = AMLVideo.objects.all() category = filter_form.data.get('category') if category: videos = videos.filter( category__exact=category ) language = filter_form.data.get('language') if language: videos = videos.filter( language__exact=language ) level = filter_form.data.get('level') if level: videos = videos.filter( level__exact=level ) videos = videos.order_by("-category", "-language", "-level") context = {'videos': videos, 'filter_form': filter_form, 'level': level, 'language': language, 'category': category,} return render(request, 'home.html', context) The forms.py is: class AMLVideoFilterForm(forms.Form): LANGUAGE = [ ('LAN', 'Language'), ('EN', 'English'), ('FR', 'French'), ('HIN', 'Hindi'), ('SPA', 'Spanish'), ('GER', 'German'), ] LEVEL = [ ('LEV', 'Level'), ('BEG', 'Beginner'), ('INT', 'Intermediary'), ('ADV', 'Advanced'), ] CATEGORY = [ ('CAT', 'Category'), ('ADN', 'Adventure'), ('ANI', 'Animal'), ('ENV', 'Environmental'), ('MOR', 'Moral'), ('FOLK', 'Folktales'), ('POE', 'Poems'), ('FUN', 'Funny'), ] language = forms.ChoiceField( required=False, choices=LANGUAGE, widget=forms.Select( attrs={ 'onchange' : "this.form.submit()", … -
How to Send an Email Django
Previously, I was using SendGrid to serve emails using Django's SMTP backend, which worked perfectly fine. However, now I would like my project to use Microsoft Exchange. When I updated my SMTP configuration in settings.py, upon the submission of some form to be emailed, the page timesout when trying to reach the server: TimeoutError: [Errno 60] Operation timed out. settings.py # E-Mail EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.microsoft365.com' EMAIL_HOST_USER = 'username@domain.com' EMAIL_HOST_PASSWORD = 'password' EMAIL_USE_TLS = True EMAIL_PORT = 587 views.py # Send email send_mail('!!New Mail!! ', content, 'noreply@domain.com', ['username@domain.com'], fail_silently=False) -
Django redirect with custom context
I am trying to send custom context in redirect request but the redirect is not working as I would like. it is redirecting me to a variable of the context instead. Here are my views def scenariopage(request,newContext): context = {} context.update(newContext) return render(request, 'scenariopage', context) def personforms(request): .... some forms code.... context = {'region':filled_form.cleaned_data['region'], 'industry':filled_form.cleaned_data['industry'], 'personUID':filled_form.cleaned_data['personUUID'], 'link': filled_form.cleaned_data['link'] } return scenariopage(request,context) This is the Terminal Debug output: [24/Sep/2019 16:10:54] "GET /scenario/2/ HTTP/1.1" 200 11616 [24/Sep/2019 16:10:57] "POST /personform HTTP/1.1" 200 7513 Not Found: /Retail [24/Sep/2019 16:10:57] "GET /Retail HTTP/1.1" 404 8631 Retailin this case is a variable contains in the context industry field. What am I doing wrong? -
Bootstrap Notify and Django Messages
How can I show error and warning Django messages using Bootstrap Notify? I'm using this template. I tried django-messages-to-bootstrap-notify but it's not working. I also used a HTML that I inspected from my browser: {% if messages %} {% for message in messages %} <div data-notify="container"><button type="button" aria-hidden="true" class="close" data-notify="dismiss" style="position: absolute; right: 10px; top: 5px; z-index: 1033;">×</button><span data-notify="icon"></span> <span data-notify="title"></span> <span data-notify="message">{{ message }}</span><a href="#" target="_blank" data-notify="url"></a></div> {% endfor %} {% endif %} This is a demo of the form. The author included a PHP code with the form and I think this is the part that shows the notification messages: if(!$mail->Send()) { $response = array ('response'=>'error', 'message'=> $mail->ErrorInfo); }else { $response = array ('response'=>'success'); } What's the best and easiest way to do this ? -
"Fields" not created with the sample polls apps mentioned in docs of django
I'm new to Django & am trying to create the polls app mentioned in the documentation section of django page. Followed exact steps mentioned & when the concerned code is executed, it says models are created but i don't see the field is added. Django version - 2.2.5 Python version - 3.6.4 python manage.py makemigrations polls as per docs, i should also see "- Add field question to choice" which is missing Expected: Migrations for 'polls': polls/migrations/0001_initial.py: - Create model Choice - Create model Question - Add field question to choice Actual: Migrations for 'polls': polls\migrations\0001_initial.py - Create model Question - Create model Choice -
Integrating Jumbo React template with Django
I am pretty new to React (and to frontend development, in general), and I am trying to integrate Jumbo React Admin template with Django. I have been able to launch Jumbo React Admin template on its own following this documentation, and I have, also, been able to integrate Django with React following this tutorial. The main difference between both tutorials (besides directory structure, that is not such a big issue) is that the first one is based in yarn, and the second one on webpack. I decided to use the official Jumbo documentation, and I am trying to do the integration using yarn. So far, I created a Django new project with a frontend application, and I copied Jumbo Admin template's directory in it. This is the resulting directories structure of the project: As you can see in the image, there is the following file: /Users/hugovillalobos/Documents/Code/JumboDjangoProject/JumboDjango/frontend/source/public/index.html but, any way, when I run yarn start, I get the following error: (JumboDjangoVenv) MacBook-Pro-de-Hugo:frontend hugovillalobos$ yarn start yarn run v1.17.3 $ react-scripts start Could not find a required file. Name: index.html Searched in: /Users/hugovillalobos/Documents/Code/JumboDjangoProject/JumboDjango/frontend/public error Command failed with exit code 1. info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command. I don't know how … -
Accounting for latency in simple multiplayer game?
At the moment, to account for latency, in my game (it is essentially tron lightcycles, but to move, one must solve a math problem), I send out the game state to both players every time one of the players turns. On the frontend, I have a function that draws and a function that undraws (to account for when there is latency). Currently, the setup is not performing the desired behavior: the players are not in sync with each other (neither movements nor positions at which users turn are the same for both players). Can someone help me out? This is my first time making a game. Here is the backend code (this code runs when a user submits an answer to a math problem in order to turn their character): def send_answer(answer, game_object, player_type, current_position, current_direction): creator_directions = ['p1up', 'p1right', 'p1down', 'p1left'] opponent_directions = ['p2up', 'p2right', 'p2down', 'p2left'] with transaction.atomic(): # d for direction if player_type == 'creator': for d in creator_directions: if is_correct_answer(getattr(game_object, d), int(answer)): context['move_direction'] = d print(context) new_problem = generate_problem_game( game_object.level, game_object.operation, game_object, player_type) setattr(game_object, d, new_problem) game_object.save() context['new_problem'] = [d, new_problem] # calculate draw and undraw positions # p1_last_pos: player 1 last position p1_last_pos = game_object.p1lastposupdate … -
How to activate virtual environment and start runserver by using .bat file with one click?
I m new to django. I got stuck while doing that, i found some resource but that didn't work for me. i have tried the command below, this start the chrome with localhost but i couldn't activate virtual environment along with run server. Anyone help me to do that, i want just one click to activate virtual environment and start server by using batch file. I m using windows @ECHO OFF start cmd.exe /C "python manage.py runserver && cd H:\djano-project\taskmate\ && D:" start C:\"Program Files (x86)"\Google\Chrome\Application\chrome.exe "http://127.0.0.1:8000/" -
How to add a user to django site, when using remote auth backend?
I am using Django for a site, and have a remote auth backend setup. Is there a way In which I can create a new user and give them permissions before they login to the site? I know I can add users through the admin page or directly through the database, but since I do not know the new users password, I am not sure if the system will see them as the same user I have tried using the admin page, but it says I need to enter a password I would like to be able to add users to the system before they logon, and give them permissions, so that when they logon they are not redirected to my unauthorized page. Is this possible? -
POST http://127.0.0.1:8000/ 401 (Unauthorized) using cors
I am working with django as backend and angular as fronted, using cors for the login, the thing is, when I try to make an insert in the backend from the fronted, it shows an error, this error POST http://127.0.0.1:8000/categoria 401 (Unauthorized) createCategoria(d: Categoria): Promise<Categoria> { return this.http .post("http://127.0.0.1:8000/categoria", JSON.stringify(d), { headers: this.headers }) .toPromise() .then(res => res.json() as Categoria) } the backend cors config and url config CORS_ORIGIN_ALLOW_ALL = False CORS_ORIGIN_WHITELIST = [ "http://localhost:4200" ] url(r'^categoria$', views.CategoriaList.as_view()), url(r'^categoria(?P<pk>[0-9]+)$', views.CategoriaDetail.as_view()), POST http://127.0.0.1:8000/categoria 401 (Unauthorized) zone.js:2969 btw , the backend is running in 127.0.0.1:8000 -
The view blog.views.BlogViews didn't return an HttpResponse object. It returned None instead
I'm having a problem with the views for my blog main page. I've read a lot of problems with the same error but couldn't find a solution that i thought matched with my problem. I am trying to emulate my old code with a new View so that i can customise it further in the future. path('', ListView.as_view( queryset=Post.objects.filter(posted_date__lte=now).order_by("-posted_date")[:25], template_name="blog/blog.html")), i was previously using just the above url pattern to display my blog posts but im moving to a view: def BlogViews(TemplateView): def get(self, request): posts = Post.objects.all().order_by("-posted_date")[:25] args = { 'posts' : posts, } return render(request, 'blog/blog.html', args) and the new url path('', BlogViews, name='blog'), However this view is not working and returns the error in the title. I'm importing TemplateView, Post and render correctly i believe. -
adding additional fields to serializer from another model
I am going to include Model to another serilializer in my project here is the specification. I have a Review model as follows class Review(models.Model): profile = models.ForeignKey(Profile, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) rating= models.ForeignKey(ProductRating, on_delete=models.DO_NOTHING) comment = models.TextField() my function is to show number of comment that users wrote for the product and I should show in serializer like that class WishList(models.Model): user = models.ForeignKey('authentication.User', on_delete=models.CASCADE, null=True) product = models.ForeignKey(Product, on_delete=models.CASCADE, null=True) serailzier.py class GetWishlistSerializer(serializers.ModelSerializer): name = serializers.CharField(source='product.name', read_only=True) rating = serializers.IntegerField(source='product.rating', read_only=True) image = serializers.ImageField(source='product.image', read_only=True) price = serializers.DecimalField(source='product.price', decimal_places=2, max_digits=10, read_only=True) review = SerializerMethodField() class Meta: model = WishList fields = ['user','product', 'name', 'rating', 'image', 'price', 'description', 'review'] def get_review(self, obj): return Review.objects.filter(product_id=obj.id).count() and it should count the number of review for specified product but it did not work it gives result like that. { "user": 1, "product": 1, "name": "Samsung A70", "rating": 5, "image": "http://localhost:8000/media/products/2019/08/30/wkl6pb_E2RUzH6.jpeg", "price": "2500.00", "description": "bla bla bla", "review": 0 } but I have one review for product: 1 it should show 1 but it shows 0 I do not know what I am missing here. Any help please? If question is unclear please let me know I will try to specify in … -
Django admin add a custom js every time user click on an element
In my django admin project i have to trigger a .js file every time an user change a select field value. In my admin/change_form.html page i add: {% block extrahead %}{{ block.super }} <script type="text/javascript" src="{% url 'admin:jsi18n' %}"></script> <script type="text/javascript" src="{% static 'js/admin.js' %}"></script> {{ media }} {% endblock %} and in my admin.js: document.onclick = function(){ console.log("test for admin.js"); } but in my browser console related to 'document' part of code i get: Uncaught SyntaxError: Invalid or unexpected token How can i use javascript code from django admin add/edit page? so many thanks in advance -
AJAX not reading json CORS allow-origin headers returned from django
I'm calling a Django view with AJAX cross-domains. I'm returning the proper CORS allow-origin headers properly (works in other ajax calls to my api), however, my AJAX response is still fail with browser console error: "Access to XMLHttpRequest at 'foo' from origin 'bar' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource." In my python console, the response is as expected: {"successMessage": "Sent referral email", "Access-Control-Allow-Origin": "", "Access-Control-Allow-Methods": "POST", "Access-Control-Allow-Headers": "", "Access-Control-Max-Age": "1000"} but for some reason this is not translating to AJAX and it's failing. If I remove the json conversion, and simply return HttpResponse(), I get a status 200 from AJAX and no CORS warning, but it still fails. I assume because it's expecting JSON and that's not what it's getting. Help! My ajax: $.ajax({ url: "http://192.168.0.23:8000/api/SendEmail?email=" + $("#refereeEmail").val() + "&refereeName=" + $("#refereeName").val() + "&referrerName=" + $("#referrerName").val(), dataType: "json" }).fail(function (xhr, status, error) { console.log("fail"); $('#email-alert').text("There was an error communicating with the server. Please try again."); $('#email-alert').show(); // handle a non-successful response console.log(xhr.status + ": " + xhr.responseText); // provide a bit more info about the error to the console }).success(function (response) { if (response.status == "ok") { console.log("worked"); // sent email, … -
Django View, get all list items in template
In Veiw, to get the selected item from an existing list in a template, I use request.POST.getlist('my_list'). In View, how to get all items from an existing list in a template? -
Django Custom Tag Problems
Hello Stack Overflow ! I am making a news site in Django as a part of my "internship", I have just started learning web development. I was given a task to make a custom template ( it HAS to be a custom template ) which will render out 3 latest news from a category, and I have to include it as a sidebar on my "article" page. I tried to write the custom tag, but it's not going to well unfortunately. This is my "last" task for the website, and I'm stuck (like many times before :P ) Here's the thing..everything is working if I include the custom tag on my "list all articles" page, it renders correctly depending on which category I click on. The thing is, once I try to include my tag into my "single article" page I hit a brick wall. The tag is still working, but is now displaying all of my articles, instead of filtering the articles related to that article's category. To simplyfiy, If i click on a "health" article to open it, I want the sidebar just to include the articles for the "health" category, I hope that makes sense. Anyone with … -
How to use `construct_change_message` to create a `change_message` in my own view to log my actions in the built-in `LogEntry` model?in django
I've added a code in my view to log every add action in my add_new_staff page. Here's the code: message = f'New user added. Added staff profile for {user.first_name} {user.last_name}' log = LogEntry.objects.log_action( user_id=request.user.id, content_type_id=ContentType.objects.get_for_model(user).pk, object_id=repr(user.id), # or any field you wish to represent here object_repr=repr(user.username), action_flag=ADDITION, # assuming it's a new object change_message=message,) # a new user has been added log.save() In here, I only made a custom get message thru message string. And I think, for this add_staff_view it is ok to do this. But now, I'm working on my update_staff_profile_view and also, I need to log this action. I saw how the change/update form in django admin page inserts the change_message in LogEntry model(it shows which fields are changed/updated), and I can't think of ways to do it inside my own update_staff_profile_view. Here's my update_staff_profile_view: @login_required def ProfileUpdateView(request): if request.method == 'POST': user_form = accounts_forms.UserUpdateForm(request.POST, instance=request.user) if request.user.is_staff == True: profile_form = accounts_forms.StaffProfileUpdateForm( request.POST, instance=request.user.staffprofile) else: profile_form = accounts_forms.StudentProfileUpdateForm( request.POST, instance=request.user.studentprofile) if user_form.is_valid() and profile_form.is_valid(): user_form.save() profile_form.save() log = LogEntry.objects.log_action( user_id=request.user.id, content_type_id=ContentType.objects.get_for_model(user).pk, object_id=repr(user.id), object_repr=str(user.username), action_flag=CHANGE, change_message = 'IM STUCK HERE',) log.save() messages.success(request, 'Your profile has been updated.') return redirect('update-profile') else: user_form = accounts_forms.UserUpdateForm(instance=request.user) if request.user.is_staff == True: … -
MultiValueDictKeyError at /login/
I'm trying to create a customized signup and login form with sessions. The data is successfully saved in the db but when I'm trying to login into the system using email and password credentials. It is throwing an error. I'm unable to figure out the reason. def user_login(request): context = {} if request.method == "POST": user_email = request.POST['user_email'] password = request.POST['password'] member = authenticate(email=user_email, password=password) request.session['user_email'] = member if member: login(request, member) if request.GET.get('HomePage', None): return HttpResponseRedirect(request.GET['HomePage']) return HttpResponseRedirect(reverse('success')) else: context["error"] = "Provide valid credentials !!" return render(request, "login.html", context) else: return render(request, "login.html", context) def form_view(request): if request.session.in_key('user'): user = request.session['user'] return render(request, 'HomePage.html', {"user": user}) else: return render(request, 'login.html', {}) def logout(request): try: del request.session['user'] except: pass return HttpResponseRedirect(reverse('user_login')) my signup form and login form class UserSignupForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput) class Meta: model = Users fields = "__all__" class LoginForm(forms.ModelForm): class Meta: model = Users fields = ['user_email', 'password'] urls urlpatterns = [ path('admin/', admin.site.urls), path('signup/', views.signup), path('login/', views.user_login, name="user_login"), path('success/', views.success, name="success"), path('logout/', views.user_logout), path('logout/', views.logout, name="logout"), login.html file <form method="POST" > {% csrf_token %} <table> <tr> <td><label for="user_email">Email</label></td> <td><input type="text" name="Email" id="user_email" required></td> </tr> <tr> <td><label for="password">Password</label> </td> <td><input type="password" name="password" id="password" required></td> </tr> <p style="color: … -
Django templating + Vue templating for the same content for SEO reasons
I'm in the process of building a Django app with limited Javascript interactivity, and am looking at how to incorporate Vue templating along with Django templating for the same content. Imagine an infinite scroll page, where SEO is very important. Django is great at solving this problem since it is per definition a server side framework. However, how would you enrich a page rendered by Django with Vue, provided that both of these technologies need to render the same content? Django would in this case render for the SEO crawlers, right before Vue takes over, Vue "hydrates" these components and make them interactive. After this happens, subsequent content that is fetched asynchronously with AJAX will also be templated using Vue. I have done some research without finding sufficient information on how to solve this: https://vsupalov.com/vue-js-in-django-template/ which is where some parts of the code sample below is based off of https://medium.com/quick-code/crud-app-using-vue-js-and-django-516edf4e4217 which outlines that combining django and vue seems to work pretty well together https://medium.com/@rodrigosmaniotto/integrating-django-and-vuejs-with-vue-cli-3-and-webpack-loader-145c3b98501a I don't get the sense that these sources are talking about SEO, or rather if they are, they utilize Vue templating only where the content is not SEO heavy(like opening a modal). Below is an initial … -
Django, keras segmentation : Tensor is not an element of this graph
I have an object to load the model. class BillOCR: def __init__(self,image_address='',retrain=False,checkpoint='unet_model/'): self.image_address = image_address self.checkpoint = checkpoint latest_weights = checkpoint+'resnet_unet_1.4' assert ( not latest_weights is None ) , "Checkpoint not found." self.model = keras_segmentation.models.unet.resnet50_unet(n_classes=3, input_height=32*24, input_width=32*18,) self.model.load_weights(latest_weights) I have declared the necessary objects and graph as global global ocr ocr = BillOCR() global model model = ocr.model global graph graph = tf.get_default_graph() and I have a django method: def classify(request): data = {"success": False} if request.method == "POST": tmp_f = NamedTemporaryFile() if request.POST.get("image64", None) is not None: base64_data = request.POST.get("image64", None).split(',', 1)[1] plain_data = b64decode(base64_data) image = np.array(Image.open(io.BytesIO(plain_data))) image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) tmp_f.write(plain_data) tmp_f.close() with graph.as_default(): k_number = ocr.model.predict_segmentation(image) K.clear_session() data["success"] = True data["result"] = k_number return JsonResponse(data) But this is leading to Tensor Tensor("activation_50/truediv:0", shape=(?, 110592, ?), dtype=float32) is not an element of this graph. How do I tackle this? K.clear_session() also didn't work. Im using Keras==2.2.4 tensorflow==1.13.1 and latest version of keras_segmentation. Loading the model everytime there's a request is way too time consuming. -
Django: Ignores readonly=True for multiple select of a ManytoManyField despite grayed out area
Bit puzzled, it seems Django Crispy forms ignores readonly=True for a multiple select field linking to a ManytoManyfield. Area is grayed-out but I am still able to change and save the selection into the database. readonly=True should supposedly gray out the area and not allowing to save any changes. readonly=True works on a CharField as intended in the same form. Why is this? is it a bug or a known problem, in such case, what fixes are suggested. class Product(models.Model): product_type = models.CharField(max_length=22, blank=True) class Package(models.Model): product_code = models.CharField(max_length=3) products = models.ManyToManyField('product.Product', blank=True) class ProductModelForm(ModelForm): class Meta: model = Package fields = '__all__' class ProductFieldsForm(ProductModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_class = 'form-horizontal' self.helper.label_class = 'col-sm-4' self.helper.field_class = 'col-sm-7' self.helper.form_tag = False prd_code = 'product_code' prds = 'products' self.helper.layout = Layout ( Field(prd_code, readonly=True), # WORKS FINE, as intended Field(prds, readonly=True), # **CAN CHANGE and SAVE (gray area)** ) -
How to generate a pdf form prepopulated from a Django formwizard values and send an email
I am trying to generate a pdf form with values filled in from a Django form wizard and send an email with the pdf. But am stuck trying to get the values and generating pdf. This is my forms.py class FormStepOne(forms.Form): qualifying_criteria = forms.MultipleChoiceField(label='Applicant company must qualify against at least one', required=True, widget=forms.CheckboxSelectMultiple, choices=CRITERIA_CHOICES) details = forms.CharField(label="Provide more details and give reasons for wanting to join the Chamber and what you are expecting from your membership", widget=forms.Textarea(attrs={"rows": 10, "cols": 20})) class FormStepTwo(forms.Form): company_name = forms.CharField( label="Company Name (in full):", max_length=100) other_name = forms.CharField( label="Other Trading Name(s) if applicable:", max_length=100, required=False) physical_address = forms.CharField( label='Physical Address:', widget=forms.Textarea(attrs={"rows": 5, "cols": 20})) email = forms.EmailField(label="Email:") website = forms.URLField(label="Website:", required=False) contact_name = forms.CharField(label="Name:", max_length=100) job_title = forms.CharField(label="Job Title:", max_length=150) contact_mobile = forms.CharField(label="Mobile", max_length=30) contact_telephone = forms.CharField( label="Telephone No", max_length=30, required=False) contact_email = forms.EmailField(label="Email Address:") views.py class FormWizardView(SessionWizardView): template_name = "join.html" form_list = [FormStepOne, FormStepTwo] file_storage = FileSystemStorage( location=os.path.join(settings.MEDIA_ROOT)) def done(self, form_list, **kwargs): form_data = [form.cleaned_data for form in form_list] criteria = form_data[0]['qualifying_criteria'] self.request.session['criteria'] = criteria self.request.session['details'] = form_data[0]['details'] return redirect('complete') class Process_Data(TemplateView): template_name = 'corporate-form.html' def get_context_data(self,**kwargs): context = super(Process_Data, self).get_context_data( **kwargs) context['criteria'] = self.request.session['criteria'] context['details'] = self.request.session['details'] return context In my views, I … -
What's the proper way to use different pipenv environments for a Django project on different computer systems?
Hopefully this isn't too stupid of a question, concerning the use of pipenv for the same Django project on different computer systems. The scenario is that I'm using pipenv with a test Django project on one laptop, everything works fine, using VS Code and it's using the proper pipenv environment for the Python environment within VS Code. The project however is within Dropbox so when I'm using a different laptop, which I do sometimes, one is my work laptop the other is my personal one at home, I can work on the same project wherever I left off. So you can probably deduce the issue I'm having. I'm using pipenv environment A on my work laptop for the Django project. But when I open the project in VS Code on my personal laptop at home I have to keep specifying the proper pipenv environment to use, which obviously is different than the one on my work laptop. Maybe I shouldn't be working this way and should just work on one laptop for the project, but I imagine others have done the same with similar setups before. Is there a "proper" way to do this, using different pipenv environments on different … -
Selected value not passed in Django
I want to pass the selected values to have dependent dropdown with data connection. I am using <select> in HTML to pass value to Django but selected values can't be passed in Python for processing. I am new to Django and prefer not to use models.py or forms.py at the moment. <select class="Lv0" name="lv0"> <option value="US">US</option> <option value="UK">UK</option> </select> views.py def search_index(request): results = [] lv0="" search_term = "" if request.GET.get('lv0'): lv0 = request.GET['lv0'] print(lv0) //this can't be printed if request.GET.get('query'): search_term = request.GET['query'] print("####test#####\n", search_term) //this is printed results = esearch(query=search_term) print(results) //this is printed context = {'results': results, 'count': len(results), 'search_term': search_term} return render(request, 'esearch/base.html', context) Below is for query that gets passed. <form class="form-inline"> <input class="form-control mr-sm-2" type="query" placeholder="Search Here" aria-label="query" name = 'query' value = ""> <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button> </form> -
How to restrict users without permissions when using remote auth backend?
I am relatively new to Django. I am user a remote auth backend, but I am wondering if there is a way that I can restrict users that do not have permissions, gotten from REMOTE_USER. Is it similar to the way you do it with a Django Auth system? Right now everyone who is logged in on my auth backend can access my site. I want to grant certain users permissions before they login, and deny all other users. Is there a way in which I can do this?