Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django- invalid token in plural form: EXPRESSION for malay language
I added 'ms' of malay language to my django website. this language is not supported by django, so I added to languages as follow: in settings.py # Django Version: 2.2.8 # Python Version: 3.6.9 LANGUAGES = ( ## Customize this ('en', gettext('en')), ('ms', gettext('ms')), ('th', gettext('th')), ) CMS_LANGUAGES = { ## Customize this 1: [ { 'code': 'en', 'name': gettext('en'), 'redirect_on_fallback': False, 'public': True, 'hide_untranslated': False, }, { 'code': 'ms', 'name': gettext('ms'), 'redirect_on_fallback': False, 'public': True, 'hide_untranslated': False, }, { 'code': 'th', 'name': gettext('th'), 'redirect_on_fallback': False, 'public': True, 'hide_untranslated': False, }, ], 'default': { 'redirect_on_fallback': False, 'public': True, 'hide_untranslated': False, }, } now when i go to mysite.com/en/admin/ it works properly. when I go to mysite.com/th/admin/ it works properly. but when I go to mysite.com/ms/admin/ it raises an error with this message: Value Error at /ms/admin/ invalid token in plural form: EXPRESSION -
Getting error as NOReverseMatch in django?
I am a newbie in django learning django with a online course by creating a realestate project.In this project I am having listings app which shows some of the listings in the web page from the database But I am getting an error of Reverse for 'listing' with arguments '('',)' not found. 1 pattern(s) tried: ['listings/listings/$'] My listings urls.py from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.index, name='listings'), url(r'^listings/<int:listing_id>$', views.listing, name='listing'), url('search', views.search,name='search') ] My listings views.py from django.shortcuts import get_object_or_404, render from django.core.paginator import EmptyPage, PageNotAnInteger, Paginator from .models import Listing def index(request): listings = Listing.objects.order_by('-list_date').filter(is_published=True) paginator = Paginator(listings, 6) page = request.GET.get('page') paged_listings = paginator.get_page(page) context = { 'listings': paged_listings } return render(request, 'listings/listings.html', context) def listing(request, listing_id): listing = get_object_or_404(Listing, pk=listing_id) context = { 'listing': listing } return render(request, 'listings/listing.html', context) def search(request): queryset_list = Listing.objects.order_by('-list_date') # Keywords if 'keywords' in request.GET: keywords = request.GET['keywords'] if keywords: queryset_list = queryset_list.filter(description__icontains=keywords) # City if 'city' in request.GET: city = request.GET['city'] if city: queryset_list = queryset_list.filter(city__iexact=city) # State if 'state' in request.GET: state = request.GET['state'] if state: queryset_list = queryset_list.filter(state__iexact=state) # Bedrooms if 'bedrooms' in request.GET: bedrooms = request.GET['bedrooms'] if bedrooms: queryset_list = queryset_list.filter(bedrooms__lte=bedrooms) … -
How do i display my views.py output on a template
this is my views.py `from django import template from django.shortcuts import render import requests from bs4 import BeautifulSoup def print_headlines(request,response_text): soup = BeautifulSoup(response_text, 'lxml') headlines = soup.find_all(attrs={"itemprop": "headline"}) for headline in headlines: print(headline.text) context = { "headline": headline } return render(request, 'home/maroweb.html', context) url = 'https://inshorts.com/en/read' response = requests.get(url) print_headlines(response.text)` then on my webpage i use {{headlines}} to display the results but nothing shows -
Django admin edit view formatting data
I'm currently going through Django admin docs and i can't seem to find anything relates to changing the changing how i want to display the data on the admin edit view of an object. I know that i can change the display value on the models side but it not the way that i would like to implement. My implement is to have all the fields on my model be encrypted and on the admin edit view it would show decrypted value of that field when editing. Is there anyway i can implement it on the edit view ? -
Does Django Class Based Views automatically assign form value for templates
I use Django 2 This is what my view.py contains class SchoolCreateView(CreateView): fields = ("name","principal","location") model = models.School The template (html file) used by this view contains the code: form.instance.pk And it works. It returns the correct primary key. I don't understand why. Why does this work when I have not defined the form object in my view? Is the value of form automatically assigned when using CBVs in Django? Follow up question. I know that form.instance represents a row in the model but what does form itself represent? My current understanding with forms is that it represents request.POST from views.py (basing my knowledge from function views). But that wouldn't make sense because the client has yet to make a POST request since he is still going to create a data entry which will be posted but is not being posted yet. -
How to extract all objects from all ids have linked with foreign key in django?
using Django 1.9 How to extract all objects from class table that linked with another class table by foreign key. I mean not all objects from one id but i mean all objects from all ids in one page. when i'm trying it gives me just one result For instance: urls.py from django.conf.urls import url from . import views app_name = 'music' urlpatterns = [ # /music/ url(r"^$", views.HomeView.as_view(), name='home'), # /music/123/ url(r'^(?P<pk>[0-9]+)/$', views.DetailView.as_view(), name='details'), # /music/song/ url(r'^song/$', views.songView, name='songs'), ] views.py from django.views import generic from .models import Album, Song from django.shortcuts import render class HomeView(generic.ListView): template_name = 'music/index.html' def get_queryset(self): return Album.objects.all() class DetailView(generic.DetailView): model = Album template_name = 'music/details.html' # Get all songs from all album (extracting songs from all of the albums in one page) def songView(request): for albums in Album.objects.all(): all_album = Album.objects.get(id=albums.id) all_song = all_album.song_set.all() return render(request, 'music/song.html', {'all_song': all_song}) songs.html {% extends 'music/base.html' %} {% block body %} {% for song in all_song %} <h2>{{ song }}</h2> {% endfor %} {% endblock %} -
Python list with multiple objects
i am trying to iterate over a list which have multiple objects inside it but unable to get the required output. please help me. here is the code enter code here expected output "studentId": "4", "status": "present" "studentId": "6", "status": "absent" { "lecture_id": "3", "students": [{ "studentId":"4", "status": "present" }, { "studentId": "6", "status": "absent" }] } def post(self, request): lecture = request.data.get("lecture_id") students = request.data.get('students') for i in students: return Response(students[i]) -
In Django Admin, can I lay out the list of objects according to foreign key (create headings and group objects under corresponding headings)?
I have 2 models, Chapter and Element. Chapters consist of elements. class Chapter(models.Model): title = models.CharField(max_length=100) # ... class Element(models.Model): chapter = models.ForeignKey(Chapter, on_delete=models.CASCADE, related_name="elements") # ... class Meta: ordering = ['index_number'] There are many elements, each belongs to a particular chapter. index_numberdetermines the position of an element in its chapter. In Django Admin, can I customize the display of the list of elements ('Select element to change' page) so that it would display headings (like 'fieldsets' headings, but basically chapter titles) and group the elements according to a chapter that they belong to? The desired output would look something like that: Chapter 1 title -------------------------- elm1_1 elm1_2 -------------------------- Chapter 2 title -------------------------- elm2_1 elm2_2 -------------------------- etc. -
django built in authenticator does not work
I am using the built in authenticater by django and have encountered 2 issues: Despite placing login decorators as such : class sales_home(View): @method_decorator(login_required) def get(self, request, *args, **kwargs): return render(request, 'sales/home.html') i am still able to access the home view by typing it into the URL . The login decorator only works when i clear my browser caches , which is not a solution in production. The second issue with the built in authenticater is that the request.user.id returns None. I am currently trying to display data based on the user's own inputs. Here is my API call : class ChartData(APIView): authentication_classes = [] permission_classes = [] def get(self, request, format=None): current_user = request.user sales_rev_data = Sales_project.objects.values_list('sales_project_est_rev', flat=True).filter(sales_project_status = 'p4').filter(sales_extras = current_user.id) labels = Sales_project.objects.values_list('sales_project_closing_date', flat=True).filter(sales_project_status = 'p4') data = { "labels1": labels, "default1": sales_rev_data, "labels2": labels, "default2": sales_rev_data, } return Response(data) because current_user.id returns None , i am unable to access the data that corresponds to the user. Your help will be greatly appreciated! -
How to retrieve and create data from model via DJANGO REST API?
I am new to Django and Django Rest Framework so I need some help. I want to receive time data from my model in Django. If there is no time stored for a particular user, it should create it, save it in my model and return that time data. I am also using Simple-JWT for token authentication which means that no one can access the database without a valid token. This is my code so far: models.py: class Mymodel(models.Model): emp= models.ForeignKey(User, on_delete = models.CASCADE) time = models.DateTimeField() views.py: def get_time(request): if (request.method == 'GET'): tk = request.GET.get('token') #token stored in LocalStorage headers = {'Authorization': 'Bearer ' + tk} url = 'http://127.0.0.1:8000/my_api/' response = requests.get(url, headers) if response: user_id = User.objects.get(username=request.GET.get('username')).pk user = User.objects.get(id = user_id) if not Mymodel.objects.filter(emp=user).exists(): current_time = timezone.now() create_time = Mymodel.objects.create(emp=user, time=current_time) data = create_time.time return HttpResponse(data) class MyAPI(generics.ListAPIView): permission_classes = [IsAuthenticated] #need to pass in JWT token in order to access the model. serializer = MySerializer def get_queryset(self): user_id = User.objects.get(username=request.GET.get('username')).pk user = User.objects.get(id = user_id) user_data = Mymodel.objects.all() queryset = user_data.filter(id=user_id) return queryset serializers.py: class MySerializer(serializers.ModelSerializer): class Meta: model = Mymodel fields = ('time') I just want to read from my table and check whether … -
Merging pdf files with PyPDF2 without saving the file and displaying it inline
I need to merge the uploaded files as one and display it inline in the browser. I am using PyPDF2 and managed to merged the file but I am writing it in the file directory. My question is how can I return it inline without saving/writing the file. Here is my code which saves/writes the merged files but doesn't display it inline(it says cannot display pdf) pms = PreventiveMaintenance.objects.filter(business_unit=business_unit) merger = PdfFileMerger() response = BytesIO() for pm in pms: if pm.pm_done: path_to_file = settings.BASE_DIR + pm.attachment.url merger.append(PdfFileReader(path_to_file)) merger.write(settings.BASE_DIR + "/media/certification_forms/result.pdf") merger.close() response = HttpResponse(response.getvalue(), content_type='application/pdf') response['Content-Disposition'] = 'inline; filename="test.pdf"' return response -
How to display an external webpage without displaying its URL?
I am currently using Django framework to create a simple web user authentication system for demo purposes. Basically after the authentication the program redirects the user to his specific dashboard page. This dashboard page is an external page and not part of my django application. One of the requirement for the project is to somehow hide/mask the external page's url to avoid copy and paste. I have tried using the iframe html tag to achieve this but it doesn't seem to work. What are some other simple ways i can use to achieve this result? (note: security is not important as this project will only be used in a demo session) views.py def userview(request): if request.user.username == 'user1': return HttpResponseRedirect('externalurl.com') views.py from django.urls import path from . import views urlpatterns = [ path('users/',views.userview, name='user_view'), path('',views.index,name='index'), ] -
Unable to send outlook email with Python Django using Microsoft Graph API
I am currently trying to integrate outlook email to my web application. I am able to retrieve emails, calendar and contacts from my outlook email using 'GET' requests. However, I am unable to send emails using 'POST' request. I am unsure where I am going wrong. Any help is appreciated. Below are some of my related code: outlookservice.py graph_endpoint = 'https://graph.microsoft.com/v1.0{0}' # Generic API Sending def make_api_call(method, url, token, payload = None, parameters = None): # Send these headers with all API calls headers = { 'User-Agent' : 'python_tutorial/1.0', 'Authorization' : 'Bearer {0}'.format(token), 'Accept' : 'application/json' } # Use these headers to instrument calls. Makes it easier # to correlate requests and responses in case of problems # and is a recommended best practice. request_id = str(uuid.uuid4()) instrumentation = { 'client-request-id' : request_id, 'return-client-request-id' : 'true' } headers.update(instrumentation) response = None if (method.upper() == 'GET'): response = requests.get(url, headers = headers, params = parameters) elif (method.upper() == 'DELETE'): response = requests.delete(url, headers = headers, params = parameters) elif (method.upper() == 'PATCH'): headers.update({ 'Content-Type' : 'application/json' }) response = requests.patch(url, headers = headers, data = json.dumps(payload), params = parameters) elif (method.upper() == 'POST'): headers.update({ 'Content-Type' : 'application/json' }) response = requests.post(url, … -
View redirect won't return flash message
To give some context, I'm testing what should happen when a User tries to update their password through a PasswordChangeForm. If any part of the new password contains the username, or the user's first name and/or last name, the password update should not take place. As a result of that, the User should be redirected to the same form with a flashed message of "Password cannot contain: Username; First Name; Last Name" However, the flashed message is not rendering in the template. How can I get the message to render otherwise? class UpdatePasswordTestCase(TestCase): '''Verify that a User receives a message telling them that a new password cannot contain their username, first name, or last name.''' @classmethod def setUpTestData(cls): cls.test_user = User.objects.create_user( "test_user", password="Secret*#7_code!", first_name='Fn', last_name='Ln' ) cls.new_password = cls.test_user.get_full_name() cls.passwords = { 'old_password': "Secret*#7_code!", 'new_password1': f"{cls.new_password}-{cls.test_user}", 'new_password2': f"{cls.new_password}-{cls.test_user}" } def test_password_update_fail(self): self.client.force_login(self.test_user) response = self.client.post( reverse("accounts:change_password", kwargs={'user_id': 1}), data=self.passwords self.assertContains(response, "Password cannot contain") # AssertionError: False is not true : Couldn't find 'Password cannot contain' in response @login_required(login_url="/accounts/sign_in") def change_password(request, user_id): user = request.user form = PasswordChangeForm(user) if request.method == 'POST': form = PasswordChangeForm(user, request.POST) if form.is_valid(): updated_password = form.cleaned_data['new_password1'] if (any(name in updated_password for name in [user.first_name, user.last_name, user.username])): … -
Django self.client.get() fails while HttpResponse() succeeds
This is in tests.py class QuizDetailView(TestCase): def test_quiz_detail_has_html(self): x = 1 # initial quiz path = reverse('quiz:detail', args=(x,)) print('\n** quiz:detail = ', path) print('** HttpResponse = ', HttpResponse(path)) print('-- self.client.get = ', self.client.get(path)) print('-- self.client.get /quiz/1 = ', self.client.get('/quiz/1')) print('-- self.client.get /quiz/1/ = ', self.client.get('/quiz/1/')) This is the output $ python manage.py test Creating test database for alias 'default'... System check identified no issues (0 silenced). . ** quiz:detail = /quiz/1/ ** HttpResponse = <HttpResponse status_code=200, "text/html; charset=utf-8"> -- self.client.get = <HttpResponseNotFound status_code=404, "text/html"> -- self.client.get /quiz/1 = <HttpResponsePermanentRedirect status_code=301, "text/html; charset=utf-8", url="/quiz/1/"> -- self.client.get /quiz/1/ = <HttpResponseNotFound status_code=404, "text/html"> So, HttpResponse is working but why does self.client not? If I manually go to the go to the webpage, then it works fine. -
How do I create a custom gunicorn setup with Django on Google App Engine?
Django project structure AppName │ main.py │ manage.yaml │ app.yaml │ gunicorn.conf.py │ └───AppName │ │ wsgi.py │ │ settings.py app.yaml # [START django_app] runtime: python37 handlers: # This configures Google App Engine to serve the files in the app's static # directory. - url: /static static_dir: static/ # This handler routes all requests not caught above to your main app. It is # required when static routes are defined, but can be omitted (along with # the entire handlers section) when there are no static files defined. - url: /.* script: auto entrypoint: gunicorn -c gunicorn.conf.py -b :8080 AppName.wsgi:app # [END django_app] gunicorn.conf.py import multiprocessing workers = multiprocessing.cpu_count() * 2 + 1 The application works without this line. entrypoint: gunicorn -c gunicorn.conf.py -b :8080 AppName.wsgi:app But I need to have a custom gunicorn.conf.py in order to set the number of workers dynamically. I've been following this doc. https://cloud.google.com/appengine/docs/flexible/python/runtime I have tried many variations of that line but I can't seem to get it to work. Also is setting the number of workers going to keep the application on? My goal here is to be safe in case of any spikes as well as have a worker always already booted … -
How to run unoconv via subprocess in django python?
If I run unoconv -f pdf test_pdf.docx in terminal, it's working fine. But if I run it in subprocess, I got this error unoconv: Cannot find a suitable pyuno library and python binary combination in /usr/lib/libreoffice ERROR: No module named 'uno' unoconv: Cannot find a suitable office installation on your system. ERROR: Please locate your office installation and send your feedback to: http://github.com/dagwieers/unoconv/issues Please help me resolve this problem -
Django CreateView - only allow n number of objects created. Redirect if limit is reached
thanks for taking the time to read this. I am making a simple CRM app with Django. This is my model. models.py class Contact(models.Model): contact_owner = models.ForeignKey(get_user_model(), on_delete=models.CASCADE,) first_name = models.CharField(max_length = 30) last_name = models.CharField(max_length = 30) contact_id = models.AutoField(primary_key=True) date_created = models.DateTimeField(auto_now_add=True) And this is my view that allows user to create contacts. views.py class CreateContact(LoginRequiredMixin, CreateView): model = Contact template_name = 'network/contacts_list.html' form_class = ContactForm def get_success_url(self): return reverse('home') def form_valid(self, form): form.instance.contact_owner = self.request.user return super(CreateContact, self).form_valid(form) def get_context_data(self, **kwargs): context = super(CreateContact, self).get_context_data(**kwargs) context['contacts'] = Contact.objects.filter(contact_owner=self.request.user) return context I am trying restrict amount of contacts a user can create. I have looked into a few ways of achieving this before writing this question. Using RedirectView. It only seems to work for GET requests. As far as I understand in my question situation, POST request is submitted. So this does not work. Using form_invalid. I thought that I could use this function to redirect me to a page if the request failed. I couldn't figure out how to pass a url in the form_invalid function. I don't think that's what it is for. Essentially, I think I need to add a count statement somewhere in the … -
Return row number with queryset in Djongo
I am working with Django and MongoDb with Djongo. How can I return a query set with row number in it? I have tried to explore aggregate functions of mongo but could not achieve the result. import uuid from djongo import models # Create your models here. class Snippet(models.Model): id = models.UUIDField(primary_key = True, default = uuid.uuid4,editable = False) title = models.CharField(max_length=100) body = models.TextField() Expected output { "id": "a3cee4c9-6e23-4710-81e2-dda67a2b98d5", "title": "sad", "body": "a sad story", "row" : "1" }, { "id": "3e8b054e-aea7-4fa0-9019-3afa1a1efd15", "title": "happy", "body": "a happy story", "row" : "2" }, { "id": "7e8d782e-583f-4f31-96e6-8dc267e69e9f", "title": "angry", "body": "an angry man", "row" : "3" } -
Adding Login/logout functionality in school management system
I want to add login,logout functionality in the Person model so that any other class inherits it such as guardians students staffs can also get those functionality. How to do that and is there any better way? from django.db import models # simplified class Person(models.Model): Name = models.CharField(max_length=200) BirthDate = models.DateField('Date of birth') Email = models.EmailField(max_length=200) CellPhone = models.CharField(max_length=14) class Guardian(Person): pass class Student(Person): guardians = models.ManyToManyField(Guardian, db_table='Student_Guardian_Bridge') Address = models.ForeignKey(Location, on_delete=models.CASCADE) class Staff_Type(models.Model): type_of_staff = models.CharField(max_length=50) def __str__(self): return self.type_of_staff class Staff(Person): staff_type = models.ForeignKey(Staff_Type, on_delete=models.PROTECT) Salary = models.IntegerField() guardians = models.ManyToManyField(Guardian, db_table='Staff_Guardian_Bridge') Address = models.ForeignKey(Location, on_delete=models.CASCADE) -
How to implement a trigger before saving values in a Django form?
I have the following view in Django that allows users to save the activities based on a specific category (see below): Every time a new activity is created, it receives 5 points as it was defined in the model : class Activity(models.model): CATEGORY = [('AUTOMATION','AUTOMATION'), ('TROUBLESHOOTING', 'TROUBLESHOOTING')] activity = models.CharField(null=False, max_length=140) type = models.CharField(max_length=10, choices=CATEGORY, default=ACTIVE) points = models.Integerfield(default=5) However, my intention is that every time a new activity is inserted then this one should receive 5 points while the previous activities increase their previous points by 5, so the latest activity always contains the lowest value of points while the oldest activity contains the highest value. Currently, I have tried to implement this logic in the code from below but I don't see any increase of points in the activities: # views.py def create_task(request): form_create = ActivityModelForm(request.POST or None) if form_create.is_valid(): obj = form_create.save(commit=False) obj.points = form_create.cleaned_data.get('points') + 5 obj.save() form_create = ActivityModelForm() template_name = 'task/formActivity.html' context = {'form': form_create} return render(request, template_name, context) # forms.py class ActivityModelForm(forms.ModelForm): class Meta: model = Activity fields = ['activity', 'type', 'points'] def __init__(self, *args, **kwargs): super(ActivityModelForm, self).__init__(*args, **kwargs) self.fields['activity'].required = True self.fields['points'].required=False self.fields['type'].required=False How should I implement my logic in the view? … -
Django test module produce these errors
I am very new at Django. I am following the tutorial by Vitor Freitas, "A Complete Beginner's Guide to Django". In the test module, I get the error shown below. Can some kind sole guide me as to my error. ERROR: test_redirection (boards.tests.test_view_reply_topic.SuccessfulReplyTopicTests) Traceback (most recent call last): File "/home/hp/Desktop/PythonProjects/myproject/myproject/boards/tests/test_view_reply_topic.py", line 34, in test_redirection self.assertRedirects(self.response, topic_posts_url) AttributeError: 'SuccessfulReplyTopicTests' object has no attribute 'response' The file it is referring to is this file class SuccessfulReplyTopicTests(ReplyTopicTestCase): def test_redirection(self): url = reverse('topic_posts', kwargs={'pk': self.board.pk, 'topic_pk': self.topic.pk}) topic_posts_url = '{url}?page=1#2'.format(url=url) self.assertRedirects(self.response, topic_posts_url) ===================================================== FAIL: test_redirection (accounts.tests.test_view_signup.SuccessfulSignUpTests) Traceback (most recent call last): File "/home/hp/Desktop/PythonProjects/myproject/myproject/accounts/tests/test_view_signup.py", line 62, in test_redirection self.assertRedirects(self.response, self.home_url) File "/usr/local/lib/python3.7/dist-packages/django/test/testcases.py", line 348, in assertRedirects % (response.status_code, status_code) AssertionError: 200 != 302 : Response didn't redirect as expected: Response code was 200 (expected 302) The file it is referring to is this file class SuccessfulSignUpTests(TestCase): def test_redirection(self): self.assertRedirects(self.response,self.home_url) -
Saving multiple fields of a model instance using a for loop - Django
I'm having a problem when trying to save data into an SQLite database from a Django View. Generally speaking, my approach is the following. 1) Getting data (dict) 2) Instantiating the model Loop - In 3) Loop over the dict to get the key, values pairs and saving them into the instance Loop - Out 4) Saving the instance The problem is that I'm getting an empty instance after the for loop instead of a populated one. Now the code models.py class OptionsHomePage(models.Model): option_a = models.IntegerField(choices=MINUTES_OPTIONS) option_b = models.IntegerField(choices=HOURS_OPTIONS) start_time_am_minutes = models.IntegerField(choices=MINUTES_OPTIONS, default=0) start_time_am_hours = models.IntegerField(choices=HOURS_OPTIONS, default=0) end_time_am_minutes = models.IntegerField(choices=MINUTES_OPTIONS, default=0) end_time_am_hours = models.IntegerField(choices=HOURS_OPTIONS, default= 0) Views Note: synonyms is a dictionary where I'm mapping the data that comes from the front to their respective values in the model ... options = OptionsHomePage() data_to_fill = request.GET.get('data_to_fill') data_to_fill = json.loads(data_to_fill) for k, v in synonyms.items(): try: # print(data_to_fill[k]) data_name = synonyms[k] value = data_to_fill[k] options.data_name = value print('{} - {} '.format(data_name,data_to_fill[k])) except Exception as e: print(e) print(options) options.save() ... The print statements there, just for seeing what's happening there gives me the following: end_time_pm_minutes - 10 delay_seconds - 11 screen_of_option - off ------------------------------ OptionsHomePage object (None) ------------------------------ Well... thanks in advance! … -
Django - Custom logging handler class can't be picked up
I'm developing a Django app (Django 2.0.7, Python 3.7, Windows 10, PyCharm) and I need to code a custom logging handler in order to store log messages into the database. I'm getting this error when i try to run the application: pydev debugger: process 27148 is connecting Connected to pydev debugger (build 192.6817.19) pydev debugger: process 28448 is connecting Unhandled exception in thread started by <_pydev_bundle.pydev_monkey._NewThreadStartupWithTrace object at 0x000001F1C52AD648> Traceback (most recent call last): File "C:\Program Files\Python\lib\logging\config.py", line 387, in resolve found = getattr(found, frag) AttributeError: module 'Inmobiliaria.inmobiliaria.utils.logs' has no attribute 'handlers' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Program Files\Python\lib\logging\config.py", line 562, in configure handler = self.configure_handler(handlers[name]) File "C:\Program Files\Python\lib\logging\config.py", line 712, in configure_handler klass = self.resolve(cname) File "C:\Program Files\Python\lib\logging\config.py", line 389, in resolve self.importer(used) File "C:\Users\facun\Desktop\DEV\forreal\backend\Inmobiliaria\inmobiliaria\utils\logs\handlers.py", line 2, in <module> from Inmobiliaria.inmobiliaria.services.application_log_services import create_application_log File "C:\Users\facun\Desktop\DEV\forreal\backend\Inmobiliaria\inmobiliaria\services\application_log_services.py", line 1, in <module> from Inmobiliaria.inmobiliaria.models import Applicationlog File "C:\Users\facun\Desktop\DEV\forreal\backend\Inmobiliaria\inmobiliaria\models.py", line 9, in <module> UserModel = get_user_model() File "C:\Users\facun\Envs\for-real\lib\site-packages\django\contrib\auth\__init__.py", line 194, in get_user_model return django_apps.get_model(settings.AUTH_USER_MODEL, require_ready=False) File "C:\Users\facun\Envs\for-real\lib\site-packages\django\apps\registry.py", line 192, in get_model self.check_apps_ready() File "C:\Users\facun\Envs\for-real\lib\site-packages\django\apps\registry.py", line 127, in check_apps_ready raise AppRegistryNotReady("Apps aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. The above exception was the … -
Django Selenium Test Using Live Database
I'm new to selenium and struggling to know where to begin with this one. This works - class SignUpViewFunctionalTests(LiveServerTestCase): port = 9000 host = '0.0.0.0' live_server_url = HTTP + LOCALHOST + ":" + "9000" def setUp(self): settings.DEBUG = True self.driver = webdriver.Remote( HTTP + LOCALHOST + ":" + str(SEL_PORT) + "/wd/hub", DesiredCapabilities.CHROME ) def tearDown(self): self.driver.quit() super().tearDown() def test_view_url(self): driver = self.driver driver.get(self.live_server_url + "/accounts/signup/") time.sleep(2) email_input = driver.find_element_by_name('email') email_input.send_keys('test@test.com') time.sleep(2) pwd_1_input = driver.find_element_by_name('password1') pwd_1_input.send_keys('Test123!') time.sleep(2) pwd_2_input = driver.find_element_by_name('password2') pwd_2_input.send_keys('Test123!') time.sleep(4) submit_btn = driver.find_element_by_name('submit') time.sleep(4) submit_btn.click() timeout = 4 WebDriverWait(driver, timeout).until( lambda _driver: _driver.find_element_by_tag_name('body')) But as soon as I inherit from STATICLIVESERVERTESTCASE it uses the live database. I know this because it fails to create the user - in the live it already exists but in the test database it won't. But get this, if i take over the test and click the submit button myself it works! The only part of the testing django docs I could find that seems to warn of strange behaviour like this is where it says of using 'an in-memory SQLite database' - the same database connection will be shared by two threads in parallel: the thread in which the live server is run …