Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
why does not show the view content in template with {{ xxx }}
I want do learn & practice python w Django. Therefore I am trying to Code a simple app, translating some text from DE to EN and give the EN text to index.html. But the view content {{ eng_text }} does not Show up in the html template. This is the views.py from django.shortcuts import render from textblob import TextBlob # Create your views here. def index(request): return render(request, 'index.html') DEtext = 'das ist ein deutscher text, der übersetzt werden soll' print (DEtext) def translate(request): tb = TextBlob(DEtext) ENtext = tb.translate(to="EN") print(ENtext) dict = {'eng_text': DEtext} return render(DEtext, 'index.html', context=dict) -
How can I specify between models of different apps but the same name, in the same view
I have a separate Django app for two different cities. I have models of the same name, for each of those cities, and would like to bring them into the same view. When i import the models of both apps, the data doesnt render, i assume because Django doesnt know which one to use. When I import just corpus_christi, the template renders the data just fine, and vice versa. How can I specify from which app i want to bring these models? Here is my view from django.shortcuts import render from django.http import HttpResponse from corpus_christi.models import Service, Member from lake_charles.models import Service, Member def index(request): return render(request, 'pages/index.html') def corpuschristi(request): residential = Service.objects.filter(service_type="Residential") commercial = Service.objects.filter(service_type="Commercial") prelisting = Service.objects.filter(service_type="Pre Listing") members = Member.objects.all() context = { 'members': members, 'residential': residential, 'commercial': commercial, 'prelisting': prelisting } return render(request, 'pages/corpuschristi.html', context) def lakecharles(request): return render(request, 'pages/lakecharles.html') -
Getting User information from FB allauth authentication using cookiecutter django
I recently used cookiecutter django from Two Scoops of django and implemented user login/creation using oauth. Problem is that I have no idea how to get the authenticated users' extra data as I do see it in the admin as a dict. All the tutorials out there only touches on how to use oauth login but not attaining data. from django.contrib.auth.models import AbstractUser from django.db.models import CharField from django.urls import reverse from django.utils.translation import ugettext_lazy as _ class User(AbstractUser): # First Name and Last Name do not cover name patterns # around the globe. name = CharField(_("Name of User"), blank=True, max_length=255) def get_absolute_url(self): return reverse("users:detail", kwargs={"username": self.username}) This is the default User model from the cookiecutter template, how do I then attain the last_name and first_name from fb? I know I can add first_name fields, that means the views.py file have to have a user creation view but it doesn't and I can't wrap my head around on how the allauth is able to create this user. Thank you! -
Can VS Code Debug Django Templates on a Remote Server?
I've begun using VS Code to edit a Django project running on a remote server and it works pretty well. However, I'm trying to debug a Django template and I'm finding that if I set a breakpoint on a template tag and refresh the web page, the debugger doesn't halt on my tag as the documentation says it should: {% for member in new_members %} # <- Breakpoint set here {{ member.user.username }} {% endfor %} Here is my launch profile: { "version": "0.2.0", "configurations": [ { "name": "Python: Django", "type": "python", "request": "launch", "program": "${workspaceFolder}/manage.py", "args": [ "runserver", "--noreload" ], "django": true } ] } When I start the debugger, I can see the Django development server starting on the remote host in the Code Terminal and the page refreshes but the debugger doesn't stop on the {% for... %} tag. Is there anything else I need to do or is remote template debugging not supported? -
How to make key field to appear in Django forms using inline formsets
When I use a single model for an object (say, a "Plant") I can make the key field (say, plant_id) to appear in the "UpdateView". For this purpose I use the following form: class PlantForm(forms.ModelForm): class Meta: model = Plant fields = ('__all__') Using the above ModelForm when I use UpdateView, the key field (plant_id) shows up in the form. And (of course) there I have the additional task of "disabling" the key field (plant_id) from being open to editing. Now if I use an inline formset using two models (Plant and PlantAsset), by design I need to use the formset something like: PlantAssetsChange = inlineformset_factory( Plant, PlantAsset, form=PlantAssetForm, can_delete=True, min_num=0, validate_min=True, max_num=100, extra=1) OR PlantAssetsChange = inlineformset_factory( Plant, PlantAsset, fields=......., can_delete=True, min_num=0, validate_min=True, max_num=100, extra=1) In this case, by design I need to use a form based on the related model (PlantAsset) (OR use its fields) to construct the inline formset. In this scenario, I find the key field of the parent model (Plant) i.e. plant_id does not show up on the page. How do I make the key field (plant_id) to appear on the page? -
Django CSP is refusing to load a certain JS file despite the 'self' directive being enabled
I'm currently in the process of implementing CSP headers via django-csp, and for the most part everything seems to be in working order. One of the things I'm trying to debug right now is why a certain JS file,'multilanguage.js' is being rejected. To the best of my knowledge I have allowed scripts to be run if it's provided from my site via the self directive. Despite this I am not sure why it's not working as intended. According to chrome it seems to fail in this following line: $("#"+ elem).append(eval(elem)[language]); JS file in question: var m=new Date(); if ( m.getHours() == 0 ){ degHour = 0 ; } else { degHour = 30 * (m.getHours()%12); } degMin = 6 * m.getMinutes(); $('.hour-block').css("transform", "rotate("+degHour+"deg) scale(1,0.7)"); $('.min-block').css("transform", "rotate("+degMin+"deg) scale(1,1)"); $.getScript("/static/js/language.js", function(){ $('.check-item li').click(function (){ localStorage.setItem('language', $(this).attr('id')); location.reload(); }); var language = localStorage.getItem('language'); if ( language == null ) { localStorage.setItem('language', 'English'); var language = localStorage.getItem('language'); } $(arrayElements).each(function(i,elem) { $("#"+ elem).append(eval(elem)[language]); **FAILING HERE** }); $("#selected_lan_img").attr("src","/static/css/languages/"+ language +".svg"); $('#'+ language).hide(); $('.country-selection').click(function (){ $('.check-item').toggle(); }); }); My Django CSP settings # Django CSP Settings CSP_DEFAULT_SRC = ("'self'",) CSP_STYLE_SRC = ("'self'", 'cdnjs.cloudflare.com', 'https://use.fontawesome.com', 'https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css','fonts.googleapis.com', 'https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css') CSP_SCRIPT_SRC = ("'self'","'sha256-VhNEptbDobqL5kYATr7A4mMh2PwDxbBXvt8R+yP5Bn0='","'sha256-4dBfmKQVHKo3lG/03tkNCWveHZb3v0bNQwXDNyYuryU='",'www.google-analytics.com', 'www.googletagmanager.com', 'https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js', 'https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.8.0/js/bootstrap-datepicker.min.js', 'https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js','https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js','ajax.googleapis.com',) CSP_FONT_SRC = ("'self'", 'use.fontawesome.com', … -
django query model A and exclude some items from related model B
I'm new to Django and I'm facing a question to which I didn't an answer to on Stackoverflow. Basically, I have 2 models, Client and Order defined as below: class Client(models.Model): name = models.CharField(max_length=200) # .. class Order(models.Model): Client = models.ForeignKey(ModelA, on_delete=models.CASCADE, related_name='orders') is_delivered = models.BooleanField(default=False) # .. I would like my QuerySet clients_results to fulfill the 2 following conditions: Client objects have a name equal to 'Doe' Order objects I can access by using the orders relationship defined in 'related_name' are only the one that are not delivered. I could do this directly in the template but I feel this is not the correct way to do it. Additionally, I read in the doc that Base Manager from Order shouldn't be used for this purpose. Finally, I found a question relatively close to mine using Q and F, but in the end, I would get the order_id while, ideally, I would like to have the whole object. Could you please advise me on the best way to address this need? Thanks a lot for your help! -
How do I pass objects to my Django template?
I think what I'm trying to do could be explained as trying to pass all of my Genre objects to my template for display. I want to display all of my columns and their entries for my Genre model on my template page table_home. Presently, when I navigate to the table_home.html page, I get NameError at /generators/table_home name 'genre' is not defined I want to do the same thing again with the System model when its working. Can someone explain what is broken with my code and where I can do some reading on passing values from views to templates? It seems mystical to me and I don't know where to go for self-help, partially because I don't know what terminology to search. In the table_home view I tried to mimic what was working in both the table view and then what seems to be working in the index view. Neither worked, and I'm not quite sure why. My views.py: from tablib import Dataset from .models import Genre, D100Generator, System def index(request): latest_table_list = D100Generator.objects.order_by('-d_100_id')[:5] context = { 'latest_table_list': latest_table_list } return render(request, 'generators/index.html', context) def table(request, table_slug): table = get_object_or_404(D100Generator, pk=table_slug) return render(request, 'generators/table.html', {'table': table}) def table_home(request): global_table_list … -
Matching model to ForeignKey based on Foreign Model's date range
Say I have two models. class ModelA(models.Model): name = models.CharField(max_length=200) start_date = models.DateField() end_date = models.DateField() def __str__(self): return '%s (%s) -> (%s)' % (self.name,self.start_date,self.end_date) class ModelB(models.Model): modelA = models.ForeignKey(ModelA,on_delete=models.SET_NULL,null=True,) name = models.CharField(max_length=150) email = models.EmailField(max_length=50) phone = models.CharField(max_length=10) date = models.DateField('Date submitted',auto_now_add=True) Given say, 10 ModelA objects, with varying date ranges, how would you match ModelB to a ModelA on form submission based on ModelB's date? -
I/O operation on closed file with print statement
I recently migrated a Django app from a provider to AWS (elastic beanstalk). It worked well for a while, but not once in a while I need to restart my server due to an error that reads I/O operation on closed file The culprit, every time, is a print statement in one of my views or functions. I don't work with files in my code and don't ever open / close files. All the other errors like this that I researched are caused with a file being open somewhere, but I never open or work with files so I am very confused. Is there anything happening in the background of a print statement (which can sometimes be as easy as print('test') to cause the error I/O operation on closed file ?? It doesn't seem to be about the structure of the code, but maybe the Python install on the server or folder permissions ? -
Connecting Django, Celery and SQS
I want to use Celery and SQS for periodic tasks in my Django application.I'm following the documentation and a couple of tutorials "Using Django 2 with Celery and SQS" and "Using Amazon SQS with Django and Celery". I think my issues is with BROKER_URL. Example AWS_SECRET_ACCESS_KEY 1xxxxa/ABCDE/FGH56/IJKL123 I tried as per the documentation: BROKER_URL = 'sqs://'+AWS_ACCESS_KEY_ID+':'+AWS_SECRET_ACCESS_KEY+'@ I printed BROKER_URL and got: 1xxxxa/ABCDE/FGH56/IJKL123 But got: ValueError: invalid literal for int() with base 10: '1xxxxa' I tried: BROKER_URL = 'sqs://{0}:{1}@'.format( urllib.quote(AWS_ACCESS_KEY_ID, safe=''), urllib.quote(AWS_SECRET_ACCESS_KEY, safe='') ) And get: AttributeError: module 'urllib' has no attribute 'quote' I tried: BROKER_URL = 'sqs://{0}:{1}@'.format( urllib.parse.quote(AWS_ACCESS_KEY_ID, safe=''), urllib.parse.quote(AWS_SECRET_ACCESS_KEY, safe='') ) And BROKER_URL is printed: 1xxxxa%ABCDE%FGH56%IJKL123 and when I run the worker I get: Access to the resource https://queue.amazonaws.com/ is denied. I'm thinking the reason is that the BROKER_URL is being passed as 1xxxxa%ABCDE%FGH56%IJKL123 instead of 1xxxxa/ABCDE/FGH56/IJKL123. But for the methods I tried that print the BROKER_URL as 1xxxxa/ABCDE/FGH56/IJKL123, I get the invalid literal error. How can I fix this? -
How to update choices for forms.ChoiceFiled in Django?
I have field in forms.py: main_choices = ((1,'option 1'),(2,'option 2'),(3,'option 3')) sub_choices = ((1,'PlaceHolder')) class MainForm(forms.Form): type = forms.ChoiceField(choices=main_choices) sub_type = forms.ChoiceField(choices=sub_choices) HTML: <form action="{% url 'app:get_url' %}" method="POST"> {% csrf_token %} {{ form.type }} {{ form.sub_type }} <button type="submit" class="app">GET</button> </form> view.py def get_ajax(request): if request.is_ajax(): data = request.POST.copy() if 'type' in data: type = int(data['type']) if type == 2: sub_choices = ((1,'Folder 1'),(2,'Folder 2')) elif type ==3: print('getCollectionList by username') sub_choices = ((1,'Collection 1'),(2,'Collection 2')) return HttpResponse() Currently, server catches ajax post data from the type field. I don't know how to put sub_choices from get_ajax action to sub_type field in forms. Can anyone explain how to do that? -
Data not displaying when I loop through with Django Template Tags
I'm pretty stumped. When I go to loop through each "Service", nothing shows in the browser. I've checked to make sure the data I've entered through the admin area is actually in the database (Postgres), and it is. Maybe i have a syntax issue somewhere? models.py from django.db import models class Service(models.Model): name = models.CharField(max_length=50) service_type = models.CharField(max_length=50) price = models.DecimalField(max_digits=4, decimal_places=2) is_published = models.BooleanField(default=True) def __str__(self): return self.name views.py from django.shortcuts import render from django.http import HttpResponse from corpus_christi.models import Service, Member, Area def corpuschristi(request): services = Service.objects.all() context = { 'services': services } return render(request, 'pages/corpuschristi.html', context) And this is my For Loop in the html page: {% for service in services %} <div class="col s12 m6"> <li class="service"> {{ service.name }} </li> </div> {% endfor %} -
My bytes input is INCORRECT (can't convert to JSON) in Python
Basically, I have this API end point that will be called if you make a POST request to it. The problem is for some reason, I can't convert the bytes to JSON so I can access the data. My code: @api_view(['POST']) def create_user(request): """ POST = Create user. """ # Check that a username with this email doesn't already exist try: data = {} print("IS IT WORKING...?") print(type(request.body)) print(request.body) # Use double quotes to make it valid JSON my_json = request.body.decode('utf8').replace("'", '"') print("MY_JSON:") print(my_json) data = json.loads(my_json) print("DATA:") print(data) s = json.dumps(data, indent=4, sort_keys=True) print("s:") print(s) except User.DoesNotExist: print("PLS WORK ON CONSOLE") return Response(status=status.HTTP_409_CONFLICT) I try to make a POST request to my path users/create/ using Postman, but when I print request.body to see the contents of my POST request, it is formatted incorrectly with a lot of random numbers and dashes. This is preventing me from converting it to JSON. It's a simple POST request with email and password fields. This is what the weird formatting looks like: https://gyazo.com/fa1cc2f04637c02f79fe59790153ae40 This is what the "json" looks like after I have decoded it and converted with double quotes (Notice the weird dashes and numbers): https://gyazo.com/3ca41106117a4e9acdd96929469313a1 After that, it ERRORS because of … -
Django - setting a user to not active for 5 seconds
In my Django project, I allow users to login. If they enter the incorrect password 7 times, their account is set to not active and an error is returned to them. What I want to do is display the error message for 5 seconds, then allow them to attempt again. How can I do this ? I store a variable in the user model which is incremented each time a an unsuccessful login is performed. If it reaches 7, an error message is displayed. Here's my code: models.py: class User(AbstractUser): loginAttempts = models.IntegerField(default=0) views.py: if user.check_password(data.get("password")): user.loginAttempts = 0 user.save() auth.login(request, user) return JsonResponse({'message': 'Successfully logged in'}, status=200) else: user.loginAttempts += 1 user.save() if user.loginAttempts >= 7: user.is_active = False user.save() return JsonResponse({'message': 'Account Locked.'}, status=400) else: return JsonResponse({'message': 'Oops, username/email or password provided is invalid'}, status=400) Currently the error message ("Account Locked") is successfully displayed after 7 attempts, however what I want is the loginAttempts variable to be set back to 0 after 5 seconds has passed. How can I do this? Thank You. -
Page not found error - Writing your first Django app, part 1
I have installed Django 2.2.5 in my conda environment and I'm following the Django tutorial for Writing your first Django app, part 1 I followed the steps exactly but I'm getting a Page Not Found error when I try to access the polls/ url. My root directory structure is like this mysite/ manage.py db.sqlite3 urls.py mysite/ __init__.py settings.py urls.py wsgi.py polls/ migrations/ __init__.py admin.py apps.py models.py tests.py urls.py views.py And my view is like this D:\TEMP\djangotest\mysite\polls\views.py from django.shortcuts import render from django.http import HttpResponse def index(request): return HttpResponse("Hello World. You're at the polls index") My two urls files are like this D:\TEMP\djangotest\mysite\polls\urls.py from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), ] D:\TEMP\djangotest\mysite\urls.py from django.contrib import admin from django.urls import include, path urlpatterns = [ path('polls/', include('polls.urls')), path('admin/', admin.site.urls), ] And I run the app from the environment like this (py3.6) D:\TEMP\djangotest\mysite>python manage.py runserver But when I go to the url indicated in the tutorial it give the 404 error - page not found from the console October 21, 2019 - 16:23:13 Django version 2.2.5, using settings 'mysite.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. Not Found: /polls [21/Oct/2019 16:23:19] "GET /polls … -
I am not able to launch my Django app with elastic beanstalk. Receive 500 - Internal Service Error
I am attempting to deploy a simple Django project, using Amazon's guide: https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create-deploy-python-django.html. However, I am receiving 500 errors, Internal Server Error. I have retrieved the error log, however am struggling to debug. The project runs fine locally. I've tried: Ensuring my WSGI path is correct Downgrading to Django 2.1.1 I've included the EB domain name in ALLOWED_HOSTS Here is the error log [Mon Oct 21 20:13:48.477960 2019] [:error] [pid 31600] [remote 127.0.0.1:0] apps.populate(settings.INSTALLED_APPS) [Mon Oct 21 20:13:48.477965 2019] [:error] [pid 31600] [remote 127.0.0.1:0] File "/opt/python/run/venv/local/lib/python3.6/site-packages/django/apps/registry.py", line 114, in populate [Mon Oct 21 20:13:48.477968 2019] [:error] [pid 31600] [remote 127.0.0.1:0] app_config.import_models() [Mon Oct 21 20:13:48.477973 2019] [:error] [pid 31600] [remote 127.0.0.1:0] File "/opt/python/run/venv/local/lib/python3.6/site-packages/django/apps/config.py", line 211, in import_models [Mon Oct 21 20:13:48.477977 2019] [:error] [pid 31600] [remote 127.0.0.1:0] self.models_module = import_module(models_module_name) [Mon Oct 21 20:13:48.477981 2019] [:error] [pid 31600] [remote 127.0.0.1:0] File "/opt/python/run/venv/lib64/python3.6/importlib/__init__.py", line 126, in import_module [Mon Oct 21 20:13:48.477985 2019] [:error] [pid 31600] [remote 127.0.0.1:0] return _bootstrap._gcd_import(name[level:], package, level) [Mon Oct 21 20:13:48.477990 2019] [:error] [pid 31600] [remote 127.0.0.1:0] File "<frozen importlib._bootstrap>", line 994, in _gcd_import [Mon Oct 21 20:13:48.477995 2019] [:error] [pid 31600] [remote 127.0.0.1:0] File "<frozen importlib._bootstrap>", line 971, in _find_and_load [Mon Oct 21 20:13:48.478000 2019] [:error] … -
How to add custom filtering fields to an Django Rest Framework APIListView
I'm using django rest framework and I have a ListAPIView that I would like to implement a complex filtering functionality that I'm using Q filters. My question is how do I generate custom fields for this filtering? url: path('', EventListView.as_view(), name='event_list_view'), serializer: class EventSerializer(serializers.ModelSerializer): class Meta: model = Event exclude = ('user', ) View: class EventListView(ListAPIView): authentication_classes = () permission_classes = () serializer_class = EventSerializer filter function: def filter_events( user: User, sort_by: int = DISTANCE, privacy_levels: [int] = [EVERYONE], categories: [Category] = None, start_date: datetime.datetime = DEFAULT_START_DATE, end_date: datetime.datetime = DEFAULT_END_DATE, distance: int = DEFAULT_DISTANCE, current_location: Point = None, unit: int = None, clubs: [UniversityClub] = None, universities: [University] = None, greeks: [GreekOrganization] = None, groups: [UserGroup] = None, users_p: [User] = None ): .... if EVERYONE in privacy_levels: everyone_q = Q(privacy_level=EVERYONE, university__in=user_universities, start_time__range=[start_date, end_date]) else: everyone_q = Q() if STUDENTS in privacy_levels: student_q = Q(privacy_level=STUDENTS, start_time__range=[start_date, end_date]) else: student_q = Q() ... -
how to ignore forward slash from django URL in a parameter
I am using django version 2.2.5. Below is my urls.py from django.urls import path, include from . import views urlpatterns = [ path('manifest/', views.home), path('manifest/<str:some_id>/', views.manifest), ] It works fine when some_id does not contain any forward slash(/). E.g. http://127.0.0.1:8000/manifest/name:19.2.4:develop:1/ In the following manifest function from views.py, I am able to get the some_id def manifest(request, some_id): print(some_id) ##prints below: ##[21/Oct/2019 19:36:55] "GET /manifest/name:19.2.4:develop:1 HTTP/1.1" 301 0 ##name:19.2.4:develop:1 However, when the some_id contains forward slash in it, I don't get the whole id. E.g., from the above URL if I would replace "develop" with "release/19.2.4" http://127.0.0.1:8000/manifest/name:19.2.4:release/19.2.4:1/ "GET /manifest/name:19.2.4:release/19.2.4:1/ HTTP/1.1" 404 3080 This is because of the forward slash being used as delimiter. Is there any way to ignore this forward slash inside of the some_id parameter? The expectation is to get name:19.2.4:release/19.2.4:1 as some_id in the views.py Note: The format of a valid some_id is it has 4 parts delimited by ":". e.g.: name:version:branch:num, where only the branch section could have one or more slash(/) in it. -
Django: single related object descriptor is deprecated, how can i replace it?
I was following this guide, when I arrived to this line: from django.db.models.fields.related import SingleRelatedObjectDescriptor I realized that SingleRelatedObjectDescriptor Class has been removed (deprecated) from the module, I searched about its deprecation in the documentation, I couldn't find anything helpful, how i can achieve its behaviour now? with what i can replace it? -
Django template 'url' tag not rendering as form field attribute value
In my Django app, I'm trying to implement an ajax request, for that, I would need a specific field in the form and setting the ajax request URL as an attribute value to the field. But the URL template tag is not rendering on the HTML. #urls.py ... path('checkdata', check_data, name='ajaxcheck') #forms.py fld_name = forms.CharField(label='Name', max_length=100, widget=forms.TextInput(attrs={'ajax-data-url': "{% 'ajaxcheck' %}"})) Output HTML: <input type="text" name="name" placeholder="Name" ajax-data-url="{% 'ajaxcheck' %}" maxlength="100" class="textinput textInput form-control" required="" id="id_name"> -
django-allauth restrict social login to registered users
What is the recommended way to restrict social login to registered users? As it is any user with a social account gets passed as authenticated after signing into a social site (google, facebook, etc) even though they aren't registered with my secure site. Lets assume I'm using the default domain/accounts/login templates. If we can sort it out with those I can make it work my forms or templates. Hopefully someone else has done this so I don't have to reinvent the wheel here.... I can post any code if you like. -
Displaying content by ID (views.py)
I've developed a university system application for practice, and get such problem: I have to display the list of specializations belonging to some chair. And here problem is: http://127.0.0.1:8000/chairs/1, http://127.0.0.1:8000/chairs/2 and etc. are showing all of the specializations like in this screenshot . But I want to display them only according to chairs id. Here are my codes: views.py: def list_of_specialties(request, chair_id): chairs = Chair.objects.all() if chair_id: chair_id = get_object_or_404(Chair, id=chair_id) bachelor_sp = Specialty.objects.filter(degree_id=1) master_sp = Specialty.objects.filter(degree_id=2) phd_sp = Specialty.objects.filter(degree_id=3) context = { 'chairs': chairs, 'chair_id': chair_id, 'bachelor_sp': bachelor_sp, 'master_sp': master_sp, 'phd_sp': phd_sp, } return render(request, 'specialties.html', context) urls.py: urlpatterns = [ path('', views.index, name='index'), path('chairs', views.chairs, name='chairs'), path('chairs/<int:chair_id>', views.list_of_specialties, name='list_of_specialties'), path('chairs/<int:chair_id>/<int:specialty_id>', views.list_of_specializations, name='list_of_specializations'), ] models.py: class Chair(models.Model): def __str__(self): return self.name name = models.CharField(max_length=100) phone = models.CharField(max_length=30) email = models.CharField(max_length=50) chairman = models.CharField(max_length=30) class Specialty(models.Model): def __str__(self): return self.name name = models.CharField(max_length=100) chair = models.ForeignKey(Chair, on_delete=models.CASCADE) degree = models.ForeignKey(Degree, on_delete=models.CASCADE) -
What is the meaning of the line 'reponse = self.client.get(reverse('polls:index'))' mean?
class QuestionIndexViewTests(TestCase): def test_no_questions(self): """ If no questions exist, an appropriate message is displayed. """ response = self.client.get(reverse('polls:index')) self.assertEqual(response.status_code, 200) self.assertContains(response, "No polls are available.") self.assertQuerysetEqual(response.context['latest_question_list'], -
Django Channels, Websocket with Parameter
I'm trying to send info back to my server when socket connects: js var id = 'testme' var endpoint = 'ws://'+ window.location.host + window.location.pathname var socket = new WebSocket(endpoint, id) consumers.py class ChatConsumer(AsyncConsumer): async def websocket_connect(self, event): info = str(self.scope['subprotocols']).replace('[', '').replace(']', '').replace("'", "") chat_room = info self.chat_room = chat_room await self.channel_layer.group_add( chat_room, self.channel_name) await self.send({"type": "websocket.accept"}) When I remove ID everything works fine; with it, the connection immediately disconnects. Anyone know why and how to fix it? (Yes, 'info' does print 'testme' as intended)