Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
(django) define models dynamically for importing different columns of csv files
I want to make web Test Report system using django to display hundreds type of csv files. each csv files have different fields and i have to display all of these csv files . so i want to define new models dynamically when new csv files(test result data)was made and has to be imported to model is there any way to solve this? -
Django Model Issue cant makemigrations
I created three table Person, Movie and Roll. I used table relationship as Onetomany and many-to-many. But when I start makemigrations. It can't take migrations. When I would like to action for makemigrations for my app It give this traceback(I use sqlitedb) RuntimeWarning: Model 'core.movie' was already registered. Reloading models is not advised as it can lead to inconsistencies, most notably with related models. new_class._meta.apps.register_model(new_class._meta.app_label, new_class) SystemCheckError: System check identified some issues: ERRORS: core.Movie_writers: (fields.E336) The model is used as an intermediate model by 'core.Movie.writers', but it does not have a foreign key to 'Movie' or 'Person'. But when I removed writes field from Movie table(model). It worked fine. this is my full models.py file class Person(models.Model): first_name = models.CharField(max_length=140) last_name = models.CharField(max_length=140) born = models.DateField() died = models.DateField(null=True, blank=True) class Meta: ordering = ('last_name', 'first_name') def __str__(self): if self.died: return '{}, {} ({}-{})'.format(self.last_name, self.first_name, self.born, self.died) return '{}, {} ({})'.format(self.last_name, self.first_name, self.born) class Movie(models.Model): director = models.ForeignKey(to='Person', on_delete=models.SET_NULL, related_name='directed', null=True, blank=True) writers = models.ManyToManyField(to='Person', related_name='writing_credits', blank=True) actors = models.ManyToManyField(to="Person", through="Role", related_name="acting_credits", blank=True) class Role(models.Model): movie = models.ForeignKey(Movie, on_delete=models.DO_NOTHING) person = models.ForeignKey(Person, on_delete=models.DO_NOTHING) name = models.CharField(max_length=140) def __str__(self): return f"{self.movie.id} {self.person.id} {self.name}" -
Creating a related object in an admin form
First time using the Django's admin framework and it's just overwhelming considering I only want to do a little thing. There is this class: class RefereeAdmin(ImportExportMixin, admin.ModelAdmin): form = autocomplete_light.modelform_factory(Referee, fields='__all__') list_display = ['name', 'player', 'referee_association', 'grade', 'rating', 'matches_by_month'] list_editable = ['rating'] search_fields = ['name', 'player__user__email', 'player__user__first_name', 'player__user__last_name'] view_on_site = True Which seems to be using a dependency, django-autocomplete-light. All I want is to add an Association field to the form and create an AssociationReferee object which takes a name, an association and a referee (the one we are creating). To populate the association select widget I need to access the request object to exclude those associations where the user has no authorization. How do I do all this? -
How to get the filter class or viewset class through model?
I want to find the corresponding filter class or viewset class only through Model. The corresponding Model can be found by filter class or viewset class, but it cannot be reversed. I have a naming of these three, there is a rule, I guess it can be found through the string name of the filter class or viewset class, but it can not be achieved class Manager(models.Model) class ManagerFilter(filters.FilterSet): class Meta: model = Manager fields = {'name': ['exact', 'in', 'startswith']} class ManagerViewSet(viewsets.ModelViewSet): filter_class = ManagerFilter I can only get the Model class, I want to get the corresponding filter class or viewset class according to this Model. -
How can I display a message to the user at a certain time Django
I was wondering how I could display a simple message to the user at the top of their screen at a certain time in Django. I haven't been able to find anything online about this, so I was wondering how I would go about doing this. Would I need to do something with DateTime? What view/model would I include the code in? Thanks for any help you can give :) -
Python web application to monitor and control multiple remote systems
I want to develop web app using python django Purpose- 1 monitor remote system(multiple client)usage in real time and display on web 2. Control remote system (multiple clients )from web to start stop service As far I know I would need socket ,thread. I am new to python and having basic knowledge and very new to web applications.. Appreciate you guidance.. -
django - How to save the uploaded file to a spefic folder specifying a name
I have a form that the user fills, submits and uploads a file with the same ID from the form. There is a table with the user name and the name of the supervisor. (user -supervisor). I want the user uploaded files to be saved in a folder under the name of the supervisor. Is this possible in django? -
Specific data pulled in foor loop
{% for min m %} currently pulls everything as I wanted HOWEVER REQUIREMENTS HAVE CHANGED Code on the home page:- {% for movies in movies %} {{ movies.title}} Tags- {{ movies.tags }} {% endfor %} Models.py I would like to run through the for loop for a specific field then again for another different field. Example :- Heading result one List containing field Tag = result one Heading result two List containing field Tag = result two -
Git command line syntax meaning?
I've created a .gitignore file but I'm not sure if it is working or not. Currently i have this in the gitignore file in the DEMOPROJECT directory *db.* __init__.py And I'm getting this output in the windows command line (venv) C:\..\..\PycharmProjects\WebP1\DEMOPROJECT>git checkout newMast Switched to branch 'newMast' D .gitignore M db.sqlite3 What is the significance of the D and M? -
How to set email field in Django?
Hi I'm making a user model in Django but getting an error regarding to email field class User(models.Model): User_id = models.AutoField(primary_key=True) user_name = models.CharField(max_length=50) first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) User_email = models.EmailField(max_length=70,blank=True) password = models.CharField(max_length=12) The error I am getting is You are trying to add a non-nullable field 'User_id' to user without a default; we can't do that (the database needs something to populate existing rows). -
How to store item based on selected week
I am building an attendance system and i have to capture their attendance every week and compute their final mark attendance. Right now, im not sure what is the best way of implementing it. But below is my current idea: Model.py: studName = models.ForeignKey(Namelist,on_delete=models.SET_NULL,blank=True, null=True, default=None) classGrp = models.ForeignKey(GroupInfo, on_delete=models.SET_NULL, null=True) currentDate = models.DateField(default=now()) wk1 = models.IntegerField(default=0) wk2 = models.IntegerField(default=0) wk3 = models.IntegerField(default=0) attendance = models.IntegerField(default=100) so my current idea is that, when the admin clicks week 1: the attendance of the student should be stored in wk1. Subsequently, if week 2 then store in week2. I am new to django n python so i am not sure how and where to implement the if-else statement. I need your suggestion how can i capture their attendance effectively. My end product is that i shld be able to compute their attendance and export their final mark attendance only. -
How write import code for foreign key used in bulk file imports using django-import-export?
"I'm trying to import data to one of my models, but it's failing because model has foreignKey Id." Same problem I am facing but given solution is not working. Adding foreignKey widget to django-import-export There is no more explanation for 'import' in django-import-export. Thankyou for helping me. -
Django pass family in template inside for cycle
In a simple view I pass a family in template like this: def page(request): family= Author.objects.all() return render(request, "myapp/page.html", {'family':family}) and I render in template like this: {% for item in family %} {{ item.pk }} {% endfor %} But, if I put my family inside a for cycle; for example: def page(request): family = [] for i in range(5): family= Author.objects.filter(name='John')[i] return render(request, "myapp/page.html", {'family':family}) it not render anything in template... Any idea? -
How to delete users information when he logs out from my app?
I am created web app, who output info about user and users friends. But when user logs out from their account on VK.com, my app continues to store information about him. Ideally I would like to remove user information from the template by clicking on the link. I tried to delete 'token' and 'user_id' from sessions, but it did not work. I am assuming need to delete 'code' which i get from SocialAuth view. But i don't know how i can do it, or problem may be something else. Can you help me? from django.shortcuts import render, redirect, reverse from django.views.generic import View import requests # Create your views here. class SocialAuth(View): def get(self, request): if 'token' in request.session: return redirect(reverse('user_detail_url')) return render(request, 'main/index.html') class UserPage(View): def get(self, request): if 'token' not in request.session: url = 'https://oauth.vk.com/access_token?client_id=7******2&client_secret=pNPPZ******9duWSq' \ '&redirect_uri=http://127.0.0.1:8000/social/user_detail/&code={}'.format(request.GET['code']) response_data = requests.get(url).json() token = response_data['access_token'] user_id = response_data['user_id'] request.session['token'] = token request.session['user_id'] = user_id user_data = requests.get(f'https://api.vk.com/method/users.get?userd_id={request.session["user_id"]}' f'&fields=photo_400&access_token={request.session["token"]}&v=5.101').json()['response'][0] friends_data = requests.get(f'https://api.vk.com/method/friends.get?user_ids={request.session["user_id"]}' f'&fields=photo_100&access_token={request.session["token"]}&v=5.101').json()['response']['items'] context = { 'user': user_data, 'friends': friends_data[:5] } return render(request, 'main/user_detail.html', context=context) def log_out(request): del request.session['token'] del request.session['user_id'] return redirect(reverse('authorize_url')) -
Test case not working properly in django?
Here I am writing some TestCase for my two functions but the code is not working.There is no redirect in function view_positions so I did assertEqual(response.status_code,200) but it says AssertionError: 302 != 200 and In case of test_create_position, I am using random username and password to login but I am not getting any error,faliures. It says Ok. What I am doing wrong here? This is my first unit testing so I want to know is this the good way of writing test case in django ? Note:there is no any error in the view.It is working fine urls.py path('add/job/positions/', views.add_jobs_positions, name='add_position'), path('list/job/positions/', views.view_jobs_position, name='view_positions'), views.py def view_jobs_position(request): if not request.user.is_superuser: return redirect('/login/') jobs_positions = Position.objects.all() return render(request, 'organization/view_positions.html', {'positions': jobs_positions}) def add_jobs_positions(request): if not request.user.is_superuser: return redirect('/login/') form = AddPositionForm() if request.method == 'POST': form = AddPositionForm(request.POST) if form.is_valid(): position = form.save() messages.success(request, 'New Position {} created.'.format(position.title)) return redirect('organization:view_positions') return render(request, 'organization/add_positions.html', {'form': form}) tests.py from django.test import TestCase class PositionTestCase(TestCase): def setUp(self): # create admin user for authentication self.admin = get_user_model().objects.create(username='admin',email='admin@admin.com',password='password321',is_superuser=True) self.admin.set_password('password321') self.admin.save() self.position = Position.objects.create(title='Sr.Python Developer') def test_get_all_positions(self): self.client.login(username='admin',password='password321') response = self.client.get(reverse('organization:view_positions')) self.assertEqual(response.status_code,200) self.assertTemplateUsed(response,'organization/view_positions.html') def test_create_position(self): #using random username and password but working as well self.client.login(username='admin564378483', password='12345667889') response … -
How to fix 'NoReverseMatch ' error in Django, Python
I got this error. NoReverseMatch at /reservation/ Reverse for 'reservation_remove' with arguments '('',)' not found. 1 pattern(s) tried: ['reservation/reservation_remove/(?P[0-9]+)/$'] I don't know how to solve it. This is my urls.py of reservation app. from django.urls import path from .import views app_name='reservation' urlpatterns = [ path('add/<int:nursery_id>/', views.add_reservation, name='add_reservation'), path('', views.reservation_detail, name='reservation_detail'), path('reservation_remove/<int:nursery_id>/', views.reservation_remove, name='reservation_remove'), path('full_remove/<int:nursery_id>/', views.full_remove, name='full_remove'), ] This is my views.py from django.shortcuts import render, get_object_or_404, redirect from django.http import HttpResponse from .models import City,Nursery from django.core.paginator import Paginator, EmptyPage, InvalidPage from django.contrib.auth.models import Group, User from .forms import SignUpForm from django.contrib.auth.forms import AuthenticationForm from django.contrib.auth import login, authenticate, logout def index(request): text_var = 'Start!!!' return HttpResponse(text_var) def allCity(request, c_slug=None): c_page = None cities_list = None if c_slug!=None: c_page = get_object_or_404(City,slug=c_slug) cities_list = City.objects.filter(city=c_page) else: cities_list = City.objects.all() paginator = Paginator(cities_list, 6) try: page = int(request.GET.get('page','1')) except: page = 1 try: cities = paginator.page(page) except (EmptyPage,InvalidPage): cities = paginator.page(paginator.num_pages) return render(request,'service/category.html',{'cities':cities}) def allSitting(request, c_slug=None): c_page = None sittings_list = None if c_slug!=None: c_page = get_object_or_404(City,slug=c_slug) sittings_list = Nursery.objects.filter(city=c_page,available=True) else: sittings_list = Nursery.objects.all().filter(available=True) paginator = Paginator(sittings_list, 6) try: page = int(request.GET.get('page','1')) except: page = 1 try: sittings = paginator.page(page) except (EmptyPage,InvalidPage): sittings = paginator.page(paginator.num_pages) return render(request,'service/city.html',{'city':c_page, 'sittings':sittings}) def SittingDetail(request, c_slug, nursery_slug): … -
Passing template variable to parent in Django
I have a number of apps that each have their own intro section. This intro section has quite a few lines of HTML and only a few lines are adjusted for each app (Think title and intro). I would like this intro section to live at the project level (where the navbar template lives), but I can't find a way to pass template variables from the app to the project. All of my apps(about 15) follow this template scheme: app_base.html extends project base.html app_base.html has an {% include %} to pull in app_intro.html all <app_unique_templates>.html that are called <app>/views.py, extend the app_base.html To reiterate, how can I pass a template variable from /views.py to project base.html template using my app template scheme? If I can't use this scheme, can I adjust it in a way that will allow me to accomplish this? Thank you all in advance! -
How do I add users to groups as they register
I am trying to add a user to groups that I have created in the django admin. How do I implement my view function so that the user is added to a group on registration? I have created a custom UserRegisterform as illustrated below to so that users can indicate Group they are in. I have a problem with implementing my view function so that the users are automatically added to groups I have researched and found this links : https://docs.djangoproject.com/en/2.2/topics/forms/ https://www.guguweb.com/2014/09/10/group-combo-box-django-user-profile-form/ have created a form as follows: forms.py from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import Group,User class UserRegisterForm(UserCreationForm): group = forms.ModelChoiceField(queryset=Group.objects.all(), required=True) email = forms.EmailField() class Meta: model = User fields = ['username', 'email', 'password1', 'password2', 'group'] my views.py file from django.shortcuts import render,redirect from .forms import UserRegisterForm from django.contrib.auth.models import Group def register(request): if request.method == 'POST': form = UserRegisterForm(request.POST) if form.is_valid(): for value in form.cleaned_data['group']: group = Group.objects.get(name= value) group.user_set.add(user) form.save() return redirect('login') else: form = UserRegisterForm() return render(request, 'users/register.html', {'form':form}) when I log into the admin site, i expect to see the user assigned to the group he/she chose. The User is added but not assigned a group -
POST method in Django Rest framework returning server error 500 on EC2 instance
I am trying to build a web app using Django Rest framework. When I run the app on localhost 127.0.0.0/8000 it works fine. But when I deploy it on an EC2 server the POST methods return 500 server error. Here is one of the post methods in the views.py - class customer_location(APIView): def post(self, request, *args, **kwargs): customer_id = json.loads(request.body).get('customer_id') queryset = customers.objects.filter(cid= customer_id) serialize = customer_details(queryset, many=True) return Response(serialize.data, status=status.HTTP_200_OK) The urls.py is like this - from django.conf.urls import include, url from django.urls import path from rest_framework import routers from . import views urlpatterns = [ url(r'^customer_location/$', views.customer_location.as_view(), name='customer_location'), ] The DEBUG mode is set to False and the EC2 instance IP address is added in the ALLOWED_HOSTS. The GET methods are working fine but the POST methods give error. I checked the logs and I am getting this - raise JSONDecodeError("Expecting value", s, err.value) from None And this is for this line in the view.py - customer_id = json.loads(request.body).get('customer_id') The inbound rules of the EC2 instance allows access for HTTP, HTTPS, SSH, PostgreSQL and Custom TCP rule for port 8000. When I run the curl command from the terminal I can get the values for the POST Method- … -
How to cope with circular import
Django==2.2.5 Python 3.7.3 Structure of yandex_general app: . ├── admin.py ├── apps.py ├── __init__.py ├── models.py ├── validators.py ├── views.py ├── yandex_const.py └── yandex_utils.py validators.py from yandex_general.yandex_utils import select_from_yandex_response def validate_retargeting_condition_id(id: int): id = select_from_yandex_response(AdEntity.RETARGETINGLISTS.value["service_name"], ids=[id]) if not id: raise ValidationError("Отсутствует такой Идентификатор условия ретаргетинга") models.py from yandex_general.validators import validate_retargeting_condition_id def validate_retargeting_condition_id(id: int): id = select_from_yandex_response(AdEntity.RETARGETINGLISTS.value["service_name"], ids=[id]) if not id: raise ValidationError("There is no such REtargeting condition") yandex_utils.py from yandex_general.models import YandexResponse def select_from_yandex_response(yandex_direct_object_name: str, ids: int = None, name: str = None) -> dict: try: selection = getattr(YandexResponse.objects.get(key="yandex_response"), yandex_direct_object_name) except ObjectDoesNotExist as e: ... Problem: Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "/usr/lib/python3.7/threading.py", line 917, in _bootstrap_inner self.run() File "/usr/lib/python3.7/threading.py", line 865, in run self._target(*self._args, **self._kwargs) File "/home/michael/PycharmProjects/ads2/venv/lib/python3.7/site-packages/django/utils/autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "/home/michael/PycharmProjects/ads2/venv/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "/home/michael/PycharmProjects/ads2/venv/lib/python3.7/site-packages/django/utils/autoreload.py", line 77, in raise_last_exception raise _exception[1] File "/home/michael/PycharmProjects/ads2/venv/lib/python3.7/site-packages/django/core/management/__init__.py", line 337, in execute autoreload.check_errors(django.setup)() File "/home/michael/PycharmProjects/ads2/venv/lib/python3.7/site-packages/django/utils/autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "/home/michael/PycharmProjects/ads2/venv/lib/python3.7/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/michael/PycharmProjects/ads2/venv/lib/python3.7/site-packages/django/apps/registry.py", line 114, in populate app_config.import_models() File "/home/michael/PycharmProjects/ads2/venv/lib/python3.7/site-packages/django/apps/config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "/home/michael/PycharmProjects/ads2/venv/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", … -
how to write query for checking list contains
I have a model with name Weekdays that contain a field with name Days. Days is a list of weekdays that already saved. ex: Days=['Monday', 'Sunday', 'Saturday'] there is a Variable in my view.py with name selected_day. ex: selected_day=['Monday'] now I want to find the object that Days field includes selected_day and I need to write a query that checks is Days contain selected_day or not. something like this maybe: my_obj=models.Weekdays.objects.get(Days contain selected_day) -
How to upload list of files to URL via django?
In Django, I was able to get the list of files from the media folder, how to select the list of files and send those files to given URL. User will select the given Location and push the files the locations. @ajax_request def listofilesVIEW(request, dir_name="media"): template_name = 'listofiles.html' path = os.path.join(settings.MEDIA_ROOT, dir_name) images = [] for f in os.listdir(path): if f.endswith(".img"): images.append("%s" % (f)) return render(request, template_name, {'images': images}) Here is the code for the checkbox: <div class="row"><div class="col"> {% for image in images %} <div class="form-check"><label class="info-title form-check-label"><input class="form-check-input" type="checkbox" value="{{ image }}" /> {{ image }} {% endfor %} </div> </div> -
AWS EC2 instance connection refused using Docker
I have tried looking for a solution for this and I don't seem to get one. I have my containers up and running, I have exposed ports 80 and 443 in the security groups configuration but I am getting a connection refused error from my browser. Checked the Nginx logs, nothing. Dockerfile FROM python:3.6-alpine ENV PYTHONUNBUFFERED 1 RUN apk update && apk add postgresql-dev gcc python3-dev musl-dev git jpeg-dev zlib-dev libmagic RUN python -m pip install --upgrade pip RUN mkdir -p /opt/services/writer_api/src COPY requirements.txt /opt/services/writer_api/src/ RUN pip install --no-cache-dir -r /opt/services/writer_api/src/requirements.txt COPY . /opt/services/writer_api/src/ WORKDIR /opt/services/writer_api/src production.yml version: "3" services: postgres: restart: always image: postgres ports: - "5432:5432" volumes: - pgdata:/var/lib/postgresql/data/ web: restart: always build: . env_file: env/prod.env command: gunicorn writer.wsgi:application --reload --bind 0.0.0.0:8000 depends_on: - postgres - redis expose: - "8000" redis: restart: always image: "redis:alpine" celery: restart: always build: . command: celery -A writer worker -l info volumes: - .:/home/user depends_on: - postgres - redis celery-beat: restart: always build: . command: celery -A writer beat -l info volumes: - .:/home/user depends_on: - postgres - redis nginx: restart: always image: nginx:1.13 volumes: - ./config/nginx/conf.d:/etc/nginx/conf.d ports: - "80:80" depends_on: - web volumes: pgdata: config/nginx/conf.d/prod.conf # first we declare our upstream … -
Value Error :Time data '2019-03-19T07:01:02Z' does not match format '%Y-%m-%dT%H:%M:%S.%fZ'
I am using dateformat function but when i search for feb month only it shows proper data but when i search for march month it shows error This is my separate dateformat.py file in templatetag folder from django.template import Library import datetime register = Library() @register.filter(expects_localtime=True) def dateformat(value): return datetime.datetime.strptime(value,"%Y-%m-%dT%H:%M:%S.%fZ") and this is my table data line <td>{{x.date_joined| dateformat|date:'d-m-Y' }}</td> Error: ValueError at / time data '2019-03-19T07:01:02Z' does not match format '%Y-%m-%dT%H:%M:%S.%fZ' -
Django TemplateSyntaxError: 'endblock', expected 'empty' or 'endfor'. Did you forget to register or load this tag?
I'm unsure where my syntax error is, if you can please spot it that would be great. {% extends 'budget/base.html' %} {% block content %} <ul class="z-depth-1"> {% for transaction in transaction_list %} <li> <div class="card-panel z-depth-0 transaction"> <div class="row"> <div class="col l5"> <span class="title"> {{ transaction.title }}</span> </div> <div class="col l5"> <span class="title">{{ transaction.amount }}</span> </div> <div class="col l1"> <span class="title bold">{{ transaction.category.name }}</span> </div> <a href=""> <i class="material-icons right"></i> </a> </div> </div> </li> {% endfor $} </ul> </section> </div> {% endblock content %} And 'budget/base.html' looks like this: {% load static %} <link rel="stylesheet" href="{% static 'css/styles.css' %}"> <!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>BudgetProject</title> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css"> <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> </head> <body> {% block content %} {% endblock %} <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script> </body> </html> I tried looking at similar problems and I'm fairly certain the syntax for the for loop is correct. My code was working until I added the {% for x in y %} {% endfor %}