Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Celery task not starting at the start time provided
I have a Django app that utilizes celery in order to handle user scheduled tasks. I'm currently having a problem where I set start time for the PerodicTask and it does not start at that specific time, rather sometime later instead. Environment: Celery 4.3 Django 2.2 Python 3.7 task = PeriodicTask(name="foo",task="bar_task", start_time=DateTime5MinutesAhead, interval=EveryHourInterval) task.save() I expect the task run first in 5 minutes from when the task was created and then every hour after that. Instead, it seems to run at some arbitrary point later, completely ignoring the start_time argument. Am I mistaken on what the start_time argument is for? I've tried with IntervalSchedule as well as CrontabSchedule and neither seem to start at the exact start time. Bonus: What's actually really weird in my findings is that if I use IntervalSchedule set to every minute it actually DOES, in fact, start on correctly and run correctly, but if I set it to anything else it no longer works. -
Can't properly install Django-requests module
I followed the steps in this doc: https://django-request.readthedocs.io/en/latest/index.html Except step 4, which I'm not sure what it means: "Make sure that the domain name in django.contrib.sites admin is correct. This is used to calculate unique visitors and top referrers." However, I get this error, when I try to load my app: django.db.utils.OperationalError: no such table: request_request -
'str' object has no attribute 'items' using Django Rest Framework
I have a working Django project and when I deploy it to my server I get this error: AttributeError at /api/myData/ Django Version: 2.2.2 Exception Type: AttributeError Exception Value: 'str' object has no attribute 'items' Exception Location: /pathToProject/lib/python3.7/site-packages/rest_framework/fields.py in to_representation, line 1729 On my local machine I am using Python3.6 but on the server I have 3.7. Requirements are the same. Any idea why this happens? settings.py file: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'corsheaders', ‘myapp’, ‘myapp2’, ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', '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', ] CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_CREDENTIALS = True CORS_EXPOSE_HEADERS = ( 'Access-Control-Allow-Origin: *', 'Access-Control-Allow-Methods: GET, POST, PUT, DELETE', 'Access-Control-Allow-Headers: Authorization', ) CORS_ORIGIN_WHITELIST = ( 'http://127.0.0.1:3000', 'http://127.0.0.1:8000', ) REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': ('rest_framework.permissions.IsAdminUser',) } ROOT_URLCONF = ‘MyProject.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'MyProject.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': ‘somedatabasename’, 'USER': 'postgres', 'PASSWORD': ’somepassword’, 'HOST': 'localhost', 'PORT': '5432', } } AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] STATIC_URL = '/static/' -
Is there a way to apply a filter to a URL generated with the URL tag in Django?
For part of my user interface I need a URLencoded URL. This code doesn't work, but it's intended to give an impression of what I'd like to do: {% url 'team_event_calendar' id=team.id | urlencode %} Basically, get a particular URL - in this case "team_event_calendar" for a particular team, and then URLencode it. I suppose I could make a new version of the URL tag which URLencodes everything, but is there a way to do it with just Django's built-in tags? -
Big django queryset in Python's if conditional expression
I have a queryset that was used in below code. result = 1 if queryset else 0 In case of small queryset it's okay but when queryset gets bigger (more than 500 000 results) program freezes, it takes some time to stop it. What is happening behind the scenes when Django's queryset is tested in the code above? Is some extra work performed during that check? Even though the queryset is big, there is no problem with calling count() or iterator() or any other methods, it is that conditional expression where the problem appears. -
Decide which model to retrieve data on Django Rest Framework
I'm trying to build a simple API which should do the following: A user makes a request on /getContent endpoint, with the geographical coordinates for this user. By content, it means audio files. Every time they send a request, we should just get a random object from a Model and return the URL field from it, to be consumed by the front end. For this, it can be a random one, it doesn't matter much which one. Also, we should keep tracking about the requests each user makes. This way, we can check how many requests the user has made, and when they were made. Every 5 requests or so, the idea is to send the user a customized content based on their location. My idea is to store this content in another model, since it would have many more fields in comparison from the standard content. Basically, at every request, I'd check if it's time to send a special content. If not, just send the random one. Otherwise, I'd check if the time is appropriate, and the user is within a valid location based on the special content's data in the model. If this validation passes, we send the … -
Django: Is there a way to make client render Python 3 functions locally?
I have a project that I want a client to run a for/while loop on his/her machine. Is there a way to do such a thing since views are run on server-side, such as below: views.py from django.shortcuts import render def index(request): for i in range(0,10000): # Do stuff return render(request, 'app/index.html') Javascript was one of the option for client side but I have some libraries that are from Python 3 I want to run. -
Django values_list extremely slow on large dataset
Getting a values_list in django is extremely slow on a large dataset (6M+ items). I have a Django application with a DB structure like: class Taxon(models.Model): name = models.TextField() class Specimen(models.Model): taxon = models.ForeignKey("Taxon", related_name='specimens') class Imaging(models.Model): taxon = models.ForeignKey("Specimen") image = models.ImageField(("Imaging")) And need to get a list of all (images, taxon) belonging to a Taxon, if there are more than "100" images of that taxon. This worked fine in development with a small database: image_list = list(Imaging.objects .annotate(items_per_taxon=Count('specimen__taxon__specimens__images')) .filter(items_per_taxon__gte=100) .values_list('image', 'specimen__taxon')) But takes 30 minutes on a full dataset (6M Taxon rows, and 2M image rows). Is there a way of indexing the 'foreign key of a foreign key' or creating a virtual column in postgres that can make this faster? -
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 …