Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Can you remove a clean_field from a form in a view?
I have a form in which I validate a field (clean_title). What I want to do is, delete the clean_title method in aCreateView view, is there any way to do it? The problem as such is that I don't want the title field validation in anUpdateView view, I just want that validation in a CreateView view. (I don't want to create another form I want to reuse this one.) In case you can't do what I want to do, is there any other alternative? # forms.py class CourseForm(forms.ModelForm): class Meta: model = Course fields = ['title', 'subtitle', 'image', 'description', 'status'] widgets = { 'title': forms.TextInput(attrs = {'class': 'form-control', 'placeholder': 'Titulo'}), 'subtitle': forms.TextInput(attrs = {'class': 'form-control', 'placeholder': 'Subtitulo'}), 'image': forms.FileInput(attrs = {'class': 'custom-file-input'}), 'description': forms.Textarea(attrs = {'class': 'form-control', 'placeholder': 'Descripcion'}), 'status': forms.Select(attrs = {'class': 'custom-select'}), } labels = {'title': '', 'subtitle': '', 'image': '', 'description': ''} def clean_title(self): title = self.cleaned_data.get('title') if Course.objects.filter(title = title).exists(): raise forms.ValidationError('Ya existe un curso registrado con ese titulo, elige otro.') return title -
Input from template to a view in Django
As you can tell, i'm new to Django, but already love it. I have a functional scraping server that scrapes 7 selects from a diagnostics page on one server. All environments I want to use this will have many of these servers with the same data to monitor performance. I would like to use this function to scrape this data from all entered target servers by input from the html template. Adding each server to monitor that will show up below the input text field from the main html page. I have completed this with a static url, but have been unsuccessful passing the different urls to scrape from the html template to the views url variable I have for the static address. I've attempted to create forms and pass that to the html template without success, including editing the views file. Reverted the code back to the original working code to not cause more confusion. html template: <form method="POST"> {% csrf_token %} <div class="field has-addons"> <div class="control is-expanded"> <input type="text" class="input" placeholder="Relay Name"> </div> <div class="control"> <button type="submit" class="button is-info"> Add Relay </button> </div> </div> </form> Views.py: import requests, bs4 from django.shortcuts import render from django.http import HttpResponse from … -
Cognito/AWS Amplify SDK to use with Django
I decided to use Django for building the REST APIs for our Mobile App. For setting the login (custom and social both), decided to go with AWS Cognito/Amplify. Does Cognito/SDK provide any SDK(Python) to share/authenticate the JWT token with Cognito. Or is there any other mechanism to authenticate the users through Cognito to use Django REST APIs. Is there enough support from Congnito/ Amplify to build backend with Django? -
how to get content inside div in django?
i have the code below, i want to get the code inside the div and store it in the database. usually in the with attribut name i have no problem. for this html <input type="text" name="post_title"/> in my views.py i have if request.POST: title = request.POST['post_title'] but now i have <div id="editor"> <p>Hello World!</p> <p>Some initial <strong>bold</strong> text</p> <p><br /></p> </div> i want to get the html code inside the div with id editor. -
How to loop over dictionary to display in frontend in django and implement user input
Ive created my own dictionary from the tweepy api results. it displays the data I want on the frontend. However, how do I go about looping over my dictionary so html is produced for each dictionary created. I also wish to have user input determine the query parameter but not sure how do it This is what I've tried but no avail.. {% for tweet in twitter_data %} <div class="tweet-container"> <img src="{{twitter_data.profile_dp}}" alt="avatar" class="avatar" /> <time class="tweet-time">{{twitter_data.created_at}}</time> <div class="push"> <div class="user"> <div class="user-string"><span class="name">{{twitter_data.user_name}}</span><span class="username">@{{twitter_data.user_screen_name}}</span></div> </div> <blockquote class="tweet"><span class="at">@lorem_bot </span>{{twitter_data.text}} <span class="tag">#lorem2015</span></blockquote> <div class="icons"> <i class="fa fa-reply"><span class="icon-number"> 10</span></i> <i class="fa fa-retweet"><span class="icon-number"> {{twitter_data.retweet_count}}</span></i> <i class="fa fa-star"><span class="icon-number"> {{twitter_data.fav_count}}</span></i> <i class="fa fa-ellipsis-h"></i> <i class="fa fa-eye"></i> </div> </div> </div> {% end for %} from django.shortcuts import render import requests import tweepy import json # Create your views here. CONSUMER_KEY = 'm' CONSUMER_SECRET = 'Xu' ACCESS_KEY = '116' ACCESS_SECRET = 'wz' auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET) auth.set_access_token(ACCESS_KEY, ACCESS_SECRET) api = tweepy.API(auth, wait_on_rate_limit=True) def index(requests): for tweet in tweepy.Cursor(api.search, query="xbox", q="{xbox}", count=1, result_type="recent", include_entities=True, lang="en").items(): twitter_data = { 'text': tweet.text, 'user_name': tweet.user.name, 'user_screen_name': tweet.user.screen_name, 'created_at': tweet.created_at, 'profile_dp': tweet.user.profile_image_url, 'retweet_count': tweet.retweet_count, 'fav_count': tweet.favorite_count } context = {'twitter_data': twitter_data} return render(requests, 'twitter/twitter.html', context) -
Django page shows status failure
today, my website looks like this: { "kind": "Status", "apiVersion": "v1", "metadata": { }, "status": "Failure", "message": "forbidden: User \"system:anonymous\" cannot get path \"/\"", "reason": "Forbidden", "details": { }, "code": 403 } Just a blank page with this error on it. Also it is not secured via HTTPS anymore. Yesterday, everything worked fine. I tried to restore the droplet on digitalocean, but still the same. What should I do now? Thank you very much -
How to add username to the filefield?
I am making use of file fields in my model and I want it to be saved as username_field.jpeg (or whatever format it is in), for example for rent_agreement I want to store it as username_rent_agreement.jpg. How am I supposed to do it? Please Help. Thanks in advance. -
I am confused what form_valid() or form_invalid() accomplished
I just started to use class based views instead of functions so sorry if this is an obvious question but what does form_valid() and form_invalid() do in a class that inherits from FormView? Django says that "This method is called when valid form data has been POSTed. It should return an HttpResponse" but what I don't get is how is it validated? I have additional checks I need to perform on the form before I can save the data (such as when signing up, making sure the two passwords entered are the same). How would I be able to add more checks if I want to? Here's the code I've been working with forms.py class SignupForm(forms.Form): email = forms.EmailField() alias = forms.CharField(max_length=15) password = forms.CharField(max_length=128, widget=forms.PasswordInput) confirm_pass = forms.CharField(max_length=128, widget=forms.PasswordInput) # used to verify if the passwords match def pwd_match(self): if self.is_valid(): cd = self.cleaned_data if cd.get('password') == cd.get('confirm_pass'): return True else: return False def fields_correct(self): if self.pwd_match() and self.is_valid(): return True return False views.py class SignupFormView(AjaxFormMixin, FormView): form_class = SignupForm template_name = 'forum/signup.html' success_url = reverse_lazy('home') def form_valid(self, form): # here I want to make sure that the passwords match and then save the user Thanks ahead of time! -
Django manage.py runserver command does not work
So I downloaded python (latest version) with everything checked and added it to PATH.I installed django, created everything I need, got the django files, but when i run python manage.py runserver it ptinys a lot of stuff, but in the end it prints I don't know anything about django or pip or python shell, I was following a tutorial but this doesnt work for me. C:\djangoproject>python manage.py runserver Traceback (most recent call last): File "C:\Program Files (x86)\Python\lib\site-packages\django\core\management\base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "C:\Program Files (x86)\Python\lib\site-packages\django\core\management\commands\runserver.py", line 60, in execute super().execute(*args, **options) File "C:\Program Files (x86)\Python\lib\site-packages\django\core\management\base.py", line 364, in execute output = self.handle(*args, **options) File "C:\Program Files (x86)\Python\lib\site-packages\django\core\management\commands\runserver.py", line 67, in handle if not settings.DEBUG and not settings.ALLOWED_HOSTS: File "C:\Program Files (x86)\Python\lib\site-packages\django\conf\__init__.py", line 79, in __getattr__ self._setup(name) File "C:\Program Files (x86)\Python\lib\site-packages\django\conf\__init__.py", line 66, in _setup self._wrapped = Settings(settings_module) File "C:\Program Files (x86)\Python\lib\site-packages\django\conf\__init__.py", line 157, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "C:\Program Files (x86)\Python\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", … -
How to use click event on <a> tag
How to use click event on tag without id Hello everybody, I have a html tag bellow: <a class="fc-day-grid-event fc-h-event fc-event fc-start fc-end fc-draggable fc-resizable" href="https://www.youtube.com/watch?v=XXXXX"><div class="fc-content"> <span class="fc-title">event</span></div><div class="fc-resizer fc-end-resizer"></div></a> this html code was built automatically by jquery so I can't add id or "onlick" event on this tag. What I want is when I click on this tag, it will open a new windows with href for me. I tried to use $('.fc-day-grid-event).on('click, function() { ...// }); But it's not working. How should I do for this case? Please help. -
IBM-Cloud Django Application integration with APP-ID
I've deployed a Python & Django Application in IBM Cloud Foundry and trying to integrate APP-ID for SSO. I received the OIDC provider information from the metadata provided from the APP-ID. But my question is how do I integrate the APP-ID with DJANGO APPLICATION for a Successful integration of SSO? Here is an example of how flask application, can be used but is there an example or process of how a Django application is done? https://dzone.com/articles/securing-your-python-app-with-openid-connect-oidc-1 For this integration, I tried to use below links for OIDC client in Django App and IBM APP-ID information for integration but no luck. APP-ID: https://dzone.com/articles/securing-your-python-app-with-openid-connect-oidc-1 OIDC: https://django-oidc-rp.readthedocs.io/en/stable/getting_started.html -
How can you use a single translation file in django?
I have many django apps in a single project that all have translations. Many of these translations are repeated across the different apps. I struggle to keep the translations consistent and hence I would prefer a single file for all translations in all apps. Is this possible? If so, how? -
How to test Django-request before deployment?
Just installed Django-requests modules. However, from the documentation, it was not clear to me where all the request data is stored or how to test that this package is working. Can someone help me understand how to test that this package is capturing all requests? -
after submit the form, I get an 500 error
after submit a form I get a 500 error and enabled debug mode for django. it shows that Exception Type: ConnectionRefusedError Exception Value: [Errno 111] Connection refused Exception Location: /usr/lib/python3.6/socket.py in create_connection, line 713 I am trying to build a django web end to manage(add/update/delete) the ftp users for our ftp(backend mysql).whenever I click submit button. it works on mysql(user info can be updated on mysql), but after clicking submit buttom, it always give me 500 error. how to fix this problem. anyone have any idea? Thank you <img id="top" src="/static/form/top.png" alt=""> <div id="form_container"> <h1><a>Create Publisher Account</a></h1> <form id="form_166666" class="appnitro" enctype="multipart/form-data" method="post" action=""> {% csrf_token %} <div class="form_description"> {% if saved %} <h2>Publisher Account</h2> <p>Account created successfully</p> </div> <ul > <li> <p>The new account has been successfully created.</p> </li> <li class="section_break"> <p> Return to <a href="/publish/publisher/add/">creation page</a>. </a> </li> {% else %} <h2>Publisher Account</h2> <p>Fill in the details below, followed by clicking 'submit' to create a new FTP account for a publisher</p> </div> <ul > {% for field in form %} <li id="li_1" > {{ field.label_tag }} <div> {{ field }} {{ field.errors }} </div> </li> {% endfor %} <li class="buttons"> <input type="hidden" name="form_id" value="166666" /> <input id="saveForm" class="button_text" type="submit" … -
Differentiate between 'account types' in Django
Thanks in advance if you're reading this... I'm a High School student working on a web application using Django, to help students find internships, and facilitate parents posting internship offers -- a sort of marketplace if you will. I'm trying to create a profile/account page for the users but I need a way to differentiate between whether the account logged in is a Student or Employer so that I can use views.py to generate a page appropriate to their account. In models.py, I have two different profile types which can be associated with a user account (handled by django.contrib.auth), see below for reference. class Student(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) profilePic = models.ImageField(default='default.jpg', upload_to='profile_pics') class Meta: verbose_name = 'Student Profile' def __str__(self): return f"{self.user.username}'s Profile" class Employer(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) profilePic = models.ImageField(default='default.jpg', upload_to='profile_pics') company = models.CharField(max_length=100, default='Unspecified') class Meta: verbose_name = 'Employer/Parent Profile' def __str__(self): return f"{self.user.username}'s Profile" In my views.py page, I'm trying to create a view for the account/profile that can detect whether the currently logged-in user's profile is linked to either the 'Student' or 'Parent' model and serve a page accordingly. I've tried a very rudimentary approach, as below, but unsurprisingly it's not working. def account(request): … -
Run a code on server side several times and use results on html render
I want to run a code which does web scraping and want result to be rendered on html page. On each user request, code in my view function generates data and shows results on page. Everything works fine but I suspect that this is the wrong way to implement my task. If many users will continuously request the page it will lead to server overload from which I am web scraping. def my_function(request): url = 'https://www.some_url.com' source_code = requests.get(url) plain_text = source_code.text soup = BeautifulSoup(plain_text, "html.parser") result = [] for link in soup.find_all('div', {'id': 'some_id'}): for link_inside in link.find_all('span', {'class': 'some_text'}): a = link_inside.text.strip() result.append(a) context = {'result': result} return render(request, 'myweb.html', context) is it possible to run the code on server side, say 12 times in a day, so I can use those results on rendering. 1) I don't want to keep or save results on my database 2) If I need to keep results on my database is it possible to erase each time and keep updated. -
How to make a correct password encryption in django users?
I would like to learn how to use JSON web-token authorization in Django. I am a newby in django, so I find several tutorials and followed them EXACTLY step by step. I have user model in my app: class User(AbstractUser): username = models.CharField(max_length=10, unique=True) email = models.EmailField(_('email address'), unique=True) USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['email', 'first_name', 'last_name'] def __str__(self): return "{}".format(self.email) Also I have a serializer: class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['url', 'email', 'username', 'first_name', 'last_name', 'password'] extra_kwargs = {'password': {'write_only': True}} def create(self, validated_data): password = validated_data.pop('password') user = User(**validated_data) user.username = validated_data.get('username') user.set_password(password) user.save() return user please, take a look at user.set_password(password) here. Then I have a api endpoint for creation a token, another endpoint for handling POST request for my users. Nothing special here. The problem is that JWT authorization works not as I expected: Problem description: I. Encryption of user password. I send JSON to POST method of my api endpoint for user creation Expected result: test user is created and password is stored in encrypted way pbkdf2_sha256$150000$mE9jeTnJdBds$X6VtRY0HKM4o4by4PzWNxtgKb8NL1mZg4W5M+y4Ohb0= Actual result: test user is created and password is stored in non-encrypted way. 123456 II. Obtain token issue Pre-conditions: I create a superuser via … -
Django Populate Form with User
My question is fairly straightforward, what is the best method for populating user information for onto a form? I currently use .save(commit=False) and then populate it manually. But is there an already built in mechanism in Django to do this automatically? Or is this as good as it gets? Below is a snippet of what I have in my views.py from django.shortcuts import render, redirect from django.contrib.auth.decorators import login_required from .forms import ContactsForm from django.contrib import messages def home(request): return render(request, 'mainapp/home.html') def about(request): return render(request, 'mainapp/about.html') @login_required def newapp(request): context = {'form': ContactsForm} if request.method == "POST": form = ContactsForm(request.POST) if form.is_valid(): instance = form.save(commit = False) # https://www.youtube.com/watch?v=2h57cqFRcqg instance.user = request.user instance.save() messages.success(request, "Saved new contact!") return redirect('home') #render(request, 'mainapp/home.html', {'form': form}) return render(request, 'mainapp/newapp.html', context) From models.py from django.contrib.auth.models import User from django.db import models class Contacts(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length = 100) email = models.CharField(max_length = 100, default='something-{}@gmail.com'.format(rand())) age = models.IntegerField(default = random.randint(a=22, b=45)) class Meta: verbose_name_plural = "Contacts" -
Running WSGI web server on a port (without using IIS)
Opening up a port for http request using WSGI (code is in Python+Django) on windows 10 - does not work for http requests coming from another machine I have a python+django+mongodb site which works great when I run it through VS and now I would like to publish it. My IIS set up with web.config with fastCGI gone bonkers and I am too frustrated to pursue it for the time being. Now I decided to run a WSGI server on a port. So here is what I did. I started my app from command line by running my manage.py like this... C:\Users\<myname>\AppData\Local\Continuum\anaconda3\python.exe manage.py runserver --noreload --settings=myapp.settings And it starts the server and I can visit the site at http://localhost:8000 and everything works great - LOCALLY. But with my machine IP x.y.z.w - I cannot access it from another machine by visiting http://x.y.z.w:8000 Why can't my server listens to the port 8000 from another machine on the SAME network? What do I have to do to allow this? I am on Windows 10 -
How to show an alert on the success url
I want to display a message that form has been successfully submitted when the user gets redirected to success url but I cannot find a solution to do it. Please help.Thanks! views class FeedbackCreate(CreateView): model = Feedback form_class = FeedbackForm template_name = 'feedback_form.html' success_url = '/qworky/dash/' def form_valid(self, form): self.object = form.save(commit=False) self.object.premises = Premises.objects.get(userprofile__user=self.request.user) self.object.client = UserProfile.objects.get(user=self.request.user) return super(FeedbackCreate, self).form_valid(form) -
How to use widgets in Django Crisp Forms
I am using Django Crispy forms and using the FormHelper. Now i want that one of the fields should use widgets. Actually, i want to populate date picker in the field using the widgets. forms.py class DeviceFilterFormHelper(FormHelper): # form_class = "form form-inline" form_id = "Device-search-form" form_method = "GET" form_tag = True html5_required = True layout = Layout( Div( Div('name', css_class="col-md-6"), Div('location', css_class="col-md-6"), css_class='row' ), Div( Div('phone_number', css_class="col-md-6"), Div('updated_date', css_class="col-md-6"), css_class='row' ), FormActions( Submit("submit", ("Search"), css_class="col-md-5"), css_class="col-8 text-right align-self-center", ), ) Below is the widget along with its attributes which i want to use in the formHelper. updated_date = forms.DateInput(attrs={ 'required': True, 'class': 'date-time-picker', 'data-options': '{"format":"Y-m-d H:i", "timepicker":"true"}' }), I just can't figure out how will i be using the widget. -
Python Django - Associating a OneToOneField on users. IntegrityError NOT NULL constraint failed
I'm making a website (obviously) with Django and I have a problem with when I create users. I want to associate my users with a model, called a Class, and the Class contains multiple users. And I assume I need to use models.OneToOneField() to associate one class with multiple users. But when I, for example, create a superuser in the terminal, I instantly get an IntegrityError when I have typed the last bit of required information and pressed enter. I know you could just set null=True in the OneToOneField but then the user isn't associated with a class. Basically, I just want a model called a Class to have multiple users associated with it, and every Class have different Keys/authentication (as shown in models.py) to do different things on my website. Full traceback (after trying to create superuser): Traceback (most recent call last): File "C:\Users\lll20\Documents\PYJA\pyja\p_env\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "C:\Users\lll20\Documents\PYJA\pyja\p_env\lib\site-packages\django\db\backends\sqlite3\base.py", line 383, in execute return Database.Cursor.execute(self, query, params) sqlite3.IntegrityError: NOT NULL constraint failed: users_user.parent_class_id The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Users\lll20\Documents\PYJA\pyja\p_env\lib\site-packages\django\core\management\__init__.py", … -
How to differentiate account types in Django?
Thanks in advance if you're reading this... I'm a High School student working on a web application using Django, to help students find internships, and facilitate parents posting internship offers -- a sort of marketplace if you will. I'm trying to create a profile/account page for the users but I need a way to differentiate between whether the account logged in is a Student or Employer so that I can use views.py to generate a page appropriate to their account. In models.py, I have two different profile types which can be associated with a user account (handled by django.contrib.auth), see below for reference. class Student(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) profilePic = models.ImageField(default='default.jpg', upload_to='profile_pics') class Meta: verbose_name = 'Student Profile' def __str__(self): return f"{self.user.username}'s Profile" class Employer(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) profilePic = models.ImageField(default='default.jpg', upload_to='profile_pics') company = models.CharField(max_length=100, default='Unspecified') class Meta: verbose_name = 'Employer/Parent Profile' def __str__(self): return f"{self.user.username}'s Profile" In my views.py page, I'm trying to create a view for the account/profile that can detect whether the currently logged-in user's profile is linked to either the 'Student' or 'Parent' model and serve a page accordingly. I've tried a very rudimentary approach, as below, but unsurprisingly it's not working. def account(request): … -
View to Download FileField From Django
I have files which are saved to the MEDIA_ROOT - and I am displaying the file paths as URLs in a table in my UI. I would like for these files to download when the user clicks the link in the table. However, when that happens I get an error because I don't have a URL or View defined to handle this I suppose. Problem is, I'm not really sure where to start - any suggestions. Below is my model, and the .html which displays the table and the link. models.py class Orders(models.Model): ... models.FileField(upload_to='web_unit', null=True, blank=True) ... def __str__(self): return self.reference index.html <div class="table-responsive"> <table id="main_table" class="table table-striped table-bordered" cellspacing="0" style="width="100%"> <thead> <tr> .... </thead> <tbody> {% for orders in orders %} <tr> <td> <!-- Update book buttons --> <button type="button" class="update-book btn btn-sm btn-primary" style="color: #FFCF8B; border-color: #FFCF8B; background-color: #FFF;" data-id="{% url 'order_update' orders.pk %}"> <span class="fa fa-pencil"></span> </button> </td> .... <td><a href="{{ orders.order_file }}">Download</a></td> #this is the link </tr> {% endfor %} </tbody> </table> When the link in the table is clicked - I'd like for the file to be downloaded - I need help on how to define the URL and the View to make this … -
Django: How to limit TimeField to hours and minutes only (comparison issue)
I'm developping a web api using django, I have a TimeField that stores hours:minutes:seconds, since it will be compared to a hours:minutes (without seconds) coming from the mobile app, the comparison will always fail. here is a comparison without seconds which is returnning an empty QuerySet: >>> journey = Journey \ ... .objects \ ... .filter((Q(route__departStation=1) | Q(route__stop__station_id=1)), ... (Q(route__arrivalStation=1) | Q(route__stop__station_id=1)), ... route__departDate="2019-07-31", route__departTime="10:57") >>> journey <QuerySet []> and here is when I add seconds to the comparison: >>> journey = Journey \ ... .objects \ ... .filter((Q(route__departStation=1) | Q(route__stop__station_id=1)), ... (Q(route__arrivalStation=1) | Q(route__stop__station_id=1)), route__departDate="2019-07-31", route__departTime="10:57:05") >>> journey <QuerySet [<Journey: Journey object (1)>]> so please, how can I prevent the seconds from being saved to the database from this TimeField(), or at least how can I limit the comparison to hours and minutes only.