Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Method GET Django and Angular error 500 internal server
I'm building a basic app with login, register, etc. now i try finish the login using Django like backend and fronted with Angular, but i can't end my login because this error, when i try login with the correct credentials and redirect to new page or url show this error. TypeError at /doctor 'list' object is not callable"in network panel" service .ts constructor(private http: Http, private httpClient: HttpClient) { } private headers = new Headers({ 'Content-Type': 'application/json' }); getDoctores(): Promise<Doctor[]> { return this.http.get(this.baseurl + '/doctor?format=json', { headers: this.headers }) .toPromise() .then(response => response.json() as Doctor[]) } component .ts constructor(private dataService: dataService, public dialog: MatDialog, private router: Router) { this.getDoctores(); this.selectedDoctor = { id: -1, nombreDoc: '', apellidoDoc: '', rutDoc: '', direccionDoc: '' , telefonoDoc: '', release_date: '' } } getDoctores(): void { this.dataService .getDoctores() .then(doctores => this.doctores = doctores); } url.py path('auth/login/', obtain_jwt_token), path('auth/refresh-token/', refresh_jwt_token), url(r'^doctor$', views.DoctorList.as_view()), url(r'^doctor/(?P<pk>[0-9]+)$', views.DoctorDetail.as_view()), view.py class DoctorList(generics.ListCreateAPIView): queryset = Doctor.objects.all() serializer_class = DoctorSerializer class DoctorDetail(generics.RetrieveUpdateDestroyAPIView): queryset = Doctor.objects.all() serializer_class = DoctorSerializer -
How to implement User system for job board (I need employers to be able to register and create posts)?
I am creating a job board where users can search a zip code and see jobs in their area. I have the following models.py: class Business(models.Model): name = models.CharField(max_length = 150) address = models.CharField(max_length = 150) city = models.CharField(max_length = 150) zip_code = models.CharField(max_length = 10) state = models.CharField(max_length = 30) phone_number = models.CharField(max_length = 10) class Job(models.Model): business = models.ForeignKey(Business, on_delete = "models.CASCADE") #when the referenced object is deleted, also delete the objects that have references to it. title = models.CharField(max_length = 100) description = models.CharField(max_length = 500) zip_code = models.CharField(max_length = 10) def save(self, *args, **kwargs): zip_code = self.business.zip_code super(Job, self).save(*args, **kwargs) To use the website to look for jobs, you do not have to sign in. However, I obviously need employer's to be able to create an account so that they can register a business and post jobs for said business. I am not sure how to approach this and have seen many different ways to go about it online. Should I have the Business model extend the User model as such: class Business(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) #other fields... and then when an employer registers show a form that includes the User fields as well as … -
Importerror: How to import django-nose package?
Installed django-nose in virtual environment: (venv) user@~/../src$ pip install django-nose DEPRECATION: Python 2.7 will reach the end of its life on January 1st, 2020. Please upgrade your Python as Python 2.7 won't be maintained after that date. A future version of pip will drop support for Python 2.7. More details about Python 2 support in pip, can be found at https://pip.pypa.io/en/latest/development/release-process/#python-2-support Requirement already satisfied: django-nose in /home/user/../venv/lib/python2.7/site-packages (1.4.6) Requirement already satisfied: nose>=1.2.1 in /home/user/../venv/lib/python2.7/site-packages (from django-nose) (1.3.7) (venv) user@~/../src$ Django settings in test.py has django-nose package mentioned as INSTALLED_APPS, shown below: from base import * import os # Installed apps INSTALLED_APPS += ('django-nose', ) TEST_RUNNER = 'django_nose.NoseTestSuiteRunner' TEST_OUTPUT_DIR = os.environ.get('TEST_OUTPUT_DIR', '.') NOSE_ARGS = [ '--verbosity=2', '--nologcapture', '--with-coverage', '--cover-package=todo', '--with-spec', '--spec-color', '--with-xunit', '--xunit-file=%s/unittests.xml' % TEST_OUTPUT_DIR, '--cover-xml', '--cover-xml-file=%s/coverage.xml' % TEST_OUTPUT_DIR, ] # Database # https://docs.djangoproject.com/en/1.8/ref/settings/#databases DATABASES = { 'default':{ 'ENGINE': 'django.db.backends.mysql', 'NAME': os.environ.get('MYSQL_DATABASE', 'xxxxx'), 'USER': os.environ.get('MYSQL_USER', 'xxx'), 'PASSWORD': os.environ.get('MYSQL_PASSWORD', 'xxx'), 'HOST': os.environ.get('MYSQL_HOST', 'localhost'), 'PORT': os.environ.get('MYSQL_PORT', '3306') } } But django-nose package is not getting imported, based on below error: (venv) user@~/../src$ ls db.sqlite3 manage.py todo todobackend (venv) user@~/../src$ python manage.py test --settings=todobackend.settings.test Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/home/user/../venv/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 350, in execute_from_command_line utility.execute() File … -
Pytest delete db after tests
I have a test suite in pytest-django and I want to create a database at the start of the test and then delete the same as soon a test is completed in order to simulate the scenario without keeping a huge chunk of data. Any help would be appreciated. Thanks in advance! -
Unable to fetch data from database using django
I have created one small project in django, in which database is connected with django and having 'Reg' as table name in database. In models.py from django.db import models class Reg(models.Model): Name = models.CharField(max_length=10) Email = models.CharField(max_length=20) TUID = models.CharField(max_length=10) Password = models.CharField(max_length=8) In views.py from django.shortcuts import render, redirect from django.contrib.auth.models import User, auth from django.contrib import messages from .models import Reg, Group from django.http import HttpResponse def login(request): raw = Group.objects.all() return render(request, 'login.html', {'raw': raw}) In login.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>login</title> </head> <body> <p>hello....</p> {% for val in raw %} <p>{{ val.Name }}</p> {% endfor %} <p>end...</p> </body> </html> expected result should be data from database, but getting only hello... end... -
DRF - How do I link back from model class with PrimaryKey to model class with ForeignKey
I have two models Job and JobDescription. I have a ForeignKey jobid defined in JobDescription. The django-rest-framework does its magic and finds the automatically created PK id in Job to link to. In serializers.py JobDescriptionSerializer jobid will give me a hyperlink to the Job id. So far so good. At this moment however, this is a one way street (JobDescription -> Job). I would like to add a field to Job model/serializer that will allow hyperlinking the other way around as well (Job -> JobDescription). I went through the Django models documentation around ForeignKey and there are some references to forward/backward relationships, but how do I implement this in the rest-framework models/serializers? Thanks for your help in advance! models.py: class Job(models.Model): title = models.CharField(max_length=100, default='') type = models.CharField(max_length=20, default='') location = models.CharField(max_length=100, default='') created_date = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['id'] def __str__(self): return self.title class JobDescription(models.Model): jobid = models.ForeignKey(Job, related_name='desc2job', on_delete=models.CASCADE) description = models.TextField(blank=False) created_date = models.DateTimeField(default=timezone.now) class Meta: ordering = ['id'] def __str__(self): return str(self.jobid) serializers.py: class JobSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Job fields = ( 'url', 'id', 'title', 'type', 'location', 'created_date') class JobDescriptionSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = JobDescription fields = ('url', 'id', 'jobid', 'description', 'created_date') -
Django Testing - authenticate() returns None
Working on making some unittests with Django, and trying to make some testing with the login process with the login form. I am using modified User model just to make the email field unique; otherwise nothing drastically different. account/views.py def post(self, request): # Retrieve the username and password username = request.POST['username'] password = request.POST['password'] # Create a user object from authentication, or return None user = authenticate(username=username, password=password) # Check if user was created if user is not None: # Rest of the code, irrelevant... account/test_views.py def test_account_login_POST_successful_login(self): # Create a user to test login CustomUser.objects.create_user( username='test_user', email='test_user@intranet.com', password='flibble' ) response = self.client.post(self.login_url, { 'username': 'test_user', 'password': 'flibble' }) self.assertEqual(response.status_code, 301) account/models.py class User(AbstractUser): # Make the email field unique email = models.EmailField(unique=True) project/settings.py # Authentication AUTH_USER_MODEL = 'account.User' Funny thing is that login works normally on the web app, but when testing it always returns None. I've tried to check_password() with the created user, and it returns true in both the test method and the view method. I've also tried putting in AUTHENTICATION_BACKEND = ['django.contrib.auth.backends.ModelBackend'], but no go. -
Celery: different settings for task_acks_late per worker / add custom option to celery
This question is a follow up of Is there any way to find out the hash value of two files? I had a problem with celery (see the question that I follow up) and in order to resolve it I'd like to have two celery workers with -concurrence 1 each but with two different settings of task_acks_late. My current approach is not very beautiful. I am doing the following: in settings.py of my django project: CELERY_TASK_ACKS_LATE = os.environ.get("LACK", "False") == "True" This allows me to start the celery workers with following commands: LACK=True celery -A miniclry worker --concurrency=1 -n w2 -Q=fast,slow --prefetch-multiplier 1 celery -A miniclry worker --concurrency=1 -n w1 -Q=fast What would be more intuitive would be if I could do something like: celery -A miniclry worker --concurrency=1 -n w2 -Q=fast,slow --prefetch-multiplier 1 --late-ack=True celery -A miniclry worker --concurrency=1 -n w1 -Q=fast --late-ack=False I found Initializing Different Celery Workers with Different Values but don't understand how to embed this in my django / celery context. In which files would I have to add the code that's adding an argument to the parser and how could I use the custom param to modify task_acks_late of the celery settings. -
Django populating model in signal with accessing request
I am in trouble in populating a table, at first see my models. from django.contrib.auth.models import User class Group(models.Model): members = models.ManyToManyField( User, through='PersonGroup', related_name='person_of_the_group' ) class PersonGroup(models.Model): group = models.ForeignKey( Group, on_delete=models.CASCADE, related_name='group_person_of_group' ) person = models.OneToOneField( User, on_delete=models.CASCADE, related_name='group_person_of_group' ) I want when I create a group, the PersonGroup should populate automatically, I tried to achieve it in the signal but failed to do it, coz, I couldn't access request.user in signal @receiver(post_save, sender=Group) def create_person(sender, instance, created, **kwargs): if created: PersonGroup.objects.create( # ) Can anyone help to access to request in the signal? I need to solve this problem in signal at any means -
Unusual error occurring when attempting to remove user from Django admin page
I am creating a simple endpoint in my project, where a user can delete their account. When I send this request, it successfully works: However when I attempt to remove a user from my admin page, this error occurs: Error: IntegrityError at /admin/users/user/ insert or update on table "django_admin_log" violates foreign key constraint "django_admin_log_user_id_c564eba6_fk_auth_user_id" DETAIL: Key (user_id)=(1) is not present in table "auth_user". My code: models.py: from django.contrib.auth.models import AbstractUser from django.db import models class User(AbstractUser): pass def __str__(self): return self.username views.py: def deleteuser(request, username): user = User.objects.get(username=username) user.delete() return JsonResponse({"message": "User successfully removed"}, status=200) -
Why is bar blacklisted in pylint
I have an error while linting my django project with pylint. Pylint shows an error while linting my django project "C0102: Black listed name "bar" (blacklisted-name)" It's correct that I have a function called bar, but why is this name blacklisted? I don't know of a built-in with that name. -
gunicorn vs celery for concurrency in django
In Django webapp that's deployed, I get a POST request from external source in views.py As soon as post request is received, I modified post function to do certain action and deliver results(1.1.1.1 is endpoint) in views.py def post(self, request, *args, **kwargs): #do some action #deliver results to 1.1.1.1 In this case, I'm currently running task as the request comes. For instance, if 5 requests come in at once, it's currently processing one by one. But, I'd like to process all requests at once(assuming there are enough server load) and deliver results back. Would increasing workers in gunicorn solve the issue of concurrency or would it be better to utilize job queue like celery? I need something lightweight. If gunicorn is enough, how many workers would need to be set? And what is best practice method? -
Assign value to one-to-many field through django code
I am trying to assign value to a database entry that is defined using the models.ForeignKey. How should I refer to the variables in the referred model? In the code below, the assignment update_user.appointments.requester_name = requesting_user does not work. Googling has not helped me find the right solution. How should one refer to such variables from django/python? Below is my models.py class AppointmentRequest(models.Model): my_name = models.TextField(default='') requester_name = models.TextField(default='') meeting_year = models.TextField(default='') class CustomUser(AbstractUser): firstname = models.TextField(default='') lastname = models.TextField(default='') appointments = models.ForeignKey(AppointmentRequest, on_delete=models.CASCADE, default='', blank=True, null=True) I want to modify the value of appointments entry, i.e., my_name, requester_name, etc. Below is the code in views.py def book_appointment(request): requesting_user = request.GET['requesting_user'] update_user = CustomUser.objects.get(username=requested_user) update_user.appointments.requester_name = requesting_user -
ModuleNotFoundError: No module named 'mylife.wsgi'
So I'm trying to deploy my website in heroku. It gets deployed successfully but when i open the site, it displays application error. When I ran the logs, it displayed no module name mylife.wsgi. Here is the full error that I got. Starting process with command `gunicorn mylife.wsgi --log-file -` Process exited with status 3 State changed from starting to crashed. Also __import__(module) ModuleNotFoundError: No module named 'mylife.wsgi' I tried changing wsgi file, even added middleware, but no luck. Here is my wsgi.py file import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mylife.settings') application = get_wsgi_application() Here is my middleware from settings.py MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', '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', ] Here is my Procfile web: gunicorn mylife.wsgi --log-file - Here is my requirements.txt Django==2.0 dj-database-url==0.5.0 dj-static==0.0.6 gunicorn==19.9.0 Pillow==3.3.0 psycopg2-binary==2.7.7 whitenoise==4.1.2 django_ckeditor Here is the file structure └───mylife ├───accounts │ ├───migrations │ │ └───__pycache__ │ ├───templates │ │ └───accounts │ └───__pycache__ ├───daily │ ├───migrations │ │ └───__pycache__ │ ├───static │ │ ├───css │ │ └───js │ ├───templates │ │ └───daily │ └───__pycache__ ├───mylife │ └───__pycache__ └───staticfiles ├───admin │ ├───css │ │ └───vendor │ │ └───select2 │ ├───fonts │ ├───img │ │ └───gis │ └───js │ ├───admin │ └───vendor … -
What are the directives available in django similar to angular directives?
Do we have any directives in django similar to Angular directives like ng-show, ng-if, ng-for etc? When I worked on Angular, those directives are very helpful to me to finish my work faster. For example: how will you use a for loop in templates of django? -
Quiero que todos los navegadores acepten la coma para decimales
Tengo un formulario que en Firefox me acepta la coma para separar los decimales pero con Chrome me acepta el punto. Quisiera que los dos navegadores me acepten siempre coma; quiero que sólo se pueda ingresar números como 560,25 o 1250,75, por ejemplo. Estamos usando HTML5, en un proyecto con Python/Django. -
How to filter models efficiently in Django?
I have a website which will have many companies (model instances) and each company will have many users (model instances). What is the best way to separate the users by company so that the users of each company are all segregated from each other? All the ways I am currently thinking about doing this seems to use some sort of filtering in every section of the site which seems very inefficient. I already used Django's Groups for different employee types. Should groups be applied at the top of the chain (i.e. companies)? Even if I applied companies to groups I would probably be filtering at the template level quite often which seems inefficient and "un-pythonic". What are the best practices here? -
call a method in views.py from template
I want to call a method in views.py from my html file in templates when the user is authenticated. I don't know what html syntax should I use here. I don't think a form or button should work since I want to simply call that method without letting user click any button. {% block content %} {% if user.is_authenticated %} <!-- I want to call the method here--> <div id="user-logout">Hi {{ user.username }}! <a href="{% url 'logout' %}">logout</a></div> {% block chess_page %} {% endblock %} <!-- else redirect to the login page --> {% else %} <meta http-equiv="REFRESH" content="0; {% url 'login' %}"> {% endif %} {% endblock %} -
different response in django unittestcases in windows and linux
I am running django unittest in windows and linux at same PC. In one testcase , I am using submit() to submit a form. From the response of submit, when I am using regex search to search a text. In linux it is giving result but same code and same test giving none result in windows. I have tried in window10 and python3.7 response_report = response_query.forms[2].submit() datasheet = re.search(f'Datasheet_72222_003_002_input.xlsx'.encode(self.encoding), response_report.body).group(0).decode(self.encoding) In windows, testcase is failing but in linux same testcase is passing. I am expecting it to run on windows -
Django Single modelAdmin for multiple apps
My project has multiple apps. Users runs processess inside these apps. I want to record the starting time and the ending time for each process. I would like to display these information in a single view at django admin. Is it possible to build a modelAdmin with data from multiple apps? Should I use models to achieve this? Thanks in advance. -
Wrap a Django serializer in another serializer
I need a nested serializer in django. I have the following serializer that works: class LocationSerializer(serializers.ModelSerializer): coordinate = serializers.SerializerMethodField() message = serializers.SerializerMethodField() def get_message(self, instance: models.Location): if len(instance.message) > 1: return instance.message return None def get_coordinate(self, instance: models.Location): if instance.point: return {"latitude": instance.point.y, "longitude": instance.point.x} class Meta: model = models.Location fields = ('id', 'street', 'zip', 'phone', 'coordinate', 'message') The json this serializer produces needs to be wrapped in a a json object like this: { "locations": //here comes the serialized data } I tried it the following way with another serializer that has the serializer above in a field: class LocationResponseSerializer(serializers.Serializer): locations = LocationSerializer(many=True) But when I trie to use this serializer I always get the following error: The serializer field might be named incorrectly and not match any attribute or key on the `Location` instance. Original exception text was: 'Location' object has no attribute 'locations'. What am I doing wrong? Just wrapping it in a response object works, but is not a solution because it looks like this is not supported by the swagger frameworks that work with Django. Thanks for the help! -
Django geting request in signal post_save
I am trying to access Django built-in request to get some important data and most of them coming through my custom middleware, that is why i need to access the request at any means. this is my signal: @receiver(post_save, sender=MyModel) def create_journal(sender, instance, created, **kwargs): if created: # request.finance_data # Do something But there is no argument like request so I need to extend whatever needed to get request here.. in the request, I have finance_data and I access that like this: request.finance_data I know i can access it from view but my case will not solve in view, i need to access it in signal at any means Can anyone help me please to get this? -
HTML image not found
I have the code below: <body> <div class="team-section"> <h1>Our Team</h1> <span class="border"></span> <div class="ps"> <a href = "#"></a><img src = "p1.jpg" alt=""></a> </div> <div class="section" id="p1"> <span class="name">name</span> <span class="border"></span> <p> Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. </p> </div> </div> </body> Can someone explain me why I have error: Not Found: /about/p1.jpg . I try to put p1.jpg in many places and the final was the same. file tree -
django rest use an url that does not go through the frontend
I'm working on a project angular and django (2.0.13). Currently the application is available in localhost:4200, and I can also reach admin with localhost:4200/admin/. But for an url that I defined localhost:4200/other/, I have the error: Error: Cannot match any routes. URL Segment: 'other' it works with the url localhost:8000/other/. my goal will be to do as for admin is to be able to use port 4200 to display url /other/ I did not find how it works for the url /admin/ thank you -
I want to load a template from the templates folder but I get an error that says the included URLconf does not appear to have any patterns in it
I am trying to load a template in my templates/pages folder and get the error: django.core.exceptions.ImproperlyConfigured: The included URLconf '<module 'pages.urls' from 'D:\\django\\pages\\pages\\urls.py'>' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import. I have tried putting the templates folder in both the project and the app directory but still get the same error. In my settings.py I have: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], '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', ], }, }, ] and: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'pages', ] my urls.py file in the root project folder named pages_project looks like: from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('pages.urls')), ] and my urls.py in my app folder named pages looks like: from django.urls import path from . import views path('', views.HomePageView.as_view(), name='home') my views.py looks like: from django.shortcuts import render from django.views.generic import TemplateView class HomePageView(TemplateView): template_name= 'home.html' I have a template file named home.html in the path pages/templates/pages/home.html and looks like: <h1>Homepage</h1>