Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
fields added in Django View not displayed with django-crispy-forms
I have this view (modified to make it simple to understand): class MyCreateViewView(CreateView): model = SomeModel def get_form(self, form_class=None): form = super().get_form(form_class) form.helper = FormHelper(form) form.fields['additional_field'] = forms.BooleanField(label="Something", required=False) form.helper.add_input(Submit('submit', "Submit")) return form Before adding the FormHelper, the field additional_field appeared on the template. Now it doesn't. The form in my template is basically one line: {% crispy form %}. The django-crispy-forms docs don't show this approach because they are focused on using forms. I'm using the CreateView from Django that builds the form for me, so I don't need a form class. So far, I noticed that doing form.helper = FormHelper(form) after programmatically adding the new field solves the problem. But this is not a solution because the view I presented here is a simplified version, and I actually have two views that are doing something similar. So I'm inheriting this class and adding extra fields in the views themselves (meaning FormHelper is already there). -
Django Ckeditor: How to change background color/styling
I am having trouble changing the background color of the rich text editor. Most places say to edit the ckeditor css file but that isn't in my django project for the way i'm doing it i think. Is there a way to change it/add styles in the settings configs? or is there a better way to do this? template: <script type="text/javascript" src="ckeditor.js"> window.CKEDITOR_BASEPATH = '/static/ckeditor/ckeditor/'; CKEDITOR.replace( 'links' ); </script> settings file: CKEDITOR_CONFIGS = { 'default': { 'toolbar': 'Custom', 'toolbar_Custom': [ ['Link', 'Unlink'], ], 'height': 200, 'width': 750, 'stylesSet': [ { "name": 'Lead', "element": 'p', "attributes": {"margin-top": "10px"}, }, ], } } -
Django Rest Framework view doesn't work when called from DRF API tool
I have the following DRF ViewSet: class ServiceStatusForListViewSet(CustomModelViewSet): pagination_class = None permission_classes = (permissions.IsAuthenticated,) queryset = models.ServiceStatus.objects.all() serializer_class = serializers.ServiceStatusForListSerializer filter_backends = (DjangoFilterBackend, SearchFilter, OrderingFilter,) search_fields = ('service__item__product__name', 'service__client_name') filter_fields = ('id', 'service', 'service__item', 'service__item__product') This view works perfectly when a GET request is sent by a React frontend application, and it returns the expected response: The problem is when I send a GET request from the browser (Chrome): It just never returns, and the "loading" indicator keeps spinning forever. All other endpoints work well from DRF API tool, but this one. -
How can I loop the list into another loop in the Django template?
I need to loop a list into another loop without duplicating the results for example: {% for x in list1 %} {% for y in list2 %} {{ y }} {% endfor %} {% endfor %} I found half of the problem where I can call the elements of a list by a dot followed by the index number for instance: {{ iterator.0 }} {{ iterator.1 }} and that is succeded indeed however I took a little thinking where I thought that I could use: forloop.counter0 for looping but I couldn't use it I tried to use it like so: {{ iterator.forloop.counter0 }} but the trick didn't succeed. so, How can I loop easily into another loop? -
For loop in Django template causing error when I use the add filter
I am trying to add two variables together in my template that will combine two scores together and print the value. The problem is when the loop gets to a game that hasn't happened yet it kicks out an error because the variable doesn't exist yet. What am I supposed to add to skip games in the loop that have no score? {% for game in games %} <p class="light-blue text-center"> Total: {{ game.scoreboard.score.home|add:game.scoreboard.score.away }} </p> {% endfor %} -
Registration form refreshes after submitting instead of sending post request in django
I'm trying to register a user but the page refreshes instead of submitting the data. At the initial stage of my project, it was working properly but when I added some more models and form it's not working and tried to register it stopped working. and it also doesn't throw any errors views.py from django.shortcuts import render from django.contrib.auth import authenticate,login,logout from .models import * from django.http import HttpResponseRedirect from django.urls import reverse from .form import * from django.db import IntegrityError from django.contrib.auth.decorators import login_required from django.contrib import messages # Create your views here. def index(request): if not request.user.is_authenticated: message = f"please sign in" else : message = f"signed in as {request.user}" return render(request, "auctions/index.html",{ "listings": Listings.objects.all(), "message": message }) def login_view(request): if request.method == "POST": form = loginForm() email = request.POST["email"] password = request.POST["password"] user = authenticate(request,username=email,password=password) if user is not None: login(request,user) return HttpResponseRedirect(reverse('index')) else: return render(request, "auctions/login.html",{ "form": form , "message": "username/password not valid" }) return render(request, "auctions/login.html",{ "form": loginForm() }) def logout_view(request): logout(request) return HttpResponseRedirect(reverse('index')) def register(request): if request.POST == "POST": form = registerForm() email = request.POST["email"] # check passwords are same password = request.POST["password"] confirmation = request.POST["id_confirmation"] if password != confirmation: return render (request, "auctions/register.html",{ … -
Accordion expands all cards when clicked at any one
{% for inv in invoices__ %} <div class="row"> <div class="col-md-12"> <div class="accordion" id="accordionExample"> <div class="card"> <div class="card-header" id="{{inv.headingId}}"> <div class="row headerContiner"> <div class="col-md-10"> <h5 data-toggle="collapse" data-target="{{inv.collapseTarget}}">{{inv.ttl}}</h5> </div> <div class="col-md-2"> <a href="{% url 'invoice_update' inv.id__ %}" class="btn text-secondary px-0"> <i class="fa fa-edit fa-lg"></i></a> <a href="{% url 'invoice_delete' inv.id__ %}" class="btn text-secondary px-0"> <i class="far fa-trash-alt fa-lg text-danger float-right"></i></a> <a href="{% url 'invoice_details' inv.id__ %}" class="btn text-secondary px-0"> <i class="fas fa-file-invoice"></i></a> <a href="{% url 'invoice_status' inv.id__ %}" class="btn text-secondary px-0"> <i class="fas fa-tasks"></i></a> </div> </div> </div> <div id="{{inv.collapseId}}" class="collapse" aria-labelledby="{{inv.headingId}}" data-parent="#accordionExample"> <div class="card-body"> <div class="row"> {% for stg in inv.stages %} <div class="col-md-3 stags"> <h6 class="stepHeading">Step {{stg.counter__}}: {{stg.title}}</h6> <p>HTML stands for HyperText Markup Language. HTML is the standard markup language for describing the structure of web pages. <a href="https://www.tutorialrepublic.com/html-tutorial/" target="_blank">Learn more.</a></p> {% if stg.isCreated %} <a href="{% url stg.editLink inv.id__ %}" class="btn text-secondary px-0"> <i class="fa fa-edit fa-lg"></i> </a> <a href="{% url stg.deleteLink inv.id__ %}" class="btn text-secondary px-0"> <i class="far fa-trash-alt fa-lg text-danger float-right"></i> </a> <a href="{% url stg.previewLink inv.id__ %}" class="btn text-secondary px-0"> <i class="fas fa-file-invoice"></i> </a> {% else %} <a href="{% url stg.addLink %}" class="btn text-secondary px-0"> <i class="fas fa-plus"></i></a> </a> {%endif%} </div> {% endfor %} </div> </div> </div> </div> … -
Running python IBM Cloud Apps Cloud Foundry with error in ModuleNotFoundError: No module named 'matplotlib'
After deployment in IBM Cloud - App Cloud Foundry using Python - Django I found the follow error running the container: APP/PROC/WEB 0 File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed 13 de mar. de 2021 10:43:24 APP/PROC/WEB 0 File "<frozen importlib._bootstrap_external>", line 678, in exec_module 13 de mar. de 2021 10:43:24 APP/PROC/WEB 0 File "<frozen importlib._bootstrap>", line 665, in _load_unlocked 13 de mar. de 2021 10:43:24 APP/PROC/WEB 0 callback, param_dict = resolver.resolve_error_handler(500) 13 de mar. de 2021 10:43:24 APP/PROC/WEB 0 File "/home/vcap/deps/0/python/lib/python3.6/site-packages/django/core/handlers/exception.py", line 141, in handle_uncaught_exception 13 de mar. de 2021 10:43:24 APP/PROC/WEB 0 response = handle_uncaught_exception(request, get_resolver(get_urlconf()), sys.exc_info()) 13 de mar. de 2021 10:43:24 APP/PROC/WEB 0 File "/home/vcap/deps/0/python/lib/python3.6/site-packages/django/core/handlers/exception.py", line 103, in response_for_exception 13 de mar. de 2021 10:43:24 APP/PROC/WEB 0 response = response_for_exception(request, exc) 13 de mar. de 2021 10:43:24 APP/PROC/WEB 0 File "/home/vcap/deps/0/python/lib/python3.6/site-packages/django/core/handlers/exception.py", line 49, in inner 13 de mar. de 2021 10:43:24 APP/PROC/WEB 0 response = self._middleware_chain(request) 13 de mar. de 2021 10:43:24 APP/PROC/WEB 0 File "/home/vcap/deps/0/python/lib/python3.6/site-packages/django/core/handlers/base.py", line 128, in get_response 13 de mar. de 2021 10:43:24 APP/PROC/WEB 0 response = self.get_response(request) 13 de mar. de 2021 10:43:24 APP/PROC/WEB 0 File "/home/vcap/deps/0/python/lib/python3.6/site-packages/django/core/handlers/wsgi.py", line 133, in __call__ 13 de mar. de 2021 10:43:24 APP/PROC/WEB 0 respiter = self.wsgi(environ, … -
create a model in django with conditions
I want to create an appointments model with Django, but with 2 conditions the first if the profile already exists than the appointments model use the information from the profile model, but if the profile dose doesn't exist than the user should fill the information in the appointments model this is my profile model class Profile(models.Model): GENDER_CHOICES = (('M', 'Male'), ('F', 'Female'),) user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) date_of_birth = models.DateField(blank=True, null=True) gender = models.CharField(max_length=1, choices=GENDER_CHOICES) phone_number = PhoneNumberField(blank=True) photo = models.ImageField(upload_to='users/%Y/%m/%d/', blank=True) def __str__(self): return f'Profile for user {self.user.username}' and this is my appointments model class Appointments(models.Model): GENDER_CHOICES = (('M', 'Male'), ('F', 'Female'),) user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) profile = models.OneToOneField(Profile, on_delete=models.CASCADE)# if profile dose not exist this will be none date_of_birth = models.DateField(blank=True, null=True)# and the user should fill this information gender = models.CharField(max_length=1, choices=GENDER_CHOICES) # and the user should fill this information phone_number = PhoneNumberField(blank=True)# and the user should fill this information date_time = models.DateTimeField() so if the one who wanted to make the appointments have already a profile the information about the gender and date of birth come from his profile if there is no profile the user should be fill those information -
Allowing user to rename the django model field names visible to him
I have a model like below. I want the user to be able to change the "external" field names (i.e. what is visible to the user) using some form of Legend (the internal field names should be the same: Product.rating1 should not change). The user opens the Product form he sees the default name of the fields (e.g. 'Rating 1' is called 'Rating 1'). But the user should be able to change this in a different form (e.g. 'Rating 1' to 'Some random name'). This new rating name should now be changed for all Products. class Product(models.Model): name = models.CharField(max_length=200) rating1 = models.IntegerField(default=0) rating2 = models.IntegerField(default=0) rating3 = models.IntegerField(default=0) class Legend(models.Model): rating1_name = models.CharField(max_length=200, default='Rating 1') rating1_abbr = models.CharField(max_length=2, default='R1') rating2_name = models.CharField(max_length=200, default='Rating 2') rating2_abbr = models.CharField(max_length=2, default='R2') rating3_name = models.CharField(max_length=200, default='Rating 3') rating3_abbr = models.CharField(max_length=2, default='R3') Desired result: The Product's database table will contain several products. However, the database table of Legend will just contain one entry that is created from the start (automatically) and it will never be deleted, the fields will just be changed. What I want is basically to in one place of my app have a form that creates these Products and another form … -
why do developers still create separate dashboard for login to perform CRUD functions instead of using the inbuilt Admin that is shipped by Django
I am a novice in Django I am just wondering why most developers would create separate dashboards to login and logout to perform all the CRUD functions. Why go through all that trouble instead of using the shipped Admin panel and create your users and assign permissions/roles to them to perform basically all the CRUD functions. -
Extract only the last 7 days of data in Python
If I have such data and I want to extract only the last 7 days of data, how can I do that? I tried to use Pandas examples, but I got errors such as module 'pandas' has no attribute 'example' or 'list' object has no attribute 'example', so I could not get the data for seven days. Also, I'm using React for the frontend. When processing data like this, is it best to do it on the frontend side or the backend side? "daily_report": [ { "date": "2020/03/27", "count": 999 }, { "date": "2020/03/28", "count": 0 }, { "date": "2020/03/29", "count": 0 }, { "date": "2020/03/30", "count": 0 }, { "date": "2020/03/31", "count": 0 }, { "date": "2020/04/01", "count": 0 }, { "date": "2020/04/02", "count": 0 }, { "date": "2020/04/03", "count": 0 }, { "date": "2020/04/04", "count": 0 }, { "date": "2020/04/05", "count": 0 }, { "date": "2020/04/06", "count": 0 }, { "date": "2020/04/07", "count": 0 }, { "date": "2020/04/08", "count": 0 }, { "date": "2020/04/09", "count": 0 }, { "date": "2020/04/10", "count": 0 }, { "date": "2020/04/11", "count": 0 }, { "date": "2020/04/12", "count": 0 }, { "date": "2020/04/13", "count": 0 }, ] def get_daily_report(self, obj): data = Entry.objects.all().values( … -
how do I send a text field input from the frontend to the backend
I have made a website, it uses react as the frontend and Django as the backend. I am trying to get an input from the frontend and send it to the backend, it doesn't seem to be working. here's the code: searchSong(e) { this.setState({ search: e.target.value }); console.log(this.state.search) } this is what takes the text field input : <TextField id="outlined-basic" label="Song" variant="outlined" value={this.state.search} onChange={this.searchSong} /> <Button variant="contained" color="secondary" onClick={this.addButtonPressed}>Search Song</Button> these are the functions that send the text input from the frontend to the backend and the states : addButtonPressed() { const requestOptions = { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ search: this.state.search, }) }; fetch("/spotify/search-song/", requestOptions) } } searchSong(e) { this.setState({ search: e.target.value }); console.log(this.state.search) } the state : this.state = { search: "" } here's the function that I made which will test if I got the correct text field input : def search_song(session_id, song_name): search_letters = "playlist/?type=" + song_name print(search_letters) this is the view that uses the function : class SearchSong(APIView): lookup_url_kwarg = 'search' def post(self, request, format=None): if not request.session.exists(request.session.session_key): request.session.create() room_code = self.request.session.get(self.lookup_url_kwarg) music = str(request.data.get(self.lookup_url_kwarg)) room = Room.objects.filter(code=room_code)[0] search_song(room.host, music) this is the endpoint being called by the frontend : from … -
Django custom registration form html
New to Django and I am attempting to create a customer registration form and was successful. However the tutorial I followed showed me how to iterate through a loop, the contents of my registration_form which doesn't really give me much flexibility from a UI perspective, or so it seems. Can someone tell me how to customize this form based on the code I've got? HTML: <h1>This is the register.html</h1> <div class="col-md-4 offset-md-4"> <form method="post"> {% csrf_token %} {% for field in registration_form %} <p> {{field.label_tag}} {{field}} {% if field.help_text %} <small style="color: grey;">{{field.help_text}}</small> {% endif %} {% for error in field.errors %} <p style="color: grey;">{{error}}</p> {% endfor %} </p> {% endfor %} <button type="submit">Register</button> </form> </div> views.py def registration_view(request): context = {} if request.POST: form = RegistrationForm(request.POST) if form.is_valid(): form.save() email = form.cleaned_data.get('email') raw_password = form.cleaned_data.get('password1') account = authenticate(email=email, password=raw_password) login(request, account) return redirect('home') else: context['registration_form'] = form else: form = RegistrationForm() context['registration_form'] = form print(context) return render(request, 'accounts/register.html', context) forms.py class RegistrationForm(UserCreationForm): email = forms.EmailField(max_length=100, help_text='Required. Add a valid email address') class Meta: model = Account fields = ('email', 'username', 'password1', 'password2', 'first_name', 'last_name') the form renders and works fine with registration, just looks kinda crappy. thanks! -
Changing language with React Native and django-modeltranslation
I would like to add option to mobile app to change language. Im using django on backend and RN as mobile. So I installed django-modeltranslation and added my model I want to translate. On mobile I display available languages. When user clicks on specific language I would like to get translated data. I have huge problem to create logic how to do it. I'm not asking about code just some hints and idea -
Make a dang form field read only after initialised
I have a ModelForm in forms.py as follows: class OrderDetailForm(forms.ModelForm): class Meta: model = OrderDetails fields = ( 'OrderID', 'ProductCode', 'Location', 'UnitPrice', 'Quantity', 'Discount', ) def __init__(self, *args, **kwargs): super(OrderDetailForm, self).__init__(*args, **kwargs) locations = self.initial['ProductCode'].productqtys_set.values_list('Sublocation', flat=True) locationslist = list(locations) locationsQueryset = SubLocations.objects.filter(id__in=locationslist) print("locations queryset in form") print(locationsQueryset) self.fields['Location'].queryset = locationsQueryset In my views.py I have the function that uses it: def AddOrderDetail(request, pk): Product = Products.objects.get(ProductID=pk) order = Orders.objects.last() locations = Product.productqtys_set.all() if request.method == "POST": form = OrderDetailForm(request.POST, initial={"ProductCode": Product, "OrderID": order}) if form.is_valid(): form.save() return redirect('orders:subslistCreate') else: form = OrderDetailForm(initial={"ProductCode": Product, "OrderID": order}) template_path = 'orders/orderdetail_form.html' context = { "form": form, } return render(request, template_path, context) now as you can read, I initialised the ProductCode and OrderID fields, of course when it's time to fill in data for the other fields, the user can edit the values in ProductCode and OrderId. I don't want the user to be able to do that. I tried setting disabled to True but that didn't allow me to initialise the fields anymore, and I also tried to set readonly to true by adding the following lines in the definition of the init function: self.fields['OrderID'].widget.attrs['readonly'] = True self.fields['ProductCode'].widget.attrs['readonly'] = True sadly that changed … -
Server Error (500) arised on django project
My Project is a website is 'learning_log' same as in the book Python Crash Course. Learning Log works fine in local machine but when I go out of local machine it shows Server Error (500). I used heroku to deploy it and renamed it 'trak-your-learnin' you can go to https://trak-your-learnin.herokuapp.com/ to view the error page. I've posted some important file so you can easily figure out the error; sorry i've posted too much code. This deploying process is really difficult for a beginner so hmp. settings.py from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '3kiqlq&v(^09b5ba3xp1krc#z0uu_2ji=eqe7t=cb)-n-^^%bz' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = [ '*', 'https://warm-taiga-24464.herokuapp.com/', '127.0.0.1', ] # Application definition INSTALLED_APPS = [ # My apps 'learning_logs', 'users', # Third party apps. 'bootstrap4', # Default django apps 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'learning_log.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': … -
Django Two Databases: Default User Auth + Legacy Database
I want to put all of the default Django authentication backend on a separate database from my legacy database. I created a new database named 'AUTH_DB' and ran the migration. As expected, it put all of the tables (auth, admin, contenttypes, sessions, etc.) on AUTH_DB. However, now I am only able to render my login.html page. After I attempt to login, I receive a connection does not exist error. I'm having trouble understanding The connection 'auth' doesn't exist at / DATABASES = { 'default': { 'ENGINE': 'sql_server.pyodbc', 'NAME': 'AUTH_DB', 'USER': '', 'PASSWORD': '', 'HOST': 'lvn-gc.database.windows.net', 'PORT': '1433', 'OPTIONS': { 'driver': 'ODBC Driver 17 for SQL Server' }, }, 'data_db': { 'ENGINE': 'sql_server.pyodbc', 'NAME': 'CRM', 'USER': '', 'PASSWORD': '', 'HOST': 'lvn-gc.database.windows.net', 'PORT': '1433', 'OPTIONS': { 'driver': 'ODBC Driver 17 for SQL Server' }, }, } DATABASE_ROUTERS = ['CRM.routers.DataRouter'] In CRM/routers.py class DataRouter: db_apps = ( 'CRM' ) def db_for_read(self, model, **hints): if model._meta.app_label in self.db_apps: return 'data_db' return model._meta.app_label def db_for_write(self, model, **hints): if model._meta.app_label in self.db_apps: return 'data_db' return model._meta.app_label def allow_relation(self, obj1, obj2, **hints): return True def allow_syncdb(self, db, model): if model._meta.app_label in self.db_apps: return db == 'data_db' return False Traceback Environment: Request Method: POST Request URL: http://127.0.0.1:8000/ Django … -
Django Templates Formsets with Foreign Key Lookup
hoping for some guidance around my below problem with displaying reverse lookup field in a template inside formsets. Maintenance Item Model class Maintenance_Item(CommonInfo): id = models.AutoField(primary_key=True) name = models.CharField(max_length=100, unique=True) name_description = models.CharField(max_length=255) is_active = models.BooleanField(default=True) def __str__(self): return self.name Checklist Model class MaintenanceCheckList(CommonInfo): CHOICES = ( ('P','Compliant'), ('F','Non-Compliant'), ) id = models.AutoField(primary_key=True) item = models.ForeignKey(Maintenance_Item, on_delete=PROTECT, related_name='item_name') is_compliant = models.CharField(max_length=20, choices= CHOICES, default=CHOICES[0][0]) def __int__(self): return self.item The current template <form class="" method='post'> {% csrf_token %} {{ form.management_form }} <table class="table my-0" id="dataTable"> <thead> <tr> <th>Maintenance Items</th> </tr> </thead> <tbody> {% for sub_form in form %} <tr> {% for i in sub_form.item_name.all %} <td>Item: {{ i.name }}</p> {% endfor %} {{ sub_form.item|add_class:"form-select" }}<p> </p>{{ sub_form.is_compliant }}</td> </tr> {% endfor %} </table> <div class="divider"></div> <div class="col-md-12"> <p class='pt-sm-2'> <button type="submit" class="btn btn-primary">Submit</button> </form> Currently, I have generic formset view which creates an row for each item in the Maintenance_Item which works brilliant and generates the formset view as shown. The challenge, I have is I want to hide the ModelChoice fields (I can do that easily with a Widget), and just display the friendly name in the ModelChoice field as a simple Text Label in the template. Note setting disabled … -
Django 'dict' object has no attribute '_mutable'
I am testing Django Rest Framework code with Postman I called http://127.0.0.1:8000/api/users/1/documents/ But received error message 'dict' object has no attribute '_mutable' What is the right way to create request via Postman? (it seems that problem with postman) I read this topic, but didn't find solution DRF request.data has no attribute _mutable My code class UserDocumentCreate(generics.CreateAPIView, generics.RetrieveAPIView): serializer_class = UserDocumentSerializer permission_classes = (UserIsOwner, IsAuthenticatedDriver) queryset = Document.objects.all() def get_serializer_class(self): if self.request.version == "1.0": return UserDocumentSerializer def create(self, request, *args, **kwargs): request.data._mutable = True request.data["owner"] = kwargs.get("pk") serializer = self.get_serializer(data=request.data) ... -
Why does django print the traceback of an exception even though I catch it?
I'm creating a django web app and am currently in the process of writing tests for it. I want to check that my URL paths are working. In order messages that clutter the screen when testing, I tried catching the exceptions that get thrown, but this doesn't seem to work. Here's my method where I'm testing the path of the home URL: def test_home(self): path = '/' try: response = self.client.get(path) except Exception: assert False, ("There seems to be a problem with the view corresponding to the path", path) self.assertEqual(response.status_code, 200, ("Couldn't load page with page", path)) And this is the output: <a lot more exceptions> During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/Users/me/opt/anaconda3/lib/python3.7/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) UnicodeDecodeError: 'utf-8' codec can't decode byte 0xf6 in position 395: invalid start byte During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/Users/me/Documents/project/project/app/tests/test_urls.py", line 16, in test_home response = self.client.get(path) UnicodeDecodeError: 'utf-8' codec can't decode byte 0xf6 in position 395: invalid start byte During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/Users/me/Documents/project/project/app/tests/test_urls.py", line 18, in test_home assert False, … -
Django AllAuth URL patterns configuration
I created a sample view to display the detail of the user. In my project, I have 2 apps, the Accounts that contain all the details of the user and the Core for the web application. I've done configuring the Django AllAuth for Google Login and here is the outcome. Models.py class Profile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) first_name = models.CharField(max_length=50, null=True, blank=True) last_name = models.CharField(max_length=50, null=True, blank=True) email = models.EmailField(max_length=254, null=True, blank=True) member_since = models.DateTimeField(auto_now_add=True) phone_number = PhoneNumberField(null=True, blank=True) street_address = models.CharField(max_length=50, null=True, blank=True) city = models.CharField(max_length=50, null=True, blank=True) country = models.CharField(max_length=50, null=True, blank=True) zip_code = models.IntegerField(null=True, blank=True) slug = models.SlugField(null=True, blank=True, unique=True) def __str__(self): return str(self.first_name) def get_phone_number(self): return self.phone_number @property def get_full_address(self): return f"{self.street_address}, {self.city}, {self.country}, {self.zip_code}" @receiver(user_signed_up) def populate_profile(sociallogin, user, **kwargs): user.profile = Profile() user_data = user.socialaccount_set.filter(provider='google')[0].extra_data first_name = user_data['given_name'] last_name = user_data['family_name'] email = user_data['email'] user.profile.first_name = first_name user.profile.last_name = last_name user.profile.email = email user.profile.save() def get_absolute_url(self): return reverse("profile", kwargs={"slug": self.slug}) def save(self, *args, **kwargs): self.slug = slugify("{obj.first_name}-{obj.last_name}".format(obj=self)) super(Profile, self).save(*args, **kwargs) Views.py class ProfileDetailView(LoginRequiredMixin, DetailView): model = Profile template_name = 'accounts/profile.html' Accounts Urls.py app_name = 'accounts' urlpatterns = [ path('profile/<slug>', ProfileDetailView.as_view(), name='profile') ] Main Urls.py from django.contrib import admin from django.urls import path, include urlpatterns = … -
template inheritance is not working in my django application
My base.html Template <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <meta content="width=device-width, initial-scale=1.0" name="viewport" /> <title>MyResume Bootstrap Template - Index</title> </head> <body> {% block content%} {% endblock content%} </body> </html> My content block template {% extends "base.html" %} {% block content %} <h1>hello world</h1> {% endblock content %} I don't know what the issue is kindly help me with a solution -
Page keeps reloading after adding a new channels consumer and route
hope you all are doing well. I have been working on creating an asynchronous notification system, I already have a chat system but it is directed only towards the /inbox/ url. The problem that I'm facing is when I add a new consumer and access the home page the home page keeps reloading again and again and the terminal doesn't show any error. this is what my code looks like: Consumers.py async def websocket_connect(self,event): print("connected",event) await self.accept() async def websocket_receive(self,event): print("received",event) async def websocket_disconnect(self,event): print(event,"closed") class ChatConsumer(AsyncWebsocketConsumer): async def websocket_connect(self,event): print("connected") self.channel_layer = channels.layers.get_channel_layer() ..... await self.accept() async def websocket_receive(self,event): print("received2",event) ..... async def websocket_disconnect(self,event): print("disconnected",event) Routing.py from . import consumers from django.urls import re_path,path websocket_urlpatterns = [re_path(r"^a/inbox/(?P<username>[\w.@+-]+)", consumers.ChatConsumer.as_asgi()), re_path(r"a/(?P<username>[\w.@+-]+)",consumers.NotificationConsumer.as_asgi()), ] I'm trying to create a notifications websocket, any leads or any correction would be much appreciated. -
How do i find one tag with multiple text Content with Beautifulsoup
Am trying to scrap a website with multiple 'p' tags with beautifulsoup and I find it very difficult. please I need help. I want to get all posts associated with p tags. the find_all on beautifulsoup will not get this done and the image is not saving I get an error that the file cannot be saved and tell me how to retrieve, add or scrap all the text in p tags and the image on the HTML code below. Can you check out my code below kompas = requests.get('https://url_on_html.com/') beautify = BeautifulSoup(kompas.content,'html5lib') news = beautify.find_all('div', {'class','jeg_block_container'}) arti = [] for each in news: title = each.find('h3', {'class','jeg_post_title'}).text lnk = each.a.get('href') r = requests.get(lnk) soup = BeautifulSoup(r.text,'html5lib') content = soup.find('p').text.strip() images = soup.find_all('img') arti.append({ 'Headline': title, 'Link': lnk, 'image': 'images' }) let's take this HTML code as a scrapping sample <html><head><title>The Dormouse's story</title></head> <body> <p class="title"><b>The Dormouse's story</b></p> <p>Once upon a time there were three little sisters, and their names were and they lived at the bottom of a well.</p> <script></script> <p>the emergency of our matter is Once upon a time there were three little sisters, and their names were and they lived at the bottom of a well.</p> <p> …