Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
External Python Scripts and Django Virtual Env
I run an external script from my Django app using subprocess this way: class ExecutePythonFileView(View): def get(self, request): # Execute script script_path = os.path.join(settings.BASE_DIR, '/Code/zenet/zenet/workers/stats_scraper.py') subprocess.call(['python', script_path]) # Return response return HttpResponse("Executed!") I would need to execute it through the Django virtual environnement though, how could I proceed? -
read and edit a csv file in django
i am trying to read and edit some cvs file in my models my model: class chart(models.Model): name = models.CharField(max_length=10) char = models.FileField(null=True, blank=True) the csv file are in char filed now in views.py: def home(request): context ={ } return render(request, 'home.html', context) how I can read csv file in views and open with pandas or matplotlib? -
Django cannot update second field with signal
When i add client to Client table, it's added automatically with signals to ClientsBalance. But the company field on ClientsBalance table is not updated to the current company (company=user.company), i would like that this field contain the current user company. class Company(models.Model): user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) name = models.CharField(max_length=64) class Client(models.Model): company = models.ForeignKey(Company, on_delete=models.CASCADE) name = models.CharField(max_length=256) class ClientsBalance(models.Model): company = models.ForeignKey(Company, null=True, blank=True, on_delete=models.CASCADE) client = models.OneToOneField('Client', on_delete=models.CASCADE,related_name='Client') def create_client(sender, **kwargs): if kwargs['created']: client = ClientsBalance.objects.create(client=kwargs['instance']) post_save.connect(create_client, sender=Client) -
Django download of pdf file redirects to login page
I try to generate and download the generated file but once the file is generated I'm redirected to the login page. The CBV looks like: class BilanStudentGeneratePdfView(LoginRequiredMixin, generic.View): def get(self, request, pk): # https://www.bedjango.com/blog/how-generate-pdf-django-weasyprint/ bilan_student = BilanStudent.objects.get(pk=pk) html_string = render_to_string('bilan/bilan_student_pdf.html', {'bilan_student': bilan_student}) html = HTML(string=html_string) filename = '{}/bilan/bilan_{}_Student_{}.pdf'.format(MEDIA_ROOT, bilan_student.bilan.pk, bilan_student.student.pk) html.write_pdf(target=filename) response = FileResponse(filename=filename, as_attachment=True, content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename={}'.format(filename) return response The file is generated but what I see is that I have a redirect to my splash page which is the login page and I don't know why: [11/Nov/2020 17:05:11] "GET /bilan/pdf/student/71/ HTTP/1.1" 200 0 [11/Nov/2020 17:05:11] "GET /bilan/pdf/student/71/ HTTP/1.1" 302 0 [11/Nov/2020 17:05:11] "GET /splash/?next=/bilan/pdf/student/71/ HTTP/1.1" 200 3270 Any help will be appreciated. -
QuerySet django . How to write a function correctly to make tests pass
how returns in tree_downwards the root organization with the requested org_id and all its children at any nesting level and returns in tree_upwords the root organization with the requested org_id and all its parents at any nesting level to make tests pas??? I will only be able to return either the parents or the organization itself models.py class OrganizationQuerySet(models.QuerySet): def tree_downwards(self, root_id): """ :type root_org_id: int """ return self.filter(???) def tree_upwards(self, child_id): """ :type child_org_id: int """ return self.filter(???) class Organization(models.Model): objects = OrganizationQuerySet.as_manager() name = models.CharField(max_length=1000, blank=False, null=False) parent = models.ForeignKey( "self", null=True, blank=True, on_delete=models.PROTECT ) class Meta: ordering = ["name"] verbose_name = "organization" def __str__(self): return self.name tests.py def test_get_tree_downwards_cluster(make_organization): org_1 = make_organization() org_2 = make_organization(parent=org_1) children = Organization.objects.tree_downwards(org_1.id) assert org_1 in children assert org_2 in children def test_get_parents_chain(make_organization): org_1 = make_organization() org_2 = make_organization(parent=org_1) org_3 = make_organization(parent=org_2) parents = Organization.objects.tree_upwards(org_3.id) assert org_1 in parents assert org_2 in parents assert org_3 in parents -
Django Connecting To Quickbooks Online Via Backend
I'm trying to push data into Quickbooks online from my backend django app but Oauth is pretty tough for me to understand. I'm attempting to use requests-oauth and the backend application workflow. https://requests-oauthlib.readthedocs.io/en/latest/oauth2_workflow.html#backend-application-flow I am able to generate a token but i'm getting a 401 back when I try to use it. I can't tell whether the code that is being returned is bad because the code that I generate via the QBO developer playground also does not work for my request. The request does work in the developer playground. Can anyone show me an example of connecting to quickbooks via a backend workflow. It doesn't seem to make sense to have a user "authenticate" with this being a backend service. Here's my attempt: class QuickbooksOnlineService: def __init__(self): self.integration_credential = IntegrationCredential.objects.get( agent_company_id=1, partner=IntegrationCredential.QUICKBOOKS ) self.auth_client = AuthClient( client_id=self.integration_credential.client_id, client_secret=self.integration_credential.client_secret, environment='sandbox', redirect_uri='https://developer.intuit.com/v2/OAuth2Playground/RedirectUrl' ) def build_client(self): auth_client = self.auth_client url = auth_client.get_authorization_url([Scopes.ACCOUNTING]) # This URL takes me to the devleoper playground and lets me generate a token and make a successful request in the developer play print(url) auth = HTTPBasicAuth(self.integration_credential.client_id, self.integration_credential.client_secret) client = BackendApplicationClient(client_id=self.integration_credential.client_id, scope=['com.intuit.quickbooks.accounting']) oauth = OAuth2Session(client=client) token = oauth.fetch_token(token_url='https://oauth.platform.intuit.com/oauth2/v1/tokens/bearer', auth=auth ) print(token) import requests url = "https://sandbox-quickbooks.api.intuit.com/v3/company/4620816365154174550/companyinfo/4620816365154174550" headers = { … -
use nginx to serve dynamically created media images in Django/React
I have a React front-end and a Django backend. I am also using nginx server. In the admin panel, I am able to add pdfs which go directly into a 'media' folder inside of the django application. In development, everything works correctly but In production, when Debug = false, the media files do not show up. I am thinking of using the nginx server to re-route to the media folder. But I think something is wrong, as the media files do not show up. Also, is this the best method to redirect to the media files? Below is my ngnix server server { listen 80; client_max_body_size 60M; location / { proxy_pass http://frontend:3000; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Host $server_name; } location /api { proxy_pass http://backend:8000; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Host $server_name; } location /admin { proxy_pass http://backend:8000/admin; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Host $server_name; } location ~^ /media { autoindex on; alias /path/to/media; } location /nginx-health-check { access_log off; return 200; } } -
TypeError at /formpage '>' not supported between instances of 'str' and 'int' also the error is specific in form.is_valid
This is forms.py from django import forms from django.core import validators def check_for_z(value): if value[0].lower() !='z': raise forms.ValidationError("NAME NEEDS TO START WITH Z") class FormName(forms.Form): name = forms.CharField() email = forms.EmailField() text = forms.CharField(widget= forms.Textarea) botcatcher = forms.CharField(required=False, widget=forms.HiddenInput, validators=[validators.MaxValueValidator(0)]) This is views.py from django.shortcuts import render from . import forms from .forms import FormName from django.http import HttpResponseRedirect def index(request): return render(request,'formapp/index.html') def form_name_view(request): form = forms.FormName() if request.method == "POST": form = forms.FormName(request.POST) if form .is_valid (): # do something code print("Validations scuces") print("NAME: "+form.cleaned_data["name"]) print("EMAIL: "+form.cleaned_data["email"]) print("TEXT:"+form.cleaned_data['text']) # return HttpResponseRedirect("/thanks/") else: form= FormName() return render(request,'formapp/form_page.html',{'form' : form}) Now actually it is throwing error on the line form.is_valid() and is showing TypeError at /formpage '>' not supported between instances of 'str' and 'int' And this is happening when I change/add attribute in the botcatcher i.e i add value='joke' Everything else is similar to normal django -
Are coding applications such are android app dev, normal django, python coding and some ethical hacking use many cores or a single core
I am planning to buy a pc, and I am confused between some parts because I don't know what type of hardware likes coding. Like a good 6 core 12 thread would be better, or an 8 core, 16 thread be better. If both are superior overpowered, Would a good 4 core machine with 8 threads do the work? -
how to display the nut,date fields in html template ? how to access foreign key fields in html tamplate?
I have three models in models.py which are Topic,Webpage and AccessRecord. class AccessRecord has foreign key relation with class Webpage i wanna use AccessRecord fields nut,date in html template which is used to display class Webpage content how we can access AccessRecord fields in which has a foreign relation with class Webpage ? this is my model: class Topic(models.Model): top_name = models.CharField(max_length=264,unique=True) def __str__(self): return self.top_name class Webpage(models.Model): topic = models.ForeignKey(Topic) name = models.CharField(max_length=264,unique=True) url = models.URLField(unique=True) def __str__(self): return self.name class AccessRecord(models.Model): name = models.ForeignKey(Webpage) date = models.DateField() nut = models.CharField(max_length=56) def __str__(self): return str(self.date) this is my view: def index(request): webpage_list = Webpage.objects.all() web_dict = {"web_records":webpage_list} return render(request,'first_app/index.html',web_dict) this is my template: <body> <h1>Hi, welcome to Django Level Two!</h1> <h2>Here are your access records:</h2> <div class="djangtwo"> {% if web_records %} <table style="float: left"> <thead> <th>Topic Name</th> <th>Site name</th> <th>Url Accessed</th> <th>Date Accessed</th> <th>Webpage nut</th> </thead> {% for web in web_records %} <tr> <td>{{ web.topic }}</td> <td>{{ web.name }}</td> <td>{{ web.url }}</td> <td>{{ web.nut }}</td> <td>{{ web.date }}</td> </tr> {% endfor %} </table> {% endif %} </div> </body> -
Serializer processes one file instead of multiple files?
I am trying to upload multiple images ,but it only takes and uploads one image . Here is the code: class ArticleImagesViewSerializer(serializers.ModelSerializer): class Meta: model = ArticleImages fields = ('id','image') def create(self, validated_data): return ArticleImages.objects.create(**validated_data) class ArticleViewSerializer(serializers.ModelSerializer): images = ArticleImagesViewSerializer(required=False,many=True) class Meta: model = Article fields = ('images','id','author') def create(self, validated_data): images_data = self.context.get('view').request.FILES article = Article.objects.create(**validated_data) for image_data in images_data.values(): ArticleImages.objects.create(article=article, image=image_data) return article Here is the output when i post multiple images: "images": [ { "id": "6ee3eebe-0b78-4da3-8d18-435db788c1bf", "image": "http://127.0.0.1:8000/images/images/download2_lhbtF5T.png" }, ], "id": "e1534f99-fc48-4892-b11c-8224a84abd15", "author": "4e9ae720-e823-4e2f-83b3-144573257d73",} The problem here is that it posted one image only when i upload multiple images. How can i solve it? -
Django Models inheritance and Serializers
I want to have several models inhering from NoticeModel but currently I only have one: class NoticeModel(SpicerModel): userId = models.ForeignKey( 'account.User', on_delete=models.CASCADE, null=False, blank=False, related_name='notice_user' ) is_read = models.BooleanField(null=False, blank=False, default=False) context = models.CharField(max_length=64, null=False, blank=False, choices=NoticeContext.CHOICES) message = models.CharField(max_length=255, null=False, blank=False, default='') class BookingRequestNotice(NoticeModel): booking_request = models.ForeignKey( BookingRequest, on_delete=models.CASCADE, null=False, blank=False, related_name='booking_event_notice' ) And here are the serialisers: class NoticeModelSerializer(serializers.HyperlinkedModelSerializer): userId = serializers.ReadOnlyField(source='userId.email') class Meta: model = NoticeModel fields = [ 'id', 'userId', 'is_read', 'context', 'message' ] class BookingRequestNoticeSerializer(NoticeModelSerializer): class Meta: model = BookingRequestNotice fields = NoticeModelSerializer.Meta.fields + ['booking_request'] To get all of the Notices, I do: class NoticeList(APIView): permission_classes = [permissions.IsAuthenticated] def get(self, request): user = getCurrentUser(request) notices = NoticeModel.objects.filter(userId=user).filter(is_read=False) serializer = NoticeModelSerializer(notices, many=True, context={'request': request}) return Response(serializer.data) The problem is that, since I am using NoticeModelSerializer I am only getting objects with the common fields (I do not get booking_request). How can I return the specific serializers without having to query each one of them individually? -
django template refresh causing session data loss
I am having a problem where I don't seem to be able to identify the root cause. I explain. I have a template where the user make a search and graphs and data make it to the page. From the query value that the user inputed, I need to pass it in a session to another template. here is what the view look like: @method_decorator(login_required, name='dispatch') class SupplierPage2(LoginRequiredMixin,APIView): def get(self, request, *args, **kwargs): query = request.GET.get('search_ress', None) print(query) context = {} #if query and request.method == 'GET': Supplier = supplier2.objects.filter(supplier = query) labels = Item2.objects.filter(fournisseur = query).values_list('reference', flat=True)[:10] labels = list(labels) default_items = Item2.objects.filter(fournisseur = query).values_list('number_of_sales', flat=True)[:10] default_items = list(default_items) label1s = Item2.objects.filter(fournisseur = query).values_list('reference', flat=True)[:10] label1s = list(label1s) default_item1s = Item2.objects.filter(fournisseur = query).values_list('number_of_orders_placed', flat=True)[:10] default_items1s = list(default_item1s) context.update({'Supplier' : Supplier, 'labels':labels, 'default_items':default_items,'label1s':label1s, 'default_item1s':default_item1s}) context2 = {'query':query} print("context",context2) request.session['query_dict'] = context2 return render(request, 'Supplier2.html',context) and here is what I get in the log when trying to query 'BOLSEI': BOLSEI context {'query': 'BOLSEI'} start 2020-11-11 14:32:10.714716 start 2020-11-11 14:32:10.715460 None context {'query': None} start 2020-11-11 14:32:20.765804 start 2020-11-11 14:32:20.766572 supplier name {'query': None} it works in a first time, as the query contains a value and all, but then when the … -
Django REST Framework | Ordering by Count from a ManyToMany Field
I'm following a Django REST Framework's Course, but I got stuck trying to set the ordering configuration from django_filters into a ViewSet. ordering = ('-members__count') In the original code of the Course, -members__count is used as query to return total members count, but when I try to use the same syntax I got this error: Error: Cannot resolve keyword 'count' into field. Choices are: auth_token, circle, created, date_joined, email, first_name, groups, id, invitation, invited_by, is_active, is_client, is_staff, is_superuser, is_verified, issued_by, last_login, last_name, logentry, membership, modified, password, phone_number, profile, user_permissions, username Maybe I'm misunderstanding this error, but all these suggested options correspond to Fields from my model. Also, in the Course its indicated that is a query representation format to get the total count of that field, so I'm a little confuse about that. Anyway, this is a resume of my code but you also can see my full detailed code in this repo in case to be required: https://github.com/cadasmeq/comparte_ride/tree/master/cride/circles. View: # Filters from rest_framework.filters import SearchFilter, OrderingFilter from django_filters.rest_framework import DjangoFilterBackend class CircleViewSet(mixins.CreateModelMixin, mixins.RetrieveModelMixin, mixins.UpdateModelMixin, mixins.ListModelMixin, viewsets.GenericViewSet): """Circle view set.""" serializer_class = CircleModelSerializer lookup_field = 'slug_name' # Filters filter_backends = (SearchFilter, OrderingFilter, DjangoFilterBackend) search_fields = ('slug_name', 'name') ordering_fields = ('rides_offered', … -
OpenStack Keystone python client, Failed to contact the endpoint at "example:5000" for discovery
I'm new to OpenStack clients and APIs Today I was trying to connect to Keystone, And create a Client object like this: from keystoneauth1.identity import v3 from keystoneclient.exceptions import ClientException from keystoneauth1.session import Session from keystoneclient.v3.client import Client def keystone_client(version=(3, ), auth_url=None, user_id=None, password=None, project_id=None): auth = v3.Password(auth_url=auth_url, user_id=user_id, password=password, project_id=project_id) sess = Session(auth=auth) try: return Client(session=sess) except ClientException as e: print(e) # TODO: USE LOGGING When I try to use the client with admin user credentials, and fetch users list, project list, any of keystone functionality like : client = keystone_client(...) clinet.services.list() client.users.list() First, this line in the client source code in a try-except block encounters exception and logs the bellow warning message LOG.warning('Failed to contact the endpoint at %s for discovery. Fallback ' 'to using that endpoint as the base url.', url) Then finally throws a time out exception, traceback: Failed to contact the endpoint at https://example:5000 for discovery. Fallback to using that endpoint as the base url. Traceback (most recent call last): File "/home/arthur/codes/dir/test/venv/lib/python3.8/site-packages/urllib3/connection.py", line 159, in _new_conn conn = connection.create_connection( File "/home/arthur/codes/dir/test/venv/lib/python3.8/site-packages/urllib3/util/connection.py", line 84, in create_connection raise err File "/home/arthur/codes/dir/test/venv/lib/python3.8/site-packages/urllib3/util/connection.py", line 74, in create_connection sock.connect(sa) TimeoutError: [Errno 110] Connection timed out During handling of the above … -
Django cannot find lightbox and bootstrap js file. Can someone solve this problem?
[11/Nov/2020 20:13:11] "GET /about HTTP/1.1" 200 3615 [11/Nov/2020 20:13:12] "GET /static/js/lighbox.min.js HTTP/1.1" 404 1677 [11/Nov/2020 20:13:12] "GET /static/js/bootstrap.bundle.min.js.map HTTP/1.1" 404 1716 Here's the relevant part of my base.html for bootstrap: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <!-- Font Awesome --> <link rel="stylesheet" href="{% static 'css/all.css' %}"> <!-- Bootstrap --> <link rel="stylesheet" href="{% static 'css/bootstrap.css' %}"> <!-- Custom --> <link rel="stylesheet" href="{% static 'css/style.css' %}"> <!-- LightBox --> <link rel="stylesheet" href="{% static 'css/lightbox.min.css' %}"> <title>Real Estate</title> </head> <body> <!-- Top Bar --> {% include 'partials/_topbar.html' %} <!-- Navbar --> {% include 'partials/_navbar.html' %} {% block content %} {% endblock %} <!-- Footer --> {% include 'partials/_footer.html' %} <script src="{% static 'js/jquery-3.3.1.min.js' %}"></script> <script src="{% static 'js/bootstrap.bundle.min.js' %}"></script> <script src="{% static 'js/lighbox.min.js' %}"></script> <script src="{% static 'js/main.js' %} "></script> </body> </html> Relevant code from settings.py # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.1/howto/static-files/ STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'real_estate_btre/static') ] And here's how my django project is laid out: admin db.sqlite3 project_name manage.py app_name static - admin, css, js, img template base.html I even ran the python mange.py runserver command as well, but I dont know why … -
How to annotate a queryset with time extracted from timestamp in seconds?
I have model with record_time field which is of IntegerField type. It stores timestamp in second (Unix epoch time). I need to annotate the queryset with time only which should be extracted from record_time. I came up with this so far annotated_qs = WorkerData.objects.annotate( time_e=datetime.fromtimestamp(F('record_time')).time() ) But this results in error (which make sense): an integer is required (got type F) How can I make this to work? -
Django: Ordering by last item in reverse ForeignKey relation
I'm trying to implement a qs.sort_by operation, but I'm not sure how to go about it. Given the following models class Group(models.Model): name = models.CharField(max_length=300) ( ... ) class Budget(models.Model): ( ... ) amount = models.DecimalField( decimal_places=2, max_digits=8, ) group = models.ForeignKey( Group, related_name="budgets", on_delete=models.CASCADE, ) Where each Group has either 0 or > 5 budgets assigned I am trying to sort a Group.objects.all() queryset by the amount of their last (as in, most recently assigned) Budget. I know that if it was a OneToOne I could do something like the following: Group.objects.all().order_by('budget__amount') With ForeignKey relations I was hoping I could do something like Group.objects.all().order_by('budgets__last__amount') But alas, that is not a valid operation, but I am not sure on how to proceed otherwise. Does anyone know on how to perform this sorting operation? (if it is indeed possible) -
NoReverseMatch in django (relative urls with templates)
I tried many of the solutions published but neither of any solution works so that's why I am looking for the solution which helps me I am trying this code:-please tell any error if I did #in my basics_app.urls from basics_app import views from django.urls import path #template tagging app_name='basics_app' urlpatterns=[ path('relative/',views.relative,name="relative"), path('other/',views.other,name="index again"), ] #in my relative.html page <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>relatives url page</title> </head> <body> <h1>welcome to relatives url templates</h1> <a href="{% url 'basics_app:views.other' %}">other page</a> </body> -
How to decode SAMLResponse in Django View?
I am writing a view to create a user in project that has logged into another site. Whenever the user logins to that site he/she gets redirected to url:https://localhost:127.0.0.1:8000/auth/ad/reply/. The site sends me an SAMLResponse from which I want to extract the email address, firstname & lastname for the user. Following is my views.py and urls.py: views.py from django.shortcuts import render, redirect from django.http import HttpResponse from django.views.decorators.csrf import csrf_exempt # Create your views here. @csrf_exempt def ad_auth(request): response = request.POST.get('SAMLResponse') return HttpResponse(response) urls.py from django.urls import path from .views import * urlpatterns = [ path('auth/ad/reply/', ad_auth, name='ad_auth'), ] Output: PHNhbWxwOlJlc3BvbnNlIElEPSJfOTJmYjAyYTMtN2ZiMC00NjZlLTk0NGItNTQxMjhlOGI5NGM2IiBWZXJzaW9uPSIyLjAiIElzc3VlSW5zdGFudD0iMjAyMC0xMS0xMVQxNDowMDoxMi43NzlaIiBEZXN0aW5hdGlvbj0iaHR0cHM6Ly9sb2NhbGhvc3Q6ODAwMC9hdXRoL2FkL3JlcGx5LyIgeG1sbnM6c2FtbHA9InVybjpvYXNpczpuYW1lczp0YzpTQU1MOjIuMDpwcm90b2NvbCI+PElzc3VlciB4bWxucz0idXJuOm9hc2lzOm5hbWVzOnRjOlNBTUw6Mi4wOmFzc2VydGlvbiI+aHR0cHM6Ly9zdHMud2luZG93cy5uZXQvYmYzODg4M2EtOGRlNi00NGFhLWJkYzktODFjMzAzY2YxMDMzLzwvSXNzdWVyPjxzYW1scDpTdGF0dXM+PHNhbWxwOlN0YXR1c0NvZGUgVmFsdWU9InVybjpvYXNpczpuYW1lczp0YzpTQU1MOjIuMDpzdGF0dXM6U3VjY2VzcyIvPjwvc2FtbHA6U3RhdHVzPjxBc3NlcnRpb24gSUQ9Il8wYjExNzMwNi03YTI2LTQ2OGQtYTI5Yy1mYTZkMjk2MTQ3MDAiIElzc3VlSW5zdGFudD0iMjAyMC0xMS0xMVQxNDowMDoxMi43NjlaIiBWZXJzaW9uPSIyLjAiIHhtbG5zPSJ1cm46b2FzaXM6bmFtZXM6dGM6U0FNTDoyLjA6YXNzZXJ0aW9uIj48SXNzdWVyPmh0dHBzOi8vc3RzLndpbmRvd3MubmV0L2JmMzg4ODNhLThkZTYtNDRhYS1iZGM5LTgxYzMwM2NmMTAzMy88L0lzc3Vlcj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3AxNTA2Z21haWwub25taWNyb3NvZnQuY29tPC9BdHRyaWJ1dGVWYWx1ZT48L0F0dHJpYnV0ZT48L0F0dHJpYnV0ZVN0YXRlbWVudD48QXV0aG5TdGF0ZW1lbnQgQXV0aG5JbnN0YW50PSIyMDIwLTExLTExVDA3OjI4OjM1LjAwMFoiIFNlc3Npb25JbmRleD0iXzBiMTE3MzA2LTdhMjYtNDY4ZC1hMjljLWZhNmQyOTYxNDcwMCI+PEF1dGhuQ29udGV4dD48QXV0aG5Db250ZXh0Q2xhc3NSZWY+dXJuOm9hc2lzOm5hbWVzOnRjOlNBTUw6Mi4wOmFjOmNsYXNzZXM6UGFzc3dvcmQ8L0F1dGhuQ29udGV4dENsYXNzUmVmPjwvQXV0aG5Db250ZXh0PjwvQXV0aG5TdGF0ZW1lbnQ+PC9Bc3NlcnRpb24+PC9zYW1scDpSZXNwb25zZT4= How do I extract information from the following SAMLResponse? Thanks in Advance. -
How to change django views into django rest farmework
I'm creating a shopping cart for my project. I created the cart but I got some help for the writing views for it but they give me Django view instead of django rest framework. I'm creating django rest api . I don't know how to change functions into rest framework in the code there is form but in django rest framework we don't create form. can you help me change the view's functions??? actually my problem is in cart_add function in the views.py #cart CART_SESSION_ID = 'cart' class Cart: def __init__(self, request): self.session = request.session cart = self.session.get(CART_SESSION_ID) if not cart: cart = self.session[CART_SESSION_ID] = {} self.cart = cart def __iter__(self): product_ids = self.cart.keys() products = Product.objects.filter(id__in=product_ids) cart = self.cart.copy() for product in products: cart[str(product.id)]['product'] = product for item in cart.values(): item['total_price'] = int(item['price']) * item['quantity'] yield item def remove(self, product): product_id = str(product.id) if product_id in self.cart: del self.cart[product_id] self.save() def add(self, product, quantity): product_id = str(product.id) if product_id not in self.cart: self.cart[product_id] = {'quantity': 0, 'price': str(product.price)} self.cart[product_id]['quantity'] += quantity self.save() def save(self): self.session.modified = True def get_total_price(self): return sum(int(item['price']) * item['quantity'] for item in self.cart.values()) def clear(self): del self.session[CART_SESSION_ID] self.save() views.py def detail(request): cart = Cart(request) return … -
How to Remove Item In the Django Admin for ManyToMany Multiple Select
My Django admin interface is rendering a multiple select, reflecting a many-to-many relationship between Contact and Email. E.g. I can choose multiple emails per contact in the add Contact page. The emails are stored in a separate table that contains just the emails. From the admin interface is it possible to remove one or all of the emails from a Contact that is already created? Is it some setting/argument used in the email admin class? -
Django seed with m2m field
I'd like to make seed data but there is an error : TypeError: Direct assignment to the forward side of a many-to-many set is prohibited. Use participants.set() instead. is there any way to create dummy data with many to many field? my django-seed managemeny commands file is like below: class Command(BaseCommand): help = "This command creates unions" def add_arguments(self, parser): parser.add_argument( "--number", default=1, type=int, help="How many unions do you want to create?", ) def handle(self, *args, **options): number = options.get("number") seeder = Seed.seeder() fake = Faker("ko_KR") users = User.objects.all() reviewers = Reviewer.objects.all() seeder.add_entity( Union, number, { "name": lambda x: str(fake.bs().split(" ")[0]) "participants": lambda x: random.choice(users), # this part is problem. I'd like to assign some of users in the field. "reviewer": lambda x: random.choice(reviewers), }, ) seeder.execute() self.stdout.write(self.style.SUCCESS(f"{number} unions created!")) -
head-up notification by using FCM in django
I am implementing head-up notification in django using firebase_admin. To do this, the following code was made because the priority property had to be included, but the head-up notification did not work. What's wrong with my code? message = messaging.Message( notification=messaging.Notification( title=title, ), android=messaging.AndroidConfig( priority='high', data={ 'channel_id': 'Channel Id', 'priority': 'high', 'sound': 'default', 'title': F'{title}', }, notification=messaging.AndroidNotification( priority='high', channel_id='Channel Id', ), ), token=registration_token, ) -
Django ModelChoiceField shows Customers objects(1) etc on list, how do i get it to show name of customers?
models.py class Customers(models.Model): Name = models.CharField(max_length=100) class Staff(models.Model): Name = models.CharField(max_length=100) class Cereals(models.Model): Name = models.CharField(max_length=100) Operator = models.CharField(max_length=100) forms.py class EditCereals(forms.ModelForm): class Meta: model = Cereals fields = ['Name', 'Operator'] widgets = { 'Operator': Select(), 'Name': Select(), } def __init__(self, *args, **kwargs): super(EditCereals, self).__init__(*args, **kwargs) self.fields['Name'] = forms.ModelChoiceField(queryset=Customers.objects.all().order_by('Name')) self.fields['Operator'] = forms.ModelChoiceField(queryset=Staff.objects.all().order_by('Name')) When i run the form 'Name' shows Customers Objects (1), Customers objects (2), etc and same with 'Operator' it shows Staff Objects (1), Staff Objects (2), etc How do i get it to show the actual names, eg Bill, Fred,