Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to merge two models into one single form?
Is it possible to merge two different models into a single form? if yes then please provide me with the solution. basically, I want to create a form in which I can also add images but it is not working as I want to make it work. models.py: class Mobile(models.Model): brand = models.CharField(max_length=30) price = models.IntegerField(default=1) color = models.CharField(max_length=30) screen_size = models.IntegerField(default=5) os = models.CharField(max_length=30, default='Samsung') def __unicode__(self): return self.brand class MobileImage(models.Model): device = models.ForeignKey(Mobile, on_delete=models.CASCADE) image = models.ImageField(upload_to='media/images/') def __unicode__(self): return self.device forms.py: from django import forms from .models import Mobile, Laptop, MobileImage class AddMobileForm(forms.ModelForm): class Meta: model = Mobile fields = '__all__' views.py: def addmobile(request): if request.method == 'POST': mobileform = AddMobileForm(request.POST) if mobileform.is_valid(): mobileform.save() return redirect('mobile') else: mobileform = AddMobileForm() context = { 'mobile_form': mobileform } return render(request, 'device/mobile_form.html', context) -
Best way to detect new objects in Django?
Although I have a decent understanding of Django and how to work with exchanges using HTTP I am still very naive when it comes to websockets, channels, ajax, etc. My notification system is built on a custom notification model, so I would like to be able to detect when a new object is created under certain filters. My question is: How can I go about detecting when a new object is created and update the webpage without refreshing? Thanks! -
How to get products according to User in Django?
I have relation between Customer and Products, and customer_id is saving in Product model table, but I want to display products on my view page according to customer, suppose if a customer logged in using his details then he can see only his products, but currently he can see all products. Please let me know How I can do it. Here is my models.py file... class Customer(models.Model): name=models.CharField(default=None) class Product(models.Model): name=models.CharField(default=None) customer=models.Foreignkey(Customer, related_name='customer_product', on_delete=models.CASCADE) here is my views.py file... def display_data(request): test_display = Product.objects.all() context = { 'test_display': test_display } return render(request, 'page.html', context) here is my page.html file...here i am trying to display products according to loggedin customer.. <p>{{test_display.count}}</p> -
how to resize of multiple images in Django models and also payment integration problem
**how can i resize of this all my image fields...photo_main to photo_8 ** another one problem is when user submit payment but payment was invalid than post will save problem... another one is user select one by one image input fields is there any way to user select multiple images at a same time... class Post(models.Model): post_id = models.CharField(default=abc, max_length=14) ages = models.IntegerField(null=True, default=0, validators=[ MaxValueValidator(120), MinValueValidator(18) ] ) zip_codes = models.IntegerField(null=True) address_user = models.CharField(max_length=400, null=True) title = models.CharField(max_length=200) country = models.ForeignKey(Country, on_delete=models.SET_NULL, null=True) state = models.ForeignKey(State, on_delete=models.SET_NULL, null=True) city = models.ForeignKey(City, on_delete=models.SET_NULL, null=True, blank=True) category = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True) phone = models.CharField(max_length=14, null=True) phone_code = models.CharField(max_length=7, choices=phone_codes, default=+91) # description = RichTextField(blank=True, null=True) description = models.TextField(blank=True, null=True) photo_main = models.ImageField(upload_to=upload_path) photo_1 = models.ImageField(upload_to=upload_path, blank=True) photo_2 = models.ImageField(upload_to=upload_path, blank=True) photo_3 = models.ImageField(upload_to=upload_path, blank=True) photo_4 = models.ImageField(upload_to=upload_path, blank=True) photo_5 = models.ImageField(upload_to=upload_path, blank=True) photo_6 = models.ImageField(upload_to=upload_path, blank=True) photo_7 = models.ImageField(upload_to=upload_path, blank=True) photo_8 = models.ImageField(upload_to=upload_path, blank=True) is_publice = models.BooleanField(default=True) list_date = models.DateTimeField(default=datetime.now, blank=False) today_date_time = models.CharField(default=d2, max_length=50) plan = models.ForeignKey(Plans_info, on_delete=models.CASCADE, null=True) author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return str(self.category) # def get_absolute_url(self): # return reverse('post_detail', kwargs={'pk': self.pk}) class Meta: # managed = True db_table = 'Skoapp_post' i'm also using this save function … -
Django | Redirect View after "liking" without scrolling
I'm making a simple blog app. I have added the ability to "like" a post on your feed. However, the only way I can figure out closing a view is by returning some form of redirect. The problem is, if the post you're "liking" is halfway down the page, I don't want it to reset the zoom to the top of the page again. Is there a way simply to redirect to the same page without affecting zoom? Here's my post model: class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField() author = models.ForeignKey(User, on_delete=models.CASCADE, related_name="author") likes = models.ManyToManyField(User, related_name="likes", blank=True) def like(self, post): self.likes.add(post) def unlike(self, post): self.likes.remove(post) I have the following setup in Views: @login_required def like(request, pk): post = Post.objects.get(id=pk) Post.like(post, request.user) return HttpResponseRedirect(reverse('Home')) @login_required def unlike(request, pk): post = Post.objects.get(id=pk) Post.unlike(post, request.user) return HttpResponseRedirect(reverse('Home')) Here's how I'm calling the Views from my URLs: path('like/<int:pk>', views.like, name='Like'), path('unlike/<int:pk>', views.unlike, name='Unlike'), I'm using a form on my template to trigger the URL: {% if user in post.likes.all %} <form action="{% url 'Unlike' post.pk %}" method="POST"> {% csrf_token %} <button type="submit" value="{{ post.id }}" class="unlike">UNLIKE</button> </form> {% else %} <form action="{% url 'Like' post.pk %}" method="POST"> {% csrf_token %} <button … -
JS funtion returning empty value to input box
when the list-item-action class button is select or is active I want to appear a name in the skill_category input box and then send it to the models of my website this code is not giving a name of list-item it is returning an empty value in the skill_catgeory input in my form $(document).ready(function() { $('.list-group-item-action').click(function() { if ($('.list-group-item-action').hasclass('active')) { var cat_txt = ""; $('.list-group-item-action').each(function() { cat_txt += $(this).val() }); $('#cat_txt').val(txt); } }); }); <div class="row"> <div class="col-4"> <div class="list-group" id="list-tab" role="tablist"> <a class="list-group-item list-group-item-action active" id="list-lead_generator-list" data-toggle="list" href="#list-lead_generator" role="tab" aria-controls="lead_generator" value="Lead generator"><i class='fas fa-users'></i>Lead generator</a> <a class="list-group-item list-group-item-action" id="list-content_creator-list" data-toggle="list" href="#list-content_creator" role="tab" aria-controls="content_creator" value="Content Creator"><i class='fas fa-pen'></i>Content Creator</a> <a class="list-group-item list-group-item-action" id="list-social-social_media_handler-list" data-toggle="list" href="#list-social_media_handler" role="tab" aria-controls="social_media_handler" value="Social Media Handler"><i class='fas fa-icons'></i>Social Media Handler</a> </div> </div> <div class="col-8"> <div class="tab-content" id="nav-tabContent"> {% comment %} <input class="bg-white rounded border border-gray-400 focus:outline-none focus:border-indigo-500 text-base px-4 py-2 mb-4" placeholder="Skill" name="Skill" type="text"> {% endcomment %} <div class="tab-pane fade show active" id="list-lead_generator" role="tabpanel" aria-labelledby="list-lead_generator-list"> <label class="container">Lead Generator <input type="checkbox" name="lead_generator" value='Lead Generator' class="lead_generator"> <span class="checkmark"></span> </label> </div> </div> </div> </div> <form method="post"> {% csrf_token %} <input type='text' name="user" class="user" value="{{user.username}}" /> <input type="text" name="skill_category" id="cat_txt" class="skill_category"> <input type="text" name="skill" id="txt" class="skill"> <div class='container nxtbtn'> <button … -
property can not read of undefined when using datatable()
I am using DataTable() to generate dynamic table. The table header is dynamic. The headers will change on the basis of month. There is nav buttons for changing the months. On the changing of the the months the table is also changed. i have written an ajax funstion for fetching data and to show in the table. The function is called when the document is ready and on the onClick() event the buttons $("#month-next-btn").click(function(){ $("#selected-month").html(incrementDecrementMonth(1)); array = yearMonthArr($("#selected-month").html()); year = array[0]; month = array[1]; // setTimeout(function(){fetchMonthlyAttendanceStatus()},10); fetchMonthlyAttendanceStatus(); setNavBtnState(year, month); }) $("#month-prev-btn").click(function(){ $("#selected-month").html(incrementDecrementMonth(-1)); array = yearMonthArr($("#selected-month").html()); year = array[0]; month = array[1]; // setTimeout(function(){fetchMonthlyAttendanceStatus()},10); fetchMonthlyAttendanceStatus(); setNavBtnState(year, month); }) function fetchMonthlyAttendanceStatus(){ var dateSelected = $("#selected-month").html(); array = yearMonthArr($("#selected-month").html()); year = array[0]; month = array[1]; $.ajax({ type: 'GET', url: '{% url "attendance:ajax-monthly-attendance-status" %}', data: { 'month': month, 'year': year }, dataType: 'json', success: function (data) { $("#monthly-attendance-status-table-header").empty(); $("#monthly-attendance-status-table-rows tr").remove(); $("#monthly-attendance-status-table-header").append(`<th class="text-center" style="border-bottom: 2px solid #EAEAEA; font-weight:normal;">ID</th> <th class="text-center" style="border-bottom: 2px solid #EAEAEA; font-weight:normal;">Name</th>`); var monthS = month.slice(0, 3); var dayLst = data.day_lst; for (var i = 0; i < dayLst.length; i++) { if (dayLst[i] < 10) { dayLst[i] = '0' + dayLst[i]; } var date = dayLst[i] + '-' + monthS; $("#monthly-attendance-status-table-header").append(`<th class="text-center" … -
i want create constraint in django
I want to create a constraint of the form code = <min_weight> - <max_weight> <weight_unit> how do i do that i just learned it class Size(models.Model): code = models.CharField(max_length=200, primary_key=True) uni = [("GC", "Gram/Con"), ("KC", "Kg/Con")] min_weight = models.IntegerField(blank=False, null=False) max_weight = models.IntegerField(blank=False, null=False) weight_uni = models.CharField(max_length=10, choices=uni, default="KC") def __str__(self): return self.code -
Get the current URL of another specifi user in Django
I have a chat application and I'm using django-webpush to push notifications. Here is how I push notifications # Web push content = message.filename() if message.text: content = message.text payload = {"head": f"A new message from {room.title()}", "body": content, "icon": "/static/chat/img/favicon.png", "url": f"https://orgachat.pythonanywhere.com/chat/room/{room.id}/"} for chatter in room.chatters.all(): if chatter != request.user and True: #todo check for chatter url send_user_notification(user=chatter, payload=payload, ttl=1000) Now what I want to do is not to push the notification if the other user (chatter) is already in the payload url "/chat/room/roomId". Is there any way to do so? -
django+xterm.js: why I get "failed: Error during WebSocket handshake: Unexpected response code: 200" when I run the website on server?
Currently I built a webssh demo based on django and xterm.js. I have successfully run the website on localhost. But when I deployed the project on my server, everytime I try connection it retured "failed: Error during WebSocket handshake: Unexpected response code: 200". I have no idea what the problem is... the code I used is from github: https://github.com/huyuan1999/django-webssh -
How do I make custom filters work in django_filters?
So I've made this custom filter in filters.py with django-filters and when I'm submitting the "YEARCHOICE", the page refreshes but it doesn't work. I think I'm having a problem with my "year_filter_method" also I want my pagination and filter system to work together. Any help would be really appreciated. Cheers! *Note it doesn't work with or without pagination. models.py from django.db import models import datetime YEAR_CHOICES = [] for r in range(2000, (datetime.datetime.now().year + 1)): YEAR_CHOICES.append((r, r)) class Music(models.Model): Song = models.CharField(max_length=100, blank=False) Year = models.IntegerField(('year'), choices=YEAR_CHOICES, default=datetime.datetime.now().year) def __str__(self): return self.Song filters.py import django_filters import datetime class MusicFilter(django_filters.FilterSet): YEARCHOICES = [] for r in range(2010, (datetime.datetime.now().year + 1)): YEARCHOICES.append((r, r)) year_filter = django_filters.ChoiceFilter(label="Year", choices=YEARCHOICES, method="year_filter_method") def year_filter_method(self, queryset): expression = Music.Year return queryset.filter(expression) views.py def music_page(request): #pagination & filter music = Music.objects.all().order_by('-id') music_filter = MusicFilter(request.GET, queryset=music) paginator = Paginator(music, 6) page_number = request.GET.get('page') page_obj = paginator.get_page(page_number) try: music = paginator.page(page_number) except PageNotAnInteger: music = paginator.page(1) except EmptyPage: music.paginator.page(paginator.num_pages) return render(request, template_name='main/music.html', context={'music': music, 'page_obj': page_obj, 'filter': music_filter}) filters.html {% load static %} <link rel="stylesheet" href="{% static 'main/filter.css' %}" type="text/css"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <div class="container"> <form method="get"> <span class="label">{{filter.form}}</span> <span class="btn-search-handler"><button id="search_btn_id" type="submit">Search</button></span> </form> </div> music.html {% include 'main/includes/navbar.html' … -
html files in django
Someone told me that it is good practice to put django html files from a scpecific app into a templates folder in which there is still another folder inside with the name of the app? I tried doing it like this and I keep getting an error. How should I go about it? enter image description here -
Django StreamingHttpResponse() is causing server to stop working
I am trying to implement StreamingHttpResponse but came across a tedious issue. The connection appears to be established then after around 2 page requests the webserver stops responding. I am truly bewildered about what is causing this issue. If it was associated with an infinite loop, the time.sleep() method should have prevented the server from overloading. I'd appreciate any help, thanks! views.py: def event_stream(): initial_data = "" while True: data = json.dumps(list(Notification.objects.filter(to_user=1).order_by("-created_date").values("info", "return_url", "from_user","to_user","created_date")), cls=DjangoJSONEncoder) if not initial_data == data: yield "\ndata: {}\n\n".format(data) initial_data = data time.sleep(1) class PostStreamView(View): def get(self, request): response = StreamingHttpResponse(event_stream()) response['Content-Type'] = 'text/event-stream' return response base.html var eventSource = new EventSource("{% url 'stream' %}"); eventSource.onopen = function() { console.log('We have open connection!'); } eventSource.onmessage = function(e) { console.log(e) } eventSource.onerror = function(e) { console.log(`error ${e}`); } </script> Server Log: 2020-10-20 19:25:51 Tue Oct 20 19:25:51 2020 - SIGPIPE: writing to a closed pipe/socket/fd (probably the client disconnected) on request /AP%20Psychology/ (ip 10.0.0.124) !!! 2020-10-20 19:25:51 Tue Oct 20 19:25:51 2020 - uwsgi_response_writev_headers_and_body_do(): Broken pipe [core/writer.c line 306] during GET /AP%20Psychology/ (10.0.0.124) 2020-10-20 19:27:33 Tue Oct 20 19:27:33 2020 - SIGPIPE: writing to a closed pipe/socket/fd (probably the client disconnected) on request /post/12/ (ip 10.0.0.124) !!! … -
Django admin list view prevent choices lookup
class CustomerChoices(object): def expensive_lookup(self): .... def __iter__(self): yield from [(a.number, a.display) for a in self.expensive_lookup()] class CustomerProfile(models.Model): account_number = models.IntegerField(unique=True, choices=CustomerChoices()) ... from django.contrib import admin from .models import CustomerProfile @admin.register(CustomerProfile) class CustomerProfileAdmin(admin.ModelAdmin): list_display = ('account_number', ...) Given above code, while I am happy with the add/edit admin to use the choices, how do I prevent django admin list view using the choices, so it doesn't make an expensive lookup? Please note that I am aware of caching methods, but what if I just want to display the account number? -
How to close django channel redis connections manually?
I have a server that has a webhook and a websocket service. They send messages to each other using channel redis layer, similar to the chatroom example online that uses channel names, but without using groups. (1 to 1 using channel names) For my use, my websocket is always connected to the server, while webhooks are requests that is on demand from users. When a user sends a webhook request, the server would find the corresponding websocket channel name via a database. The webhook service would then send message to websocket, the websocket would find the webhook channel name (from said database) and send a message back. Then finally, the webhook service would generate a response. This webhook instance would then disappear. (it is based on AsyncHttpConsumer). The problem I found out is that when it's on Heroku, I have limited redis connections (20), and they timeout. Every user that uses my service would have their own redis connection, and after 20, I would get an error message (ERR max number of clients reached). Since the webhook request-response only takes around several seconds, I don't need the redis connection to stay alive for the default 300 seconds. But if I … -
Configurating the Width of Columns in Django Admin
I am trying to adjust width of one of the columns in Django Admin so I found several answers like this but it didn't solve my issue Is this the best way to do it? if not what is another better solution? here is the admin.py class PostAdmin(admin.ModelAdmin): list_display = ['id','design'] class Media: css = ('/css/fancy.css'.format(settings.STATICFILES_DIRS[0]+ '/css/fancy.css'),) here is the fancy.css .column-design { width: 20px; } -
Configured ec2 amazon aws and the webapp is not being showed
After configured zone at Route 53 pointing my ec2 instance to my domain, my web application is not being showed, only "Welcome to nginx" message. My web application is a Django web app, deployed using gunicorn and nginx. At Route 53, the only record I created was a www A record, pointing to the ec2 instance ip. $ dig imobiliarianossapraia.com.br ; <<>> DiG 9.11.3-1ubuntu1.13-Ubuntu <<>> imobiliarianossapraia.com.br ;; global options: +cmd ;; Got answer: ;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 31542 ;; flags: qr rd ra; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 1 ;; OPT PSEUDOSECTION: ; EDNS: version: 0, flags:; udp: 65494 ;; QUESTION SECTION: ;imobiliarianossapraia.com.br. IN A ;; ANSWER SECTION: imobiliarianossapraia.com.br. 300 IN A 54.172.168.83 ;; Query time: 97 msec ;; SERVER: 127.0.0.53#53(127.0.0.53) ;; WHEN: Wed Oct 21 01:00:59 UTC 2020 ;; MSG SIZE rcvd: 73 -
Reason for filter(admin_approved=True,valid_from__lte=now, valid_to__gte=now) not working immediately?
I have a project where there are posts that I want to be displayed for a certain period of time valid_from and valid_to so the issue here is that I have added the correct filters and choosen the time but the posts keep displaying although the time valid_to has passed. I was in doubt until I added a countdown which became negative and exceeded the time valid_to value. I am trying to understand the reason behind this issue and how to fix it? here is the models: class Post(models.Model): valid_from = models.DateTimeField(blank=True, null=True) valid_to = models.DateTimeField(blank=True, null=True) Here is the veiws: class PostListView(ListView): model = Post template_name = "post.html" context_object_name = 'posts' now = timezone.now() queryset = Post.objects.filter(valid_from__lte=now, valid_to__gte=now) -
Why doesn't a django sqlite3 database work the same on one machine vs the other?
I'm working on learning Django, but I've run into to a problem with my database not transferring correctly (or it's transferring correctly and I'm missing something, which is what I think is happening). I have a Django model Link in models.py class Link(models.Model): title = models.CharField(max_length=100) alt = models.CharField(max_length=100) dest = models.CharField(max_length=100) image = models.FilePathField(path='static/misc/link_in_bio/img/') def __str__(self): title = self.title + ' Link' return self.title class Meta: ordering = ('title', ) Then I made instances of this model and confirmed they are entered into the database correctly. They are then referenced in a page's html like so: {% for link in links %} <div id="space"> <div class="w3-container"> <div class="w3-panel" style="padding: 0.06em"> <button class="block" type="button" title="{{link.title}}" onclick="window.open('{{link.dest}}')"> <img src="../{{link.image}}" alt="{{link.alt}}" style="max-height: 7em"> </button> </div> </div> </div> {% endfor %} On my development machine everything works exactly as expected and shows this: Then, when I deploy it on Heroku, everything builds correctly, python manage.py makemigrations and python manage.py migrate run correctly, but when I view the page it simply shows this: I also can't login to the admin page with the superuser I already created on the first machine, and I know this is related but I'm not sure how to approach … -
Is it possible to save a react Js rendered page to html and / or pdf server side?
This is more of a general question, hence I'm not including any code. I've looked at quite a few options for both pdf and html, but haven't figured out a good solution. I'm trying to take the output of what would be rendered by reactJs in a browser and save it to the hosting server instead of (or as well as) displaying it in the browser. Specifically I'm generating a report using a pretty standard React functions, styled with css, and want to save that report upon rendering to the server. The API which I also control is Django based. I've looked at react-pdf/renderer, react-pdf, pdfkit on the Django side (w/wkhtmltopdf), reactdomserver to generate static html files, but can't quite piece together a solution. Would love some feedback if anyone's done something like this before. -
Django postgres SplitArrayField throws error when submitting form
I'm new to django and finding myself a bit stuck on some stuff. I'm trying to implement a page which provides a table like this: +--------+-+-+-+ +--+--+ |Employee|1|2|3| |30|31| +--------+-+-+-+ +--+--+----------+ |Name1 |0|0|8|....| 8| 8|SAVEBUTTON| +--------+-+-+-+ +--+--+----------+ with each cell as an input field. Feel free to suggest a better implementation too, I'm a django (and in general) newbie and learning as I'm using it. This is the error I get when trying to save data from my view: File "/usr/local/lib/python3.8/site-packages/django/forms/forms.py", line 443, in changed_data initial_value = field.to_python(hidden_widget.value_from_datadict( File "/usr/local/lib/python3.8/site-packages/django/contrib/postgres/forms/array.py", line 195, in to_python return [self.base_field.to_python(item) for item in value] File "/usr/local/lib/python3.8/site-packages/django/contrib/postgres/forms/array.py", line 195, in <listcomp> return [self.base_field.to_python(item) for item in value] TypeError: to_python() missing 1 required positional argument: 'value' A different but similar error on the django admin page: File "/usr/local/lib/python3.8/site-packages/django/forms/forms.py", line 177, in is_valid return self.is_bound and not self.errors File "/usr/local/lib/python3.8/site-packages/django/forms/forms.py", line 172, in errors self.full_clean() File "/usr/local/lib/python3.8/site-packages/django/forms/forms.py", line 374, in full_clean self._clean_fields() File "/usr/local/lib/python3.8/site-packages/django/forms/forms.py", line 392, in _clean_fields value = field.clean(value) File "/usr/local/lib/python3.8/site-packages/django/contrib/postgres/forms/array.py", line 206, in clean cleaned_data.append(self.base_field.clean(item)) TypeError: clean() missing 1 required positional argument: 'value' Relevant models.py parts: class DayField(forms.IntegerField): widget=forms.NumberInput(attrs={'max': 24, 'min':0, 'size':2, 'maxlength':2, 'style':'width: 40px; -webkit-appearance: none; -moz-appearance: textfield;', 'oninput':"this.value=this.value.replace(/[^0-9]/g,''); if (this.value.length > this.maxLength) … -
Created a web service using Flask. But getting the output in HTML tags
Result image My aim is to display 'Hello inputname' web.py from flask import Flask,jsonify import requests app = Flask(__name__) @app.route('/<name>',methods=['GET']) def index(name): return jsonify({'out' : "Hello "+str(name)}) if __name__ == '__main__': app.run(debug=True) -
Django + Vuejs Not Able to Get Csrftoken from response header
I have an issue regarding setting up Django and Vuejs in order to make them work together. My issue is regarding csrftoken and how this it is passed between Django and Vuejs. Therefore, my setup is as follow: Django is running on http://localhost:8000 Vuejs is running on http://localhost8080 I am using django rest framework and SessionAuthentication. settings.py """ Django settings for core project. Generated by 'django-admin startproject' using Django 3.1.2. 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 = "8g+_gwm=s^kw69y3q55_p&n(_y^^fa!8a^(f7c)#d&md2617o9" # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ["*"] # Cors setup # CORS_ORIGIN_ALLOW_ALL = False # For CSRF CORS_ALLOWED_ORIGINS = [ "http://localhost:8080", "http://127.0.0.1:8080", ] CSRF_TRUSTED_ORIGINS = [ "http://localhost:8080", "http://127.0.0.1:8080", ] # For Cookie CORS_ORIGIN_WHITELIST = ("http://localhost:8080", "http://127.0.0.1:8080") CORS_ALLOW_CREDENTIALS = True # CSRF_USE_SESSIONS = False CSRF_COOKIE_HTTPONLY = False SESSION_COOKIE_SAMESITE = "None" CSRF_COOKIE_SAMESITE = None SESSION_COOKIE_HTTPONLY = False # Application … -
Django - get model in navbar
I have a class in models: class Customer(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True) name = models.CharField(max_length=200, null=True, blank=True) email = models.CharField(max_length=200, null=True, blank=True) device = models.CharField(max_length=200, null=True, blank=True) which also has a unique id in database. I want to somehow access the "Customer" from template. I know that first i have to get the object in "views.py" and the access it by {{ }} tag. But is there a different way? My point is that i want to access the Customer and then the related order etc. in navbar which is "included" in every template on the site - so i can't make a view for it. Or maybe I'm understanding it wrong. If so - please correct me. I would like to access similarly to {{ request.user.id }}. -
Django REST Framework multi token per user
I want to use Django REST Framework in my project, As you know by default DRF allow us to have just one token per a user but I have to allow users to login from some different devices and give them independent token for any device. Question: how I can use multi token per a user in my project and manage them in admin panel?