Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do you fix a memory leak within Django tests?
Recently I started having some problems with Django (3.1) tests, which I finally tracked down to some kind of memory leak. I normally run my suite (roughly 4000 tests at the moment) with --parallel=4 which results in a high memory watermark of roughly 3GB (starting from 500MB or so). For auditing purposes, though, I occasionally run it with --parallel=1 - when I do this, the memory usage keeps increasing, ending up over the VM's allocated 6GB. I spent some time looking at the data and it became clear that the culprit is, somehow, Webtest - more specifically, its response.html and response.forms: each call during the test case might allocate a few MBs (two or three, generally) which don't get released at the end of the test method and, more importantly, not even at the end of the TestCase. I've tried everything I could think of - gc.collect() with gc.DEBUG_LEAK shows me a whole lot of collectable items, but it frees no memory at all; using delattr() on various TestCase and TestResponse attributes and so on resulted in no change at all, etc. I'm quite literally at my wits' end, so any pointer to solve this (beside editing the thousand or … -
How can i get all the product categories a suppliers product belongs
I am working a Supplier Management System. I need to make a particular type of query which I am having issue implementing. I have the user models, and then the user_type which is of two types the suppliers and the admin. Of Course, the filter I need to implement is based of the supplier because only the supplier is able to create product in which they have to specify what categories as well. My Problem: How can I get all categories a supplier products belongs to. models.py class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_length=254, unique=True) def get_email(self): return self.email class user_type(models.Model): is_admin = models.BooleanField(default=False) is_supplier = models.BooleanField(default=False) user = models.OneToOneField(User, on_delete=models.CASCADE) def __str__(self): if self.is_supplier == True: return User.get_email(self.user) + " - is_supplier" else: return User.get_email(self.user) + " - is_admin" class Category(models.Model): name = models.CharField(max_length=256) def __str__(self): return self.name class Product(models.Model): name = models.CharField(max_length=36) price = models.PositiveIntegerField() category = models.ForeignKey(Category, on_delete=models.CASCADE) quantity = models.PositiveIntegerField() user = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.name -
How to validate accessToken in Azure AD
I just wanted to know how can we validate the azure ad access token in a backend API in my case i.e. Django rest framework. Consider that I have a single page app or a native app and a backend API (django rest framework) completely independen of each other. In my case if my single page app/native app wants to access certain data from the backend API, and inorder to access the API, user should be logged in the backend API. So what my approch is to make use of MSAL library to get the access token from the SPA/native app and then once token is acquired, pass that token to backend API, validate it, get the user info from graph api. If user exists in the DB then login the user and pass the required info. If user info doesn't exist then create the user, login and pass the info from the API. So my question is when I pass the access token to my backend api, how can I validate that the token that a user/SPA/native app has passed to backend API is valid token or not? Is it just we need to make an API call to … -
Django-OIDC with keycloak - OIDC callback state not found in session oidc_states
I am trying to implement Keycloak SSO with Django API using OIDC. Getting below error message after requesting the call to Keyclock as a response SuspiciousOperation at /^oidc/callback/ OIDC callback state not found in session oidc_states! The same thing I did in the Flask framework and it's working as expected. Please find the below details. Django Log: [20/Mar/2021 15:30:57] "GET / HTTP/1.1" 404 2229 [20/Mar/2021 15:31:03] "GET /hi HTTP/1.1" 302 0 [20/Mar/2021 15:31:03] "GET /oidcauthenticate/?next=/hi HTTP/1.1" 302 0 failed to get or create user: Claims verification failed [20/Mar/2021 15:31:11] "GET /oidccallback/?state=UziLDF2ZcE9p2WrUIihUahgUsWdQ8zYQ&code=22d5a22b-16a6-42e3-81ba-9b569a3f1c81.2cd52631-8c4c-4f2e-a718-c908611336a3.81db1495-24af-402d-8244-a82f32bf4355 HTTP/1.1" 302 0 Not Found: / [20/Mar/2021 15:31:11] "GET / HTTP/1.1" 404 2229 Settings: Django settings for keycloakexample project. Generated by 'django-admin startproject' using Django 3.1.7. For more information on this file, see https://docs.djangoproject.com/en/3.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.1/ref/settings/ """ 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 = '_vg@)t*rri()^^wm7yl*i&$%gk2h1h%!xk$xms19ceb3*2z&g^' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition … -
Public Key not found Django
I'm trying to place this secret key in my env DJPADDLE_PUBLIC_KEY=-----BEGIN PUBLIC KEY----- abcdefghijklmnoopasdasdhjahsdjahsdjkahsjdhasdsadasdasdasdasdasdasdaasda abcdefghijklmnoopasdasdhjahsdjahsdjkahsjdhasdsadasdasdasdasdasdasdaasda abcdefghijklmnoopasdasdhjahsdjahsdjkahsjdhasdsadasdasdasdasdasdasdaasda abcdefghijklmnoopasdasdhjahsdjahsdjkahsjdhasdsadasdasdasdasdasdasdaasda abcdefghijk== -----END PUBLIC KEY----- my settings.py from decouple import config DJPADDLE_PUBLIC_KEY = config('DJPADDLE_PUBLIC_KEY') but i get this error DJPADDLE_PUBLIC_KEY not found. Declare it as envvar or define a default value. This is how it looked like previously in my settings file DJPADDLE_PUBLIC_KEY = '''-----BEGIN PUBLIC KEY----- abcdefghijklmnoopasdasdhjahsdjahsdjkahsjdhasdsadasdasdasdasdasdasdaasda abcdefghijklmnoopasdasdhjahsdjahsdjkahsjdhasdsadasdasdasdasdasdasdaasda abcdefghijklmnoopasdasdhjahsdjahsdjkahsjdhasdsadasdasdasdasdasdasdaasda abcdefghijklmnoopasdasdhjahsdjahsdjkahsjdhasdsadasdasdasdasdasdasdaasda abcdefghijk== -----END PUBLIC KEY-----''' -
How to add additional fields, like count of objects to ModelSerializer with many=True
I don't know how to add additional fields to my ModelSerializer, which accepts many=True. Here is all my code: ViewSet def list(self, request, *args, **kwargs): contracts = self.request.user.all_contracts serializer = ContractGetSerializer(contracts, many=True, context={'request': request}, ) return Response({"results": serializer.data}, status=status.HTTP_200_OK) ContractGetSerializer serializer. It also has inner Many=True fields class ContractGetSerializer(serializers.ModelSerializer): files = FileModelSerializer(many=True) is_author = serializers.SerializerMethodField('is_author_method') contract_signing_status = serializers.SerializerMethodField('get_recipient_signing_status') def is_author_method(self, foo): return foo.owner.id == self.context['request'].user.id class Meta: model = Contract fields = ['id', 'is_author', 'title','contract_signing_status','files', ] Now my ContractGetSerializer returns a ReturnList with all contracts. How can I add additional fields to that ReturnList and make it a dictionary? I need for instance to return only 5 recent contracts (filtered by timestamp). Also, I need to add total SIGNED contracts, and total PENDING contracts, counting all contracts data, so that my frontend would not need to do this. -
Django template pagination is not working with link
This is my template code for pagination : <div class="paginationWrapper mt-3"> {{match_list.paginator.num_pages}} {% if match_list.paginator.num_pages > 1 %} <ul class="pagination"> {% if match_list.has_previous %} <li> <a href="?p={{match_list.previous_page_number}}{%if request.GET.q%}&q={{request.GET.q}}{%endif%}{%if request.GET.sports%}&sports={{request.GET.sports}}{%endif%}{%if request.GET.match_status%}&match_status={{request.GET.match_status}}{%endif%}" class="page-link"><i class="fas fa-angle-double-left"></i></a> </li> {% endif %} {% if match_list.number|add:'-4' > 1 %} <li><a href="?p={{match_list.number|add:'-5'}}">&hellip;</a></li> {% endif %} {% for i in match_list.paginator.page_range %} {% if match_list.number == i %} <li class="active"><a class="page-link" href="javascript:void(0);">{{ i }}</a></li> {% elif i > match_list.number|add:'-5' and i < match_list.number|add:'5' %} <li><a href="?p={{i}}{%if request.GET.q%}&q={{request.GET.q}}{%endif%}{%if request.GET.sports%}&sports={{request.GET.sports}}{%endif%}{%if request.GET.match_status%}&match_status={{request.GET.match_status}}{%endif%}" class="page-link">{{ i }}</a></li> {% endif %} {% endfor %} {% if match_list.paginator.num_pages > match_list.number|add:'4' %} <li><a href="?p={{ match_list.number|add:'5' }}">&hellip;</a></li> {% endif %} {% if match_list.has_next %} <li><a href="?p={{match_list.next_page_number}}{% if request.GET.q%}&q={{request.GET.q}}{%endif%}{%if request.GET.sports%}&sports={{request.GET.sports}}{%endif%}{%if request.GET.match_status%}&match_status={{request.GET.match_status}}{%endif%}"><i class="fa fa-chevron-right" aria-hidden="true"></i></a></li> {% else %} <li class="disabled"><span><i class="fa fa-chevron-right" aria-hidden="true"></i></span></li> {% endif %} </ul> {% endif %} </div> And here it is my changelist_view for pagination: def changelist_view(self, request, extra_context=None): match_all = MatchSchedules.objects.filter().order_by('-id') sports = request.GET.get('sports') matchStatus = request.GET.get('match_status') searchs = request.GET.get('q') startDate = request.GET.get('match_datetime__range__gte') endDate = request.GET.get('match_datetime__range__lte') if sports: match_all = match_all.filter(tournament__sports__id=sports) if searchs: match_all = match_all.filter(Q(match_status__icontains=searchs) | Q(competitor_first_name__icontains=searchs) | Q( competitor_second_name__icontains=searchs) | Q(tournament__sports__sport_name__icontains=searchs)) if matchStatus: match_all = match_all.filter(match_status=matchStatus) if startDate or endDate: match_all = match_all.filter(Q(match_datetime__icontains=startDate) | Q(match_datetime__icontains=endDate)) paginator = Paginator(match_all, 10) print(match_all.count()) page = … -
How to add can i add comment form with queryset in Django?
Info: i have sales_item QuerySet in view. i want to approve, decline and add some comments on specific sales_items. Problem: The code below of views file is getting error Sale matching query does not exist. models.py class Authorize(models.Model): APPROVED = 'AP' DECLINED = 'DL' STATUS_CHOICES = [ (APPROVED, 'Approved'), (DECLINED, 'Declined'), ] user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) sales_item = models.ForeignKey(Sale, on_delete=models.CASCADE, null=True, blank=True) comments = models.TextField(max_length=1000, blank=True) created_at = models.DateTimeField(auto_now_add=True) status = models.CharField(choices=STATUS_CHOICES, default=APPROVED, max_length=2) views.py def SalesListView(request): queryset = Sale.objects.all() auth_form = AuthorizeForm(data=request.POST) if request.method == 'POST': pk = request.POST.get('pk') sales = Sale.objects.get(id=pk) if auth_form.is_valid(): approved = auth_form.save(commit=False) approved.sales_item = sales approved.save() context = { 'sales': queryset, 'form': auth_form } return render(request, 'pending_sale.html', context) -
Open EDX can't decode .weight file, Internal Server error (XBlock)
I'm developing an XBlock in Open EDX, and I'm stuck in the process of serving a static file with .weight extension. The environment is devstack (docker) for Juniper Release. The static file is stored in /edx/var/edxapp/staticfiles, which I want to use it in the js file of my XBlock. The file has the extension .weight, as it contains the weights of a Neural Network (face-api.js). When I try to GET this file, I get a 500 status error, and the message 'utf-8' codec can't decode byte 0xa6 in position 0: invalid start byte. Here some screenshots, GET request of the file (1) GET request of the file (2) I think that the problem is that Django and Python are not able to decode the content of those files, and can't return the proper file. Or maybe there's some trouble with Nginx. Thanks for your help! Joan -
BranchSemanticsTemplate has no field named 'semantics_tmplt'
Django 3.1.7 Model class BranchSemanticsTemplate(ArchivedMixin, FlagMixin, clients.model_mixins.BranchMixin, semantics.model_mixins.SemanticsLevelTwoMixin, models.Model): """ As a general rule of thumb samantics level 2 has its own template. If a branch needs a special template for that semantics, stipulate it in this model. """ semantics_tmplt = models.ForeignKey("tmplts.SemanticsLevel2Tmplt", on_delete=models.PROTECT, verbose_name=gettext("Semantics template")), branch_tmplt = models.ForeignKey("tmplts.BranchTmplt", on_delete=models.PROTECT, verbose_name=gettext("Branch template")), def __str__(self): return "{} - {} - {} - {}".format(str(self.branch_tmplt), str(self.branch), str(self.semantics_level_two), str(self.semantics_tmplt), ) class Meta: verbose_name = gettext("Branch template - branch- semantics - semantics template") verbose_name_plural = verbose_name constraints = [UniqueConstraint(fields=['branch', 'semantics_level_two', 'semantics_tmplt', 'branch_tmplt', ], name='semantics_branch_template')] Traceback (venv) michael@michael:~/PycharmProjects/ads6/ads6$ python manage.py migrate Operations to perform: Apply all migrations: admin, auth, clients, commerce, contenttypes, dashboard, generals, images, semantics, sessions, staticassets, tmplts, toponyms Running migrations: Applying dashboard.0001_initial...Traceback (most recent call last): File "/home/michael/PycharmProjects/ads6/venv/lib/python3.8/site-packages/django/db/models/options.py", line 575, in get_field return self.fields_map[field_name] KeyError: 'semantics_tmplt' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/michael/PycharmProjects/ads6/venv/lib/python3.8/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/home/michael/PycharmProjects/ads6/venv/lib/python3.8/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/michael/PycharmProjects/ads6/venv/lib/python3.8/site-packages/django/core/management/base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "/home/michael/PycharmProjects/ads6/venv/lib/python3.8/site-packages/django/core/management/base.py", line 371, in execute output = self.handle(*args, **options) File "/home/michael/PycharmProjects/ads6/venv/lib/python3.8/site-packages/django/core/management/base.py", line 85, in wrapped res = handle_func(*args, … -
How do I fix "improperlyconfigured" error?
Just started learning Django but met with an error right off the bat I got the error: django.core.exceptions.ImproperlyConfigured: The included URLconf '<module 'app.urls' from 'C:\\django tutorial\\mysite\\app\\urls.py'>' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import. these are the files that have my code in it: views.py: from django.shortcuts import render from django.http import HttpResponse def index(response): return HttpResponse('Tech with Adil') app.urls.py: from django.urls import path from . import views urlpatters = [ path("", views.index, name='index') ] and mysite.urls.py: from django.contrib import admin from django.urls import path, include urlpatterns = [ path('', include('app.urls')), path('admin/', admin.site.urls) ] -
Django Rest Framework - problem with filtering data
in my models i have Book and Author with M2M relationship. models.py from django.db import models from django.db import models class Book(models.Model): title = models.CharField(max_length=200) published_date = models.DateField(auto_now_add=False) categories = models.CharField(max_length=300, null=True, blank=True) average_rating = models.FloatField(null=True, blank=True) ratings_count = models.IntegerField(null=True, blank=True) thumbnail = models.URLField(null=True, blank=True) def authors(self): return self.author_set.all() def __str__(self): return f'title: {self.title} \n' \ f'date of publication: {self.published_date}' class Author(models.Model): name = models.CharField(max_length=200) books = models.ManyToManyField(Book) def __str__(self): return str(self.name) in my serializer i'm getting authors from def authors in models.py serializers.py class Meta: model = Author fields = ['name'] class BookSerializer(serializers.ModelSerializer): authors = AuthorSerializer(many=True) class Meta: model = Book fields = [ 'authors', 'title', 'published_date', 'categories', 'average_rating', 'ratings_count', 'thumbnail' ] so in views.py i want to filter books by authors views.py class BooksListAPIView(generics.ListAPIView): queryset = Book.objects.all() serializer_class = BookSerializer filter_backends = (filters.OrderingFilter, DjangoFilterBackend) filter_fields = ['published_date', 'authors'] ordering_fields = ['published_date'] but it gives me this error 'Meta.fields' must not contain non-model field names: authors any idea how can i filter data with authors so i can extract books of given authors. I would like to have a choice of selecting filters. Thanks in advance. -
Export Excel File Using Ceklry Task
I want to download an excel File Using CCelery Task Here is my celery task @celery_app.task(name="download_xls", base=PortalTask) def data_export_download_task(all, object_id ,user_id): user = User.objects.get(id=user_id) master_data = Mymodel.objects.get( object_id=object_id) response = HttpResponse(content_type='application/ms-excel') response['Content-Disposition'] = 'attachment; filename="{}.xls"'.format(master_data.name) wb = xlwt.Workbook(encoding='utf-8') ws = wb.add_sheet('data.name') row_num = 0 font_style = xlwt.XFStyle() font_style.font.bold = True if all == 'yes': header = get_all_data_header(scenario) else: header = get_vendor_header(scenario) for col_num in range(len(header)): ws.write(row_num, col_num, header[col_num], font_style) # Sheet body, remaining rows font_style = xlwt.XFStyle() if all == 'yes': rows = get_all_data_values(scenario) else: rows = get_vendor_values(scenario) data = [] for each in rows: t = {} for key, value in each.items(): if key in header: if key =="status_id": value = DropDown.objects.get(id = value) t.update({key: value}) t.update({key: value}) a = list(t.values()) data.append(a) for row in data: row_num += 1 for col_num in range(len(row)): ws.write(row_num, col_num, str(row[col_num]), font_style) wb.save(response) return response Everything is working fine but the return is not working It's failing the celery task It's saying that TypeError: Object of type method is not JSON serializable -
How to display another user's dashboard/profile (Django)
I'm a little lost how to implement a feature whereby the logged in user can view another user's dashboard on clicking View Dashboard. I am getting lost with how to properly set up the urls.py and views.py file so hoping I can get some support here. My JavaScript function (I'm doing most of my front-end rendering through JS): const viewDashboard = function(clickedUser){ console.log("Going to the Dashboard of:" + " " + clickedUser); userName = "/" + clickedUser; window.location.href = userName; }; My urls.py: [...] path('<username>', views.view_dashboard, name='view_dashboard'), [...] My views.py: def view_dashboard (request, username): # If no such user exists raise 404 try: user = User.objects.get(username=username) except: raise Http404 context = locals() template = 'dashboard.html' return render (request, template, context) The error traceback (when clicking on a user called Henry's view dashboard button): Traceback (most recent call last): File "/Users/x/Desktop/Coding/anybody/avenv/lib/python3.6/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/Users/x/Desktop/Coding/anybody/avenv/lib/python3.6/site-packages/django/core/handlers/base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/x/Desktop/Coding/anybody/anybody1/testingland/views.py", line 260, in view_dashboard return render (request, template, context) File "/Users/x/Desktop/Coding/anybody/avenv/lib/python3.6/site-packages/django/shortcuts.py", line 19, in render content = loader.render_to_string(template_name, context, request, using=using) File "/Users/x/Desktop/Coding/anybody/avenv/lib/python3.6/site-packages/django/template/loader.py", line 61, in render_to_string template = get_template(template_name, using=using) File "/Users/x/Desktop/Coding/anybody/avenv/lib/python3.6/site-packages/django/template/loader.py", line 19, in get_template raise TemplateDoesNotExist(template_name, chain=chain) … -
In Django is it possible to delete a range of data from a table whose integer values sum up to a certain value?
Example I have this model models.py class Share(models.Model): member = models.ForeignKey( Member, on_delete=models.CASCADE, related_name='share') week = models.ForeignKey( WeekModel, on_delete=models.CASCADE, related_name='share') month = models.ForeignKey( MonthModel, on_delete=models.CASCADE, related_name='share', blank=True, null=True) year = models.ForeignKey( YearModel, on_delete=models.CASCADE, related_name='share', blank=True, null=True) shares = models.PositiveIntegerField(default=0) jamii = models.FloatField(blank=True, null=True, default=0) fine = models.FloatField(blank=True, null=True, default=0) created_at = models.DateTimeField(auto_now_add=True) date = models.DateTimeField(blank=True, null=True) #weeknumber = models.PositiveIntegerField(blank=True, null=True) monthname = models.CharField(max_length=100) years = models.PositiveIntegerField(blank=True, null=True) class Meta: db_table = 'share' unique_together = [("member", "week")] ordering = ['member__user__username'] natsorted(ordering) Is it possible to query by date the values that add up to a given integer from the share field and delete them? -
Using class based view UpdateView in case change or delete nested model
models.py class Project(models.Model): project_name = models.CharField(max_length=150) class Task(models.Model): project = models.ForeignKey(Project, on_delete=models.CASCADE) task_name = models.CharField(max_length=250) is_done = models.BooleanField(default=False) views.py from django.views.generic import ListView from django.views.generic.edit import DeleteView from django.urls import reverse_lazy from .models import Project class ProjectListView(ListView): model = Project context_object_name = 'projects' class ProjectDeleteView(DeleteView): model = Project success_url = reverse_lazy('projects') project_list.html {% for project in projects %} <p>{{ project.project_name }} - <a href="{{ project.id }}/delete">Delete</a> </p> <ul> {% for task in project.task_set.all %} <li>{{ task.task_name }} - <a href="#">Done</a> - <a href="#">Delete</a></li> {% endfor %} </ul> {% endfor %} How I can use class based view UpdateView for the Project model in case change or delete nested model Task? -
user_logged_in is not working djnago rest framework
I have created registration api and login api using drf and i wanted to store all user login using signals user_loggged_in. it work fine when super user logged in but it doesn't work when user logged in. -
How to make structure to show 2d array in html where array data is render based on django (view.py) send?
suppose array be like ... arr = [['1', '2', '3'],[1', '2', '3'],[1', '2', '3']] here if every time data passed by django view.py can be different. Means array size can be varied as requirement it can be like this at second time arr = [['1', '2'],[1', '2']] how can I make general structure in html? is there JavaScript needed ?if yes then how to send data from view.py to javascript ? -
Django web app: storing Chat messages in database
I am creating a web app using Django and would like to allow any 2 users (but only 2 at a time) to be able to chat with each other. It doesn't need to be anything fancy and it will only be between the 2 related users on a Transaction object, so the Chat object will look up to the Transaction object. Someone told me it's not a good idea to store chat messages in just a regular Message table in a database, and that I should use a messaging service, since the chat messages would not be encrypted in the database. The chat messages will allow 2 users to plan to meet up with each other, which is somewhat confidential, but I don't think it's anything to worry about. Or am I wrong? I was also considering using the django-messages library, but I think it would be easier to just add a new object to my table. I found this StackOverflow post from 10 years ago about how this solution is good but didn't find many discussions about this recently. Below is a picture of the schema suggested: enter image description here What do people think, is it better … -
Django package versions have conflicting dependencies. (emove package versions to allow pip attempt to solve the dependency conflict)
ERROR: Cannot install -r requirements.txt (line 10), -r requirements.txt (line 11), -r requirements.txt (line 16), -r requirements.txt (line 9) and Django==2.0.13 because these package versions have conflicting dependencies. The conflict is caused by: The user requested Django==2.0.13 django-crontab 0.7.1 depends on Django>=1.8 django-dbbackup 3.3.0 depends on Django>=1.5 django-debug-toolbar 2.2 depends on Django>=1.11 django-storages 1.10.1 depends on Django>=2.2 To fix this you could try to: loosen the range of package versions you've specified remove package versions to allow pip attempt to solve the dependency conflict ERROR: ResolutionImpossible: for help visit https://pip.pypa.io/en/latest/user_guide/#fixing-conflicting-dependencies -
Why do we direct the urls file in our main directory to the newly created urls file in the app directory in Django?
I was learning Django and noticed people directing the URLs file in the main directory of the project to a new created URL.py file in the app folder? Why can't we directly put the path in the URL file in the main directory? Instead of using include, we could have directly put the path there. Why aren't we doing it? -
Heroku keeps crashing
C:\Users\urvis\Desktop\rajpatel322.github.io\Practice_Project>heroku logs 2021-03-20T06:20:17.463462+00:00 app[web.1]: gunicorn.errors.HaltServer: <HaltServer 'Worker failed to boot.' 3> 2021-03-20T06:20:17.463474+00:00 app[web.1]: 2021-03-20T06:20:17.463474+00:00 app[web.1]: During handling of the above exception, another exception occurred: 2021-03-20T06:20:17.463475+00:00 app[web.1]: 2021-03-20T06:20:17.463478+00:00 app[web.1]: Traceback (most recent call last): 2021-03-20T06:20:17.463479+00:00 app[web.1]: File "/app/.heroku/python/bin/gunicorn", line 8, in 2021-03-20T06:20:17.463602+00:00 app[web.1]: sys.exit(run()) 2021-03-20T06:20:17.463630+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/app/wsgiapp.py", line 58, in run 2021-03-20T06:20:17.463750+00:00 app[web.1]: WSGIApplication("%(prog)s [OPTIONS] [APP_MODULE]").run() 2021-03-20T06:20:17.463785+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/app/base.py", line 228, in run 2021-03-20T06:20:17.463952+00:00 app[web.1]: super().run() 2021-03-20T06:20:17.463954+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/app/base.py", line 72, in run 2021-03-20T06:20:17.464081+00:00 app[web.1]: Arbiter(self).run() 2021-03-20T06:20:17.464105+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/arbiter.py", line 229, in run 2021-03-20T06:20:17.464249+00:00 app[web.1]: self.halt(reason=inst.reason, exit_status=inst.exit_status) 2021-03-20T06:20:17.464273+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/arbiter.py", line 342, in halt 2021-03-20T06:20:17.464458+00:00 app[web.1]: self.stop() 2021-03-20T06:20:17.464461+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/arbiter.py", line 393, in stop 2021-03-20T06:20:17.464655+00:00 app[web.1]: time.sleep(0.1) 2021-03-20T06:20:17.464658+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/arbiter.py", line 242, in handle_chld 2021-03-20T06:20:17.464810+00:00 app[web.1]: self.reap_workers() 2021-03-20T06:20:17.464814+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/arbiter.py", line 525, in reap_workers 2021-03-20T06:20:17.465021+00:00 app[web.1]: raise HaltServer(reason, self.WORKER_BOOT_ERROR) 2021-03-20T06:20:17.465074+00:00 app[web.1]: gunicorn.errors.HaltServer: <HaltServer 'Worker failed to boot.' 3> 2021-03-20T06:20:17.536146+00:00 heroku[web.1]: Process exited with status 1 2021-03-20T06:20:17.597483+00:00 heroku[web.1]: State changed from starting to crashed 2021-03-20T06:20:18.502462+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=triksnas.herokuapp.com request_id=8cab5dfb-ac60-4ccc-bd18-bb5be54dcd71 fwd="67.173.81.219" dyno= connect= service= status=503 bytes= protocol=https 2021-03-20T06:20:18.776461+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=triksnas.herokuapp.com request_id=9e323197-2f69-457a-8769-affa013553b5 fwd="67.173.81.219" dyno= connect= service= status=503 bytes= protocol=https 2021-03-20T06:22:08.971134+00:00 heroku[router]: at=error code=H10 desc="App crashed" … -
Passing dynamic url with parameters from JavaScript to Django
I have this form for adding and updating data: form.addEventListener('submit', function(e){ e.preventDefault() var url = "{% url 'api:task-create' %}" if(activeItem != null ){ url = `http://localhost:8000/api/task-update/${activeItem.id}/` activeItem = null } var title = document.getElementById('title').value fetch(url, { method: 'POST', headers:{ 'Content-type': 'application/json', 'X-CSRFToken': csrftoken, }, body: JSON.stringify({'title':title}) }).then(function(response){ renderList() document.getElementById('form').reset() }) }) when adding url without parameters like this {% url 'foo:bar' %} it works fine, but when I do this: {% url 'foo:bar' <any var> %}, I am getting NoReverseMatch error. Currently I am using static url as you can see up top inside if statement and it works perfectly fine. I tried using ` to make it literal string still doesnt work. I just want urls getting passed be dynamic. -
How Override Djoser base endpoint users/me
I am a bit new to Djoser and what i am wanting to do is when an authenticated user naviates to the users/me API endpoint it returns with the user id email and name. I would like for it to also return custom information how would I do that? -
DRF Login/logout with Token authentication possibly with Session Authentication
I am beginner in django and I am trying to use Basic and Token Authentication for Login/logout views referring below tutorial except that I have own function based view. https://gutsytechster.wordpress.com/2019/11/12/user-auth-operations-in-drf-login-logout-register-change-password/ I use django.contrib.auth authenticate in to check for user credential and return a token instead of login method which I suppose creates a session in django. But the tutorial asks for auth.logout method for logging out which would require HTTPRequest object instead of rest_framework.Request object. However it works for logout and when I try to use auth.login method it give me the following error. The request argument must be an instance of django.http.HttpRequest, not rest_framework.request.Request my understanding is that django.contrib.auth methods login, logout works with session authentication and rest_framework.Request extends HTTPRequest. My questions are Does this error happens as I dint set up session authenticationin middleware? if so why logout alone works? Shouldn't it throw the same error for not referring to HTTPRequest object. Any help would be appreciated as I try to understand the basics well before going for any other approach. My view here @api_view(["POST"]) def login(request): serializer = LoginSerializer(data=request.data) serializer.is_valid(raise_exception=True) user = get_and_authenticate_user(**serializer.validated_data) data = AuthUserSerializer(user).data #login(request, user) return Response(data=data) def get_and_authenticate_user(username, password): user = authenticate(username=username, password=password) …