Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
passing url parameter in django template using form
I'm writing a page that takes an id and finds a user that matches that id. this is the URL pattern that I wrote in urls.py: re_path(r'^users/id=(?P<username>[0-9]{9})$' , views.usershow , name = 'usershow') , I want to pass username using forms and so I wrote this in templates: <form action="{% url 'CMS:usershow' %}" method="GET" > {% csrf_token %} <input name="id" type="number" placeholder="search"> <button type="submit">find</button> </form> but it shows me this error : Reverse for 'usershow' with no arguments not found. 1 pattern(s) tried: ['dashboard/users/id=(?P<username>[0-9]{9})$'] how can I pass it using forms with this URL pattern? -
Django template variable string as html
I've written a small view which contains some html embedded into one of the list arrays. When I use that list item in a template, the data is interpreted by the template as a literal string rather than html. How do I get django to not ignore html tags inside of a variable? views.py def home(request, username='Pedro'): template_name = 'main/index.html' url = "https://www.duolingo.com/users/{}".format(username) getUserData(url) context = { 'username': username, 'wordLists': wordlists, 'explanations': explanations, 'words': words, } # print(context) return render(request, template_name, context) def getUserData(url): response = requests.get(url) userdata = response.json() for language in userdata['language_data']: for index in userdata['language_data'][language]['skills']: if index.get('levels_finished') > 0: wordList = index.get("words") wordlists.append(wordList) explanations.append(index.get("explanation")) for wordItem in wordList: words.append(wordItem) template {% block content %} {% for e in explanations %} {{ e }} {% endfor %} {% endblock %} results -
How to load the data into existing table in postgresql database in django
I am developing a webapplication using django where i am trying to load the user data during signup into the postgresql database but how to insert the user data into the database. I have execute python manage.py makemigrations app python manage.py migrate it is creating the new table but i want the data to be insereted from the form to be saved in the database. settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'OPTIONS': { 'options': '-c search_path=provisioning' }, 'NAME': 'OneClickProvisioning', 'USER': 'postgres', 'PASSWORD': 'Hanu@2789', 'HOST': 'localhost', 'PORT': '5432', } } forms.py class UserRegistrationForm(forms.Form): fname = forms.CharField( required=True, label='FirstName', max_length=32 ) lname = forms.CharField( required=True, label='LastName', max_length=32 ) urls.py from django.contrib import admin from django.urls import path from django.conf.urls import url from Provisioning import views urlpatterns = [ url('admin/', admin.site.urls), url(r'^home/', views.home), url(r'^signup/', views.signup), ] views.py -------- def signup(request): if request.method == 'POST': form = UserRegistrationForm(request.POST) if form.is_valid(): userObj = form.cleaned_data username = userObj['username'] password = userObj['password'] if not (User.objects.filter(username=username).exists()): User.objects.create_user(username, password) user = authenticate(username = username, password = password) login(request, user) return HttpResponseRedirect('/Login.html') when clicking on the signup button it has to store the user input data in to the database and redirect to the login page once user … -
Keep input order of ModelMultipleChoiceField with Select2MultipleWidget
I have a many-to-many field in my model and I am using a Select2MultipleWidget to search values for input, but after selected the values are being sorted alphabetically as it seems. I've already tried changing the ModelMultipleChoiceField to OrderedModelMultipleChoiceField (like in this post), but it doens't help: class OrderedModelMultipleChoiceField(ModelMultipleChoiceField): def clean(self, value): qs = super(OrderedModelMultipleChoiceField, self).clean(value) return sorted(qs, lambda a,b: sorted(qs, key=lambda x:value.index(x.pk))) and authors = OrderedModelMultipleChoiceField(queryset=UserProfile.objects.all(), widget=Select2MultipleWidget) How can I make them preserve the order of input? -
How to use ajax in django,to pass the model object and store it in database without refreshing the page?
i'm doing a small project in django,in that i thought of adding a favorite button in one of the pages so that on clicking on that button it has to return the model object and it has to be stored in another database for the reference,but its not happening Here is my home/bookdetails.html <!DOCTYPE html> {% extends 'home/Base.html' %} {% block title %} Book Details {% endblock %} {% load staticfiles %} <link rel="stylesheet" href="{{ STATIC_URL }}/home/css/heart.css"> <script src="{% static 'js/heart.css' %}"></script> <script src="https://code.jquery.com/jquery-3.1.0.min.js"></script> <script src="{% static 'js/app.js' %}"></script> {% block body %} {% if error_message %}<p><strong> {{ error_message }} </strong></p>{% endif %} <script type="text/javascript"> $(document).ready(function(){ $("#sub").click(function(event) { var userbooks = '{{ userbooks }}'; $.ajax({ type: "GET", url: "{% url 'home:favoriteAjax' %}" data:{userbbooks:userbooks} datatype:'json' success: function() { alert("successfully added to favorites") } } }); }); }); </script> <p>Book name:{{ userbooks.book_name }}</p><br> <p>Book author:{{ userbooks.book_author }}</p><br> <p>Book genre:{{ userbooks.book_genre }}</p><br> <p>Book ISBN:{{ userbooks.book_ISBN }}</p><br> <button type="submit" id="sub" onclick="changeText()">Favourite</button> {% endblock %} my urls.py: from django.urls import path from . import views app_name='home' urlpatterns=[ path('',views.HomeView,name='home'), path('addBooks/',views.addBooks,name='addBooks'), path('myBooks/',views.BooksView.as_view(),name='myBooks'), path('<int:pk>/', views.BookDetailsView.as_view(), name='myBooks'), path('search/', views.SearchedBooks.as_view(), name='searchedBooks'), path('favorite_ajax/', views.favorite_ajax, name='favoriteAjax'), ] my models.py: from django.db import models from django.contrib.auth.models import User class UserBooks(models.Model): user_id = models.ForeignKey(User,on_delete=models.CASCADE,null=True) … -
How to give request to the admin by user created by admin
I have created an admin site and along with two users. Now user needs to request the admin to create, update and delete the topics. In the meantime, every user has to give access to delete their own created topic. How to process this using Django? -
Why i can't start a django project use uwsgi after update the code
I met a problem, i can't start my django project use uwgsi after update the code. I can use before. I try django runserver to start, actually, that's work. but just can't use uwgsi. Here is my uwsgi config. [uwsgi] chdir = /var/myblog module = mysite.wsgi home = /root/venv_myblog/ master = true processes = 10 socket = 127.0.0.1:8001 vacuum = true pidfile=uwsgi.pid Here is the problem: urlconf_module = import_module(urlconf_module) File "/root/venv_myblog/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 978, in _gcd_import File "<frozen importlib._bootstrap>", line 961, in _find_and_load File "<frozen importlib._bootstrap>", line 950, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 655, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 205, in _call_with_frames_removed File "./webapp/urls.py", line 15, in <module> ModuleNotFoundError: No module named 'webapp.views.opencv_tutorials' But i can run it via runserver: System check identified no issues (0 silenced). February 01, 2019 - 08:44:19 Django version 2.1.4, using settings 'mysite.settings' Starting development server at http://127.0.0.1:9000/ Quit the server with CONTROL-C. Can't figure why!!! Need help!!!!!!! Please!!!! -
Django - on checking checkbox add model to M2M relationship
I've got a Declaration model which has a BooleanField called for_employees, M2M field on Employee. What I want to achieve is on checking checkbox add this declaration to all employees, but it went worse. This my code class Declaration(models.Model): employees = models.ManyToManyField(Employee, blank=True, related_name='declarations', verbose_name='Employees') for_employees = models.BooleanField('Employees', default=False) # On check becomes True # getting all employees def add_employees(self): if self.for_employees: employees = Employee.objects.all() for employee in employees: employee.declarations.add(self) # self isn't saved, so it doesn't have data in it employee.save() def save(self, *args, **kwargs): # my big headache self.add_employees() super().save(*args, **kwargs) -
Redirect Login Form To SSO Depending On Email Domain
As a bit of a hobby I am making a site where I want users to be able to login with site credentials or a SAML SSO (Azure AD, but maybe some other SSO providers in the future). I am using Django for the project. I am planning to create a second page which handles SSO (I am planning on using django-saml2-auth to facilitate that). However, to make it slightly easier for users I want to redirect them automatically to the page if they input user@example.org into the username field. People using SSO would only come from that domain and would be expected to use SSO to login. As some users would still need to login with regular credentials I don't want to force SSO using django-saml2-auth. I've seen quite a few services do this and I am thinking a little bit of JavaScript is all I need (as no sensitive/important/critical information is being transferred it shouldn't be bad if it is client side) to redirect them to the SSO page. Would any of you be able to point me in the right direction on this? Sorry if there is a question like this already - I couldn't find one. -
Django - Dependant Dropdown Filter without using ForeignKeys
Is there a way in Django to create a dependant dropdown menu without uisng ForeignKeys? Lets say I have the following model: class CSV4(models.Model): var1 = models.CharField(max_length=100) var2 = models.CharField(max_length=100) var3 = models.CharField(max_length=100) var4 = models.CharField(max_length=100) var5 = models.CharField(max_length=100) var6 = models.CharField(max_length=100) var7 = models.CharField(max_length=100) var8 = models.CharField(max_length=100) var9 = models.CharField(max_length=100) So var2 should be dependant on what was selected in var1 and so on. I tried this in my filters.py and the filter works, it is just not dependant: class CSVFilter(django_filters.FilterSet): entries = CSV.objects.values_list('var1', flat = True).distinct() var1_choices = [(e, e) for e in entries] #print("e" , var1_choices ) var1= django_filters.ChoiceFilter(choices = var1_choices ) entries = CSV.objects.values_list('var1', flat=True).distinct() var2_choices = [(e, e) for e in entries] var2= django_filters.ChoiceFilter(choices=var2_choices ) var3= CSV.objects.values_list('var3', flat=True).distinct() var3_choices = [(e, e) for e in entries] var3= django_filters.ChoiceFilter(choices=var3_choices ) var4= CSV.objects.values_list('var4', flat=True).distinct() var4_choices = [(e, e) for e in entries] var4= django_filters.ChoiceFilter(choices=var4_choices ) And in the template: <form method="POST"> {% csrf_token %} {{ filter.form }} <button type="submit">Search</button> </form> <ul> {% for i in filter.qs %} <li> {{ i.var1}} - {{ i.var2}} - {{ i.var3}} - {{ i.var4}} <a href = "{% url 'appp:edit_results' i.id %}"> <button>Edit</button> </a> </li> {% endfor %} </ul> So I have … -
'Options' object has no attribute 'get_all_related_objects'
Getting the above error while trying to log in. I have implemented django-users2 module. The following is the modules that I am using Django Version: 2.1.5 Python Version: 3.6.7 Installed Applications: ['myapp.apps.MyAdminConfig', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.humanize', 'category', 'tag', 'parttimejob', 'myapp.core', 'jobtype', 'users', 'django_extensions', 'jobmessages', 'search', 'profiles', 'employers', 'employees', 'jobtemplates', 'tempus_dominus', 'social_django', 'background_task'] 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', 'social_django.middleware.SocialAuthExceptionMiddleware'] Traceback: File "/usr/local/lib/python3.6/dist-packages/django/core/handlers/exception.py" in inner 34. response = get_response(request) File "/usr/local/lib/python3.6/dist-packages/django/core/handlers/base.py" in _get_response 126. response = self.process_exception_by_middleware(e, request) File "/usr/local/lib/python3.6/dist-packages/django/core/handlers/base.py" in _get_response 124. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/local/lib/python3.6/dist-packages/django/views/generic/base.py" in view 68. return self.dispatch(request, *args, **kwargs) File "/usr/local/lib/python3.6/dist-packages/django/utils/decorators.py" in _wrapper 45. return bound_method(*args, **kwargs) File "/usr/local/lib/python3.6/dist-packages/django/views/decorators/debug.py" in sensitive_post_parameters_wrapper 76. return view(request, *args, **kwargs) File "/usr/local/lib/python3.6/dist-packages/django/utils/decorators.py" in _wrapper 45. return bound_method(*args, **kwargs) File "/usr/local/lib/python3.6/dist-packages/django/utils/decorators.py" in _wrapped_view 142. response = view_func(request, *args, **kwargs) File "/usr/local/lib/python3.6/dist-packages/django/utils/decorators.py" in _wrapper 45. return bound_method(*args, **kwargs) File "/usr/local/lib/python3.6/dist-packages/django/views/decorators/cache.py" in _wrapped_view_func 44. response = view_func(request, *args, **kwargs) File "/usr/local/lib/python3.6/dist-packages/django/contrib/auth/views.py" in dispatch 61. return super().dispatch(request, *args, **kwargs) File "/usr/local/lib/python3.6/dist-packages/django/views/generic/base.py" in dispatch 88. return handler(request, *args, **kwargs) File "/usr/local/lib/python3.6/dist-packages/django/views/generic/edit.py" in post 141. if form.is_valid(): File "/usr/local/lib/python3.6/dist-packages/django/forms/forms.py" in is_valid 185. return self.is_bound and not self.errors File "/usr/local/lib/python3.6/dist-packages/django/forms/forms.py" in errors 180. self.full_clean() File "/usr/local/lib/python3.6/dist-packages/django/forms/forms.py" in full_clean 382. … -
Django: DATETIME_INPUT_FORMATS with USE_L10N?
It is documented that when USE_L10N is True, that DATETIME_INPUT_FORMATS are ignored. And this was well explained here: django DATETIME_INPUT_FORMATS not working But I am left wondering then, if USE_L10N how does one add to the legal datetime formats? I know DATETIME_INPUT_FORMATS is ignored, great, but what isn't? Ignored that is. And can one do the equivalent in L10N terms? -
How to get the output of a filter in django
I have a query in django and when I am trying to get the raw sql query using .query then I am getting following output..Now I want to print the values of this object and raw sql query. print("This",MessageSceduletime.objects.filter(scheduled_start_time__gte=present_time, scheduled_start_time__lte=threshold, user__status=1).exclude(status=2).query) Here present time is current time and threshold is 48 hours from present time.User_status 1 means that user is active and 2 means not active. -
How to use django rest framework_social_oauth2 to allow signups from google accounts?
While the documentation on the facebook connectivity is excellent I am not able to figure out how to connect the same to a google account, have used the same structure as show in here for converting the token but google gives me this response { "error": "access_denied", "error_description": "Your credentials aren't allowed" } Please let me know if there is any additional data that I need to provide to help solve this issue. -
How to display message payload data in template
I'm getting the messages from Gmail I am unable to display the message body in a template I got encoded from payload after I decoded it using base64, after I stored this in the dictionary in python after I am displaying in template it is displaying the payload data msg = service.users().messages().get(userId='me', id=message['id']).execute() msg_str = base64.urlsafe_b64decode(msg['payload']['body']['data'].encode('UTF8')) return render(request,'emailapp/index.html',{'msgdecddata':msg_str}) need to execute payload data in template -
Running apps present in same project in different ports at the same time using django
I am writng multiple apps inside the same django project Now I want to run each app individually my project name is : myproject and i have 2 apps inside it : app1, app2 Now i want to run app1 in different port(7000) and app2 in different port(7002) simultaneously. Is there any way to acheive it?? -
how to change a value of an entry dynamically on change of another value from django-admin
from django.contrib import admin from .models import Order class OrderAdmin(admin.ModelAdmin): list_display = ('id', 'name', 'product', 'email','is_valid','is_delivered', 'order_date') list_display_links = ('id', 'name',) list_editable = ('is_valid','is_delivered') search_fields = ('name', 'email', 'product') list_per_page = 25 admin.site.register(Order, OrderAdmin) Here, when 'is_valid' is changed by the admin, I want to decrement the value of another integer field by 1 -
Django Rest Frame not able to get the parent id of the self-nested object
******* Models ******* class Category(models.Model): category_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=50) parent_id = models.ForeignKey('self', on_delete=models.SET_NULL, null=True, blank=True) notes = models.CharField(max_length=200) def __str__(self): return '{0}, parent: {1}'.format(self.name, self.parent_id) class Game(models.Model): name = models.CharField(max_length=50) category_id = models.ForeignKey(Category, on_delete=models.CASCADE) start_time = models.DateTimeField('Start Time', null=True, blank=True) end_time = models.DateTimeField('End Time', null=True, blank=True) opponent1 = models.CharField(max_length=200, null=True, blank=True) opponent2 = models.CharField(max_length=200, null=True, blank=True) description = models.CharField(max_length=200) status_id = models.ForeignKey(Status, on_delete=models.CASCADE) def __str__(self): return '{0}: {1}'.format(self.name, self.category_id) def get_absolute_url(self): return reverse('game-detail', args=[str(self.id)]) ******* Serializer ******** class CategorySerializer(serializers.ModelSerializer): class Meta: model = Category fields = '__all__' class GameSerializer(serializers.ModelSerializer): category_id = CategorySerializer(read_only=True) class Meta: model = Game fields = '__all__' I am writing an API to get the parent_Id from the category_id from all the games that the API returns. But when I return all the game it does not show the value of the parent_Id. I also tried to add a subcategory to the CategorySerializer but it still does not work class SubCategorySerializer(serializers.ModelSerializer): class Meta: model = Category fields = '__all__' class CategorySerializer(serializers.ModelSerializer): subcategories = SubCategorySerializer(read_only=True) class Meta: model = Category fields = '__all__' Can someone help me to fix it? Thanks in advance. -
The QuerySet value for an exact lookup must be limited to one result using slicing - Django 2.1 and Python 3
I am the form_valid method to save the right question to an answer form. I am using get_object_or_404 to plug the question into the form. However, I keep getting multiple errors, regarding multiple values being returned or not limiting the results to an exact value. I would like to select the right question, so I can save the answer with the question. Can someone please show me where I am going wrong and how to select the specific question I need? I have been at this for hours - googling and trying different things. This is where I am stuck now: views.py class CreateAnswer(CreateView): model = Answer fields = ['answer'] def form_valid(self, form): answer = form.save(commit=False) profile = Profile.objects.get(user=self.request.user) institution = Institution.objects.all() question = Question.objects.filter(institution=institution) answer.question = get_object_or_404(Answer, question=question) answer.answerer = profile return super().form_valid(form) -
Django 2 Reference multiple users into one Model
I'm working on a project using Python(3.7) and Django(2) in which I have multiple models using the User model. I have a gig model, A gig can be created by a user and another user user can buy this gig, so I want to build a model to store the purchase information in which I want to include the Gig Model and the user who has created the Gig as seller and the user who is buying the gig as buyer in the model. How can I create a model like that? Here my Gig Model: class Gig(models.Model): CATEGORY_CHOICES = ( ('GD', 'Graphic & Design'), ('DM', 'Digital Marketing'), ('WT', 'Writing & Translation'), ('VA', 'Video & Animation'), ('MA', 'Music & Audio'), ('PT', 'Programming & Tech'), ('FL', 'Fun & Lifestyle'), ) title = models.CharField(max_length=500) category = models.CharField(max_length=255, choices=CATEGORY_CHOICES) description = models.CharField(max_length=1000) price = models.IntegerField(blank=False) photo = models.FileField(upload_to='gigs') status = models.BooleanField(default=True) user = models.ForeignKey(User, on_delete=models.CASCADE) created_at = models.DateTimeField(default=timezone.now) def __str__(self): return self.title And here, what I want to achieve something like: class Order(models.Model): gig = models.ForeignKey(Gig, on_delete=models.CASCADE) seller = "I want to add the gig creator here" buyer = "I want to add thee gig buyer here" -
How to set value to text field in html page, for dynamically generated checkbox fields using forms django?
I setup quiz app, where choice field(Multiple choice) is dynamically added using the django form set. This choice is checkbox type, i want to pass value to text field if i checked the checkbox.My problem is, i cant write a function to set value to text field, because the checkbox is dynamic. i tried to get the total no of checkbox displayed to the page and created thus much text box also. I tried a jquery which will set val to text field, if i checked checkbox. writing code for each checkbox is not possible because checkbox it dynamic.Is there any method in JavaScript to make it work.? test.html <form action="{% url 'polls:checkanswer' question.id %}" method="post"> {% csrf_token %} {% for choice in question.testchoice_set.all %} <input type="checkbox" name="choice" id="choices{{ forloop.counter }}" value="{{ choice.id }}" /> <label for="choice{{ forloop.counter }}">{{ choice.choice_opt }}</label><br /> {% endfor %} <input type="submit" value="Vote" /> <input type="text" name="nvalue" id="nvalue"> </form> <script> var totalCheckboxes = $('input:checkbox').length; $("#nvalue").val(totalCheckboxes); var i; //dynamically creating textboxes based on no of checkbox for (i = 1; i <= totalCheckboxes ; i++) { m = i; var i = document.createElement("input"); i.type = "text"; document.body.appendChild(i); i.value = ""; //i.hidden = true; i.id = 'choice'+m; … -
give public access to s3 bucket rather than serving static website for aws serverless application
i am new to aws serverless, and trying to host django app in aws serverless. now aws serverless uses s3 bucket for static website hosting which cost around $0.50 (I am in free tier). my question is instead of hosting static website can i not give public access to s3 bucket? as it would save me money. is it possible to use public bucket for aws serverless? -
Django: get id of object with only one field
I've a model Cart that has 2 fields, I'd rather change these 2 fields and keep only date_added. Right now I cannot do it because I use the cart_id field to create the Cart object and extract it's id: cart_id and date_added class Cart(models.Model): cart_id = models.CharField(max_length=100) date_added = models.DateField(auto_now_add=True) class Meta: db_table = 'Cart' ordering = ['date_added'] def __str__(self): return self.id In my view.py, I'm just creating the Cart object with the cart_id field as Random. This only to create this object and after that, obtain it's id, to replace "Random" with the id of the Cart recently created. This is not DRY at all. cart = Cart.objects.create(cart_id="Random") cart_id = cart.id How can I avoid this unnecessary step? -
Django project students will add new template files and fix permissions automatically
I am currently making a Django website for my school. On the website, students will have their own web pages linked on the main site that only they can access. My question is, therefore, the best way to approach this so that only people with access can access the students' web page. The biggest problem with this is that students will have a different amount of template files. My goal is to do this automatically so that they never have to add something in the source code when adding new web pages. I have something right now that is using groups and checking if a certain student has the correct group that goes with it and using URL dispatcher to do it automatically. Current url: -
Start with Apache2 for django server deployment
Please solve my problem that i am not able to find the path of Apache 2 folder and path to var/www folder in the virtual environment. I have installed Apache 2, mod-wsgi in my virtual environment I wanted to deploy Django on Apache wsgi server.