Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Logout button is not showing in Django Todowoo app
Logout button i s not showing up in my Browser -
ForeignKey relationship on two fields which are unique together
I'd like to make a relationship like so in django: class ColorModel(models.Model): article = models.ForeignKey(ArticleModel, to_field='name', on_delete=models.CASCADE) color = models.CharField(max_length=10) class Meta: unique_together = ('article', 'color') class TaillesModel(models.Model): article = models.ForeignKey(ColorModel, on_delete=models.CASCADE) color = models.ForeignKey(ColorModel, on_delete=models.CASCADE) size = models.CharField(max_length=10) quantity = models.IntegerField() So each article has multiple colors, and each of those colors has multiple sizes in different quantities. However, this gives me those errors: Reverse accessor for 'TaillesModel.article' clashes with reverse accessor for 'TaillesModel.color'. HINT: Add or change a related_name argument to the definition for 'TaillesModel.article' or 'TaillesModel.color'. front.TaillesModel.color: (fields.E304) Reverse accessor for 'TaillesModel.color' clashes with reverse accessor for 'TaillesModel.article'. HINT: Add or change a related_name argument to the definition for 'TaillesModel.color' or 'TaillesModel.article'. I don't understand what related_name is supposed to be set to here. Thanks in advance for your help. -
Trouble Uploading files with Django Rest Framework GenericViewSet class
I know there are lots of questions with answers about uploading files with Django but none of the ones I have read have helped me. Many answers say I need to get my uploaded files from request.FILES but I have seen answers saying that's deprecated. Django Rest Framework 3: Uploading files without request.FILES. Anyways here is my code: My model: class DamagePhoto(models.Model): ... omitted for brevity ... damage = models.ForeignKey(Damage, related_name='photos', on_delete=models.CASCADE) photo = models.ImageField(max_length=256, upload_to=get_image_path, blank=True, null=True) side = models.CharField(max_length=16, choices=choices) My view: class VehicleDamagePhotoViewSet(mixins.ListModelMixin, mixins.CreateModelMixin, mixins.RetrieveModelMixin, mixins.UpdateModelMixin, mixins.DestroyModelMixin, viewsets.GenericViewSet): serializer_class = DamagePhotoSerializer queryset = DamagePhoto.objects.all() lookup_field = 'uid' lookup_url_kwarg = 'uid' lookup_value_regex = '[0-9a-f-]{36}' ordering_fields = ['modified', ] ordering = ['modified'] def get_serializer_context(self): print(f"get_serializer_context() called. request.FILES is {self.request.FILES}.") return {'request': self.request} def get_damage(self, damage_uid): return Damage.objects.get(uid=damage_uid) def get_queryset(self): return self.queryset.filter(damage__uid=self.kwargs['damage_uid']) def perform_create(self, serializer): print(f"preform_create() called request.FILES is {self.request.FILES}.") return serializer.save(damage=self.get_damage(self.kwargs['damage_uid'])) The serializer: class DamagePhotoSerializer(serializers.ModelSerializer): @transaction.atomic def create(self, validated_data, *args, **kwargs): request = self.context['request'] print(f"serializer create request.FILES is {request.FILES}.") return super(DamagePhotoSerializer, self).create(validated_data=validated_data, *args, **kwargs) class Meta: model = DamagePhoto fields = ('__all__') The part of my unit test that fails: url = reverse("vehicle:damagephoto-list", kwargs={'damage_uid': new_damage.uid}) image_path_1 = '/Users/red/myproject/test_data/photos/test_image.jpg' file_ob = {'photo': ('test_image.jpg', open(image_path_1, "rb"))} data = { 'file': file_ob, … -
Django as backend for React native mobile app, How can we authenticate users with social media signup?
Using Django Rest framework we can support mobile apps, for websites Django can authenticate users based on social media using Allauth library. When user signup with Facebook ,a new tab opens and authenticate user with permission. How can we do this for mobile apps ? I think Standard packages like AllAuth wont support it. I do not need the codes, but any guidance will be useful -
How can I update multiple models using Django's class based views?
I have seen similar questions but the question was not explained in a way that explains my current scene. I have this in my models.py: class CustomUser(AbstractUser): USER_TYPE = ((1, 'HOD'), (2, 'Staff'), (3, 'Student')) user_type = models.CharField(default=1, choices=USER_TYPE, max_length=1) class Student(models.Model): course = models.ForeignKey( Course, on_delete=models.DO_NOTHING, null=True, blank=False) admin = models.OneToOneField(CustomUser, on_delete=models.CASCADE) gender = models.CharField(max_length=1, choices=GENDER) address = models.TextField() profile_pic = models.ImageField(upload_to='media') session_start_year = models.DateField(null=True) session_end_year = models.DateField(null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now_add=True) In my forms.py, I have this: class StudentForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(StudentForm, self).__init__(*args, **kwargs) for visible in self.visible_fields(): visible.field.widget.attrs['class'] = 'form-control' class Meta: model = Student fields = ['course', 'gender', 'address', 'profile_pic', 'session_start_year', 'session_end_year'] widgets = { 'session_start_year': DateInput(attrs={'type': 'date'}), 'session_end_year': DateInput(attrs={'type': 'date'}), } class CustomUserForm(forms.ModelForm): email = forms.EmailField(required=True) first_name = forms.CharField(required=True) last_name = forms.CharField(required=True) password = forms.CharField(widget=forms.PasswordInput) widget = { 'password': forms.PasswordInput() } def __init__(self, *args, **kwargs): super(CustomUserForm, self).__init__(*args, **kwargs) for visible in self.visible_fields(): visible.field.widget.attrs['class'] = 'form-control' def clean_email(self): if CustomUser.objects.filter(email=self.cleaned_data['email']).exists(): raise forms.ValidationError("The email is already registered") return self.cleaned_data['email'] class Meta: model = CustomUser fields = ('first_name', 'last_name', 'email', 'username', 'password', ) help_texts = {'username': None} I created a form using this context: context = {form': [CustomUserForm(), StudentForm()]} Now, I am trying to … -
How to fix locking failed in pipenv?
I'm using pipenv inside a docker container. I tried installing a package and found that the installation succeeds (gets added to the Pipfile), but the locking keeps failing. Everything was fine until yesterday. Here's the error: (app) root@7284b7892266:/usr/src/app# pipenv install scrapy-djangoitem Installing scrapy-djangoitem… Adding scrapy-djangoitem to Pipfile's [packages]… ✔ Installation Succeeded Pipfile.lock (6d808e) out of date, updating to (27ac89)… Locking [dev-packages] dependencies… Building requirements... Resolving dependencies... ✘ Locking Failed! Traceback (most recent call last): File "/usr/local/lib/python3.7/site-packages/pipenv/resolver.py", line 807, in <module> main() File "/usr/local/lib/python3.7/site-packages/pipenv/resolver.py", line 803, in main parsed.requirements_dir, parsed.packages, parse_only=parsed.parse_only) File "/usr/local/lib/python3.7/site-packages/pipenv/resolver.py", line 785, in _main resolve_packages(pre, clear, verbose, system, write, requirements_dir, packages) File "/usr/local/lib/python3.7/site-packages/pipenv/resolver.py", line 758, in resolve_packages results = clean_results(results, resolver, project) File "/usr/local/lib/python3.7/site-packages/pipenv/resolver.py", line 634, in clean_results reverse_deps = project.environment.reverse_dependencies() File "/usr/local/lib/python3.7/site-packages/pipenv/project.py", line 376, in environment self._environment = self.get_environment(allow_global=allow_global) File "/usr/local/lib/python3.7/site-packages/pipenv/project.py", line 366, in get_environment environment.extend_dists(pipenv_dist) File "/usr/local/lib/python3.7/site-packages/pipenv/environment.py", line 127, in extend_dists extras = self.resolve_dist(dist, self.base_working_set) File "/usr/local/lib/python3.7/site-packages/pipenv/environment.py", line 122, in resolve_dist deps |= cls.resolve_dist(dist, working_set) File "/usr/local/lib/python3.7/site-packages/pipenv/environment.py", line 121, in resolve_dist dist = working_set.find(req) File "/root/.local/share/virtualenvs/app-lp47FrbD/lib/python3.7/site-packages/pkg_resources/__init__.py", line 642, in find raise VersionConflict(dist, req) pkg_resources.VersionConflict: (importlib-metadata 2.0.0 (/root/.local/share/virtualenvs/app-lp47FrbD/lib/python3.7/site-packages), Requirement.parse('importlib-metadata<2,>=0.12; python_version < "3.8"')) (app) root@7284b7892266:/usr/src/app# What could be wrong? -
Viewing Answer To Previous Question in Django using POST and AJAX
So I am trying to make a Quiz website for which I have chosen django as backend and sqlite as database temporarily. I have set a pager and previous and next button in the page. Now for going forward There is no problem but when I go backwards I want the server to remember what the user answered before and make that radio button active. I am very new in web dev and I am sry if this question is obvious. Also I am eager to use AJAX calls so that the page doesn't refresh when I change the Question.Also pls feel free to recommend a better method of achieveing the above -
Django Flatpage Catchall URLConf and Name for `url` Templatetag
I've gone back and forth between these two flatpage URL patterns: urlpatterns += [ # path('about', views.flatpage, {'url': '/about'}, name='about'), re_path(r'^(?P<url>.*)$', views.flatpage), ] When using the explicit path, I can use the name in my templates like so: <a href="{% url 'about' %}">About</a> But when using the catchall, I can't figure out whether this is possible. I've got quite a few flatpages (maybe a dozen or more, and I'll likely add more later), so having the catchall is an attractive option. However, I really like being able to use the url templatetag. Can I get the best of both worlds? -
Restart Apache in Lightsail Terminal
As I found a blocker in one approach to make a Django app production ready I've gone with a different approach documented here. In particular, this question is about this step where it says «Restart Apache for the changes to be taken into effect» and has the following associated command sudo /opt/bitnami/ctlscript.sh restart apache Thing is, ctlscript.sh isn't in that folder but in /opt/bitnami/stack. Then, when running in that forder sudo ctlscript.sh restart apache I get this error sudo: ctlscript.sh: command not found The file is there so I thought it would be something related with permissions (as pointed here). So, ran The script is in the right folder, so the problem points to incorrect permissions. sudo chmod 755 ctlscript.sh but running the command to restart Apache got me into the same "command not found" error. -
Django do not reload fixture for some test cases
For every test class I generated base .json fixture with data. It is pretty clear and fast way, because I do not need to spent time to generate data. Any additional data I can generate with factories directly in test. class ProfileViewTests(MyProjectTestCase): fixtures = [os.path.join('compiled', 'test_companies_and_users.json')] def test1(self): pass def test2(self): pass The issue that the loading of some fixtures is takes up to 15 sec., because they creating a huge piece of test data environment. And now 70% of time I'm wasting to loading fixtures after every test case. The upside is because when we update objects we do not need care about flushing this data, but downside that time is increasing with every test. I can move some data to setUpTestData, but revisit all this data for all this tests is almost impossible. My question is there a decorator to say some tests cases do not reload fixtures, if they not modify data. @do_not_flush_data_from_database_for_next_test_case_from_this_class def get_users_test(self): pass Or any other way to speed up this -
Django user authentication not working on every subpage
i have strange (and probable simple) problem with user authentication in Django. I added to base.html file this code: {% if user.is_authenticated %} <p>{{user.get_username}} is logged in</p> <a href="{% url 'logout' %}">logout</a> {% else %} <p>You are not logged in!</p> <a href="{% url 'login' %}">login</a></a> {% endif %} Then i added this line to every other template: {% extends "base.html" %} It looks good because every subpage display this lines of code, unfortunately sometimes is displaying code when user is authenticated and sometimes where he is not authenticated.For example when i switch between two subpages once i get information that user with his login is logged, on this second webpage i get information that i am not logged in and when i come back to that first subpage i am again authenticated... How could i change it? What could be a problem? my views about login: def login_user(request): login_user = {} login_user.update(csrf(request)) return render_to_response('login.html', login) def auth_view(request): username = request.POST.get('username', '') password = request.POST.get('password', '') user = auth.authenticate(username=username, password=password) if user is not None and user.is_active: auth.login(request, user) return redirect('loggedin') else: return HttpResponseRedirect('invalidlogin') def logged_in(request): return render_to_response('loggedin.html', {'user': request.user}) and my 'login' urls: path('login', views.login, name='login'), path('authorized', views.auth_view, name='authorized'), path('loggedout', … -
rendering forms into inherited html take me to the base html page
I'm new to Django. I've a base HTML page "base.html" in my templates folder which contains a navbar, when I tried to inherit this page to another page that renders a database or forms it's take me back to the "base.html" page. Here's my base page <!DOCTYPE html> {% load static %} <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>base</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous"> </head> <body> <nav class="nav"> <a class="nav-link active" href="{% url 'index' %}">HOME</a> <a class="nav-link" href="{% url 'admin:index' %}">admin</a> <a class="nav-link" href="{% url 'my_app:database' %}">database</a> </nav> {% block content_block %} {% endblock %} </body> </html> so in the bar a database button where anchor inside this database page , this anchor tag navigate to my form <!DOCTYPE html> {% extends 'base.html' %} {% block content_block %} <div class='container'> <a href="{% url 'my_app:form' %}">Form</a> </div> {% endblock %} and here's my page where i want to render my form in it <!DOCTYPE html> {% extends 'base.html' %} {% block content_body %} <form method="POST"> {{form.as_p}} {% csrf_token %} <input type="submit" name='submit'> </form> {% endblock %} when I navigate to my form it's navigate to the home page however the link is how I expected http://127.0.0.1:8000/data/form/ but it … -
ObtainAuthToken in django
I am following a Django course and the teacher is simply importing ObtainAuthToken from rest_framework.authtoken.views. When i import that i get this exc: raise TypeError( TypeError: Abstract base class containing model fields not permitted for proxy model 'TokenProxy'. Tracing the exception got me to this line from rest_framework.authtoken.views import ObtainAuthToken I think it's not that complicated but if it needs clarification i will add my views and urls. Thanks in advance. -
migrate django model primary key UUID field to CharField
I need to change the id field size on an oracle database to support storing longer id's. By default using the UUIDField in django creates a table with varchar field of 32 bytes but we now need it to store ids generated by uuid.uui4 and of supplied id's of character lengths up to 80. What is the least hacky way to do this in django so that the migrations are consistent across environments while keeping foreign key relationships in other models? class CurrentModel(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) class desiredModel(models.Model): id = models.CharField(max_length=80, primary_key=True, default=uuid.uuid4) -
Bootstrap data table not working on refreshing table using Ajax in Django project
I had success to refresh the table using Ajax. However, the bootstrap datatable can't apply to my refreshing table. If I not using this method to refresh the table. Bootstrap can work properly applied. I just want to refresh my table and paging table. I am beginner on coding please help. base.html ... <html> <head> <link rel="stylesheet" href="{% static 'plugins/datatables-bs4/css/dataTables.bootstrap4.min.css' %}"> <link rel="stylesheet" href="{% static 'plugins/datatables-responsive/css/responsive.bootstrap4.min.css' %}"> </head> ... <body> ... <script src="{% static 'plugins/datatables/jquery.dataTables.min.js' %}"></script> <script src="{% static 'plugins/datatables-bs4/js/dataTables.bootstrap4.min.js' %}"></script> <script src="{% static 'plugins/datatables-responsive/js/dataTables.responsive.min.js' %}"></script> <script src="{% static 'plugins/datatables-responsive/js/responsive.bootstrap4.min.js' %}"></script> <script> $(function () { $('#Table').DataTable({ "paging": true, "lengthChange": false, "searching": false, "ordering": false, "info": false, "autoWidth": false, "responsive": false, }); }); </script> </body> </html> table.html {% extends "base.html" %} {% block content %} {% load static %} <head> <title>table</title> <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script> <script> function playSound() { var audio = new Audio("../../media/juntos.mp3"); audio.play(); } var cacheData; var data = $('#div_refresh').html(); var auto_refresh = setInterval( function () { $.ajax({ url:'refresh', type: 'GET', data: data, dataType: 'html', success: function(data) { if (data !== cacheData){ playSound(); cacheData = data; $('#div_refresh').fadeOut("slow").html(data).fadeIn("slow"); } } }) }, 2000); </script> </head> <body> <div id='div_refresh'> </div> </body> {% endblock content %} refresh_table.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> … -
How to bind input fields from model forms into vue
Usually you can grab input fields you manually created through v-model like these: <input class="form-control mb-2" name="username" v-model="username" type="text" placeholder="username" autocomplete="off"> <input class="form-control" type="password" v-model="password" placeholder="password"> However, how can I grab and place v-model on fields that are auto-generated by Django through model forms? <form method="post"> {% csrf_token %} {{ user_form }} <button class="btn btn-primary mt-3">Register</button> </form> -
django-auth-ldap INVALID_CREDENTIALS when authenticating
I am attempting to utilize the django-auth-ldap library however I am unable to connect to the server successfully. When I navigate to the django login screen and use an account associated with our active directory server I get the following error in the logs Caught LDAPError while authenticating user@domain.com: INVALID_CREDENTIALS({'msgtype': 97, 'msgid': 1, 'result': 49, 'desc': 'Invalid credentials', 'ctrls': [], 'info': '80090308: LdapErr: DSID-0C090446, comment: AcceptSecurityContext error, data 52e, v2580'},) I have my settings.py file setup as follows. import ldap, logging from django_auth_ldap.config import LDAPSearch, GroupOfNamesType AUTHENTICATION_BACKENDS = [ "django_auth_ldap.backend.LDAPBackend", "django.contrib.auth.backends.ModelBackend", ] AUTH_LDAP_SERVER_URI = "ldap://serverIP" AUTH_LDAP_AUTHORIZE_ALL_USERS=True AUTH_LDAP_BIND_DN = "cn=service user,OU=ServiceAccounts,dc=domain,dc=com" AUTH_LDAP_BIND_PASSWORD = "password" AUTH_LDAP_USER_SEARCH = LDAPSearch( "dc=domain,dc=com", ldap.SCOPE_SUBTREE, "(sAMAccountName=%(user))" ) # Populate the Django user from the LDAP directory. AUTH_LDAP_USER_ATTR_MAP = { "first_name": "givenName", "last_name": "sn", "email": "mail", } AUTH_LDAP_ALWAYS_UPDATE_USER = True AUTH_LDAP_CACHE_TIMEOUT = 1 When I test the following ldapsearch command everything works as expected ldapsearch -H ldap://serverIP -D user@domain.com -b "dc=domain,dc=com" -W "(samAccountName=serviceUser)" and from this output I can see that the serviceUser has the following DN CN=service user,OU=ServiceAccounts,DC=DOMAIN,DC=COM -
Django: annotate() + distinct(fields) is not implemented
I have following models: class Village(models.Model): packages_required = models.IntegerField() . . class PackageSent(models.Model): village = models.ForeignKey('myapp.Village') package_count = models.IntegerField() sending_user = models.ForeignKey('myapp.Users') sending_account_user = models.ForeignKey('myapp.Users') . . And I need to select all Villages along with their PackageSent models. I built the following query: Village.objects.filter( filter_logic ).order_by( order_by_logic ).annotate( packages_missing=F("packages_required") - Sum("packagesent__package_count"), users_involved=Count("packagesent__sending_account_user", distinct=True) ).prefetch_related( models.Prefetch( "packagesent_set", queryset=PackageSent.objects.filter( filter_logic ).annotate( total_account_sent=Sum("package_count"), sending_users=ArrayAgg("sender_user_id") ).distinct( "sending_account_user_id" ), to_attr="packages_sent" ) ) However this query raises annotate() + distinct(fields) is not implemented error. The query I need for PackageSent model in MySQL syntax: SELECT *, SUM(package_count) AS `total_account_sent`, GROUP_CONCAT(sending_user) AS `sending_users` FROM `myapp_packagesent` ps LEFT JOIN `myapp_village` v ON v.id = ps.village_id GROUP BY `sending_account_user`, `village_id` ORDER BY `total_account_sent` DESC I would like to do this in a template: {% for village in object_list %} . . . {% for package_sent in village.packages_sent %} . . . {% endfor %} {% endfor %} How can I achieve the results I want? Technologies used: Django 3.0 PostgreSQL -
ConnectionAbortedError in Django
Whenever this view is executed my server showed up with some error which I don't know why! the view which I was executing is @api_view(['POST']) def Signin(request): if request.method == 'POST': username = request.POST.get('username') passw = request.POST.get('password') email = request.POST.get('email') fullname = request.POST.get('fullname') college = request.POST.get('college_name') city = request.POST.get('city') country = request.POST.get('country') User.objects.create_user( username=username, password=passw, email=email) Userinfo.objects.create( user_name=username, full_name=fullname, user_email=email, college_name=college, city=city, country=country , varified_user=False) return Response({'status': 'created'}) And what i know after checking my database is my code is executing till user_name=username, full_name=fullname, user_email=email, college_name=college, city=city, country=country , varified_user=False) because I can see the data which I was inserting, now i don't know what error can cause by return Response({'status': 'created'}). The message in my terminal is Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). September 29, 2020 - 21:19:18 Django version 3.1, using settings 'backend.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. [29/Sep/2020 21:19:31] "POST /api/usercheck/ HTTP/1.1" 200 18 [29/Sep/2020 21:19:34] "POST /api/usercheck/ HTTP/1.1" 200 18 [29/Sep/2020 21:19:35] "POST /api/usercheck/ HTTP/1.1" 200 21 [29/Sep/2020 21:19:58] "POST /signin/ HTTP/1.1" 200 3318 ---------------------------------------- Exception happened during processing of request from ('127.0.0.1', 65332) Traceback (most recent call last): File "C:\Python38\lib\socketserver.py", … -
[Django rest_framework]Problems in using redis as Django DRF cache
I'm trying to open the redis cache for the rest framework. My configuration seems to be correct. When I run, it reports an error. As shown below: Watching for file changes with StatReloader Performing system checks... Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\HUANG\AppData\Local\Programs\Python\Python38\lib\site-packages\rest_framework\settings.py", line 177, in import_from_string return import_string(val) File "C:\Users\HUANG\AppData\Local\Programs\Python\Python38\lib\site-packages\django\utils\module_loading.py", line 17, in import_string module = import_module(module_path) File "C:\Users\HUANG\AppData\Local\Programs\Python\Python38\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 783, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "C:\Users\HUANG\AppData\Local\Programs\Python\Python38\lib\site-packages\rest_framework_extensions\utils.py", line 6, in <module> from rest_framework_extensions.key_constructor.constructors import ( File "C:\Users\HUANG\AppData\Local\Programs\Python\Python38\lib\site-packages\rest_framework_extensions\key_constructor\constructors.py", line 4, in <module> from rest_framework_extensions.key_constructor import bits File "C:\Users\HUANG\AppData\Local\Programs\Python\Python38\lib\site-packages\rest_framework_extensions\key_constructor\bits.py", line 3, in <module> from django.db.models.sql.datastructures import EmptyResultSet ImportError: cannot import name 'EmptyResultSet' from 'django.db.models.sql.datastructures' (C:\Users\HUANG\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\sql\datastructures.py) During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\HUANG\AppData\Local\Programs\Python\Python38\lib\threading.py", line 932, in _bootstrap_inner self.run() File "C:\Users\HUANG\AppData\Local\Programs\Python\Python38\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "C:\Users\HUANG\AppData\Local\Programs\Python\Python38\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Users\HUANG\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\management\commands\runserver.py", line 118, in inner_run self.check(display_num_errors=True) File "C:\Users\HUANG\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\management\base.py", line 392, … -
Wagtail V2 API force HTTPS for the html_url and detail_url
I am currently developing a portfolio website that has a Django + Wagtail backend to manage the content in a React frontend that talks to each other through Wagtail V2 API and Django-Rest-Framework. I am currently running into an issue where I am able to get the pages from the API, but when my frontend tries to load individual page details the Wagtail v2 API is sending the detail_url as a http url where my nginx setup requires https. I have looked all over the wagtail documentation and stackoverflow for the answer to forcing the detail_url to be a https url but I cannot find the answer or documentation anywhere, nor do I know where to start. What part is causing the http? Is it Django, Wagtail or Rest-Framework? And how do I get it to be https This is what my JSON code looks like from the backend { "meta": { "total_count": 2 }, "items": [ { "id": 3, "meta": { "type": "pages.HomePage", "detail_url": "http://dylan.primic.com/api/v2/pages/3/", "html_url": "http://dylan.primic.com/", "slug": "home", "first_published_at": "2020-09-29T14:58:50.272668Z" }, "title": "Home" }, { "id": 4, "meta": { "type": "pages.AboutPage", "detail_url": "http://dylan.primic.com/api/v2/pages/4/", "html_url": "http://dylan.primic.com/about-me/", "slug": "about-me", "first_published_at": "2020-09-29T15:00:10.624868Z" }, "title": "About Me" } ]} Any help will … -
ManyToManyField with model_to_dict(self)
Not sure if the title is the correct one, sorry for the inconvenience. I'm having a problem on sending a ManyToManyField from a model to a dictionary using the model_to_dict() Below is my code models.py from django.db import models from django.forms import model_to_dict from app_1.models import * class Stuff(models.Model): thing_1 = models.CharField(max_length=100, null=True, blank=True) thing_2 = models.ManyToManyField(OtherStuff, blank=True, related_name="thing") def toJSON(self): item = model_to_dict(self) item['thing'] = self.thing.toJSON() return item When I run a query and load my Stuff model, I get the following error: from app_2.models import * s = Stuff.objects.get(pk=1) # here is where I send my model to a dictionary s.toJSON() Traceback (most recent call last): File "<input>", line 1, in <module> File "P:\test\app\app_2\stuff\models.py", line 10, in toJSON return item AttributeError: 'ManyRelatedManager' object has no attribute 'toJSON' I've come across multiple ways of sending a ManyToManyField to a dictionary, however, none of them use the model_to_dict(). I'd like to use this method due to it's simplicity of usage. -
page is loading very slow
Hi there I have a page and it is loading very slow. I had a very similiar question but this time I guess it requires another solution. I use django for my website and it has some jquerry in the template however I guess that the issue can be on the views. I will post my views and if it is neccessary my templates. Thank you in advance. views.py from django.shortcuts import render import openpyxl def index(request): wb=openpyxl.load_workbook('ders.xlsx') ws=wb.active context_lectures=[] context_lecture=[] context_select=[] for i in range(ws.max_row): day=ws.cell(row=i+1,column=6).value a=0 for j in range(len(day)): if day[j].isupper() and j!=0 and a!=j: day=day[:j]+' - '+day[j:] a=j+3 hour=ws.cell(row=i+1,column=7).value b=0 for k in range(len(hour)): if k%9==0 and k!=0: hour=hour[:k+b]+' - '+hour[k+b:] b+=3 lectures=ws.cell(row=i+1,column=2).value[:4] lecture=ws.cell(row=i+1,column=2).value select=ws.cell(row=i+1,column=1).value+' | '+ws.cell(row=i+1,column=2).value+' | '+ws.cell(row=i+1,column=3).value+' | '+ws.cell(row=i+1,column=4).value+' | '+day+' | '+hour if lectures in context_lectures: pass else: context_lectures.append(lectures) if lecture in context_lecture: pass else: context_lecture.append(lecture) if select in context_select: pass else: context_select.append(select) return render(request,'index.html',{'context_lectures': context_lectures,'context_lecture':context_lecture,'context_select':context_select}) and I would also ask where should I deploy my xlsx file. I didn't found a solution so I deployed it on the main project folder where manage.py is. -
Twilio with Django
I am trying to use Twilio with Django. I have followed this tutorial and it works properly. I am now trying to apply that within my own project. I've taken a copy of package.json into my project's root directory and I've run npm install to set up the node_modules directory. I have also copied the get_token and call views as is. Something is going wrong in the JS because I can see the get_token call but not the call call (if you know what I mean). My call button is an exact copy of the example project and when I click it I get the following error: Received an error from MediaStream: Object { info: {…} } twilio.min.js:99:91242 error http://127.0.0.1:8000/static/twilio.min.js:99 onerror http://127.0.0.1:8000/static/twilio.min.js:99 _initializeMediaStream http://127.0.0.1:8000/static/twilio.min.js:99 makeOutgoingCall http://127.0.0.1:8000/static/twilio.min.js:99 connect http://127.0.0.1:8000/static/twilio.min.js:99 accept http://127.0.0.1:8000/static/twilio.min.js:99 (Async: promise callback) accept http://127.0.0.1:8000/static/twilio.min.js:99 connect http://127.0.0.1:8000/static/twilio.min.js:99 callCustomer http://127.0.0.1:8000/static/prospecting/js/browser-calls.js:106 onclick http://127.0.0.1:8000/?page=3:1 My Twilio settings have been checked, double checked and triple checked. I believe them to be correct. -
Django-React argument of type 'WindowsPath' is not iterable - When processing the login post request
I am developing a simple Django react JWT authentication system. When I try to obtain the access token, I get the following stack trace. I was getting it just random with the website working, now I can't get the token. The server is not shutting down. [29/Sep/2020 17:40:27] "POST /api/token/obtain/ HTTP/1.1" 200 486 Traceback (most recent call last): File "C:\Users\bratca\AppData\Local\Programs\Python\Python38-32\lib\wsgiref\handlers.py", line 138, in run self.finish_response() File "C:\Users\bratca\AppData\Local\Programs\Python\Python38-32\lib\wsgiref\handlers.py", line 196, in finish_response self.close() File "C:\Users\bratca\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\servers\basehttp.py", line 114, in close super().close() File "C:\Users\bratca\AppData\Local\Programs\Python\Python38-32\lib\wsgiref\simple_server.py", line 38, in close SimpleHandler.close(self) File "C:\Users\bratca\AppData\Local\Programs\Python\Python38-32\lib\wsgiref\handlers.py", line 335, in close self.result.close() File "C:\Users\bratca\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\http\response.py", line 253, in close signals.request_finished.send(sender=self._handler_class) File "C:\Users\bratca\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\dispatch\dispatcher.py", line 173, in send return [ File "C:\Users\bratca\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\dispatch\dispatcher.py", line 174, in <listcomp> (receiver, receiver(signal=self, sender=sender, **named)) File "C:\Users\bratca\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\__init__.py", line 57, in close_old_connections conn.close_if_unusable_or_obsolete() File "C:\Users\bratca\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\backends\base\base.py", line 525, in close_if_unusable_or_obsolete self.close() File "C:\Users\bratca\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) File "C:\Users\bratca\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\backends\sqlite3\base.py", line 261, in close if not self.is_in_memory_db(): File "C:\Users\bratca\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\backends\sqlite3\base.py", line 380, in is_in_memory_db return self.creation.is_in_memory_db(self.settings_dict['NAME']) File "C:\Users\bratca\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\backends\sqlite3\creation.py", line 12, in is_in_memory_db return database_name == ':memory:' or 'mode=memory' in database_name TypeError: argument of type 'WindowsPath' is not iterable [29/Sep/2020 17:40:27] "POST /api/token/obtain/ HTTP/1.1" 500 59 and the following error right after it, I guess it's a chain of …