Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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) … -
Django - Group permissions per vendor or company
I am using a custom User model. I would like to enforce permissions based on vendor and group. A vendor can create groups and assign those groups permissions from given list of permissions. I have been reading about group permissions and have concluded that Django's Group model is not good choice for this as it doesn't allow multiple groups with same name and some other issues. I looked into some projects like Django-guardian. But don't seem to get an example that fits my case. What I want to do is. A Vendor will have staff users who will then be assigned to groups. So to check permission for a given group or user I will need to take Vendor into consideration. They must be member of the vendor staff and then the permission group. Can anyone point me in the right direction. Thank you -
nginx 502 error on digitalocean after copying code from dev folder to mail folder
I have a Django app deployed on DigitalOcean with Nginx, PostgresSQL. I have copied my code from my main folder to another dev-folder, so initially, both the folders have the same code. Now, I run python manage.py runserver 0.0.0.0:8000 in my def-folder and can access my application on https://server_ip:8000/. Now, I can make any changes in my code without affecting the main application. Once changes are done, I run cp -a /source/. /dest/ to copy my changes from the dev-folder to the main folder. It all looks good, but after copying code from the dev-folder to the main folder, my application gives a 502 error. The error disappears after running systemctl restart gunicorn. But why nginx is giving 502, when there is no timeout issue. Also, is this the accepted way of maintaining dev branch?? -
Django image file upload API no media is getting saved
I am trying to upload image to the server using Django API. The link is getting saved into the database but the actual media is not getting saved in /media folder. My models.py class File(models.Model): # file = models.FileField(blank=False, null=False) file = models.ImageField(upload_to='media/', blank=True) remark = models.CharField(max_length=20) timestamp = models.DateTimeField(auto_now_add=True) url.py: path('upload/', views.FileView.as_view(), name='file-upload'), serializer.py User Interest Serializer class UserInterestSerializer(serializers.ModelSerializer): class Meta: model = UserInterest fields = "__all__" views.py class FileView(generics.ListCreateAPIView): queryset = File.objects.all() serializer_class = FileSerializer Global setting: if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Output: Link name is getting saved in the database: "id": 18, "file": "https://<URL>/media/home/tguser/tgportal/core/media/check.png", "remark": "ok", "timestamp": "2021-03-19T16:43:50.131435Z" } But actual media is not getting saved into media folder. Multiplart/form-data is set through postman. Am i doing anything wrong? Do i need /media folder permission? Any help is appreciated. Thanks, PD -
django server is auto reloading and not stopping
I am working on a web project. One moment before all was good but suddenly django localhost server kept itself reloading and not stopping auto-reloading the pages. First I got the following error connectionreseterror: (errno 104) connection reset by peer But now it's not showing any error just reloading itself over and over again. What could be the cause for this? Any help will be appriciated -
'bytes' object has no attribute 'encode' in EmailMessage
I am trying to make an app in Django which accepts information from user and send a HTML template as pdf through an e-mail to the user. But I am getting this error 'bytes' object has no attribute 'encode' Here is my view for the email def email(request, serial_no): user = get_object_or_404(Student, pk=serial_no) # roll_no = {'roll': str(user['roll_no'])} html = render_to_string('card.html', {'user': user}) response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'filename={}'.format(user.roll_no + '.pdf') pdf = weasyprint.HTML(string=html, base_url='').write_pdf( stylesheets=[weasyprint.CSS(string='body { font-family: serif}')]) to_emails = [str(user.roll_no) + '@gmail.com'] subject = "Certificate from Nami Montana" email = EmailMessage(subject, body=pdf, from_email='SSC', to=to_emails) email.attach("{}".format(user.roll_no) + '.pdf', pdf, "application/pdf") email.content_subtype = "pdf" # Main content is now text/html email.encoding = 'utf-8' email.send() return HttpResponseRedirect(reverse('id_card:submit')) Thanks in advance