Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django determine if a item has been paid or not
i want to determine if an item has been brought or not by a user and if it's paid a diffrent content should get displayd but i dont know how to get these two models together (nooby). models.py class Post_Sell_Multiple(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(verbose_name="Post Title", max_length=40) content_preview = models.TextField(verbose_name="Post Content Preview", max_length=500) content = EncryptedTextField(verbose_name="Post Content", max_length=10000) ... class Post_Paid_Sell_Multiple(models.Model): paying_user = models.ForeignKey(User, on_delete=models.CASCADE) post_sell_multiple = models.ForeignKey(Post_Sell_Multiple, on_delete=models.CASCADE) status = StatusField(default='unpaid') STATUS = Choices('unpaid', 'paid') paid_date = models.DateField(auto_now_add=True, null=True) def publish(self): self.paid_date = timezone.now() self.save() class Meta: unique_together = ('paying_user', 'post_sell_multiple') ordering = ['-paid_date'] template.html <h1>{{ post.title }}</h1> {% if post.postcover %} <div> <img class="float-right postcover" src="/media/{{ post.postcover }}"> {% if post.post_paid_sell_multiple.STATUS == 'paid' %} <p>{{ post.content|safe|linebreaksbr }}</p> {% else %} <p>{{ post.content_preview|safe|linebreaksbr }}</p> {% endif %} what i want is first to get a relation between those two models and second if it's unpaid = display content_preview if it's paid = display content but it seems that im missing something in the relations because if i now create a post object nothing gets saved to the Post_Paid_Sell_Multiple model. thanks in advance -
how to display login_required_message in django
I want to display login_required message like you have to login first to give the review while redirecting to the login page. How can i achieve this. views.py @login_required(redirect_field_name='next',login_url='shop:users_signin') def review(request,slug): if request.method == "POST": form = ReviewForm(request.POST) if form.is_valid(): review = form.save(commit=False) review.product = Product.objects.get(slug=slug) review.user = request.user review.save() messages.success(request, 'Review Saved.') return redirect('shop:detail', slug) else: return redirect('shop:detail',slug) -
django programming error : column does not exist
Hello I am running a django app using Django. The app is working correctly . But when I add a new field in my model.py I got this error ProgrammingError at /admin/challenges/challenge/ column challenge.category does not exist LINE 1: ..., "challenge"."modified_at", "challenge"."title", "challenge... I found similar questions but they didn't solve my problem. I tried to run "python manage.py migrate" and it doesn't solve the problem Could any one help me please ? -
Problems with django rest framework default field validation
I have the following problems for a nested model like this: def Post(models.Model) name = models.CharField(unique=True) content = models.TextField() def Comment(models.Model) post = models.ForeignKey(Post) content = models.CharField() I created default model serializers with all fields. Problems: The default model serializer does not work for nested models. I have to explicitly write create/update. This has been explained in the documentation, so nothing against it. Although I think choosing sane default can cater to 99% of use cases (and for the rest, behaviour can be customisable). I will try to take a shot at this. When I try to use json from existing post object, serializer is_valid() fails saying "unique constraint on name fails". But I wanted it to update and not create. Should is_valid not be create/update aware based on id being passed in json. When creating a new nested json with many comments, is_valid() fails saying that "post is empty". Of course I will not have post id in the json, as post creation is yet to happen. So is_valid becomes useless. Should is_valid not depend on if id is passed in json? Also, I can not use data/validated_data without having is_valid pass. Setting validators = [] also does not … -
Django ModelAdmin.get_formsets_with_inlines , to restrict data specific to the current user / owner
In order to restrict access of main model data to the current logged in user, I have used a queryset in admin.py similar to : @admin.register(MyModel) class MyModel(admin.ModelAdmin): def get_queryset(self, request): qs = super().get_queryset(request) if request.user.is.superuser: return qs return qs.filter(resource_owner=request.user) ... Owner is the name of the field that stores the current logged in user and this works like a charm ! However, this obviously does not work with inlines. I have searched the documentation and (could be wrong but) understand that one could use ModelAdmin.get_formsets_with_inlines to achieve this. Being a trainee , I am not certain how one would apply this formset to restrict access only to the owners inline model data just as the above queryset is being applied to the main model. The documentation is quoted below as : For example if you wanted to display a particular inline only in the change view, you could override get_formsets_with_inlines as documentedfollows: class MyModelAdmin(admin.ModelAdmin): inlines = [MyInline, SomeOtherInline] def get_formsets_with_inlines(self, request, obj=None): for inline in self.get_inline_instances(request, obj): # hide MyInline in the add view if not isinstance(inline, MyInline) or obj is not None: yield inline.get_formset(request, obj), inline I have tried to apply the above formset but am too inexperienced … -
how to access all fields of other models with the help of Forign Key in django
i want to enroll student and want to get student information from student model and course information from course models. student and course are separate apps. how i get the list of student names and the list of courses in enroll view here is a code Course Model class course(models.Model): course_name = models.CharField(max_length=30) course_fee = models.IntegerField(default=3000) cr_hrs = models.IntegerField(default=2) def __str__(self): return self.course_name Student Model class student(models.Model): first_name = models.CharField(max_length=20) last_name = models.CharField(max_length=20) father_name = models.CharField(max_length=30) dob = models.DateField() image = models.ImageField(upload_to='images/', null=True) phone_number = models.BigIntegerField() email = models.EmailField(unique=True, null=True) def __str__(self): return self.first_name Enroll Model from course.models import course from student.models import student class enroll(models.Model): student = models.ForeignKey(student, on_delete=models.CASCADE) course = models.ManyToManyField(course) enroll_date = models.DateField() enrolled_by = models.ForeignKey(User, on_delete=models.CASCADE) fee_paid = models.BooleanField(default=False) Enroll View def create(request): if request.method == 'POST': if request.POST['student'] and request.POST['course']: enrolled = enroll() enrolled.student = request.POST['student'] enrolled.course = request.POST['course'] enrolled.enrolled_by = request.user enrolled.save() return redirect('/enroll/list') else: return render(request, 'enroll/create.html', {'error': 'All fields are requried.'}) else: return render(request, 'enroll/create.html', {}) html file <form class="needs-validation" novalidate method="POST" action="{% url 'enroll_create' %}" enctype="multipart/form-data" name="student_form"> {% csrf_token %} <select class="form-control" name="student"> {% for enroll in enrolled.all %} <option value="{{enroll.student.first_name}}" >{{enroll.student.first_name}} {{enroll.student.last_name}}</option> {% endfor%} </select> <select class="form-control" name="course" > {% … -
How to find video-duration,video-size and MIME-type?
I have a video, which is uploaded using below code and get API. One more requirement is, know the video-duration,video-size, and MIME-type from that uploaded video? Can anyone help me with this? MODELS.PY from django.db import models class Video(models.Model): name= models.CharField(max_length=500) videofile= models.FileField(upload_to='videos/', null=True, verbose_name="") def __str__(self): return self.name + ": " + str(self.videofile) VIEWS.PY from rest_framework.views import APIView from rest_framework.parsers import MultiPartParser, FormParser from rest_framework.response import Response from rest_framework import status from .serializers import VideoSerializer class VideoView(APIView): parser_classes = (MultiPartParser, FormParser) def post(self, request, *args, **kwargs): video_serializer = VideoSerializer(data=request.data) if video_serializer.is_valid(): video_serializer.save() return Response(video_serializer.data, status=status.HTTP_201_CREATED) else: return Response(video_serializer.errors, status=status.HTTP_400_BAD_REQUEST) -
Django 2: csrfmiddlewaretoken in url when hit back
I have a home page divided in two sections, where in one of them I have a form the user can fill and submit. The form submission should refresh only the div that contains that form. For that I'm using AJAX as I show below. Everything works fine except when I hit back after the form submission. The csrfmiddlewaretoken appears in the url as a parameter. Any idea if this is normal? How can I prevent it? The form: <form id="post-form"> {% csrf_token %} <fieldset> <legend>Facebook Login</legend> <div class="form-group"> <label for="InputName">Name</label> <input type="text" class="form-control" placeholder="name"> </div> <button type="submit" class="btn btn-primary">Submit</button> </fieldset> </form> AJAX script: <script src="{% static "vendor/jquery/jquery.min.js" %}"></script> <script src="{% static "vendor/bootstrap/js/bootstrap.bundle.min.js" %}"></script> <script src="https://cdn.jsdelivr.net/npm/js-cookie@2/src/js.cookie.min.js"></script> <script> var csrftoken = Cookies.get('csrftoken'); function csrfSafeMethod(method) { // these HTTP methods do not require CSRF protection return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method)); } $.ajaxSetup({ beforeSend: function(xhr, settings) { if (!csrfSafeMethod(settings.type) && !this.crossDomain) { xhr.setRequestHeader("X-CSRFToken", csrftoken); } } }); </script> <script type="text/javascript"> $('#post-form').on('submit',function(event){ event.preventDefault(); console.log("form submitted!"); // sanity check $.ajax({ type:'POST', url:'{% url 'test:test_url' %}', data:{ Name:$('#InputName').val(), }, success:function(context){ $('#post-form').html(context); } }); }); </script> -
Using tastypie to retrieve data from foreign key
These are two models in my Django app : models.py class Posts(models.Model): title = models.CharField(max_length=200, blank=True) author = models.ForeignKey(user,on_delete=models.CASCADE,default=None, blank=True) content = models.TextField() class Unposted(models.Model): article = models.ForeignKey(Posts, on_delete=models.CASCADE) upload_at = models.DateTimeField(default=datetime.now, blank=True) I'm trying to retrieve data from Posts using an API request to Unposted. Here's what I have until now but I'm unsure how to get data from the Posts model. Right now I just get a JSON response with only the upload_at field. resources.py class UnpostedResource(ModelResource): class Meta: queryset = Unposted.objects.all() resource_name = 'unposted' -
Django log file created as root
I have a setup for django logging to write log in a new file every day. LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'file': { 'level': 'DEBUG', 'class': 'logging.handlers.TimedRotatingFileHandler', 'filename': '/path/to/log/dev.log', 'when': 'midnight', 'backupCount': 60, }, }, 'loggers': { 'django': { 'handlers': ['file'], 'level': 'DEBUG', 'propagate': True, }, }, } It works fine when gunicorn keeps on running for days. However, when I start a gunicorn service that has stop at least since the previous day, a new dev.log file is created as root instead of my_gunicorn_user, why ? I use : Ubuntu 18.04 NGINX 1.14.1 python 3.5.2 gunicorn 19.9 django 2.1.1 NGINX is running as www-data and gunicorn my_gunicorn_user $ ls -l /path/to/ drwxrwxr-x 2 my_gunicorn_user users bla bla bla log $ ls -l /path/to/log/ -rw-r--r-- 1 my_gunicorn_user webapps bla bla dev.log.the_day_before_yesterdy -rw-r--r-- 1 my_gunicorn_user webapps bla bla dev.log.yesterday -rw-r--r-- 1 root root bla bla today dev.log -
how to add data to child model along with parent mode?
I am working on rest framework.i want to add data to child model along with parent model. basically creating two records at a time records. models.py class Visit(models.Model): name = models.CharField(max_length=200) gender = models.CharField(choices=GENDER_CHOICE, max_length=1) mobile = models.CharField(max_length=18,default="") email = models.CharField(max_length=256, null=True, blank=True) address = models.TextField(null=True, blank=True) visit_type = models.IntegerField(choices=VISIT_TYPE) visit_purpose = models.CharField(max_length=250) visitor_photo = models.FileField(upload_to="visitor/",null=True, blank=True) id_photo = models.FileField(upload_to="id_card/",null=True, blank=True) date_created = models.DateTimeField(default=timezone.now, editable=False) class Status(models.Model): status = models.ForeignKey(Visit,on_delete=models.CASCADE,related_name="status") description = models.CharField(max_length=200) from_time = models.DateField() to_time = models.DateTimeField(null=True, blank=True) aproved = models.BooleanField(default=False) visit_complete = models.BooleanField(default=False) exit_time = models.DateTimeField(null=True, blank=True) date_created = models.DateTimeField(default=timezone.now, editable=False) serializers.py class StatusSerializers(serializers.ModelSerializer): class Meta: model = Status fields = "__all__" class VisitSerializers(serializers.ModelSerializer): class Meta: model = Visit fields = "__all__" def create(self, validated_data): print(validated_data) model_b = Visit.objects.create(**validated_data) Status.objects.create(status=model_b) return model_b views.py @api_view(['GET', 'POST']) def create_visitor(request): if request.method == 'GET': visitor = Visit.objects.all() serializer = VisitSerializers(visitor,context={'request': request},many=True) return Response(serializer.data) elif request.method == 'POST': serializer = VisitSerializers(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) in above code i am able to create child recod ie.Status model record but i dont know how to add other fileds to it while creation. -
How to make a test that serialized data returns in json format?
Hello all and thanks for people that is going to answer. I have a Class in my model and the view that serialize that class. I would like to make some tests to be sure that datas returns in json format. Here's my class in the model: class VariableCompensation(models.Model): VC_VALUE = 1 VC_PERCENTAGE = 2 VC_RULE = 3 VC_CHOICES = ( (VC_VALUE, _('Value')), (VC_PERCENTAGE, _('Percentage')), (VC_RULE, _('Rule')), ) date_entered = models.DateField(verbose_name=_('Date of insertion')) deadline = models.DateField(verbose_name=_('Expiring Date')) active = models.BooleanField(verbose_name=_('Active or Inactive'), default=True) value = models.FloatField(verbose_name=_('Value'), null=True, blank=True) created_on = models.DateTimeField(default=timezone.now) updated_on = models.DateTimeField(auto_now=True) compensation_type = models.PositiveSmallIntegerField(verbose_name=_('Compensation Type'), choices=VC_CHOICES, null=True, blank=True) dossier_group = models.ForeignKey(DossierGroup, related_name='compensations', on_delete=models.CASCADE) And here's my class serialized: class VariableCompensation(models.Model): VC_VALUE = 1 VC_PERCENTAGE = 2 VC_RULE = 3 VC_CHOICES = ( (VC_VALUE, _('Value')), (VC_PERCENTAGE, _('Percentage')), (VC_RULE, _('Rule')), ) date_entered = models.DateField(verbose_name=_('Date of insertion')) deadline = models.DateField(verbose_name=_('Expiring Date')) active = models.BooleanField(verbose_name=_('Active or Inactive'), default=True) value = models.FloatField(verbose_name=_('Value'), null=True, blank=True) created_on = models.DateTimeField(default=timezone.now) updated_on = models.DateTimeField(auto_now=True) compensation_type = models.PositiveSmallIntegerField(verbose_name=_('Compensation Type'), choices=VC_CHOICES, null=True, blank=True) dossier_group = models.ForeignKey(DossierGroup, related_name='compensations', on_delete=models.CASCADE) -
Django pagination is not working properly with very large dataset
When i am using pagination with very large dataset it work too slow, maybe i am not implementing it properly please help. how to make it fast.anything that i can change or implement so that it work fine view.py def display(request): user_list = Finaltest1.objects.all() searchlen= user_list.count() paginator = Paginator(user_list, 100) page = request.GET.get('page') users = paginator.get_page(page) return render(request,'displayLogs.html',{'users': users,'searchlen':searchlen}) model.py class Final(models.Model): name = models.TextField(db_column='Date',primary_key=True, blank=True, null=False) # Field name made lowercase. corr = models.TextField(db_column='CorrelationId', blank=True, null=True) # Field name made lowercase. <div class="pagination" style="border-style:inset;border-width:5px;padding-bottom: 5px"> {% if users.has_previous %} <a class="pagination-action" href="?page=1"> <i class="fas fa-angle-double-left"></i></a> <a class="pagination-action" href="?page={{ users.previous_page_number}}"> <i class="fas fa-angle-left"></i></a> {% endif %} {% for num in users.paginator.page_range %} {% if users.number == num %} <span class="pagination-number pagination-current"><strong>{{ num }}</strong></span> {% elif num > users.number|add:'-3' and num < users.number|add:'3' %} <a class="pagination-number" href="?page={{ num }}">{{num}}</a> {% endif %} {% endfor %} {% if users.has_next %} <a class="pagination-action" href="?page={{ users.next_page_number }}"><i class="fas fa-angle-right"></i></a> <a class="pagination-action" href="?page={{ users.paginator.num_pages }}"> <i class="fas fa-angle-double-right"> </i></a> {% endif %} </div> -
Instead of Primary Key Send Different Field in Django Rest Framework
asd Serializers.py class MovieSerializer(serializers.ModelSerializer): class Meta: model = Movie fields = [ 'popularity', 'director', 'genre', 'imdb_score', 'name', ] Views.py class MovieList(generics.ListCreateAPIView): queryset = Movie.objects.all().order_by('-id')[:10] serializer_class = MovieSerializer permission_classes = (IsAuthenticated,) def list(self, request): queryset = self.get_queryset() serializer = MovieSerializer(queryset, many=True) return Response(serializer.data) def post(self, request, format=None): data = request.data if isinstance(data, list): serializer = self.get_serializer(data=request.data, many=True) else: serializer = self.get_serializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) I am send my data like this annd it is working correctly. But... { "popularity": 83.0, "director": "Victor Fleming", "genre": [ 1, 2, 3, 4 ], "imdb_score": 8.3, "name": "The Wizard of Oz" } But i want to send data somewhat like this - { "popularity": 83.0, "director": "Victor Fleming", "genre": [ "Adventure", "Family", "Fantasy", "Musical" ], "imdb_score": 8.3, "name": "The Wizard of Oz" } See the Genre List - Instead of Primary Key i am sending name. These are my Models class Genre(models.Model): name = models.CharField(max_length=30, unique=True) # make unique def __str__(self): return self.name class Movie(models.Model): popularity = models.FloatField(max_length=10) director = models.CharField(max_length=30) genre = models.ManyToManyField(Genre) imdb_score = models.FloatField(max_length=10) name = models.CharField(max_length=30) Even when i am listing data or getting the data it should send genre name instead of id. I … -
Which process will be faster back-end work or sql query?
The scenario I was working on a search system which backend framework is Django 2 and Database is MySQL. The search system hit in the database with parameter and compile 4 table join query. Which make that search a little bit slower for lots of data I know. The query: itemViewCategory = Item.objects.raw("select *, company.slug as companySlug, company.name as companyName, field.id as fieldId, field.name as fieldName, category.name as categoryName from company inner join category on company.business_type = category.id inner join category_field on category_field.category_id = category.id inner join custom_field as field on category_field.field_id = field.id where category.id = (select id from category where slug= %s) and field.name LIKE %s order by company.name", [slug,product]) Now I need to count that query result for different work. I can do that 2 way Use a for loop to count that data. I can Do another query for count that data. Now my question is which process will be faster? I do some google and become too much confused. -
Object of type QuerySet is not JSON serializable
I have these list objects that are callable by name. They have number values that users can input. how would I turn each of those lists to form that chart js can render? I tried with this: Django Queryset to dict for use in json but could not get it working. Getting "Object of type QuerySet is not JSON serializable". Chart js would need to have own line for each of those list and show the values in those lines. This is how far I got with the link in views: First I get all of users lists: user_lists = List.objects.filter(user=user) Then I get number values for each list list_data = {} for list in user_lists: list_data[list.name] = DataItem.objects.filter(list=list) Here is where I get stuck when I should convert these lists to something that chart.js can understand.. list_data_json = json.dumps(list_data, cls=DjangoJSONEncoder) btw am I in the right tracks to put this conversion to views, right? or does it belong somewhere else? Dont know if these are needed but here are models for these lists and the data items in them: class List(models.Model): name = models.CharField(max_length=100, default="") user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='lists') def __str__(self): return self.name class Meta: unique_together = ['name', … -
DRF Response returning all fields when using queryset method only
I'm doing a university project that requires me to implement a Web App using an API as backend and I've decided to use DRF to do it but I'm having some troubles right now. I'm trying to override the list method in View to only show some fields when retrieving the list of all airports' records but still all fields are being returned in the Response. Model: class Airport(models.Model): code = models.CharField(max_length=10) name = models.TextField() carriers = models.ManyToManyField(Carrier, related_name='airports') def __str__(self): return self.name Serializer: class AirportSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = models.Airport fields = ('id', 'name', 'code', 'url', 'carriers') View: class AirportView(viewsets.ModelViewSet): queryset = models.Airport.objects.all() serializer_class = AirportSerializer def list(self, request): airports = models.Airport.objects.only('id', 'name', 'code') data = AirportSerializer(airports, many=True, context={'request': request}).data return Response(data) Response: { "id": 4, "name": "Leo", "code": "Test", "url": "http://localhost:8000/api/airports/4/", "carriers": [] }, { "id": 5, "name": "asdasd", "code": "aasdasd", "url": "http://localhost:8000/api/airports/5/", "carriers": [ "http://localhost:8000/api/carriers/1/" ] }, { "id": 6, "name": "asdasd", "code": "aasdasd", "url": "http://localhost:8000/api/airports/6/", "carriers": [ "http://localhost:8000/api/carriers/1/" ] } How can I solve this? Is there a better way to do it, I mean not using QuerySet.only method? -
Django redirect non-logged in user to login page
I have created my own class that inherits from LoginView CustomLoginView(LoginView) in authentication/views.py. This class is in charge of authenticating users. The url is 'authentication/login' I would like to redirect all non logged-in users to this page instead of being redirect to Django default url admin/login/?next=/admin/. I tried to made some change in the settings as follow but it didn't work: AUTHENTICATION_BACKENDS = [ 'django.contrib.auth.backends.ModelBackend', 'authentication.views.CustomLoginView', ] -
How to generate tables by SQLAlchemy like `django manage.py inspectdb `?
When connected with mysql in django, we can use python manage.py inspectdb table1 >> app/models.py to generate specified table automaticly. Is it possible to use SQLAlchemy to do the same thing? -
Django: Refresh data on webpage after update in SQLite
I'm preparing a dashboard web application (in Django 2.1.7) that is supposed to monitor status of different processes. To do so, I've created a class ReportEntry in models.py class ReportEntry(models.Model): process = models.CharField(max_length=30) received = models.DateTimeField(auto_now_add=True) status = models.SmallIntegerField(default=1) To view the dashboard, I'm using django-tables2. The view.py script comprises from .tables import SimpleTable from django_tables2 import SingleTableView from .models import ReportEntry class TableView(SingleTableView): table_class = SimpleTable processes = ReportEntry.objects.values('process').distinct() queryset = [ReportEntry.objects.filter(**k).latest('received') for k in processes] refresh = [a.refresh() for a in ReportEntry.objects.all()] template_name = "simple_list.html" This web application works correctly. Now, I'd like to insert a new entry to the SQLite DB (suppose I'd like to update the status of the process) using a Python script below from sqlite3 import connect def create_connection(db_file): try: conn = connect(db_file) return conn except Exception as e: print(e) return None if __name__ == '__main__': from datetime import datetime, timedelta database = r'C:\Apps\Python3702\my_venv\web\mysite\db.sqlite3' conn = create_connection(database) cur = conn.cursor() sql = '''INSERT INTO main.monitor_reportentry(process,received,status) VALUES(?,?,?)''' cur.execute(sql, ['test', datetime.now(), 1]) conn.commit() conn.close() When I execute the script and insert the data into SQLite DB, I try to refresh the webpage with my dashboard, but the contents are not updated. The only thing that works … -
Pagination with id in url instead od "?page="
I have an application in Django 1.8 and my problem is the parameter "?page=" in the address. My goal is address in 127.0.0.0.1/blog/1 - and search results. Can I count on a hint? My urls: urlpatterns = [ url(r'^$', MyListView.as_view(), name='list'), url(r'/(?P<slug>[-\w]+)/(?P<pk>\d+)$', views.BlogDetailView.as_view(), name='blog_detail'), ] My view: class MyListView(ListView): model = models.Blog queryset = models.Blog.objects.order_by('-pub_date') template_name = 'blog/blog_list.html' context_object_name = 'blog_list' paginate_by = 10 def get_context_data(self, **kwargs): context = super(MyListView, self).get_context_data(**kwargs) context['blog'] = models.Blog.objects.all() return context code in template {% if is_paginated %} <ul class="pagination"> {% if page_obj.has_previous %} <li><a href="?page={{ page_obj.previous_page_number }}">&laquo;</a></li> {% else %} <li class="disabled"><span>&laquo;</span></li> {% endif %} {% for i in paginator.page_range %} {% if page_obj.number == i %} <li class="active"><span>{{ i }} <span class="sr-only">(current)</span></span></li> {% else %} <li><a href="?page={{ i }}">{{ i }}</a></li> {% endif %} {% endfor %} {% if page_obj.has_next %} <li><a href="?page={{ page_obj.next_page_number }}">&raquo;</a></li> {% else %} <li class="disabled"><span>&raquo;</span></li> {% endif %} </ul> {% endif %} -
How can I operate Django-ORM model singlely?
My directory structure like : ├─bin ├─conf │ └─django_settings.py ├─docs ├─log └─src └─main.py └─models.py Sorry, I'm new to Django. In my main.py, I want use django-orm to read data from my mysql table campaign_plan , but when I tried ro run main.py, error django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. happend, How can I successfully get the right data? models.py from django.db import models class CampaignPlan(models.Model): campaign_id = models.CharField(max_length=64, blank=True, null=True) rule_id = models.IntegerField(blank=True, null=True) status = models.IntegerField(blank=True, null=True) account_id = models.CharField(max_length=64, blank=True, null=True) class Meta: managed = False db_table = 'campaign_plan' unique_together = (('campaign_id', 'rule_id', 'status'),) main.py import sys, os BASE_DIR = os.path.dirname(os.path.dirname(__file__)) sys.path.append(os.path.join(BASE_DIR,'conf')) sys.path.append(os.path.join(BASE_DIR, "src")) os.environ.setdefault("DJANGO_SETTINGS_MODULE", "django_settings") from models import CampaignPlan class AutoManagementService(object): def __init__(self, campaign_plan): self.campaign_plan = campaign_plan def run(self): pass campaign_plans = CampaignPlan.objects.all() -
Django Rest framework Serializer necessary?
I had one business requirement to be implemented lately which required me to just fetch the data and render the response. So some API endpoint would return a response as: [{"id" :1,"name":"first"} ,{"id" :2,"name":"second":}] Can I just render this data by constructing a list of dictionaries which can be populated with various ORM queries instead of rendering the response through a serializer? Would it be an efficient solution in case I won't be using this serializer ever for POST request? -
background image of the extended html template is not loading in html page, How to solve this problem?
I have two html files 'base.html' and 'home.html', the file 'base.html' is having a background image, which is loading properly in 'base.html', I am extending the 'base.html' in 'home.html' , But when I am opening 'home.html' then that background image is not loading in 'home.html' page. Code from 'base.html' is as : <!doctype html> <html> <head> <title>Medicine information</title> <style> body { background-image: url("images/med2.jpg"); background-color: #cccccr; background-size: cover; } </style> </head> <body> {% block content %} replace me {% endblock content %} <h2> thanks for visiting !!</h2> </body> </html> code from 'home.html' is : {% extends "htmlfiles/base.html" %} {% block content %} <H1 style="background-color:DodgerBlue;" > Welcome to our site </H1> <HR> <H2 style="background-color:MediumSeaGreen;">Enter following details </H2> <form action="{% url 'results_strength_view' %}" id='b1' method = 'GET'> {%csrf_token %} {{ form.as_p }} <input type='submit' value='Get Different Options for Strength' /> </form> <HR> {% endblock content %} -
Django : Use decorator 'user_passes_test' using LDAP group witout django DB
I want to use LDAP AUTH for django. For the moment I have also a django Model Backend where are all my users and theirs groups. In my code, an user passes a test in order to access to application. This operation check if the group to allow is in the user information. But now I wanted to stop using Model Authentication and use only LDAP AUTH... How can I manage to use the same function to allow access, with LDAP groups without creating an user in the Model?