Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django rest Framework : Behavior of a PrimaryKeyRelatedField with a nested representation
I have an API built with django rest framework. Here is the code : models.py class Ingredient(models.Model): barcode = models.CharField(max_length=13, primary_key=True) name = models.CharField(max_length=255) image = models.CharField(max_length=255) class Recipe(models.Model): name = models.CharField(max_length=255) favorite = models.BooleanField() owner = models.ForeignKey( 'auth.User', related_name="recipes", on_delete=models.CASCADE) class Component(models.Model): ingredient = models.ForeignKey(Ingredient, on_delete=models.CASCADE) recipe = models.ForeignKey( Recipe, related_name='components', on_delete=models.CASCADE) quantity = models.FloatField() serializers.py class IngredientSerializer(serializers.ModelSerializer): name = serializers.CharField(read_only=True) image = serializers.CharField(read_only=True) class Meta: model = Ingredient fields = '__all__' class ComponentSerializer(serializers.ModelSerializer): ingredient = serializers.PrimaryKeyRelatedField(queryset=Ingredient.objects.all()) # ingredient = IngredientSerializer() class Meta: model = Component fields='__all__' class RecipeSerializer(serializers.ModelSerializer): components = ComponentSerializer(many=True) owner = serializers.ReadOnlyField(source='owner.username') class Meta: model = Recipe fields = '__all__' With the code in this state, I can create a new component by selecting a existing ingredient, an existing recipe and entering a quantity. However, the serialization of the components is not nested : { "id": 8, "quantity": 123.0, "ingredient": "3218930313023" }, When I change the code to ingredient = IngredientSerializer() in the ComponentSerializer class, the representation is nested as intended : { "id": 9, "ingredient": { "barcode": "3218930313023", "name": "Crêpes L'Authentique", "image": "https://static.openfoodfacts.org/images/products/321/893/031/3023/front_fr.16.400.jpg", }, "quantity": 123.0 } But when I try to add a component with an existing recipe and an existing ingredient, I get … -
Django Rest Framework not filtering all filter_fields
i have this viewset: class CompanyViewSet(OwnerMixin, viewsets.ModelViewSet): queryset = company_models.Company.objects.all().order_by('-id') serializer_class = company_serializers.CompanySerializer mini_serializer_class = company_serializers.CompanyMiniSerializer # filtering search_fields = ('name', 'id', 'business_sector__business_sector', ) ordering_fields = ('name', 'id', 'business_sector__business_sector', ) filter_fields = ('follower', 'name', 'business_sector__business_sector', 'candidate__primary_skill__skill', 'candidate__business_sector__business_sector', 'client__primary_skill__skill', 'client__business_sector__business_sector') def get_serializer_class(self): try: obj = self.get_object() if obj: return self.serializer_class except: pass return self.mini_serializer_class def get_queryset(self): queryset = company_models.Company.objects.all().order_by('-id') name = self.request.query_params.get('name', None) if name is not None: queryset = company_models.Company.objects.filter(name__icontains=name) return queryset when i go to api/companies?follower=2 the filter works. for all the other query params it does not work. -
Unable to connect to the localhost/phpmyadmin database through my django project
I am trying to connect to the localhost/phpmyadmin through xampp server for my django project, and getting this error django.db.utils.OperationalError: (1044, "Access denied for user ''@'localhost' to database 'djangoproject'") When i type python manage.py runserver on my command prompt, im getting the above mentioned error. There is no password set on my phpmyadmin, it is just by default user 'root' and password [null] I have written the given below code in my manage.py file to connect to the database page. DATABASES = { 'default' : { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'djangoproject', 'USER': ' root ', 'PASSWORD': '', 'HOST': 'localhost', 'PORT':'' } } There is also this written in my phpmyadmin page on the top A user account allowing any user from localhost to connect is present. This will prevent other users from connecting if the host part of their account allows a connection from any (%) host. I do not understand what is wrong. kindly help. I am a beginner in django framework. -
Design Decision Django Rest Framework - Django as Frontend
I am currently developing my first more complex Web Application and want to ask for directions from more experienced Developers. First I want to explain the most important requirements. I want to develop a Web App (no mobile apps or desktop apps) and want to use as much django as possible. Because I am comfortable with the ecosystem right now and don't have that much time to learn something new that is too complex. I am inexperienced in the Javascript World, but I am able to do a little bit of jQuery. The idea is to have one database and many different Frontends that are branded differently and have different users and administrators. So my current approach is to develop a Backend with Django and use Django Rest Framework to give the specific data to the Frontends via REST. Because I have not that much time to learn a Frontend-Framework I wanted to use another Django instance to use as a Frontend, as I really like the Django Template language. This would mean one Django instance one Frontend, where there would be mainly TemplateViews. The Frontends will be served on different subdomains, while the backend exposes the API Endpoints on … -
NoReverseMatch errors during Django forgot password email system
I am trying to create a system for resetting forgotten passwords through email but am getting some errors. My urls are: from django.contrib.auth import views as auth_views urlpatterns = [ url(r'^$', auth_views.login, name='login'), url(r'^logout/$', auth_views.logout, name='logout'), ## more irrelevant urls here ## url(r'^password/reset/done/$', auth_views.PasswordResetDoneView.as_view(), name='password_reset_done'), url(r'^password/reset/$', auth_views.PasswordResetView.as_view(), name='password_reset'), url(r'^password/reset/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$', auth_views.PasswordResetConfirmView.as_view(), name='password_reset_confirm'), url(r'^password/reset/complete/$', auth_views.PasswordResetCompleteView.as_view(), name='password_reset_complete'), ] When the email address is submitted at password_reset, the email sends but I get this error: Internal Server Error: /password/reset/ Traceback (most recent call last): File "C:\python\lib\site-packages\django\core\handlers\exception.py", line 41, in inner response = get_response(request) File "C:\python\lib\site-packages\django\core\handlers\base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\python\lib\site-packages\django\core\handlers\base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\python\lib\site-packages\django\views\generic\base.py", line 68, in view return self.dispatch(request, *args, **kwargs) File "C:\python\lib\site-packages\django\utils\decorators.py", line 67, in _wrapper return bound_func(*args, **kwargs) File "C:\python\lib\site-packages\django\utils\decorators.py", line 149, in _wrapped_view response = view_func(request, *args, **kwargs) File "C:\python\lib\site-packages\django\utils\decorators.py", line 63, in bound_func return func.__get__(self, type(self))(*args2, **kwargs2) File "C:\python\lib\site-packages\django\contrib\auth\views.py", line 439, in dispatch return super(PasswordResetView, self).dispatch(*args, **kwargs) File "C:\python\lib\site-packages\django\views\generic\base.py", line 88, in dispatch return handler(request, *args, **kwargs) File "C:\python\lib\site-packages\django\views\generic\edit.py", line 183, in post return self.form_valid(form) File "C:\python\lib\site-packages\django\contrib\auth\views.py", line 453, in form_valid return super(PasswordResetView, self).form_valid(form) File "C:\python\lib\site-packages\django\views\generic\edit.py", line 79, in form_valid return HttpResponseRedirect(self.get_success_url()) File "C:\python\lib\site-packages\django\views\generic\edit.py", line 67, in … -
How can I use a bult-in validator in the general clean method or the clean method of a field;
I know I can call the validators in the field, but I want to call them in the clean() or clean_field method, because I want to use a combination of them and reuse them in multiple forms. So, I start from: def clean_description(self): description = self.cleaned_data['description'] MinLengthValidator(min_length,'Ensure that {} has at least {} characters.'.format(field_str,min_length))() return short_description but this doesn't work, the Validation Error is not raised. -
Pop groups from django admin UserChangeForm
I'm trying to remove the Groups section from django-admin UserChangeForm so I wrote the following. class MyUserChangeForm(EmailRequiredMixin, UserChangeForm): def __init__(self, *args, **kwargs): super(MyUserChangeForm, self).__init__(*args, **kwargs) self.fields.pop('groups') class EmailRequiredUserAdmin(UserAdmin): form = MyUserChangeForm add_form = MyUserCreationForm add_fieldsets = ((None, {'fields': ('username', 'email', 'password1', 'password2'), 'classes': ('wide',)}),) admin.site.unregister(User) admin.site.register(User, EmailRequiredUserAdmin) I get the following error and I do not know how to proceed. u"Key 'groups' not found in 'UserForm'. Choices are: date_joined, email, first_name, is_active, is_staff, is_superuser, last_login, last_name, password, user_permissions, username." Any help would be really appreciated. -
Python error while loading shared libraries: libpython3.5m.so.1.0: cannot open shared object file: No such file or directory
On my Fedora 25 I have configured the virtual environment with python 3.5 and after upgrading the system to Fedora 27 I cannot longer launch django app withing the virtual env (python manage.py runserver) neither check the version of the python: error while loading shared libraries: libpython3.5m.so.1.0: cannot open shared object file: No such file or directory Could you please advice what to do next? I'm not advanced user in terms of python configuration. Shall I reinstall python 3.5 or try to set up virtual environment once again? Any help greatly appreciated. -
Heroku failed to open json file and showed [error 2]: no such file or directory
guys. i had deployed a django app to Heroku. This app supposed to load the json file named "intent.json". It can run in local host without any error but it failed to run in Heroku. Below is the code: import json; with open('intents.json') as json_data: intents = json.load(json_data); Error from heroku log: FileNotFoundError: [Errno 2] No such file or directory: 'intents.json' However, i can run the server with heroku run bash command. Did anyone faced this problem before? -
How can I call multiple views in one url address in Django?
I'm trying to show forms defined by new_measurement on index.html, but I only manage to get IndexView() to work. I tried various combinations between IndexView() and new_measurement(), but those didn't work out at all. I know that IndexView() doesn't pass anything related to new_measurement(), and new_measurement() isn't called, which is the core of my problem. I'd really appreciate if someone more experienced with Django could tell me what I could, or should do. Thank you. Here's my views.py: from django.shortcuts import render from django.utils import timezone from .models import Measurement from .forms import MeasurementForm from django.views import generic class IndexView(generic.ListView): model = Measurement context_object_name = 'measurement_list' template_name = 'index.html' queryset = Measurement.objects.all() def new_measurement(request): if request.method == "POST": form = MeasurementForm(request.POST) if form.is_valid(): measurement = form.save(commit=False) measurement.measurement_date = timezone.now() measurement.save() else: form = MeasurementForm() return render(request, 'index.html', {'form': form}) urls.py: from django.urls import path from . import views urlpatterns = [ path('', views.IndexView.as_view(), name='index'), ] forms.py: class MeasurementForm(forms.ModelForm): class Meta: model = Measurement fields = ('measurement_value', 'measurement_unit') index.html: {% extends "base.html" %} {% block content %} <h1>Climate Measurement Tool</h1> <h2>Add a new measurement</h2> <form method="POST" class="post-form"> {% csrf_token %} {{ form.as_p }} <button type="submit" class="save">Add</button> </form> <h2>Measurements</h2> {% if measurement_list … -
Error with system for email password resets
I have been having trouble creating a system for resetting passwords using email. I encountered a problem yesterday which I was unable to solve: NoReverseMatch error with password reset emails After reading some of the relevant docs, I tried to replace the views with the class-based equivalents introduced in 1.11 as below: urls.py: from django.contrib.auth import views as auth_views urlpatterns = [ url(r'^$', auth_views.login, name='login'), url(r'^logout/$', auth_views.logout, name='logout'), ## more irrelevant urls here ## url(r'^password/reset/done/$', auth_views.PasswordResetDoneView, name='password_reset_done'), url(r'^password/reset/$', auth_views.PasswordResetView, name='password_reset'), url(r'^password/reset/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$', auth_views.PasswordResetConfirmView, name='password_reset_confirm'), url(r'^password/reset/complete/$', auth_views.PasswordResetCompleteView, name='password_reset_complete'), ] This has introduced a new error which is not very helpful: Internal Server Error: /password/reset/ Traceback (most recent call last): File "C:\python\lib\site-packages\django\core\handlers\exception.py", line 41, in inner response = get_response(request) File "C:\python\lib\site-packages\django\core\handlers\base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\python\lib\site-packages\django\core\handlers\base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) TypeError: __init__() takes 1 positional argument but 2 were given [11/Feb/2018 12:35:38] "GET /password/reset/ HTTP/1.1" 500 62168 How can I get my system working? -
How would I create my own filter?
I'm trying to query a subset of users based on certain conditions. Filtering by most conditions is relatively straightforward, but some are a bit more complex. For example, here is a function that I'm trying to incorporate into a query filter: def prefs_are_none(profile): none = True if profile.get_faves() or profile.get_choices(): none = False return none I'm not sure how to add that functionality into this query: user_list = Profile.objects.annotate( distance_away=Distance( 'last_location', current_user.last_location ) ).filter(last_location__distance_lte=( current_user.last_location, D(km=200) ), public=True, # additional filters would ideally go here) Here's the model for the Profile which clears up certain the methods used above(get_faves(), get_choices()): class Profile(models.Model): fave1 = models.CharField(max_length=54, blank=True, null=True, verbose_name='Learn A') fave2 = models.CharField(max_length=54, blank=True, null=True, verbose_name='Learn B') choice1 = models.CharField(max_length=54, blank=True, null=True, verbose_name='Teach A') choice2 = models.CharField(max_length=54, blank=True, null=True, verbose_name='Teach B') public = models.BooleanField(default=False, verbose_name='Public') last_location = models.PointField(null=True) objects = ProfileManager() def __str__(self): return self.user.username def get_faves(self): list_of_faves = [self.fave1, self.fave2] return [field for field in list_of_faves if field] def get_choices(self): list_of_choices = [self.choice1, self.choice2] return [field for field in list_of_choices if field] So essentially in the query I'm trying to check, through the get_faves() and get_choices() functions, that a profile does not have either empty--this is what's currently happening in … -
" Errno 13 Permission denied 'bnr_code.csv'"?
I have deployed a Django project on server using apache2 and wsgi, Its showing an error which I probably know that why its coming. Error: IOError at / [Errno 13] Permission denied: 'bnr_code.csv' Request Method: GET Request URL: http://93.188.167.63:8080/pep_learn/ Django Version: 1.10.8 Exception Type: IOError Exception Value: [Errno 13] Permission denied: 'bnr_code.csv' Exception Location: /home/pep_web/binaryDs/views.py in <module>, line 6 Python Executable: /usr/bin/python Python Version: 2.7.12 I have tried some slandered solutions which are available as given bellow: chmod 777 pep_web/ chmod 771 pep_web/ sudo chown :www-data pep_web/ But nothing is working This is the file which uses 'bnr_code.csv' AA = {"A":"1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0", "C":"0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0", "D":"0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0", "E":"0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0", "F":"0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0", "G":"0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0", "H":"0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0", "I":"0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0", "K":"0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0", "L":"0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0", "M":"0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0", "N":"0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0", "P":"0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0", "Q":"0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0", "R":"0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0", "S":"0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0", "T":"0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0", "V":"0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0", "W":"0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0", "Y":"0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1"} line = [] seqs = ["ATTTRY","ATSSRY"] def bnr(x): Des = [] for n in x: Des.append(AA[n.upper()]) des = ",".join(Des) return des def Des_write(ps): f = open("bnr_code.csv",'w') for p in ps: a = bnr(p) f.write(p+','+a+'\n') f.close() Des_write(seqs) Please help -
How to inherit from ForeignKey to extend model field?
I am trying to create a custom ForeignKey. I have inherited from it and trying to override __init__ method to provide the positional arguments to and on_delete like the following: from django.contrib.auth.models import User class CurrentUserField(models.ForeignKey): def __init__(self, **kwargs): super().__init__(User, models.CASCADE, **kwargs) class DemoModel(models.Model): owner = CurrentUserField() info = models.TextField() It gives me the following error when I am running makemigrations: TypeError: __init__() got multiple values for argument 'on_delete' I can't seem to figure out what the problem is. I am only providing two values for two positional arguments. -
Share objects between users in django
Guys i am very new to django, i have done research but most i have found does not exactly solve my problem . In my application, i want users to be able to share objects created by other users . For example model.py #This a model object users can share def BusinessObjects(models.Model): businessname=models.CharField(max-length=230) businesstype=models.CharField(max-length=230) creator=models.ForeignKey(Users,unique=True,on_delete=models.CASCADE) share=models.ManyToManyField(Users,related-name="sharer",null=True) So a user can create just one object of the businessObjects .And this object can be shared by other users .What is the best way possible to go about this . Creating a view, model which enable users to add objects created by other users .And these shared model objects will be added in to a list which i can pull out and display to the users . I will be very much grateful if you can help me out with hint to go about creating a good model and view to meet up my desire output .Thanks in advance -
IntegrityError:duplicate key value violates unique constraint "login_account_userprofile_user_id_key"
IntegrityError comes when user uploading the profile pic, on form.save() it gives error, here is the code (" ` " it is uses for formality at last of line) models.py class UserProfile(models.Model): user = models.OneToOneField(User)` image = models.FileField(upload_to ="profile_image")` def __str__(self): return self.user.username` forms.py class ProfilePicForm(ModelForm): class Meta: model = UserProfile fields = ("image",)` view.py def profile_pic(request): if request.method =="POST": form = ProfilePicForm(request.POST, request.FILES) if form.is_valid(): form.instance.user =request.user form.save() return redirect('/login/profile') else: args = {'form': ProfilePicForm()} return render(request, 'login_account/profile_pic.html',args)` -
django "class name" object is showing instead of name
I would like to change the default behavior of how the admin recent changes sidebar displays the name of "objects" added. In the recent actions module, it shows new objects as "MyModelName object" I would like to change how these are named in the Admin. Ideally, I would like to be able to change it from "MyModelName object" to, as object. I was thinking that str for my Profile model handled this, but it doesn't appear to. Any assistance is appreciated. from django.db import models # Create your models here. class profile(models.Model): name= models.CharField(max_length=120) description = models.TextField(default='description default text') def _str_(self): return self.name -
error while running python script inside django project
I have a python script inside my django project: import os, sys, django os.environ["DJANGO_SETTINGS_MODULE"] = "settings" sys.path.insert(0, os.getcwd()) sys.path.append('/home/alisoltanics96/ertasite/ertasite/ertaapp') django.setup() from ertaapp.models import Course def he(): dmes = Course.objects.all().filter() dmes = dmes.count() print(dmes) when I try to call he() gives me error: NameError: name 'Course' is not defined -
Site query does not exist .... Request URL http://127.0.0.1:8000/admin/login/?next=/admin/
i have done this .. from django.contrib.sites.models import Site >>> site = Site.objects.create(domain='example.com', name='example.com') but still getting error help me what to do i i m trying to access auth_views.login and admin python shell error.. C:\Users\MOIZ\Desktop\theme\fproject\fproject>python mannage.py runserver python: can't open file 'mannage.py': [Errno 2] No such file or directory C:\Users\MOIZ\Desktop\theme\fproject\fproject>python manage.py shell Python 3.6.3 (v3.6.3:2c5fed8, Oct 3 2017, 18:11:49) [MSC v.1900 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) >>> from django.contrib.sites.models import Site >>> Site.objects.create(name='example.com',domain='example.com') Traceback (most recent call last): File "C:\Users\MOIZ\Desktop\theme\fproject\fproject\env\lib\site-packages\djan go\db\backends\utils.py", line 64, in execute return self.cursor.execute(sql, params) File "C:\Users\MOIZ\Desktop\theme\fproject\fproject\env\lib\site-packages\djan go\db\backends\sqlite3\base.py", line 328, in execute return Database.Cursor.execute(self, query, params) sqlite3.IntegrityError: UNIQUE constraint failed: django_site.domain The above exception was the direct cause of the following exception: Traceback (most recent call last): File "<console>", line 1, in <module> File "C:\Users\MOIZ\Desktop\theme\fproject\fproject\env\lib\site-packages\djan go\db\models\manager.py", line 85, in manager_method -
How to write form validation that checks if an entered value is equal to an already saved value in the same model?
I am trying to build a way for a user to type in a "code" and if the code equals the same string as a value stored in a separate model field, then allow the form to save AND update a model boolean field called "registered". Here is my model: def random_key(size=25, chars=string.ascii_uppercase + string.digits): return ''.join(random.choice(chars) for _ in range(size)) class Keyreg(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) privKey = models.CharField(max_length=50, default=random_key, editable = False) pubKey = models.CharField(max_length=50, default='feedme123') registered = models.BooleanField(default=False) Here is my modelForm: class KeyregForm(forms.ModelForm): class Meta: model = models.Keyreg fields = ('pubKey',) def clean(self): cleaned_data = super(KeyregForm, self).clean() privKey = # data already saved in db... ? pubKey = cleaned_data.get('pubKey') if pubKey != privKey: raise forms.ValidationError("Your Registration Is Invalid.") return cleaned_data I am looking for pubKey (user input) to equal privKey. If pubKey == privKey, save the form AND change registered to TRUE. Any help would be awesome and thank you for your time. -
convert POSTGIS fetch record into GeoJson for display on map(Leaflet)
I have two tables: one is buffer table and the second one is uc_boundry table in postgis. I used raw query as : cursor.execute( "SELECT name,Tehsil,ST_AsGeojson(ST_INTERSECTION(p.geom,q.geom)) FROM buffer as p,uc_boundry as q WHERE ST_Intersects(p.geom, q.geom)" ) result = cursor.fetchall() This query define in view and also give fetch results but problem is that, fetched results is not in a proper geojson formate that support leaflet to show on a map. How to convert complete query results in geojson unless only geometry in json. -
Use sessions to count pageviews django detailview
I am trying to count the visits to a view. I would like for the counter to increment by 1 every time someone calls up the view. Then, I want the "visits" field on the model to automatically update with the latest count. However, I am not sure how to implement this. Using some code I've found, I am trying this: models.py class Statute(models.Model): address = models.ForeignKey(Address, null = True) statute_name = models.CharField(max_length=25, default='') category = models.CharField(max_length=55, default='') section_number = models.CharField(max_length=55, default='') section_title = models.CharField(max_length=255, default='') timestamp = models.DateTimeField(editable=False) visits = models.IntegerField(default=0) content = models.TextField(default='') slug = models.SlugField() views.py def get_context_data(self, **kwargs): context = super(LibraryInStateView, self).get_context_data(**kwargs) state = State.objects.get(slug=self.kwargs.get('state')) statute = Statute.objects.all() context['latest_statutes'] = statute.filter( address__zipcode__city__county__state=state).order_by( '-timestamp') context['statute_count'] = Statute.objects.filter( address__zipcode__city__county__state=state).count() context['view_count'] = self.request.session['views']+1 return context -
how to keep alive Angular 4 app?
In Angular 4 application button clicks are not working if the user is idle for sometimes. The user has to reload entire application to make it work again. How to keep it alive? I have simple code. my.component.html <button type="button" (click)="click_func(value)">demo</button> my.component.ts click_func(param1:string){ this._apiService.myapi(param1) .subscribe(res=>{if(res){this.somedata=res}}) } myservice.service.ts myapi(param1:string):Observable<any>{ return this._http.get(this.apiurl+'/'+param1) .map((response:Response)=>response.json()) } The API is written in Django. I am using SSO on the server to authenticate. -
import app name into project urls.py Django
I am building django app using python IDLE on Windows, how can I import app module into the urls.py? Because if I directly use the app name , e.g. accounts.urls, it gives me the error: name "accounts" is not difined. Thanks a lot! -
How to render image from jinja2 template?
I'm trying to render link image to website using jinja2 but nothing is printing in my website code: def esp(): a = [] m = Match('1122282') p = m.latest_batting p1=(p[1]['image_path']) print(p1) p2= 'http://www.espncricinfo.com' p3=urljoin(p2,p1) print(p3) a.append(p3) print(a) return(a) value of a is ['http://www.espncricinfo.com/db/PICTURES/CMS/263700/263765.1.jpg'] html code: <html> <body> <img class="team-logo" src=[a][0]> </body> </html> I can see only image box without any image in website how can I fix this ?