Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to reflect data from model.object defined with manytomanyfield?
i am tying to add input data into that particular field into database using manytomanyfield option. this is my view code-- def home(request): contacts = Contact.objects return render(request,'index.html',{'contacts':contacts,'fields':Field.objects}) def addContact(request): if(request.GET): contact = Contact() contact.save() for obj in Field.objects.all(): obj.save() messages.success(request, 'Contact Added Successfully') return redirect('add_contact') return render(request,'add_contact.html',{'fields':Field.objects}) def addField(request): if(request.GET): field = Field() field.field_name=request.GET['field_name'] field.field_type=request.GET['field_type'] field.is_required=request.GET['is_required'] field.save() messages.success(request, 'Field Added Successfully') return redirect('add_field') return render(request,'add_field.html') this is my model code-- class Field(models.Model): field_name = models.CharField(max_length=100) field_type = models.CharField(max_length=50) is_required = models.BooleanField() def __str__(self): return self.field_name class Contact(models.Model): attribute = models.ManyToManyField(Field) def name(self): return self.attribute this is my html code- <form action=""> <div class="container"> <h1>Add Contact</h1><br><br> <div class="box"> {% if messages %} <ul> {% for message in messages %} <li><h4>{{message}}</h4></li> {% endfor %} </ul> {% endif %} </div> {% for field in fields.all %} <div class="col-lg-4 mb-20"> <label for="{{ field }}">{{ field }}</label> <input type="{{ field.field_type }}" id="{{ field }}" name="{{ field }}"> </div> {% endfor %} </div> <div class="col-12 mb-20"> <br /><br /><br /><br /> <input type="submit" value="submit" class="button btn-success"> <input type="submit" value="cancel" class="button btn-danger"> </div> </div> </form> I am trying to add data to my form which is having labels (labels are values stored in field_name) and corresponding … -
Django - Changing the url to redirect from a middleware on the fly
I'm building a SSO login meant to be used from links send by emails. Each link should auto-connect the user (SSO), and be clickable multiple times (they have a TTL, which depends on the email) It works fine, but I'm concerned about the end-user sharing his url on social networks (basically copy/pasting the url, which contains the SSO token), allowing anyone following the link to be logged in automatically. My first attempt was to try to remove the GET SSO_TOKEN parameter, from my SSOMiddleware, as follow: if remove_token_middleware: request.GET._mutable = True # GET is not mutable by default, we force it # Remove the token from the url to avoid displaying it to the client (avoids sharing sso token when copy/pasting url) del request.GET[SSO_TOKEN_PARAM] request.GET._mutable = False # Restore default mutability return login(request, user) if service.get("auto_auth") else None Basically, my thought was that since the SSO_TOKEN is in the request.get object, removing it from it would eventually change the url where the user gets redirected In my controller, here is how the user gets "redirected" (using render) return render(request, 'campagne_emprunt/liste_offres_prets.html', locals()) When using render, there is no redirection, and the SSO token is still visible in the URL (in the … -
How to group by using django
I'm trying to group by using Django. I have three models as follows: class Tutorial(models.Model): name = models.CharField(max_length=200, unique=True, blank=False, null=False) class Category(models.Model): name = models.CharField(max_length=200, unique=True, blank=False, null=False) tutorial = models.ForeignKey(Tutorial, on_delete=models.DO_NOTHING, null=False) class Video(models.Model): name = models.CharField(max_length=200, unique=True, blank=False, null=False) tutorial = models.ForeignKey(Tutorial, on_delete=models.DO_NOTHING, blank=False, null=False) category = models.ForeignKey(Category, on_delete=models.DO_NOTHING, blank=False, null=False) In my view I have something as follows: @login_required def player(request): tutorial_id = request.POST.get('id', None) videos = Video.objects.filter(tutorial=tutorial_id).values("name", "category__name") With that in videos I get: [{'name': 'video1', 'category__name': 'category1'}, {'name': 'video2', 'category__name': 'category1'}, {'name': 'video4', 'category__name': 'category2'}] But the result that I want is: [ {'category': 'category1', 'videos': [{'name': 'video1}, {'name': 'video2'}]}, {'category': 'category2', 'videos': [{'name': 'video4}]}, ] Any idea how to do that? -
Vote Model Operations causing unknown troubles
I made a Vote model given below. My blog model has two operations that upvotes or downvotes the specific blog. For example, When a single user upvotes, the votes field in Blog increases and a UserVote Model has a record of it and when the same user downvotes, it changes it's vote_type and updates the record. The problem comes in when a second user casts a vote. After an upvote, when the second user downvotes, it says that he has already voted (although it should've changed his vote_type to downvote) I've been going through this problem and I can't find a solution of it anywhere. class Blog(models.Model): title = models.CharField(max_length=100, blank=True, default='') description = models.TextField(max_length=1500) created = models.DateTimeField(auto_now_add=True) owner = models.ForeignKey('auth.User', related_name='blog', on_delete=models.CASCADE, null=True) image = models.FileField(blank=True, null=True) votes = models.IntegerField(default=0) def upvote(self, user): try: if UserVote.objects.filter(user=user, blog=self, vote_type='down').exists(): self.post_votes.update(user=user, blog=self, vote_type='up') self.votes += 2 else: self.post_votes.create(user=user, blog=self, vote_type='up') self.votes += 1 self.save() except IntegrityError: return 'already_voted' return 'ok' def downvote(self, user): try: if UserVote.objects.filter(user=user, blog=self, vote_type='up').exists(): self.post_votes.update(user=user, blog=self, vote_type='down') self.votes -= 2 else: self.post_votes.create(user=user, blog=self, vote_type='down') self.votes -= 1 self.save() except IntegrityError: return 'already_voted' return 'ok' class UserVote(models.Model): user = models.ForeignKey('auth.User', related_name='user_votes', on_delete=models.CASCADE) blog = models.ForeignKey(Blog, related_name='post_votes', on_delete=models.CASCADE) vote_type … -
Form filter - Unsupported lookup 'gte' for FloatField
I'm trying to make a FormFilter. I have in my model something like: class TabelaPrecoItem(models.Model): [...] preco = models.FloatField() . My FormFilter: class TabelaItemProdutosFilter(django_filters.FilterSet): preco__gte = django_filters.NumberFilter(lookup_expr='gte') preco__lte = django_filters.NumberFilter(lookup_expr='lte') class Meta: model = TabelaPrecoItem fields = ['preco__gte', 'preco__lte'] And when I fill the inputs and search I get the following error: Unsupported lookup 'gte' for FloatField or join on the field not permitted. I didn't find anything that can helps me. I already tried to use NumericRangeField, but I don't know how to put it in 2 different inputs on template. -
How to retrieve data from related Models?
I am new to Django and I am trying to create a site to manage class information for example students and their statistics. When I click a class I can see the details of the class and which students are in this class. However, I want to have also an average score of every student but I don't know how to retrieve the data from my Statistics Model. I tried select_related but didn't work. Thank you in advance. My models .py file: class Classes(models.Model): name = models.CharField(max_length=256) day_and_time= models.CharField(max_length=256) def __str__(self): return self.name def get_absolute_url(self): return reverse("classesapp:class_detail", kwargs={"pk": self.pk}) class Students(models.Model): name = models.CharField(max_length=256) student_class = models.ForeignKey( Classes, related_name = 'students', on_delete=models.SET_NULL, null=True ) def __str__(self): return self.name def get_absolute_url(self): return reverse("classesapp:student_detail", kwargs={"pk": self.pk}) class Statistics(models.Model): student= models.ForeignKey( Students, related_name='statistics', on_delete=models.CASCADE, null=True ) date = models.DateField(blank=True, null=True) dictation_score = models.FloatField() writing_score = models.FloatField() test_score = models.FloatField() grammar_score = models.FloatField() in_class_performance = models.FloatField() class Meta: ordering = ["-date"] def get_absolute_url(self): return reverse("classesapp:classes_list") My views .py file: class ClassesDetailView(DetailView): stats = models.Students.objects.select_related('statistics') context_object_name = "class_detail" model = models.Classes template_name = "classesapp/class_detail.html" What I want to do: Image from the site what I want to do -
Python venv not creating virtual environment
I'm trying to create a virtual environment for my current Django project using python3 -m venv env however the command doesn't create any directory with bin/include/lib folders. What exactly am I missing here? -
how to access django static folder on virtualmin
I am trying to deploy django website on virtualmin panel.i uploaded my django website into filemanager.if i am trying to access my django website,it shows contents without accessing static folder.how do i access static folder?Any help is appreciated. -
How can write a unit test for the code which is having a autofield value as primary key in django
I am new to testing please help and thanks in advance BackupRequestmodel class BackupRequest(models.Model): request_no = models.ForeignKey(AllRequest, on_delete=models.CASCADE) requirement = models.CharField(max_length=49) backup_type = models.CharField(max_length=49) purpose = models.CharField(max_length=150, null=False) department = models.ForeignKey(Department, on_delete=models.CASCADE) location = models.ForeignKey(Location, on_delete=models.CASCADE) def __str__(self): return self.request_no.__str__() How to write a unit test for this model the dependent models are given bellow AllRequestModel class AllRequest(models.Model): form_type = models.ForeignKey(RequestType, related_name='requests', default=None, on_delete=models.CASCADE) request_no = models.AutoField(max_length=50, default=None, primary_key=True, ) status = models.IntegerField(default=0) requested_by = models.CharField(max_length=50, blank=False, default='') requested_on = models.DateTimeField(auto_now_add=True, editable=False) updated_by = models.CharField(max_length=50, blank=False, default='') updated_on = models.DateTimeField(auto_now_add=True, editable=True) def __str__(self): return str(self.request_no) RequestTypeModel class RequestType(models.Model): name = models.CharField(max_length=150) -
Why static files not loaded when im using slug in url?
When im using slug in my url, the .html files wont load the static files. I've already declared the static folder as "assets" and the rest of the 'templates'(the .html file) are good. but when it comes to example : "127.0.0.1:8000/edit_audio/2/" the edit_audio.html wont load my static files but when i access "127.0.0.1:8000/edit_audio" the html files works fine with the static css files this is my static configuration on settings.py STATIC_URL = '/assets/' STATICFILES_DIRS = [ os.path.join(BASE_DIR,'assets'), ] This is on urls.py urlpatters = [ url(r'^edit_audio_upload/(?P<pk>\d+)/$',views.edit_audio_upload, name='edit_audio_upload'), ] urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) This is the href link from other html {% for audio in data3 %} <a href="{{ audio.get_absolute_url }}"> <button type="button" class="btn btn-success waves-effect waves-light" data-toggle="" data-target=""><span class="mdi mdi-pencil"></span></button> </a> {% endfor %} This is the models.py class Audio(models.Model): #some atributes declaration def get_absolute_url(self): return "/edit_audio_upload/%s/"%(self.id) -
Django social auth Google Auth canceled
I am trying to use social auth in Django with Google. and i am getting the following error. AuthCanceled at /catalog/^oauth/complete/google-oauth2/ Authentication process canceled Request Method: GET Request URL: http://127.0.0.1:8000/catalog/%5Eoauth/complete/google-oauth2/?state=3FwzA2UbNRram1e2bKqgvIcqEZVBUhSr&code=4%2FrQEexCHB7NtsonIttQm06uiSW0sygmGq7ZOTF9dWF4goCMZ3z57qD05bXCZ1l-PCQOCigFD63Zu5e292VT54WGk&scope=email+profile+openid+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.email+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.profile&authuser=0&session_state=764d828d122f96666600d89286108f374b1c057b..5f2c&prompt=consent Django Version: 2.2.2 Exception Type: AuthCanceled Exception Value: Authentication process canceled Exception Location: C:\Users\sdixit23.EAD\Envs\my_django_environment\lib\site-packages\social_core\utils.py in wrapper, line 254 Python Executable: C:\Users\sdixit23.EAD\Envs\my_django_environment\Scripts\python.exe Python Version: 3.7.3 Python Path: ['C:\Users\sdixit23.EAD\Dropbox\Programming Guru ' 'DXC\WebAppDev\django_projects\glacier', 'C:\Users\sdixit23.EAD\Envs\my_django_environment\Scripts\python37.zip', 'C:\Users\sdixit23.EAD\Envs\my_django_environment\DLLs', 'C:\Users\sdixit23.EAD\Envs\my_django_environment\lib', 'C:\Users\sdixit23.EAD\Envs\my_django_environment\Scripts', 'c:\users\sdixit23.ead\appdata\local\programs\python\python37-32\Lib', 'c:\users\sdixit23.ead\appdata\local\programs\python\python37-32\DLLs', 'C:\Users\sdixit23.EAD\Envs\my_django_environment', 'C:\Users\sdixit23.EAD\Envs\my_django_environment\lib\site-packages', 'C:\Users\sdixit23.EAD\Envs\my_django_environment\lib\site-packages\odf', 'C:\Users\sdixit23.EAD\Envs\my_django_environment\lib\site-packages\odf', 'C:\Users\sdixit23.EAD\Envs\my_django_environment\lib\site-packages\odf', 'C:\Users\sdixit23.EAD\Envs\my_django_environment\lib\site-packages\odf', 'C:\Users\sdixit23.EAD\Envs\my_django_environment\lib\site-packages\odf', 'C:\Users\sdixit23.EAD\Envs\my_django_environment\lib\site-packages\odf', 'C:\Users\sdixit23.EAD\Envs\my_django_environment\lib\site-packages\odf'] Server time: Thu, 26 Sep 2019 13:01:30 +0100 -
Explanation needed with Django and AMP logic using 1 url
I'm using AMP at one of my parts of the website with Django template and python, my question is what will happen to a page (*SEO wise) if I take and break an AMPed page (only on desktop) and leave the page AMPed on mobile?! To be more specific, I have made a full AMP page for both mobile and desktop which use the url (/example-amp-url) and now I need to add a widget to the page which is rendered with js and not AMPed at all but render it only on desktop. Any one knows how it would impact on my SEO? Because for now in my site-map this page is AMPed both on mobile search and on desktop page (if Im losing the AMP on desktop it is fine but if I lose both its a huge problem thats why Im afraid to test it) -
DetailedView and expiring items not working in Django
I'm working on a simple application, where elements should expire automatically after 5 minutes. In models.py I have the following: from django.utils import timezone def calc_default_expire(): return timezone.now() + timezone.timedelta(minutes=5) class MyModel(models.Model): uploaded_at = models.DateTimeField(auto_now_add=True) expire_date = models.DateTimeField(default=calc_default_expire) ... In my views.py, I have the following: from django.views.generic import DetailView from .models import MyModel from django.utils import timezone class MyModelDetail(DetailView): model = MyModel queryset = AppFile.objects.filter(expire_date__gt=timezone.now()) I'm getting some strange behaviour. Even after 5 minutes, when I call the url of the expired item, it still gets returned (http code 200). However, when I restart the builtin django dev server, and call the url again, I'm getting a 404, which is the desired result. I see two possible causes: the built-in webserver is caching some stuff (I doubt this to be honest, I could not find anything in the docs that mentions this behaviour) I'm doing something wrong in my queryset filter (but I'm not seeing it). Expire_date seems to be calculated correctly when I add new items. Anyone got a clue what I'm missing here? USE_TZ = True in my settings.py BTW. -
CORS problems in Vue Axios frontend and Django Rest API backend
Repository with the project I am getting information about blocked access by CORS policy and none of the solutions I looked at seemed to be working. Access to XMLHttpRequest at 'http://localhost:8000/search' from origin 'http://localhost:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. My server is hosted locally on localhost:8000 and frontend is on loacalhost:8080. I want to post text data in Vue with Axios in file: store.js%43:56 : axios.post('http://localhost:8000/search', { queryText: 'TEST_TEXT' }).then(function (response) { // handle success console.log(response) }).catch(function (response) { // handle error console.log(response) }) the backend is written in Django with Rest API. I followed those instructions but the response is still the same. The view responsible for the response is here and settings were set up here I do not want to: Disable web security in Chrome Use JSONP Use a third party site to re-route my requests If anyone would like to run the project just install requirements.txt from main folder and follow README from main and frontend folders. -
How to add(sync) separate django user in LDAP groups?
Env: python - 3.6.6 django - 2.x.x django-auth-ldap - 2.0.0 python-ldap - 3.2.0 Explanation: E.g. there is a user in django DB, which was synced from LDAP by following code (taken from this answer): from django_auth_ldap.backend import LDAPBackend # in settings.py AUTH_LDAP_MIRROR_GROUPS is enabled ldap_backend = LDAPBackend() ldap_backend.populate_user('username') User is created in django DB and groups are similar as in LDAP. After that this user was added(or removed) into group: user.groups.add(some_group) # this group exists in LDAP too # or for example remove user from group Question: How to sync this ralation between User and Group from django to LDAP? PS: I tried to find something useful in django_auth_ldap.backend.LDAPBackend and django_auth_ldap.backend._LDAPUser but didn't find anything for backward sync. -
Django: open PDF file object
in my Django app I´m trying to open and show pdf files that wasn´t loaded to a model, but can´t find the appropiate way. I have a group of PDF invoices that I manualy copied to media/my_folder (I use Dropbox as media host to be able to do that). Then I want to show each invoice when requested. After investigating several posts, I think the way to do it is creating a file object dinamycaly. invoice_path = "my_folder/" + invoice_number + ".pdf" f = open(invoice_path, 'w') myfile = File(f) Then I understand the in the template I could be able to access the file as it was loaded to the model. <p><a href="{{ myfile.url }}" target="_blank">Ver factura AFIP</a></p>7 I get a FileNotFoundError, I guess I´m not setting the path to media files correctly. Any clues? Thanks! -
How to use is_superuser in the django models
I want to override from_db_value in the Field class, I want if the user was a superuser the value will be returned completely otherwise the value has special format. how can I use is_superuser in this purpose? class Foo(models.CharField): def from_db_value(self, value, expression, connection): if is_superusers: return value else: return "----" -
Realizing rating in django
What is a better way of realizing rate field in model. Now I have this one: class Story(models.Model): ... rate = models.(help here) class Rating(models.Model): rate = models.FloatField(validators=[MinValueValidator(0.0), MaxValueValidator(10.0)]) story = models.ForeignKey(Story, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) Or there is another way of doing this? -
Django fixture error: unable to add integer
I am trying to run django fixture. unable to add integer field in the database. As well choice field only adding whatever set in default in model. Fixture JSON eg: { "model": "alert_engine.BaseAlert", "fields": { "created_ts": "2019-03-17T14:05:59.402Z", "update_ts": "2019-03-17T14:05:59.402Z", "name": "running", "category": "activity", "ttl": 2 } } Model: class BaseAlert(BaseModel): name = models.CharField(_("Alert Name"), max_length=30, unique=True) category = models.CharField(_("Alert Category"), max_length=30, choices=ALERT_CATEGORIES,default="activity") ttl = models.IntegerField(_("Alert ttl"), blank=True, null=True) Table in db looks like: +----------------------------------+----------------------------+----------------------------+---------------------------+--------------+------+ | id | created_ts | update_ts | name | category | ttl | +----------------------------------+----------------------------+----------------------------+---------------------------+--------------+------+ | 49e1990b91b94fb4b4af6858b352e6f4 | 2019-09-26 16:25:58.147321 | 2019-09-26 16:25:58.147337 | running | activity | NULL | | c264b4a8ad584f69bfa8a648493b6a28 | 2019-09-26 16:25:58.144618 | 2019-09-26 16:25:58.144636 | walking | activity | NULL | | f001dc3b567f4178a0fd03a36c8b5a4c | 2019-09-26 16:25:58.145954 | 2019-09-26 16:25:58.145969 | running | activity | NULL | 'ttl' field is showing NULL, expected some integer value eg: 2 and category field showing 'activity'everytime, even in fixture json have different category -
Django - Accessing Images from Foreign Key Field
Im trying to make a seperate Image model to save all of my pictures for the Articles model. I have created the Image Model with the foreign key to my Article model. After doing that, I am stuck, I'm trying to get the pictures for each article to render for the relevant article, but I'm not making any progress. Anyone with a few spare minutes to help ? Thank you !!! my view: class ArticlesView(generic.ListView): context_object_name = 'latest_article_list' template_name = 'news/articles.html' paginate_by = 5 def get_context_data(self, **kwargs): context = super(ArticlesView, self).get_context_data(**kwargs) context['categories'] = Category.objects.all() return context def get_queryset(self): category_pk = self.request.GET.get('pk', None) if category_pk: return Article.objects.filter(article_category__pk=category_pk).order_by("-pub_date") return Article.objects.order_by("-pub_date") my models : class Article(models.Model): title = models.CharField('title', max_length=200, blank=True) slug = AutoSlugField(populate_from='title', default="", always_update=True, unique=True) author = models.CharField('Author', max_length=200, default="") description = models.TextField('Description', default="") is_published = models.BooleanField(default=False) article_text = models.TextField('Article text', default="") pub_date = models.DateTimeField(default=datetime.now, blank=True) article_category = models.ForeignKey(Category, on_delete="models.CASCADE", default="") def __str__(self): return self.title class ArticleImages(models.Model): article = models.ForeignKey(Article, on_delete="models.CASCADE", related_name="Images") image = models.ImageField("Image") and the template i'm trying to render the images in : <section class="container post-details-area"> <div class="container single-article-div"> <hr class="hr-single"> <h2 id="article-title" class="single-article-titles">{{ article.title }}</h2> <hr class="hr-single"> <img class="single-article-img" src="{{ article.article_image.url }}" alt=""> <!-- *********************************** --> <hr … -
Django-filter 'icontains' isn't passing to my URL
I'm using the 3rd-party Django-filter to make a search bar for my blog posts. import django_filters from .models import Post class PostFilter(django_filters.FilterSet): title = django_filters.CharFilter(field_name='title') class Meta: model = Post fields = { 'title': ['icontains'], } I read that CharFilter and TextFilter default to exact however i thought i was changing that below. I've tried contains and icontains. The search is passing to the url such as: "...blog/?title=foo". I've manually typed the ".../blog/?title__icontains=foo" url and this works, however the working url is not the url is that is being passed once i click my search button. Any help would be appreciated, thanks. -
How to save list of objects using bulk_update method in Django?
I have a loop iterating over objects and adding them to the list f or note in notes: old_note = Note( user_id=note['id']), author=note['author'], ) existing_notes.append(old_note) Worklog.objects.bulk_update( existing_notes, [ 'user_id', 'author', ], batch_size=1000) but it's not working as i wish it should. When i run my script with celery task in django , it's kinda crashing. PLease help guys , if any is capable to show my mistake. My final goal is to add all objects i need into list and update them in database at once, cause i have really a lot of data -
I want to get the list of all the employees that are registered with the company along with their designation
I am working on a model and I want to get the details of the employees in an organization along with their designations. I cannot think of anything at this point of time. This is my first time asking a question here so any help would mean a lot and if I havent provided the exact details please tell me. I think these should be sufficient enough for the answe. Here is my organization and userorgdetail models: class Organization(models.Model): id = models.IntegerField(primary_key=True) name = models.CharField(max_length=256) employees = models.ManyToManyField(InSocialUser, related_name='organizations', blank=True, through="UserOrgDetail") description=models.TextField(blank=True) class UserOrgDetail(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) user = models.ForeignKey(InSocialUser, related_name='org_details', on_delete=models.CASCADE) org = models.ForeignKey(Organization, related_name='employee_details', on_delete=models.CASCADE) designation = models.CharField(max_length=256) REQUIRED_FIELDS = ['user','org'] Here is my serializers file: class OrgSerializer(serializers.ModelSerializer): class Meta: model = Organization fields = ('id','name','employees') class UserOrgDetailSerializer(serializers.ModelSerializer): class Meta: model = UserOrgDetail fields = '__all__' class UserOrgDetailReadSerializer(UserOrgDetailSerializer): user = serializers.PrimaryKeyRelatedField(read_only=True) org = OrgSerializer(read_only=True) views.py class OrganizationAPIView( mixins.CreateModelMixin, generics.ListAPIView): permission_classes = [permissions.IsAuthenticatedOrReadOnly] serializer_class = OrgSerializer filter_backends = [filters.OrderingFilter,filters.SearchFilter] search_fields = ['name'] ordering_fields = ['name'] ordering = ['name'] queryset = Organization.objects.all() def post(self, request, *args, **kwargs): return self.create(request, *args, **kwargs) def perform_create(self, serializer): serializer.save() class UserOrgDetailAPIView( mixins.CreateModelMixin, generics.ListAPIView): permission_classes = [permissions.IsAuthenticated] serializer_class = UserOrgDetailReadSerializer filter_backends = [filters.OrderingFilter,filters.SearchFilter] … -
How to display a variable in a template?
drf class ShipmentViewSet(viewsets.ModelViewSet): queryset = Shipment.objects.all() serializer_class = ShipmentSerializer def get_renderer_context(self): context = super().get_renderer_context() action = self.action if (action == 'retrieve'): context['shipments'] = Shipment.objects.all() elif (action == 'list'): print(6) context['foo'] = 'bar' return context vue.js <template> <div> <h1>Shipments list</h1> {{ foo }} </div> </template> <script> import $ from 'jquery' export default { name: "shipment_list", created() { this.loadShipments() }, methods: { post_create() { $.ajax({ url: 'http://127.0.0.1:8001/shipments/', type: 'POST', data: {}, dataType: 'jsonp', success: (response) => { console.log(response) }, error: (response) => console.log(response) }) }, loadShipments() { $.ajax({ type: 'GET', url: 'http://127.0.0.1:8001/shipments/', dataType: 'jsonp', success: (response) => { console.log(response) }, error: (response) => { console.log('error') console.log(response) } }) } } }; </script> I need to display the foo variable in the template. To do this, I overridden the get_renderer_context method and the variable is there. But when rendering the page I get error Property or method "foo" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property. Also I get next response {readyState: 4, getResponseHeader: ƒ, getAllResponseHeaders: ƒ, setRequestHeader: ƒ, overrideMimeType: ƒ, …} abort: ƒ ( statusText ) always: ƒ () catch: … -
Form receives old data from model
I have form which should receive it initial value from the latest entry stored in models. However if I edit or delete model data through admin panel, initial data displayed in the form remains the same old one (despite the fact that it is deleted in models). I am baffled what I am doing wrong. At first I thought that its Chrome who saves old data, but it remains the same after resting it with ctr+shift+r. My forms.py: from stv.models import BazineKaina, class DrgSkaiciuokle(forms.Form): bazine_kaina = forms.DecimalField(max_digits=5, decimal_places=2, required=True, label="Įveskite bazinę kainą:", initial= BazineKaina.objects.latest('data'), ) def clean_bazine_kaina(self): bazine_kaina = self.cleaned_data['bazine_kaina'] return bazine_kaina My models.py: class BazineKaina(models.Model): bazka = models.DecimalField(max_digits=5, decimal_places=2) data = models.DateField(auto_now=False, auto_now_add=True) def __str__(self): return str(self.bazka) class Meta: verbose_name_plural = "Bazinė kaina" get_latest_by = 'data' Please help me to find out why old data is still received by form? EDIT: I found out, that if I restart the server data will be refreshed, but that cant be solution in production. How to make form get new data every time its called?