Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Will we write all the code in views python file?
I'm just learning Django. My English is not good, I apologize in advance. Can't I create separate files for each view, such as Codeigniter or Laravel? Do I have to write the codes of all pages in a single file? This is very difficult and complicated for me. There will be thousands of lines of code. Is there a good way? -
How to read LDAP Tree with Django
Been Searching for a week now, only found backends for Django that can use LDAP Auth, but I don't need auth I just need to read the tree and view it in Django application. I've tried to use this great package but it reads nothing. here is how I used it in my code : for sure installed it first using pip: pip install django-ldapdb then I added this lines to settings.py: DATABASES = { 'ldap': { 'ENGINE': 'ldapdb.backends.ldap', 'NAME': 'server_name', 'USER': 'user', 'PASSWORD': 'password', 'HOST': 'ip_of_host', 'PORT': '389', }, 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), }, } DATABASE_ROUTERS = ['ldapdb.router.Router'] I expected to read the tree using the command : python manage.py inspectdb But it simply reads nothing! -
How to convert nan to NULL in database table using Pandas
In my CSV some columns are empty but when I'm inserting CSV data so in the place of the empty column nun is coming but I want NULL in the table file = request.FILES['csvfile'] df = pd.DataFrame(data, columns=['company’]) if not df.loc[i]['company'] == 'NaN': company = df.loc[i]['company'] else: company = None Company.objects.update_or_create(company_name=company) I want Null in the database table when the column is empty But when I'm using the above code that giving me nun in the place of the empty column -
Pyinstaller / Django - pkg_resources.DistributionNotFound: The 'django-oauth-toolkit' distribution was not found
Creating an .exe build for a Django Project with PyInstaller, Project is using django-oauth-toolkit I have used the PyInstaller Hooks as well for django-oauth-toolkit. My hook file is like below: Hooks/hook-django-oauth-toolkit.py from PyInstaller.utils.hooks import copy_metadata, collect_data_files datas = copy_metadata('django-oauth-toolkit') datas += collect_data_files('oauth2_provider') Included in settings.py INSTALLED_APPS = [ 'oauth2_provider', Included in urls.py url(r'^o/', include('oauth2_provider.urls', namespace='oauth2_provider')), PyInstaller Command: pyinstaller D:\djangoProject\manage.py --additional-hooks-dir=D:\djangoProject\Hooks After that: djangoProject.exe runserver localhost:8000 Got the following error: File "site-packages\oauth2_provider__init__.py", line 4, in File "site-packages\pkg_resources__init__.py", line 900, in require File "site-packages\pkg_resources__init__.py", line 786, in resolve pkg_resources.DistributionNotFound: The 'django-oauth-toolkit' distribution was not found and is required by the application What should I do further? -
Django Applications with Apache and mod_wsgi on Ubuntu(aws)
not able to upload my project on apache server.i am getting this error and the server is not working but i can run the server in virtualenv. please help me out myprojectenv) ubuntu@ip-172-31-30-51:~/autobot$ tail -f /var/log/apache2/error.log [Tue Sep 24 09:16:36.552922 2019] [mpm_prefork:notice] [pid 8130] AH00169: caught SIGTERM, shutting down [Tue Sep 24 09:16:37.432345 2019] [wsgi:warn] [pid 26849] mod_wsgi: Compiled for Python/2.7.11. [Tue Sep 24 09:16:37.432374 2019] [wsgi:warn] [pid 26849] mod_wsgi: Runtime using Python/2.7.12. [Tue Sep 24 09:16:37.435410 2019] [mpm_prefork:notice] [pid 26849] AH00163: Apache/2.4.18 (Ubuntu) mod_wsgi/4.3.0 Python/2.7.12 configured -- resuming normal operations [Tue Sep 24 09:16:37.435425 2019] [core:notice] [pid 26849] AH00094: Command line: '/usr/sbin/apache2' [Tue Sep 24 09:22:32.100910 2019] [mpm_prefork:notice] [pid 26849] AH00169: caught SIGTERM, shutting down [Tue Sep 24 09:22:33.171471 2019] [wsgi:warn] [pid 28383] mod_wsgi: Compiled for Python/2.7.11. [Tue Sep 24 09:22:33.171498 2019] [wsgi:warn] [pid 28383] mod_wsgi: Runtime using Python/2.7.12. [Tue Sep 24 09:22:33.174493 2019] [mpm_prefork:notice] [pid 28383] AH00163: Apache/2.4.18 (Ubuntu) mod_wsgi/4.3.0 Python/2.7.12 configured -- resuming normal operations [Tue Sep 24 09:22:33.190552 2019] [core:notice] [pid 28383] AH00094: Command line: '/usr/sbin/apache2' -
How To integrate (Benefit Payment Gateway) via Python Code
Documentation is not so clear How To integrate via Python Code I Tried Many Things But No One Works Nothing Found -
Why does Django drop the SQL DEFAULT constraint when adding a new column?
In the latest Django (2.2), when I add a new field to a model like this: new_field= models.BooleanField(default=False) Django runs the following commands for MySQL: ALTER TABLE `app_mymodel` ADD COLUMN `new_field` bool DEFAULT b'0' NOT NULL; ALTER TABLE `app_mymodel` ALTER COLUMN `new_field` DROP DEFAULT; COMMIT; While this works when everything is updated, this is very problematic because old versions of the application can no longer create models after this migration is run (they do not know about new_field). Why not just keep the DEFAULTconstraint? -
NoReverse MAtch at /
I have developed my blog following https://tutorial.djangogirls.org/en. The website runs on localhost, but it shows NoReverse Match at / error in pythonanywhere.com This error is shown when the view is not specified. however I have given code snippets to show the views. 1)my views.py from django.utils import timezone from .models import Post # Create your views here. def post_list(request): posts = Post.objects.filter(published_date__lte=timezone.now()).order_by('published_date') return render(request, 'blog/post_list.html', {'posts': posts}) def post_detail(request, pk): post = get_object_or_404(Post, pk=pk) return render(request, 'blog/post_detail.html', {'post': post}) 2)post_detail.html {% block content %} <div class="post"> {% if post.published_date %} <div class="date"> {{ post.published_date }} </div> {% endif %} <h2>{{ post.title }}</h2> <p>{{ post.text|linebreaksbr }}</p> </div> {% endblock %} 3)post_list.html {% block content %} {% for post in posts %} <div class="post"> <div class="date"> <p>published: {{ post.published_date }}</p> </div> <h2><a href="{% url 'post_detail' pk=post.pk %}">{{ post.title }}</a></h2> <p>{{ post.text|linebreaksbr }}</p> </div> {% endfor %} {% endblock %} 4)and base.html <html> <head> <title>Krishna's blog</title> <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css"> <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap-theme.min.css"> <link href="//fonts.googleapis.com/css?family=Lobster&subset=latin,latin-ext" rel="stylesheet" type="text/css"> <link rel="stylesheet" href="{% static 'css/blog.css' %}"> </head> <body> <div class="page-header"> <h1><a href="/">Django Girls Blog</a></h1> </div> <div class="content container"> <div class="row"> <div class="col-md-8"> {% block content %} {% endblock %} </div> </div> </div> </body> </html> 1)the error that … -
Form always invalid when running in pytest
I'm having an issue trying to get valid form in pytest. I am testing data changes through a Django Admin action. No matter what data I post to the form, form.is_valid() will always return False. Passing a dictionary to the form directly works, however I would like to be able to test through the action to make sure that the action filters out the locked records. # test_admin.py @pytest.mark.django_db class BaseTestCase(TestCase): """Base TestCase with utilites to create user and login client.""" def setUp(self): """Class setup.""" self.index_url = '/' self.login() self.django_db_setup() def create_user(self): """Create user and returns username, password tuple.""" username, password = 'testadmin', 'password123' user = User.objects.create_superuser( username, 'admin@test.com', password, first_name='Admin', last_name='Account', ) self.user = user return (username, password) def login(self): """Log in client session.""" username, password = self.create_user() self.client.login(username=username, password=password) @staticmethod def django_db_setup(): call_command('loaddata', 'fixtures/fixture.json') class AdminTestCase(BaseTestCase): def test_responsible_list(self): products = Product.objects.filter(pk__in=[230005, 229724]) form_data = { 'action': 'set_product_class', 'apply': 'Submit', 'product_class': '1', ACTION_CHECKBOX_NAME: products.values_list('pk', flat=True), } self.client.post('/admin/store/product/', form_data, follow=True) # Assert product_classes have changed # actions.py def set_product_class(modeladmin, request, queryset): # Exclude products that are locked queryset = queryset.exclude(is_locked=True) form = None if 'apply' in request.POST: form = SetProductClassForm(data=request.POST) if form.is_valid(): # action code # forms.py class SetProductClassForm(forms.Form): _selected_action … -
The function login(request, user) successfully logs the user in. But after redirection, request.user.is_authenticated is False. What am I doing wrong?
At Checkpoint 1, request.user is available and is_authenticated is True. def login_view(request): if request.user.is_authenticated: return redirect('publicusers:dashboard', permanent=True) else: # POST if request.method == "POST": login_form = LoginForm(request.POST) context["login_form"] = login_form if login_form.is_valid(): username = login_form.cleaned_data['username'] password = login_form.cleaned_data['password'] user = None try: user = authenticate(request, username=username, password=password) except: context["error_message"] = "There was an error authenticating." return render(request, "login.html", context) if user is not None: if user.is_active: login(request, user, backend='publicusers.backends') # Checkpoint 1 print('User:', type(user), request.user, request.user.is_authenticated, request.session) return redirect(reverse('publicusers:dashboard'), context) At Checkpoint 2, request.user.is_authenticated is False; but request.session is available and prints the same result in both the functions. def dashboard_view(request): # Checkpoint 2 print('Dashboard:', request.user.is_authenticated, request.session) if not request.user.is_authenticated: return redirect('publicusers:login', permanent=True) context = { "head_title": "Dashboard", "page_title": "Dashboard Page", "content": "Dashboard Content", } return render(request, "dashboard.html", context) Any assistance would be greatly appreciated. -
Do I have to manage Database concurrency in django?
I came across this article https://medium.com/@hakibenita/how-to-manage-concurrency-in-django-models-b240fed4ee2 Which describes how a request can change a record that another request is currently working with. Now this article is from 2017 and I haven't found anything about django cobcurrency since. Also manage.py is single threaded. Does this mean the issue is now managed by django internally or do I have to manage concurrency manually still when I deploy it with apache? -
Celery: why are there seconds of time gap from when a task is accepted and when it starts to execute?
I have a celery task: @app.task(bind=True, soft_time_limit=FreeSWITCHConstants.EXECUTE_ATTEMPTS_LOCAL_SOFT_TIME_LIMIT) def execute_attempt_local(self, attempt_id, provider_id, **kwargs): ... that is processed by a (remote) worker with the following config: celery -A mycompany.web.taskapp worker n -Q execute_attempts-2 --autoscale=4,60 This task gets spawned thousands at a time and has historically completed in 1-3s (it's a mostly I/O bound task). Recently as our app's overall usage has increased, this task's completion time has increased to 5-8s on average and I'm trying to understand what's taking up the extra time. I noticed that for many tasks taking 5-8 seconds, ~4s is taken in the in between the task being accepted by the thread and executing the first line of the task: [2019-09-24 13:15:16,627: DEBUG/MainProcess] Task accepted: mycompany.ivr.freeswitch.tasks.execute_attempt_local[d7585570-e0c9-4bbf-b3b1-63c8c5cd88cc] pid:7086 ... [2019-09-24 13:15:22,180: WARNING/ForkPoolWorker-60] PERF - entering execute_attempt_local What is happening in that 4s? I'm assuming I have a Celery config issue and somewhere there is a lack of resources for these tasks to process quicker. Any ideas what could be holding them back? -
Django views calls functions several times
I am creating a browser-based RPG where fighting mechanics are built into a model called "Battle". It performs actions on Hero, Monster and Item models according to some formulas. Each action adds a message to a "battle log". A player can issue a fight against another player or NPC in a form. When the form is submitted, it calls the same view, the Battle object is created, the characters are drafted and the game mechanics are run. For some reason, old "Battle" objects are still "selected" between runs of these views, as long as it's in the same web session. So even though I create a new object, the old battle log gets carried over to this new object. What am I doing wrong here? def battle_log(request): if request.session["last_battle"]: pk = request.session["last_battle"] b = Battle.objects.get(pk=pk) context_log = [] for l in b.messages: context_log.append(l) request.session["last_battle"] = "" context = { 'battle_log' : context_log, } return render(request, 'battle.html', context) else: return redirect('/game/monster') def fight_select_monster(request): row = [] form = SelectMonster() context = { 'form': form } if request.method=='POST': form = SelectMonster(request.POST) if form.is_valid(): monster = request.POST.get('monster') hero = request.POST.get('hero') hero = Hero.objects.get(pk=hero) monster = Monster.objects.get(pk=monster) hero.save() monster.fatigue = 0 b = Battle() … -
Fresh cookiecutter django project shows "Invalid syntax" at environ.py
I started my first project with cookiecutter using the cookiecutter-django template. When I tried to start it from PyCharm using the virtualenv, it gave me an error in a lib file: environ.py, telling me this: File "/home/madtyn/venvs/nana/lib/python3.6/site-packages/environ.py", line 114 raise ValueError, "No frame marked with %s." % fname ^ SyntaxError: invalid syntax After searching, I consulted somebody and I was recommended another way. I tried, as they told me, to make a new venv, activate it and run the server from command line but the same thing seems to happen. I don't think I did anything wrong. These are my specifications: Kubuntu (64bit arch) Python 3.6.8 (both the venv and the main one) cookiecutter 1.6.0 (installed through pip3) PyCharm 2019.2.2 -
How can I apply groupby on django queryset
I have a queryset say, a_query = <QuerySet [{'id': 1, 'user_id': 10, 'name': 'xyz'}, {'id': 2, 'user_id': 10, 'name': 'abc'},{'id': 3, 'user_id': 12, 'name': 'pqr'}]> So here I want to apply groupby on user_id so the result should be, [(10, [['xyz', 1], ['abc', 2]]), (12, ['pqr', 1])] I tried using itemgetter and groupby but that doesn't work. -
How can we create API for signup in web and app in django
I have created user signup API for a web app, when I use same for the native app it is throwing an error "ValueError at /api/v1/user/create, Illegal ID token provided: None. ID token must be a non-empty string." View.py class CustomUserCreateView(generics.CreateAPIView): class CustomUserSerializer(serializers.ModelSerializer): class Meta: model = CustomUser fields = ['email'] serializer_class = CustomUserSerializer def perform_create(self, serializer): ref_code = self.request.data.get('ref_code', '') if ref_code: try: referral = Referral.objects.get(ref_code=ref_code) # ru = Wallet.objects.get(user_id=referral.user_id) # ru.total_balance += 25 # ru.cash_bonus += 25 id_token = self.request.data.get('token', None) decoded_token = auth.verify_id_token(id_token) uid = decoded_token['uid'] uuuiiiddd = str(uid) descr = 'Refer Code Used bonus from App. Code used by = '+uuuiiiddd Transaction.objects.create(user_id=referral.user_id, transaction_type='BONUS', description=descr, amount=25, status='PENDING') UserBonusDatail.objects.create(user_id=referral.user_id, description=descr, amount=25, status='PENDING') # ru.save() except Referral.DoesNotExist: raise exceptions.ValidationError('referral-incorrect') email = self.request.META.get('HTTP_EMAIL', '') username = self.request.META.get('HTTP_USERNAME', email) id_token = self.request.META.get('HTTP_TOKEN', None) decoded_token = auth.verify_id_token(id_token) uid = decoded_token['uid'] serializer.save(uuid=uid, ref_code=ref_code, email=email, username=username) Serializer.py class CustomUserSerializer(serializers.ModelSerializer): ''' Serializer for CustomUser ''' class Meta: model = CustomUser fields = ['email', 'username', ] extra_kwargs = {'password':{'write_only' : True}} Models.py @receiver(post_save, sender=CustomUser) def create_additional_userinfo(sender, instance, created, **kwargs): if created: try: referral = Referral.objects.get(ref_code=instance.ref_code) referral.friend.add(instance) Wallet.objects.create(user=instance, total_balance=50, cash_bonus=50) Transaction.objects.create(user=instance, transaction_type='BONUS', description='SignUp with refer code bonus from App', amount=50, status='SUCCESS', expiry_date=datetime.datetime.now() + datetime.timedelta(days=30)) UserBonusDatail.objects.create(user=instance, description='SignUp with … -
How to fix LNK1104: cannot open file 'MSVCRT.lib' outside c++
I want to install django-admin in my project in virtualenv. After pip install django-admin I receive: fatal error LNK1104: cannot open file 'MSVCRT.lib' Microsoft Visual Studio 10.0\\VC\\Bin\\link.exe' failed with exit status 1104 I found solutions to fix this for all projects in c++, but can't find any solutions for django. Tried to create c++ project - works. For other non virtualenv c++ required libraries (ex. numpy) : Broken toolchain: cannot link a simple C program. -
Django staticfiles not loading in Production
I have created one Django project. It has several static files like CSS, JS, images etc. Below is file structure mysite |- mysite |- myapp |-- static |-- CSS |-- JS |- staticfiles settings.py STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) In developer mode, I'm able to serve the static files. But to serve static files in Production mode I run below command python manage.py collectstatic And it collected all the static files to staticfiles directory at the root of the project. But with some warnings like one below Found another file with the destination path 'admin/css/vendor/select2/LICENSE-SELECT2.css'. It will be ignored since only the first encountered file is collected. If this is not what you want, make sure every static file has a unique path. But when I visit my website css and js were missing. It didn't find the static files. I'm using Django 2.2. I've 'django.contrib.staticfiles' in my installed apps. But it's not serving files. Please don't mark it as duplicate. I've tried all possible ways but I didn't get success with it, that's why I've created a new question. -
Get data of previous months data in python django
Hi I am using django and my model look like this class SignupMonthlyPoint(models.Model): user = models.ForeignKey(Profile, on_delete=models.CASCADE, related_name='SignupMonthlyPoints') timestamp = models.DateTimeField(auto_now_add=True) value = models.FloatField() And I am getting last 30 days data like this def get_signupfromlinkmonthlypoints(): total_for_last_month =request.user.profile.SignupMonthlyPoint.filter( timestamp__gt=datetime.datetime.now() - relativedelta(months=1) ).aggregate( total=Sum('value') )['total'] print(total_for_last_month) but When I analyzed its last 30 days data not last month data. I want to make this like data of whole august month as it's last month of September, then data of whole july month and so on. -
Need to have url like /stories/<id>/episodes/1
When I create a new episode, id automatically increments. What I need? Imagine, I have 10 episodes for a different stories, so if I create an episode for story(for example, with id=5), it will assign id for new episode as 11. Url will be like /stories/5/episodes/11, but I need something like /stories/5/episodes/1. It would be good to store episodes id according to story, not all number episodes from all stories. How to do that? class Story(models.Model): title = models.CharField(max_length=255) description = models.TextField(max_length=255) cover = models.ImageField(upload_to=upload_location) created_at = models.DateTimeField(auto_now_add=True) author = models.ForeignKey(User, on_delete=models.CASCADE) class Episode(models.Model): title = models.CharField(max_length=255) description = models.TextField(max_length=255) created_at = models.DateTimeField(auto_now_add=True) story = models.ForeignKey(Story, on_delete=models.CASCADE) -
Calling a python function from bootstrap button in django web frame work
I am building a web interface using Django and want to run some code of python on button click event of bootstrap button. I want to know in which python file should I write that code and how to call that function. The code I am trying to run is using subProcess module of python to run a command on terminal and get error and output streams. The code it self is working fine in python 3.7 but I don't know how to call that code on button click. I am using django for the first time. <button type="button" class="btn btn-primary" name="sra" onclick="myFunction()">Primary</button> <script> function myFunction(){ #this is the part where I am stuck } </script> -
Django select2 chained dropdown with elasticsearch
I would like to have a chained dropdown with elasticsearch as back end using Django. I have two indices in ES and I will use index A for the chained dropdown and index B for the search given contraints selected in index A using common fields. Like below where after selecting Lv0, Lv1 and clicking submit form(I hope this can pass the selected variables to index B for query), query can be made over index B. I have successfully searched over index B alone many days ago but I have been stuck in adding index A and having it work with index B for a week. I have below using django-select2. models.py class Lv0(models.Model): name = models.CharField(max_length=255) class Meta: ordering = ('name',) def __str__(self): return self.name class Lv1(models.Model): name = models.CharField(max_length=255) lv0 = models.ForeignKey('Lv0', related_name="lv1", related_query_name="lv1",on_delete=models.CASCADE) class Meta: ordering = ('name',) def __str__(self): return self.name forms.py from esearch import models from esearch.models import Lv0, Lv1 #select2 dependent searchable fields class CateChainedSelect2WidgetForm(forms.Form): lv0 = forms.ModelChoiceField( queryset=Lv0.objects.all(), label='Lv0', widget=ModelSelect2Widget( search_fields=['name__icontains'], max_results=500, #dependent_fields={'vertical': 'verticals'}, attrs={'data-minimum-input-length': 0}, ) ) lv1 = forms.ModelChoiceField( queryset=Lv1.objects.all(), label='Lv1', widget=ModelSelect2Widget( search_fields=['name__icontains'], dependent_fields={'lv0': 'lv0'}, max_results=500, attrs={'data-minimum-input-length': 0}, ) ) views.py class TemplateFormView(FormView): template_name = 'esearch/base.html' Above only creates two dependent … -
How do I make it go to the home page?
I'm using Django and after login, I redirect to the main page. If there are still tokens in the session, I don't want to go to the login page. How can I do that ? class LoginPageView(TemplateView): template_name = 'login.html' def get(self, request, *args, **kwargs): if request.session['token']: return redirect('login') else: return redirect('home') My Urls: from django.urls import path from django.conf.urls import url from . import views urlpatterns = [ path('', views.HomePageView.as_view(), name='home'), path('login/', views.LoginPageView.as_view(), name='login'), url(r'^sign-in/$', views.sign_in, name='sign-in') ] I wrote code like this, but it doesn't work. KeyError at /login/ 'token' -
docker-compose up fails when docker-compose run is successful
I am trying to dockerize my Django-postgres app and run 2 commands using docker-compose My Dockerfile is: FROM python:3 ENV PYTHONUNBUFFERED 1 RUN mkdir /code WORKDIR /code ADD requirements.txt /code/ RUN pip install -r requirements.txt ADD . /code/ My docker-compose.yml is: version: '3' services: web: build: . command: bash -c "python app/manage.py migrate && python app/manage.py runserver 0.0.0.0:8000" volumes: - .:/code ports: - "8000:8000" depends_on: - db db: image: postgres ports: - "5432:5432" environment: POSTGRES_PASSWORD: password and my settings .py has the following database code: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'postgres', 'USER': 'postgres', 'PASSWORD': 'password', 'HOST': 'db', 'PORT': '5432', } } My db and web containers are up when I run: docker-compose run web python app/manage.py migrate docker-compose run web python app/manage.py runserver 0.0.0.0:8000 But when I run docker-compose up it fails with the error: web_1 | django.db.utils.OperationalError: could not connect to server: Connection refused web_1 | Is the server running on host "db" (172.23.0.2) and accepting web_1 | TCP/IP connections on port 5432? Can anyone please help me find where I am going wrong? -
How to retrieve Django model id from admin page via javascript
Suppose I have a Django model like this one. class Car(models.Model): speed = models.IntegerField() color = models.CharField(max_length=120) I registered it in admin via admin.site.register(Car) I want to add custom JS button for admin site object view, which will alert value of a color of an instance of a Car model. So when I press it I get something like "The car with id 13 is red" How can I get id of an object and value of a color field via JavaScript?