Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django compressor isn't working on heroku
I'm using Django with the Django compressor package on heroku. To make the setup easier I'm using the official Django + Heroku package. My base.html template has the following include tag: {% include 'base/js.html' %} This file contains all JS files: {% load static %} {% load compress %} {% compress js %} <script src="{% static 'libs/jquery/dist/jquery.min.js' %}"></script> <script src="{% static 'libs/bootstrap/dist/js/bootstrap.bundle.min.js' %}"></script> # ... {% endcompress %} I've enabled COMPRESS_OFFLINE = True and my release task has the following command: python manage.py compress Since heroku does the collectstatic before running this command I've added another collectstatic command after the compress command. The first problem is that if I push my code with this settings, the JS just disappears. Event if I add normal html in the js.html file it's not displayed like it was never included. If I move the content from js.html to the base.html file I will get this error: OfflineGenerationError: You have offline compression enabled but key "37bfd22c7ae7d3c1ebae6f1f6cf17b892d51be333cd571cb6c1466d1291cd228" is missing from offline manifest. You may need to run "python manage.py compress". I've also tried running the compress command again but nothing happens. The error is still there. -
Django worker not handling oath replies correctly with daphne
Creating title for this question was tricky, so please forgive. I am trying to setup SSO with MicroSoft and Django. Found a promising plugin to handle this, but having some issues I think may be related to django / daphne more than the plugin itself. The plugin is designed to handle the callback from MS SSO, and there a django view that handles the response. Well, this is not working as expected. The question however is about the behavior of what I am seeing in the logs while troubleshooting. I can see the callback come in: worker logs: 2018-11-23 17:23:54,920 - DEBUG - worker - Dispatching message on http.request to channels.handler.ViewConsumer Bad Request: /microsoft/auth-callback/ daphne logs 2018-11-23 17:23:54,920 INFO "127.0.0.1" - - [23/Nov/2018:17:26:28 +0000] "POST /microsoft/auth-callback/ HTTP/1.1" 400 665 "https://login.microsoftonline.com/common/reprocess?ctx=****&sessionid=*******" "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:63.0) Gecko/20100101 Firefox/63.0" However, this is where it dies. The reply is supposed to have a payload containing the session state. However, while watching the django worker log, I restarted the django worker. While shutting down the workers, I see this appear in the logs: 2018-11-23 17:30:26,746 - INFO - worker - Shutdown signal received while idle, terminating immediately {'state': '****', 'session_state': '***'} This … -
How to test POST method using DRF and HyperlinkedModelSerializer serializer
I am using Django Rest Framework (DRF), and I am trying to test a POST method. These are my models: class CustomUser(AbstractUser): def __str__(self): return self.email class Meta: ordering = ('id',) verbose_name = 'user' class Brand(Group): owner = models.ForeignKey(User, on_delete=models.CASCADE, related_name='%(class)ss', related_query_name='%(class)s') description = models.TextField('description', max_length=3000, blank=True) facebook_url = models.URLField('facebook url', blank=True) twitter_url = models.URLField('twitter url', blank=True) instagram_url = models.URLField('instagram url', blank=True) pinterest_url = models.URLField('pinterest url', blank=True) portfolio_url = models.URLField('portfolio url', blank=True) phone_number = PhoneNumberField('phone number', blank=True) These are my serializers: class CustomUserSerializer(HyperlinkedModelSerializer): brands = HyperlinkedRelatedField( many=True, read_only=True, view_name='brand-detail' ) class Meta: model = CustomUser fields = ( 'url', 'username', 'email', 'brands', ) class BrandSerializer(HyperlinkedModelSerializer): addresses = HyperlinkedRelatedField(many=True, read_only=True, view_name='address-detail') class Meta: model = Brand fields = ( 'url', 'name', 'owner', 'description', 'facebook_url', 'twitter_url', 'instagram_url', 'pinterest_url', 'portfolio_url', 'phone_number', ) These are my views: class CustomUserViewSet(ModelViewSet): """"A view set for viewing and editing custom users.""" queryset = CustomUser.objects.all() serializer_class = CustomUserSerializer class BrandViewSet(ModelViewSet): """A view set for viewing and editing brands.""" queryset = Brand.objects.all() serializer_class = BrandSerializer And this is my test, I am using pytest: @pytest.mark.django_db def test_create_brand_with_valid_data(client): """Tests POST method with valid data to create a Brand instance.""" user = CustomUser.objects.create(username='x', email='x@example.com', password='abc123', ) data = { 'owner': f'http://testserver/api/users/{user.id}/', … -
Session being set but not persisted
Problem The django.contrib.auth.login function is succeeding, but the session does not seem to persist. Code I am creating my own set of functions to use with an AJAX client inside of my Django server. I have the following code in urls.py: from django.contrib.auth import authenticate, login from django.conf.urls import url from django.http import JsonResponse import json def auth_login(request): username = json.loads(request.body)['username'] password = json.loads(request.body)['password'] user = authenticate(request, username=username, password=password) if user is not None and user.is_active: login(request, user) return JsonResponse({}, status=200) else: return JsonResponse({}, status=400) urlpatterns = [ url(r'auth/login/', auth_login, name='login') ] Details As mentioned above, the call to login() succeeds. request.session is being set properly, and I can access if from within auth_login. On subsequent requests, request.session does not exist and django.contrib.auth.get_user returns AnonymousUser. (Possibly relevant) I am also using the seemingly-popular https://django-tenant-schemas.readthedocs.io/en/latest/. This urls.py file is in an application that is per-tenant, so the user is actually authenticating on tenantname.hostname.com/tenant/auth/login/. The tenant's django_session table is being set correctly. For each attempted login, I can see session_key, session_data, and expire_data. The cookie for tenantname.hostname.com is empty after attempted logins. I'm just out of ideas as to what other things I could try to lead me to a solution. Question(s) … -
Start function on run with Flask
I have a flask app @app.route("/hello") def generater(): return "hello world if __name__ == '__main__': app.run() My application runs fine, but i would like to know how I could make a request to http://127.0.0.1:5000/hello when I compile my code -
Can't login django super user using custom command
This is my super user creation logic in djagno, class UserManager(BaseUserManager): use_in_migrations = True def _create_user(self, mobile, username, password, **extra_fields): if not mobile: raise ValueError('The given email must be set') user = self.model(mobile=mobile, username=username, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, mobile, username, password=None, **extra_fields): extra_fields.setdefault('is_staff', False) extra_fields.setdefault('is_superuser', False) extra_fields.setdefault('is_active', False) return self._create_user(mobile, username, password, **extra_fields) def create_superuser(self, mobile, username, password, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) extra_fields.setdefault('is_active', True) return self._create_user(mobile, username, password, **extra_fields) This works when I create a superuser using, python manage.py createsuperuser However when I try using this Custom command, class Command(BaseCommand): def handle(self, *args, **options): logger = logging.getLogger(__name__) with open('config/config.yaml', 'r') as stream: try: conf = yaml.load(stream) username = conf['users']['root']['username'] mobile = conf['users']['root']['mobile'] password = conf['users']['root']['password'] if not User.objects.filter(mobile=mobile).exists(): User.objects.create_superuser(mobile, username, password) except yaml.YAMLError as e: logger.error(str(e)) The User gets created and has all the permissions, yet I can't log into django admin using these credential, I get the following error, Please enter the correct mobile and password for a staff account. Note that both fields may be case-sensitive. Can someone help. -
Return Class based view from function based view
So I set up a login view, and upon successful login I'd like to go to a page of my choice by referencing another class based view. I'm not entirely sure how to achieve this. Login view def login_view(request): if request.method == 'POST': form =AuthenticationForm(data=request.POST) if form.is_valid(): user=form.get_user() login(request,user) #Not sure what to do next #return HttpResponseRedirect(reverse(request, Dashboard))? else: #TODO else: form = AuthenticationForm() Dashboard class I'm trying to get to class Dashboard(ListView): model = models.Note template_name = 'notemanager/dashboard.html' def get_context_data(self, request,**kwargs): context = super().get_context_data(**kwargs) notedata = models.Note.objects.filter(added_by = User) reminderdata = models.Reminder.objects.filter(added_by = User) context['notes'] = notedata context['reminder'] = reminderdata return context -
Posting JSON boolean Django
I'm trying to send a POST request containing a boolean value like this: { "is_manager": true } The request is then handled by an overriden adapter from django-allauth: from allauth.account.adapter import DefaultAccountAdapter class CustomUserAccountAdapter(DefaultAccountAdapter): def save_user(self, request, user, form, commit=True): """ Saves a new `User` instance using information provided in the signup form. """ from allauth.account.utils import user_field user = super().save_user(request, user, form, False) user_field(user, 'is_manager', request.data.get('is_manager', False)) user.save() return user But i get this error: TypeError: 'bool' object is not subscriptable I tried using json.loads but this method only accepts strings as argument. What can i do? Thanks in advance. -
Django uploading to Amazon s3 with chunks
We're using the S3Boto3Storage to upload media files to our s3 storage on Amazon. This works pretty well. Since we're using Cloudflare as a "free" version we're limited to a maximum of 100MB per request. This is a big problem. Even the Enterprise plan is limited to 500MB. Is there a way to use a kind of "chunked uploads" to bypass the 100MB-per-request limit? model.py class Media(models.Model): name = models.CharField(max_length=100, null=True) file = models.FileField(upload_to=get_path) storage.py from storages.backends.s3boto3 import S3Boto3Storage class MediaStorage(S3Boto3Storage): location = 'media' file_overwrite = False views.py @api_view(['POST']) def upload_media(request): if request.method == 'POST': serializer = MediaSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) -
How to get the current path in a django view?
So the question is really simple i need a method to get the current url in a class based view in django, requests.path doesnt work im not sure why - Do i need to import something? I tried : "from django.http import request" but that doesnt have an Attribute path. -
All data points are not appearing in a line chart made using chart.js
I am using Django 2.0 for back-end development of a BPO website. In that one, I am trying to show one accounting information (trail balance) of an organisation in a table and two separate line chart for credit and debit accounts.I am using Chart.js for plotting the line chart. The corresponding functions in view.py file of django are: #this preprocess function is used to find out the credit and debit accounts def preprocess(a): label1 = [] label2 = [] arr1 = [] arr2 = [] for i in range(len(a)): if int(a[i,1])!=0: label1.append(a[i,0]) arr1.append(int(a[i,1])) else: label2.append(a[i,0]) arr2.append(int(a[i,2])) return label1,label2,list(arr1),list(arr2) @login_required def Acc_Info(request): obj = request.user if(request.method=='GET'): obj1 = Company.objects.get(username=obj) dt = int(datetime.date.today().year) obj2 = AccountingInfo.objects.filter(company_code=obj1,date=dt) if obj2.exists(): obj2 = AccountingInfo.objects.get(company_code=obj1,date=dt) path = settings.MEDIA_ROOT+'/'+str(obj2.info) # names = ['Name of Account','Credit','Debit'] data = pd.read_csv(path) data = np.array(data) # dr = list(data[:,1]) # cr = list(data[:,2]) label1,label2,dr,cr = preprocess(data) print("\n\ncr = ",cr) print("\n\ndr = ",dr) Debit_sum = data[:,1].sum(dtype=np.float64) Credit_sum = data[:,2].sum(dtype=np.float64) return render(request,'Acc_Info.html',{'f':True,'lc':len(cr),'lr':len(dr),'label1':label1,'label2':label2,'cr':cr,'dr':dr,'year':datetime.date.today().year,'data':data,'Suspense':Credit_sum-Debit_sum,'Credit_sum':Credit_sum,'Debit_sum':Debit_sum}) else: return render(request,'Acc_Info.html',{'f':False,'year':dt}) else: obj1 = Company.objects.get(username=obj) dt = request.POST['year'] obj2 = AccountingInfo.objects.filter(company_code=obj1,date=dt) if obj2.exists(): obj2 = AccountingInfo.objects.get(company_code=obj1,date=dt) path = settings.MEDIA_ROOT+'/'+str(obj2.info) data = pd.read_csv(path) data = np.array(data) label1,label2,dr,cr = preprocess(data) print("\n\ncr = ",cr) print("\n\ndr = ",dr) Credit_sum = data[:,2].sum(dtype=np.float64) Debit_sum = … -
Save chinese character in Django SQLite model field & Displaying in Template
How do I save chinese characters in Django model fields and show this properly in the HTML template and django-admin? I would like to save chinese names into the database. They are only 3 characters long. If this is too complex, are there any workaround such as outputting the characters in image file and saving the characters as an image? I don't plan on manipulating the characters stored 'in-string', only saving and showing them on the template. Thank you. -
Django: Combining textbox and dropdown from values stored in database in Django forms
I've two models User and Company. I have created two custom forms from these models and showing in the same template for signup. Logic is like, if the company already exists in the database then it shouldn't create a new record in the Company but just assign the existing company to the user. Otherwise, create a new company and assign to the user. For the convenience, on the signup template, I want to show the dropdown with all the existing company names from the company table. So that either user can select the name from the list or write his own company. Following is my code files signup.html {{ company_info_form.company_name|as_crispy_field }} {{ company_info_form.company_address|as_crispy_field }} forms.py class CompanyInformationForm(ModelForm): company_name = forms.CharField(label = popover_html('Company Name', 'Company Name')) company_address = forms.CharField(label = popover_html('Company Address', 'Compnay Address')) class Meta: model = CompanyInformation fields = ( "company_name", "company_address" ) views.py (for GET request): form = RegistrationForm() company_info_form = CompanyInformationForm() args = {"form": form, "company_info_form": company_info_form} return render(request, "registration/signup.html", args) I assume I don't need to do many changes if I can make a combo of textbox and dropdown both. As I will read the value to apply the logic. P.S. Let me know if you … -
Site matching query problem with redirects app
I would like to use "redirects app" for redirect all paths from an old site to a new site. On my site I've already "sitemap framework" and "syndication feed framework". Without "redirects app" I don't have problems to see feeds page and sitemap page. I've followed the indications of the official guide to install "redirects app"(only 4 clear steps) and, after the installation, I can see the redirects options in to the admin panel, but I can't see anymore feeds page and sitemap page because it's shown me this error: Environment: Request Method: GET Request URL: http://127.0.0.1:8000/blog/feed/ Django Version: 2.1.3 Python Version: 3.6.7 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'django.contrib.redirects', 'django.contrib.sitemaps', 'blog', 'kernel', 'service', 'team'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.contrib.redirects.middleware.RedirectFallbackMiddleware'] Traceback: File "/var/www/html/dev/miosito/django/v2.1/versions/devenv/lib/python3.6/site-packages/django/contrib/sites/models.py" in _get_site_by_request 41. SITE_CACHE[host] = self.get(domain__iexact=host) File "/var/www/html/dev/miosito/django/v2.1/versions/devenv/lib/python3.6/site-packages/django/db/models/manager.py" in manager_method 82. return getattr(self.get_queryset(), name)(*args, **kwargs) File "/var/www/html/dev/miosito/django/v2.1/versions/devenv/lib/python3.6/site-packages/django/db/models/query.py" in get 399. self.model._meta.object_name During handling of the above exception (Site matching query does not exist.), another exception occurred: File "/var/www/html/dev/miosito/django/v2.1/versions/devenv/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner 34. response = get_response(request) File "/var/www/html/dev/miosito/django/v2.1/versions/devenv/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 126. response = self.process_exception_by_middleware(e, request) File "/var/www/html/dev/miosito/django/v2.1/versions/devenv/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 124. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/var/www/html/dev/miosito/django/v2.1/versions/devenv/lib/python3.6/site-packages/django/contrib/syndication/views.py" in call 39. feedgen … -
Using django.contrib.session with django.contrib.auth
I would like to use Django's session-based authentication. I have used the following page as an example: https://docs.djangoproject.com/en/2.1/topics/auth/default/#how-to-log-a-user-in. Specifically, my login view looks like this: def auth_login(request): username = json.loads(request.body)['username'] password = json.loads(request.body)['password'] user = authenticate(request, username=username, password=password) if user is not None and user.is_active: login(request, user) return JsonResponse({}, status=200) else: return JsonResponse({}, status=400) The only difference between this and the example from the link above is that there they suggest to redirect to a success page. My application is single-page so I'm making AJAX requests and returning JSON responses. This example does not set a session ID in the cookie for this site, however the request succeeds. If I make a subsequent request to a secure resource, I'm still getting a 403 error. This is my first Django project, so I'm likely forgetting something simple. Any thoughts? -
Django Templates and render() - How to access multiple values
Learning Django and I'm having an issue with accessing 2 different values. In views.py under def home(request, I've added a list of 2 dictionary objects and passed it through under context. It works perfectly, I'm about to for loop over the dictionary in my front_page.html template, but I've also added a simple if title variable which only works if I place {'title': 'Competitive'} before the variable context. from django.shortcuts import render # Create your views here. owl = [ { 'title': 'Competitive' }, { 'Team': 'Dynasty', 'Location': 'Souel Korea', 'Colors': 'Black & Gold', }, { 'Team': 'OutLaws', 'Location': 'Houston', 'Colors': 'Green & Black', } ] def home(request): context = { "owl": owl } return render(request, 'overwatch_main_app/front_page.html', context, {'title': 'Competitive') def second(request): return render(request, 'overwatch_main_app/about.html', {'title': 'Boom'}) I've even tried comp = {'title': 'Competitive'}, and placing comp into the render(). It only works when I place comp, or {'title': 'Competitive'}before content and then content doesn't work. return render(request, 'overwatch_main_app/front_page.html', comp, context) return render(request, 'overwatch_main_app/front_page.html', {'title': Competitive'} , context) How can I pass more than 1 value of dictionaries to my template via render() front_page.html {% extends 'overwatch_main_app/base.html' %} {% block content %} <h1> OverWatch</h1> {% for o in owl %} <p>{{o.Team}}</p> … -
Encode decode problem while writing to excell worksheet in django view
I get below unicodedecodeerror while trying to write to excell worksheet. Exception Type: UnicodeDecodeError Exception Value: 'ascii' codec can't decode byte 0xc3 in position 7: ordinal not in range(128) The string that could not be encoded/decoded was: i>����R< My view lines : def file_write(input): handle1=open('/tmp/filelog.txt','a') handle1.write(str(input)) handle1.close() workbook = xlsxwriter.Workbook('report.xlsx') worksheet = workbook.add_worksheet() teachertitle = "ÖĞR" file_write(teachertitle) worksheet.write("A4", teachertitle, titlescell) workbook.close() The strange thing is. File_write function is working well and it writes "ÖĞR" to a local text file. But when i try to write "ÖĞR" to excell workseeht it throws error. I also tried worksheet.write("A4", teachertitle.encode('utf-8'), titlescell) but still problem continue. I also have # -- coding: utf-8 -- at the beginning of views.py -
Using different database values for BooleanField in Django
I am converting an old MS Access database to a Django-based website. I've converted the data to a SQLite database, and automatically generated the models using inspectdb (which worked as well as could be expected). It seems that MS Access stores boolean values as -1 for True and 0 for False. Rather than modify the database (it is a lot of tables!) I'm trying to subclass models.BooleanField, as follows: class MsAccessBooleanField(models.BooleanField): def from_db_value(self, value, expression, connection): if value == -1: return True if value == 0: return False def to_python(self, value): if value == -1: return True if value == 0: return False def get_prep_value(self, value): if value == True: return -1 if value == False: return 0 return None def get_db_prep_value(self, value, connection, prepared=False): if value == True: return -1 if value == False: return 0 return None When I view entries via the Admin interface, this seems to work (-1 values appear as Yes in the dropdown; 0 values as No). However (this is the problem), when modifying the value and saving, I can only save as No or Unknown (selecting Yes produces a message that no value has been specified). Any idea what I might be doing … -
How can i fetch data from django models(database) using celery(asynchronously) from previously existing data
tasks.py import string from django.contrib.auth.models import User from django.utils.crypto import get_random_string from celery import shared_task @shared_task def create_random_user_accounts(total): for i in range(total): username = 'user_{}'.format(get_random_string(10, string.ascii_letters)) email = '{}@example.com'.format(username) password = get_random_string(50) User.objects.create_user(username=username, email=email, password=password) return '{} random users created with success!'.format(total) views.py from django.contrib.auth.models import User from .tasks import create_random_user_accounts from django.http import JsonResponse def users(request): obj = list(User.objects.values()) create_random_user_accounts.delay(20) return JsonResponse(obj,safe=False) here i am inserting some random datas to User model using celery And it is working while fetching same data. But, i want to fetch 'existing data' from database 'without inseting' them on same request. Please share me some idea how can i do that. -
Using ajax how to populate the events data in Full Calender
Am using FullCalender in My django project. using forloop i can able to populate the data when the script was in same html page but now i want to seperate js file. urls.py url(r'deal/$', views.deal,name="deal") Views.py def deal(request): if request.method == 'POST': form = Deals_Form(request.POST, request.FILES) if form.is_valid(): print(form) form.save() messages.success(request, "Insertion Success!") return redirect('/deal') else: messages.success(request,"You missed to fill some fields!") return redirect('/') else: all_events = DealsCalendar.objects.all() get_event_types = DealsCalendar.objects.only('event_type') form = Deals_Form() product_data = Product.objects.all() pro_name = [] for i in product_data: pro_name.append(i.name) # if filters applied then get parameter and filter based on condition else return object if request.GET: event_arr = [] if request.GET.get('event_type') == "all": all_events = DealsCalendar.objects.all() for i in all_events: event_sub_arr = {} event_sub_arr['title'] = i.event_name start_date = datetime.datetime.strptime(str(i.start_date.date()), "%Y-%m-%d").strftime("%Y-%m-%d") end_date = datetime.datetime.strptime(str(i.end_date.date()), "%Y-%m-%d").strftime("%Y-%m-%d") event_sub_arr['start'] = start_date event_sub_arr['end'] = end_date event_arr.append(event_sub_arr) return HttpResponse(json.dumps(event_arr)) context = { "events":all_events, "form":form, "data":pro_name, "product_data":product_data } return render(request,'dashboard/dealscalender/deals_calender.html',context) script $(function () { // #1. CALENDAR INIT if ($("#fullCalendar").length) { var calendar, d, date, m, y; date = new Date(); d = date.getDate(); m = date.getMonth(); y = date.getFullYear(); calendar = $("#fullCalendar").fullCalendar({ header: { left: "prev,next today", center: "title", right: "month,agendaWeek,agendaDay" }, selectable: true, selectHelper: true, select: function select(start, end, … -
Django admin sending a message based on inline formset
I'm writing a reservation program using the Django admin. The program will warn the user (via Django messages) when the total nights for all room changes is greater than the total nights for the reservation. So if a reservation is for 7 nights and the user enters the guest into room "A" for 4 nights and room "B" for 4 nights (totaling 8 nights) the user will see a warning. The reason for a warning and not a simple form error is that a group can have multiple rooms per night, which would make it possible for the above to occur. The code works (below is the relevant pieces). warn_if_rc_nights_gt_reservation_nights(), which houses the logic to warn the user, operates on the form instance (when the form is only being rendered) or the raw request.POST variables (when the form is being saved/POSTed) in order to tally up the total nights for room changes and reservations. I'm OK with using the form instance to tally the total nights, but I have a problem with the raw POST variables, since it's more error-prone (POST variables are not clean() yet) and un-Django-like. I'd rather use a built-in class method or function to accomplish this. … -
Listing tags of each post
I use django-tagging and can not figure out how to list and display each posts' tag seperately. views.py def news (request): haberler = Haberler.objects.all().filter(status=1).order_by('-created') #tags = Tag.objects.usage_for_model(Haberler, counts=True) // to list all tags of a model return render(request, 'haberler/haberler.html',{'haberler':haberler, 'tags':tags, }) haberler.html <div class="col s12 m8 l9 xl9"> <div class="col s12 grey-text haber-date">{{haberler.created|date:'d/m/Y'}}</div> <div class="col s12" style="font-family:Purista Semibold">{{haberler.title}}</div> <div class="col s12 haber-icerik"><span class="grey-text text-darken-3">{{haberler.content|safe}}</span></div> <div class="col s12" style="margin-top:1rem;"> <!--<p>{{haberler.tags}}</p>--> {% for tag in tags %} <div class="grey lighten-3" style="display:inline; border:thin solid #999;padding:.3rem; font-size:.8rem;border-radius: 3px;">{{ tag.name }}</div> {% endfor %} </div> </div> {{haberler.tags}} lists tags of a related post as a comma seperated string which i could not give style for each tag. Thank you in advance. -
How to get instance of django model by class name and object id
I have a class name MyModel and the object id 123. How to get the instance of django model? -
Django - User is not loggin out after closing the browser even after setting `SESSION_EXPIRE_AT_BROWSER_CLOSE = True`
I am using my own login and logout system , even after setting SESSION_EXPIRE_AT_BROWSER_CLOSE = True after closing browser , the user aint logging out. I am not good at sessions and cache so can u tell me what else stuff i have to do to make it work. Do i need to make change in my login and logout views. A remember me key is also added in loginform Views.py login view @csrf_protect @never_cache def loginremember(request): if request.method == "POST": form = AuthenticationRememberForm(data=request.POST) if form.is_valid(): if not form.cleaned_data.get('remember_me'): request.session.set_expiry(0) login(request, form.get_user()) if request.session.test_cookie_worked(): request.session.delete_test_cookie() return HttpResponseRedirect(redirect_to) else: form = AuthenticationRememberForm(request) request.session.set_test_cookie() return render(request,'registration/login.html',{'form':form}) Views.py logout view def logoutv(request): logout(request) return HttpResponseRedirect('/') Setting have a SESSION_EXPIRE_AT_BROWSER_CLOSE = True in it already. Except this i made no changes anywhere related to sessions. -
prismjs for django template
I tried using prismjs in my django template , but i couldn't. Here i am uploading my files so that you guys can have a look. My code goes here... views.py def prism(request): return render(request , "latest_files.html") home.html {% extends "base.html" %} {% block body %} <pre><code class="language-Django"> {% for post in posts|dictsortreversed:"id"|slice:"18" %} <ul> <li class="pointer" onclick="location.href='{% url 'detail' post.id %}'">{{ post.title }}</li> </ul> {% endfor %} </code></pre> {% endblock %} I linked .js and .css files carefully cause it worked for python earlier. Thanks in Advance !