Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django's REST framwork Quickstart Error
I followed all the steps from the tutorial here. But when I try to run the server I get the following error further down. Since I am new to django i am unsure where to start to debug. The full console output can be found Here Unhandled exception in thread started by <function wrapper at 0x7f4e9dc9c7d0> Traceback (most recent call last): File "/home/user/Projects/djangoApi/tutorial/env/local/lib/python2.7/site-packages/django/utils/autoreload.py", line 228, in wrapper fn(*args, **kwargs) ..... ValueError: Empty module name -
Django date picker range Javascript post
i'm trying to user Date Picker Range from http://www.daterangepicker.com/ and i have this on my html: <script type="text/javascript"> $(function() { $('input[name="daterange"]').daterangepicker({ locale: { format: 'DD/MM/YYYY ' }, ranges: { 'Hoy': [moment(), moment()], 'Ayer': [moment().subtract(1, 'days'), moment().subtract(1, 'days')], 'Ultimos 7 dias': [moment().subtract(6, 'days'), moment()], 'Ultimos 30 dias': [moment().subtract(29, 'days'), moment()], 'Este Mes': [moment().startOf('month'), moment().endOf('month')], 'Mes pasado': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')] } }); $(window).scroll(function() { if ($('input[name="daterange"]').length) { $('input[name="daterange"]').daterangepicker("close"); } }); }); </script> <form action="{% url 'subestados' %}" method="post"> <div class="col-md-3 mb-3"> <label>Rango: </label> <input type="text" name="daterange" class="form-control"/> </div> </form> my urls.py: url(r'^subestados/$',se.tabla, name='subestados'), url(r'^subestados/(?P<yearb>[0-9]{4})/(?P<monthb>[0-9]{2})/(?P<dayb>[0-9]{2})/(?P<yearf>[0-9]{4})/(?P<monthf>[0-9]{2})/(?P<dayf>[0-9]{2})/$',se.tabla, name='subestados'), I've seen other post about this, but i can't find a solution that works for me, i understand there is a ajax method to make the post but i don't know how to implement it: $.ajax({ url:'/', type : "POST", data: {start : 'start', end : 'end'}, success: function(response){}, complete: function(){}, error: function(xhr, textStatus, thrownError){} }); The javascript works i can see the calendar and all the options but can't find the way to do what i want. Any clues about this ? -
SyntaxError at django with Apache and wsgi
This is error_log file of httpd when running the django app File "/var/www/html/mailqenv/lib/python3.4/site-packages/celery/utils/functional.py", line 11, in <module> [Tue Nov 28 21:26:18.349280 2017] [:error] [pid 3665] [remote 41.187.94.200:84] from kombu.utils.functional import ( [Tue Nov 28 21:26:18.349296 2017] [:error] [pid 3665] [remote 41.187.94.200:84] File "/var/www/html/mailqenv/lib/python3.4/site-packages/kombu/utils/__init__.py", line 5, in <module> [Tue Nov 28 21:26:18.349322 2017] [:error] [pid 3665] [remote 41.187.94.200:84] from .compat import fileno, maybe_fileno, nested, register_after_fork [Tue Nov 28 21:26:18.349333 2017] [:error] [pid 3665] [remote 41.187.94.200:84] File "/var/www/html/mailqenv/lib/python3.4/site-packages/kombu/utils/compat.py", line 29, in <module> [Tue Nov 28 21:26:18.349350 2017] [:error] [pid 3665] [remote 41.187.94.200:84] from typing import NamedTuple [Tue Nov 28 21:26:18.349400 2017] [:error] [pid 3665] [remote 41.187.94.200:84] File "/var/www/html/mailqenv/lib/python3.4/site-packages/typing.py", line 133 [Tue Nov 28 21:26:18.349408 2017] [:error] [pid 3665] [remote 41.187.94.200:84] def __new__(cls, name, bases, namespace, *, _root=False): [Tue Nov 28 21:26:18.349412 2017] [:error] [pid 3665] [remote 41.187.94.200:84] ^ [Tue Nov 28 21:26:18.349416 2017] [:error] [pid 3665] [remote 41.187.94.200:84] SyntaxError: invalid syntax The conf file of httpd: Alias /static /var/www/html/mailqueue/static <Directory /var/www/html/mailqueue/static> Require all granted </Directory> <Directory /var/www/html/mailqueue/mailqueue> <Files wsgi.py> Require all granted </Files> </Directory> <Directory /var/www/html/mailqueue> Order deny,allow Allow from all </Directory> WSGIDaemonProcess mailqueue python-path=/var/www/html/mailqueue:/var/www/html/mailqenv/lib/python3.4/site-packages WSGIProcessGroup mailqueue WSGIScriptAlias / /var/www/html/mailqueue/mailqueue/wsgi.py` But if I activated my virtual environment and run with python manage.py … -
Angular V5 and Django rest framework, Hide and show the navigation
I am working on Angular V5 with Django rest framework. I am trying to hide the and show the button like Login or Logout using AuthService functionality. It is working fine when logged in but when I load or Refresh the page it is showing "Login" button again. My code snippets are as below. 1- AuthService.ts export class AuthService { public isLoggedIn: boolean = false; private headers: Headers = new Headers({'Content-Type': 'application/json'}); constructor(private http: Http, private common: CommonService) {} login(user): Promise<any> { var csrftoken = this.common.getCookies(); console.log('CommonService :: ',csrftoken); let url: string = '/login/'; this.headers.set("X-CSRFToken" , csrftoken); return this.http.post(url, user, {headers: this.headers}).toPromise(); } public isAuthenticated(): boolean { return this.isLoggedIn; } logout(): boolean { return this.isLoggedIn = false; } } export class LoginComponent implements OnInit { user: User = new User(); constructor( private router: Router, private auth: AuthService) { } ngOnInit() { } onUserLogin(): void { this.auth.login(this.user) .then((user) => { if (user.json().status === 'success') { localStorage.setItem('user', user.json().id); // localStorage.removeItem('user'); this.auth.isLoggedIn = true; this.router.navigate(['/profile']); } }) .catch((err) => { this.user['status'] = 'failed'; this.user['message'] = err.json().message; console.log('onUserLogin Post call Error ::', this.user); }); } } 3- header.html page <nav> <a routerLink="/">Dashboard</a> <a routerLink="/profile">My Account</a> <a routerLink="/contactus">Contact Us</a> <a routerLink="/admin" *ngIf="!auth.isLoggedIn">Admin</a> <a routerLink="/logout" *ngIf="auth.isLoggedIn" … -
Django get object after save in save_model
it's possible get the object in function save_model after its save. For example: def save_model(self, request, obj, form, change): o = super(CampaignAdmin, self).save_model(request, obj, form, change) # do something with "o" -
Prefetch on a one-to-many in Django not behaving as expected
I have a simple one-to-many relationship in Django, for example: class Team(models.Model): team_mascot = models.CharField( max_length=200, null=True) class Player(models.Model): first_name = models.CharField(max_length=200, null=True) last_name = models.CharField(max_length=200, null=True) team = models.ForeignKey( 'players.Team', blank=True, null=True, on_delete=models.SET_NULL, related_name='players', related_query_name='player', ) On the Player admin page(s), I want to display some information about the Team associated with that player if the player has a team, including information about other players on that team. I want to optimize this query with a prefetch for all the related players to the current players' team. This should be fairly simple, but I can't seem to get the right prefetch. Here's what I've tried: def prefetch_all_team_players(self): return self.prefetch_related( Prefetch('team__players', to_attr='all_team_players') ) and: def prefetch_all_team_players(self): return self.select_related('team').prefetch_related( Prefetch( 'team__players', to_attr='all_team_players' ) ) and: def prefetch_all_team_jobs(self): from myproj.players.models import Team team_queryset = Team.objects.all() return self.prefetch_related( Prefetch('team__players', to_attr='all_team_players', queryset=team_queryset) ) I'm using this on the appropriate admin page. However, all_team_players is not being populated as expected. I'm not getting any value. player.all_team_players.all() doesn't give me anything. The alternative is of course just using player.team.players.all() wherever I need it, which works. But I'm trying to gain performance with the prefetch. Any ideas on what I'm missing here? -
Allow just one domain in google auth in django
I need some help. I'm using google sing in in my django app, but i need to restrict the allowed domains. And i did not found any method to do this. The auth is working and all is already configured and working fine. Thanks in advance. -
Saving data from google map api to database in django
Hello I have got question what is the best way to save data from google map api in javascript to my MySQL database which I am using in Django project. Now I have got in forms museum name and museum category which i can save to my database and this is working, I want now to add option to add museum location to my database where User can search for this location and move marker directry on building where it is using google map api. The problem is I don't know how to save to my database position of lat and lng (x,y) and name of location where the marker was placed when user push Save button. My html page looks like this: {% extends 'base.html' %} {% block head_title %}Add museum | {{ block.super }}{% endblock head_title %} {% block content %} <h1>Add museum</h1> {% if form.errors %} {{ form.errors }} {% endif %} <form method="POST">{% csrf_token %} <input type="text" , name='name' , placeholder="Museum name"><br/> <input type="text" , name='category' , placeholder="Museum category"><br/> <div id="map"></div> <button type='Save'>Save</button> </form> <style> /* Always set the map height explicitly to define the size of the div * element that contains the map. */ … -
django 1.8 shell_plus stuck on importing 'logging.config'
I'm trying to upgrade my django 1.7.0 project to django 1.8. I've installed the new version, and am trying to run manage.py shell_plus. This appears to freeze. I've added a print statement in python2.7/importlib/__init__.py, and found that it's trying to import logging.config, and after this it appears to do nothing. I do not know how to fix this. -
Optional image input field's kicking me out of session
This problem has been puzzling me for few hours now. I'm designing an update profile page where user can update photo if user wishes. The problem is that when I leave the image input field blank and edit other fields and hit submit, nothing is changed and I get kicked out of session, on the other hand when I select an image to upload and hit submit everything is updated and function runs as I designed it. Here's relevant code: class User(models.Model): photo = models.CharField(max_length=100, null=False, blank=True) It's a Charfield 'coz I store only reference to the image in database. HTML: <input type="file" name='photo' class="form-control"> View: if request.method == 'POST': photo = request.FILES['photo'] if photo: fs = FileSystemStorage() filename = fs.save(photo.name, photo) uploaded_file_url = fs.url(filename) if uploaded_file_url[-4:] not in ALLOWED_EXTENSIONS: error = 'Invalid File Type' errors.append(error) print(uploaded_file_url) You can ignore the print statement. I spread bunch of those all over the this function so I can see how the function works at each stage. Thanks to this I was able to determine that when the file input field is left blank other code is no longer being processed and program exits out. But clearly the field is supposedly optional. I … -
UpdateView gives blank/empty forms instead of previous data I edit
I'm using UpdateView to edit data using forms. But, when I click edit button the forms are blank/empty without the previous data. I even added {% with server.id as server_id %} {% with forms.id as edit_form %} in my index.html.. Does anoyone have anyclue what I am missing? view.py- from django.shortcuts import render_to_response from django.shortcuts import get_object_or_404 from django.shortcuts import render, redirect from django.template import RequestContext from django.views.generic import TemplateView, UpdateView, DeleteView, CreateView from DevOpsWeb.forms import HomeForm from DevOpsWeb.models import serverlist from django.core.urlresolvers import reverse_lazy from simple_search import search_filter from django.db.models import Q class HomeView(TemplateView): template_name = 'serverlist.html' def get(self, request): form = HomeForm() query = request.GET.get("q") posts = serverlist.objects.all() if query: posts = serverlist.objects.filter(Q(ServerName__icontains=query) | Q(Owner__icontains=query) | Q(Project__icontains=query) | Q(Description__icontains=query) | Q(IP__icontains=query) | Q(ILO__icontains=query) | Q(Rack__icontains=query)) else: posts = serverlist.objects.all() args = {'form' : form, 'posts' : posts} return render(request, self.template_name, args) def post(self,request): form = HomeForm(request.POST) posts = serverlist.objects.all() if form.is_valid(): # Checks if validation of the forms passed post = form.save(commit=False) #if not form.cleaned_data['ServerName']: #post.servername = " " post.save() #text = form.cleaned_data['ServerName'] form = HomeForm() return redirect('serverlist') args = {'form': form, 'text' : text} return render(request, self.template_name,args) class PostDelete(DeleteView): model = serverlist success_url = reverse_lazy('serverlist') class PostEdit(UpdateView): … -
How to assign position in a queryset to a model parameter in Django for all objects in queryset
I am trying to create a waitlist for an app in Django. In order to do this, each user is assigned a waitlist_position number in their user profile. The profile model looks like this: from django.contrib.auth.models import User from django.db import models class Profile(models.Model): user = models.OneToOneField(User) referral_count = models.PositiveIntegerField(null=False, default=0) waitlist_position = models.PositiveIntegerField(null=False, default=0) The position of the user in the waitlist is determined by their date joined and the number of referrals they've made. Rather than calculate the waitlist position every time the user accesses the app, I thought it would be most efficient to update the positions once everyday as a scheduled task. In order to do that I can get the updated ordering in the following queryset: queryset = User.objects.order_by('-profile__referral_count', 'date_joined') The waitlist position field should be equal to the position of the user in that queryset. My question is, what is the most efficient way to assign this value? I know I could iterate through the queryset, update the value and then save each user (one by one) to the database, but that seems like an unnecessary number of DB calls... Is there a way to batch update but with different values? Or to iterate … -
Django: How to keep db structure without data after running tests?
I want to use the --keepdb option that allow to keep the database after running tests, because in my case, the creation of the dabatase takes a while (but running tests is actualy fast) However, I would like to keep the database structure only, not the data. Each time a run tests, I need an empty database. I know I could use tearDown method to delete each object created, but it is a tedious and error-prone way to do. I just need to find a way to tell Django to flush the whole dabatase (not destroy it) at the end of the unit tests. Is there an easy way to do it? Thanks! -
How does django-contrib-requestprovider work?
I found this middleware (django-contrib-requestprovider) in comments on SO, it was suggested to solve the problem of getting current request outside of views. The source code is very simple, but I can't understand, how the process_request function works (does it invokes every time, when request comes?), and how this middleware will work when django is run multithreaded. -
django chartit accumulate field values
I have a model like this class Match(models.Model): defender = models.ForeignKey(Player,...) attacker = models.ForeignKey(Player,...) time = models.DateTimeField(...) ratingChange = models.IntegerField(...) and I would like to make a graph which shows the absolute rating for a certain player with time. I understand that I get the corresponding matches by 'source': Match.objects.filter(Q(defender__name='myname) | Q(attacker__name='myname')) which works fine. However, the variable ratingChange just gives the change of rating during that match. I'd need to accumulate all the rating changes before passing them to the terms key of DataPool, something like np.cumsum('ratingChange'). Is that even possible with chartit? Here is the full DataPool object: matchdata = \ DataPool( series= [{'options': { 'source': Match.objects.filter(Q(defender__name='myname) | Q(attacker__name='myname'))}, 'terms': { 'Date':'time', 'Points':'ratingChange' } } ]) -
Django SplitDateTimeWidget
I'm trying to get the widget working on my form but for whatever reason, it ends up looking like a charfield. I've searched for related material, but I don't find anything current that says my code is wrong. What am I missing here? models.py class ServiceReportModel(models.Model): report_number = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) site = models.ForeignKey(customers_models.SiteModel, on_delete=models.PROTECT) request_number = models.ForeignKey(ServiceRequestModel, on_delete=models.PROTECT, null=True, blank=True, related_name='s_report_number' ) reported_by = models.ForeignKey(main_models.MyUser, related_name='reports') reported_date = models.DateTimeField(auto_now_add=True) updated_by = models.ForeignKey(main_models.MyUser, blank=True, null=True, related_name='+') updated_date = models.DateTimeField(auto_now=True) equipment = models.ForeignKey(customers_models.EquipmentModel, on_delete=models.PROTECT) report_reason = models.CharField(max_length=255, null=True) time_in = models.DateTimeField(blank=True, null=True) time_out = models.DateTimeField(blank=True, null=True) actions_taken = models.TextField(null=False, blank=False) recommendations = models.TextField(null=True, blank=True) def get_absolute_url(self): return reverse('service-report', kwargs={'pk': self.pk}) def __str__(self): return '%s - %s, %s' % (self.site.company, self.reported_date.strftime('%d %B %Y'), self.equipment.name) class Meta: ordering = ['reported_date'] verbose_name = 'Service Report' verbose_name_plural = 'Service Reports' forms.py class ServiceReportCreateForm(forms.ModelForm): time_in = forms.SplitDateTimeField(widget=SplitDateTimeWidget( date_format='%d/%m/%Y', time_format='%H:%M.%S')) time_out = forms.SplitDateTimeField(widget=SplitDateTimeWidget( date_format='%d/%m/%Y', time_format='%H:%M.%S')) class Meta: model = ServiceReportModel fields = [ 'site', 'request_number', 'reported_by', 'equipment', 'report_reason', 'actions_taken', ] widgets = { 'report_reason': forms.TextInput(attrs={ 'class': 'form-control', 'placeholder': 'Enter Reason for Service Report'}), 'actions_taken': forms.Textarea(attrs={ 'class': 'form-control', 'placeholder': 'To the best of your abilities, list all actions taken during service. Please include' + 'dates, times, and equipment … -
How to solve strange URL ERROR in Django?
I have form like this.. {% extends 'DATAPLO/base.html' %} {% load staticfiles %} {% block content %} <form action="/cholera/SeqData/result_page/" method="post"> <div style=" color: #1f5a09; margin: auto; margin-top: 10px; height: 15%; border: 1px solid green; box-sizing: border-box;background: #9fc36a; width: 100%"> <div style= "margin-left: 15px;"> <p style="color: #000000 "; > <b>Enter year range to explore seqence data country wise</b> </p> </div> {% csrf_token %} <div style= "margin-left: 5px; margin-right: 50px;margin-top: 2px"> <b>Start year:</b> {{ form.start_year }} </div> <div style= "margin-left: 13px; margin-right: 54px;margin-top: 2px"> <b> End year:</b> {{form.end_year }} </div> <div style= "margin-left: 17px; margin-right: 50px;margin-top: 2px"> <b>Country:</b> {{form.country }} </div> <div style= "margin-left: 75.5px; margin-right: 50px;margin-top: 5px"> <input type="submit" value="Submit"/> </div> </div> </form> {% endblock %} Views like this.. def input_form(request): if request.method == 'POST': form = InForm(request.POST) else: form = InForm() return render(request, 'SeqData/in_form.html', {'form': form}) def result_page(request): form = InForm(request.POST) if form.is_valid(): val1 = form.cleaned_data['start_year'] val2 = form.cleaned_data['end_year'] val3 = form.cleaned_data['country'] if val1 <= val2: IDs = SequenceDetails.objects.all().filter(country=val3).filter(year__range =[val1,val2]) return render(request,'SeqData/slider.html',{'IDs':IDs}) else: return render(request,'SeqData/ERROR.html',{'val1':val1, 'val2':val2}) project URL.py like this.. urlpatterns = [ url(r'^cholera/', include('table.urls'), name='cholera'), url(r'^cholera/', include('DATAPLO.urls')), url(r'^cholera/', include('SeqData.urls')), ] Application URL.py like this.. from django.conf.urls import url from . import views urlpatterns = [ url(r'^SeqData/$', views.input_form, name='input_form'), url(r'', … -
Whether serving HTML as a static file is recommended in Django?
We have AngularJS and Django based web app. The app will have different portals for a different type of users. Currently, whenever a user is logged in, depending on their user type the response will be a static HTML file.Once it is served the angular will make an API call to get the current user details and with that subsequent API calls will be made(When 403 occurs it is planned to close the session from angularjs and redirect the user to login/correct dashboard). Since the HTML is served as static all the static assets will be directly server(not via Django). We are also planning to use push notifications(django-channels). I want to understand whether the process followed is recommended? The other option is setting user variable in base Dashboard html(html response from a successful login) and depending on that user type variable angularjs will render the corresponding view within the dashboard html, api calls will also be made by accessing user variable set by Django in the base dashboard. I would like to understand the advantages and disadvantages of both these options and which is recommended. P.S I prefer option 2 -
Django FileUpload choice inside of a dropdown (ModelChoiceField)
Hi is it possible to put a choice inside of a dropdown and when it is clicked it will allow user to upload file, right now I have a dynamic dropdown built using ModelChoiceField but I want to add a choice that will allow the user to upload the file if they don't want to choose to use the default choices. Something like the one in the picture but when the '------------' choice is clicked it will pop up something that will allow user to upload file. Image example I've been looking for the answer but couldn't find one unfortunately. thanks. -
User Model Signal Call to flag a user in a table
I'm trying to solve a problem where a user logs in with their windows NT login and if they fall within a list of NT names in another table in the model / existing database table I'd like to flag them as a CFO by placing a 1 in the is_cfo field. Is it possible to do this way if not how would you solve this problem? The list of NTNames would be in the following model: class QvDatareducecfo(models.Model): cfo_fname = models.CharField(db_column='CFO_FName', max_length=100, blank=True, null=True) # Field name made lowercase. cfo_lname = models.CharField(db_column='CFO_LName', max_length=100, blank=True, null=True) # Field name made lowercase. cfo_ntname = models.CharField(db_column='CFO_NTName',primary_key=True, serialize=False, max_length=7) # Field name made lowercase. cfo_type = models.IntegerField(db_column='CFO_Type', blank=True, null=True) class Meta: managed = False db_table = 'QV_DataReduceCFO' My User model uses LDAP authentication and pulls the Users information from AD into the following model: class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(unique=True) username = models.CharField(max_length=7, unique=True) formattedusername = models.CharField(max_length=11, unique=True, primary_key = True) first_name = models.CharField(max_length=40) last_name = models.CharField(max_length=140) date_joined = models.DateTimeField(default=timezone.now) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_cfo = models.BooleanField(default=False) facility = models.CharField(max_length=140) officename = models.CharField(max_length=100) jobdescription = models.CharField(max_length=140) positioncode = models.CharField(max_length = 100) positiondescription = models.CharField(max_length=140) coid = models.CharField(max_length=5) streetaddress = models.CharField(max_length=140) title … -
How to dispalay icons of django site after deploying
Hello I recently deployed a django website on heroku and used aws to store my media and static files, the site was deployed successfully except i cant find the icons used by the template on production but those icons work locally what can i do to solve this. Thank you in anticipation of your favourable response -
Django - Save modelformset data to session in CBV
Goal: I'm trying to save modelformset data to session. I have a view where a same set of form fields need to be filled out for items chosen from a checkbox in a previous view. Problem: My modelformset somehow returns only the last set of inputs is passed after cleaned_data (but I can see all inputs in request.POST). I don't get validation or any kind of errors (If I switch the inputs, the input that was passing before does not pass cleaned_data) request.POST <QueryDict: {'form-TOTAL_FORMS': ['1'], 'form-INITIAL_FORMS': ['0'], 'form-MIN_NUM_FORMS': ['0'], 'form-MAX_NUM_FORMS': ['1000'], 'csrfmiddlewaretoken': ['#abbr', '#abbr', '#abbr'], 'form-0-pd_month': ['8', '5', '7'], 'form-0-pd_day': ['28', '28', '28'], 'form-0-pd_year': ['2017', '2017', '2017'], 'form-0-var': ['t1', 't2', 't3'], 'form-0-id': ['', '', '']}> cleaned_data {'pd': datetime.date(2017, 7, 28), 'var': 't3', 'id': None} I checked In a Django Formset being returned in a Post, all Forms are showing all fields changed even though none have Django save only first form of formset Django formset only adding one form Only last label input value being returned in Django and 100 more as well as Django doc but none of these work for me. Code: I pasted as minimal code as possible without compromising the big picture. views.py #checklist view … -
How to write a test case for this Django custom tag
Django version : v1.10 I found this answer in order to have a if-else tag to compare the request.path in Django templates https://stackoverflow.com/a/19895344/80353 from django import template from django.template.base import Node, NodeList, TemplateSyntaxError register = template.Library() class IfCurrentViewNode(Node): child_nodelists = ('nodelist_true', 'nodelist_false') def __init__(self, view_name, nodelist_true, nodelist_false): self.view_name = view_name self.nodelist_true, self.nodelist_false = nodelist_true, nodelist_false def __repr__(self): return "<IfCurrentViewNode>" def render(self, context): view_name = self.view_name.resolve(context, True) request = context['request'] if request.resolver_match.url_name == view_name: return self.nodelist_true.render(context) return self.nodelist_false.render(context) def do_ifcurrentview(parser, token): bits = token.split_contents() if len(bits) < 2: raise TemplateSyntaxError("'%s' takes at least one argument" " (path to a view)" % bits[0]) view_name = parser.compile_filter(bits[1]) nodelist_true = parser.parse(('else', 'endifcurrentview')) token = parser.next_token() if token.contents == 'else': nodelist_false = parser.parse(('endifcurrentview',)) parser.delete_first_token() else: nodelist_false = NodeList() return IfCurrentViewNode(view_name, nodelist_true, nodelist_false) @register.tag def ifcurrentview(parser, token): """ Outputs the contents of the block if the current view match the argument. Examples:: {% ifcurrentview 'path.to.some_view' %} ... {% endifcurrentview %} {% ifcurrentview 'path.to.some_view' %} ... {% else %} ... {% endifcurrentview %} """ return do_ifcurrentview(parser, token) Was wondering if there's a way to write test case to cover this custom code? I want to maintain our test coverage percentage -
Tests for DRF with MongoDB
I would like to ask about testing approach to DRF with MongoDB. I am interested in test my endpoints, but modules like APIRequestFactory() or APIClient() don't work with NoSQL database. Maybe someone knows how to test endpoint using some DRF module? Thanks in advance -
Django Form does not seem to be updating
I have a simple form that im updating via template, however when I hit the submit button, the content of the config text area looks to have updated, however if I refresh the page, the old content returns. im not sure if the code in the view is processing the changes correctly or not, am I missing something? Thanks @login_required @user_passes_test(lambda u: u.has_perm('config.can_change_configtemplate')) def edit_template(request, template_id): template = get_object_or_404(ConfigTemplates, pk=template_id) # create a new form form = EditTemplateForm(request.POST or None, instance=template) if form.is_valid(): form.save() return render(request, 'config/edit_template.html', { 'TemplateForm': form, }) template: <form id="edit_template" action="" method="post"> {% csrf_token %} <table> <tr> <td coslpan="2">{{ TemplateForm.template_name.label }}: {{ TemplateForm.template_name }}</td> </tr> <tr> <td> {{ TemplateForm.config.label }}: </br> {{ TemplateForm.config }} </td> <td> <h3>Variables:</h3> <ul class="variable"> {% for data in Variables %} <li>{{ data }}</li> {% if forloop.counter|divisibleby:25 %} </ul> <ul class="variable"> {% endif %} {% endfor %} </ul> </td> </tr> <tr> <td> {{ TemplateForm.remote_config.label }}: </br> {{ TemplateForm.remote_config }} </td> <td>&nbsp; </td> </tr> </table> <div class="update-footer"> <input type='submit' value='Update Template' /> </div>