Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Get highest count and corresponding value in Django query
I have a patient model with "disease" as one of the fields. I want to count the top 5 diseases in all patient objects and return the counts for each of them. How could I do that? -
Send Email in Django From Gmail Account
In my settings.py file I have the following: ACCOUNT_EMAIL_VERIFICATION = "none" EMAIL_HOST = "smtp.gmail.com" EMAIL_HOST_USER = "thatotherbatman@gmail.com" EMAIL_HOST_PASSWORD = "supersecretstring" EMAIL_PORT = 587 EMAIL_USE_TLS = True Then I run python manage.py shell And do: from django.conf import settings from django.core.mail import send_mail send_mail("foo", "bar", settings.EMAIL_HOST_USER, ["otheruser@gmail.com"]) Which produces this: socket.gaierror: [Errno 8] nodename nor servname provided, or not known I've also enabled less secure apps in my google account. What am I doing wrong? -
Django Rest API, return json list of a model with only required fields - lambda did not work
In my Django Rest API, I have problem trying to do a query list and return json response based on the fields that I require (like just id, username instead of all in the model). One way is trying with lambda but it didnt work. This is a continuation for this: Django API list with pagination - Page is not JSON serializable I have an API query where I want to list model record of specific fields. For example (just id and username) instead of all the fields in the model. I am trying to use lambda to generate the json fields according to a helper function .as_dict() defined in the model. But it causes an error as show in the traceback below. Here is my function based rest API, see the lambda part at the bottom that is the problem: @api_view(['POST']) def employee_management_employee_get_list_by_page(request): # ----- YAML below for Swagger ----- """ description: employee_management_employee_get_list_by_page parameters: - name: token type: string required: true location: form - name: page type: string required: true location: form - name: page_limit type: string required: true location: form """ token = request.POST['token'] try: auth_employee = AuthEmployeeSessionToken.objects.get(token=token) except AuthEmployeeSessionToken.DoesNotExist: return Response("Invalid Token", status=status.HTTP_406_NOT_ACCEPTABLE) employee_list = Employee.objects.filter(company = … -
django authentication package: 'auth' not registered as a namespace
I'm trying to build a simple website with user authentication based on this tutorial, but I'm running into the above error. As per the instructions I set a url as folllows: url('^accounts/', include('django.contrib.auth.urls')) I got this error in response: 'auth' is not a registered namespace So I tried to register a namespace as the tutorial repo shows: url('^accounts/', include('django.contrib.auth.urls', namespace="auth")), then I get the error : Specifying a namespace in include() without providing an app_name I realised that the tutorial is using django 1.8.3, but I'm on 2.0. The issue is resolved when I switch to the same django version in virtualenv, but I'm now having to a change a number of other things across the project to keep it from breaking. Any way to fix without require django 1.8? Thanks. -
Temporary list of users that sent request
My scenario is like a game matchmaking, Django gets the users ID that wants to play and queue or cache them. then match those who are in queue together. How do i create a global list of users that requested to play, users can request with GET or POST method. How do i retrieve users from that global list? so i can match them together. -
Client Authentication in Django rest framework powered App using django-oauth-toolkit
I am creating a project in django for my mobile app. The django project is the API backend for the mobile App. I have created a signup for the user model using django rest framework. The signup API works fine. Now, i want to let only the request from my mobile app to be served. For this i created an oauth application Authorization grant type " client-credentials " class UserSerializer(ModelSerializer): email = serializers.EmailField( required=True, validators=[UniqueValidator(queryset=User.objects.all())] ) username = serializers.CharField( validators=[UniqueValidator(queryset=User.objects.all())] ) password = serializers.CharField(min_length=8) def create(self, validated_data): user = User.objects.create_user(validated_data['username'], validated_data['email'], validated_data['password']) return user class Meta: model = User fields = ('id', 'username', 'email', 'password') read_only_fields = ('id',) write_only_fields = ('password',) This is the user serializer and the view is class UserCreateAPIView(CreateAPIView): queryset = User.objects.all() serializer_class = UserSerializer permission_classes = (IsAuthenticatedOrCreate, TokenHasScope) But the problem is I can make direct calls to the signup api without using the toke. How to make sure that the User Create API is called when only the token is passed or the post request to be valid when the token is passed. -
ImportError: No module named 'datasets' while integrating with django
I'm trying to integrate inception_v3 inside my django app. I have cloned the repository https://github.com/tensorflow/models inside my django app. I have made a file test.py in which i'm importing the following: from .models.research.slim.datasets import dataset_utils when i'm running test.py from my terminal, i'm getting the desired output, but when running the command of runserver django is giving me error of ImportError: No module named 'datasets' the dataset folder is inside "models/research/slim" and the test.py file as well as the models folder are within my django app. website/myapp/test.py, models i'm using a ubuntu 16.04 OS with python3.5 -
Encoding Japanese/International characters on IIS7.5 with wfastcgi and Django website
I have a Django website set up with IIS7.5 and wfastcgi. Some of the data saved to the models is in Japanese. Everything works fine when locally using Django's runserver, but when using the IIS setup the Japanese characters are incorrectly encoded. For example, on the Django admin page when I try to edit the existing data with Japanese characters "test3種別" in one of the models I get the message: with ID "test3%8E%ED%95%CA" doesn't exist. Perhaps it was deleted? "test3%8E%ED%95%CA" is "test3種別" in Shift-JIS encoding. The database (sqlite3) is being searched for the correct id, wrongly encoded. I have set the web.config file to include <globalization fileEncoding="shift_jis" requestEncoding="utf-8" responseEncoding="utf-8" culture="ja-JP" uiCulture="ja-JP" /> but this hasn't fixed the problem. I've looked around for a solution with not much luck. Does anyone know how to solve this problem? Any help would be appreciated. -
Redis Server: "Cannot import BACKEND %r specified for %s"
When I run "redis-server" on one command prompt, it seems to work fine, but when I open another command prompt and start my Django project with "python manage.py runserver", I get this error: "Cannot import BACKEND %r specified for %s" % (self.configs[name]['BACKEND'], name) channels.asgi.InvalidChannelLayerError: Cannot import BACKEND 'asgi_redis.RedisChannelLayer' specified for default Does anyone know what it means? -
Django URL using javascript to get client end information
My problem that I am trying to resolve is that I made an Ajax-autocorrect input feature and "onclick" of a button I get the value inside that input and attempt to make the page redirect to a Django URL. Here is the URL inside my url.py file: url(r'^groups/add-member/(?:/(?P<pk_group>[-\w]+))?/(?:/(?P<pk_member>[-\w]+))?/$', views.add_member, name='add-member') inside the HTML I have this script: <script> function add_member(id){ var input=document.getElementById("myText").value console.log(id) //Correctly gets ID # console.log(input) //Correctly gets the name (string) of member instance url = "{% url 'add-member' 0 zzzz %}".replace('0', id).replace('zzzz',input); } </script> And the resulting error that I get is: Reverse for 'add-member' with arguments '(0, '')' not found. 1 pattern(s) tried: ['flexfeed/groups/add-member/(?:/(?P<pk_group>[-\\w]+))?/(?:/(?P<pk_member>[-\\w]+))?/$'] I'm having trouble understanding my error. If anyone could suggest how to fix this issue or possibly suggest a difdferent approach to this particular problem I'd really appreciate it! The end goal is that I want my page to redirect to my update view at the correct link! -
django 2.0 path aren't added
i use path instead of url in django 2.0 but there is a problem Following is my code oauth2_endpoint_views = ([ path('authorize/', oauth2_views.AuthorizationView.as_view(), name='authorize'), path('token/', oauth2_views.TokenView.as_view(), name='token'), path('revoke-token/', oauth2_views.RevokeTokenView.as_view, name='revoke-token'), ], 'oauth2') if settings.DEBUG: oauth2_endpoint_views += ([ path('application/', oauth2_views.ApplicationList.as_view(), name='list'), path('application/register', oauth2_views.ApplicationRegistration.as_view(), name='register'), path('application/<int:pk>/', oauth2_views.ApplicationDetail.as_view(), name='detail'), path('application/<int:pk>/delete/', oauth2_views.ApplicationDetail.as_view(), name='delete'), path('application/<int:pk>/update/', oauth2_views.ApplicationUpdate.as_view(), name='update'), path('authorized-tokens/', oauth2_views.AuthorizedTokensListView.as_view(), name='authorized-token-list'), path('authorized-tokens/<int:pk>/delete/', oauth2_views.AuthorizedTokenDeleteView.as_view(), name='authorized-token-delete'), ], 'oauth2') I added path, but i can't found path application, application/register ... how can i solve the problem? -
Django2.0:UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe5 in position 0: invalid continuation byte
While i install Django 2.0 in windows 10, and use command python manage.py runserver Get below errors, and the localhost:8000 can't be opened System check identified no issues (0 silenced). You have 14 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions. Run 'python manage.py migrate' to apply them. December 06, 2017 - 10:50:09 Django version 2.0, using settings 'mysite.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. Unhandled exception in thread started by .wrapper at 0x0000011FCC05AB70> Traceback (most recent call last): File "C:\Anaconda3\lib\site-packages\django\utils\autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "C:\Anaconda3\lib\site-packages\django\core\management\commands\runserver.py", line 142, in inner_run ipv6=self.use_ipv6, threading=threading, server_cls=self.server_cls) File "C:\Anaconda3\lib\site-packages\django\core\servers\basehttp.py", line 163, in run httpd = httpd_cls(server_address, WSGIRequestHandler, ipv6=ipv6) File "C:\Anaconda3\lib\site-packages\django\core\servers\basehttp.py", line 66, in __init__ super().__init__(*args, **kwargs) File "C:\Anaconda3\lib\socketserver.py", line 453, in __init__ self.server_bind() File "C:\Anaconda3\lib\wsgiref\simple_server.py", line 50, in server_bind HTTPServer.server_bind(self) File "C:\Anaconda3\lib\http\server.py", line 138, in server_bind self.server_name = socket.getfqdn(host) File "C:\Anaconda3\lib\socket.py", line 673, in getfqdn hostname, aliases, ipaddrs = gethostbyaddr(name) UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe5 in position 0: invalid continuation byte Anybody knows what seems to be the problem? -
Django: Cannout update model through form POST, only Shell
What are you trying to accomplish? (Please include sample data.) I am trying to create a form in Django that takes in data and saves them in a database. Paste the part of the code that shows the problem. (Please indent 4 spaces.) index4.html <form action="post_url/" method="post"> {% csrf_token %} {{ form }} <input type="submit" value="Submit" /> </form> urls.py (project folder) from django.conf.urls import url from django.contrib import admin from exercises.views import * urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^numbers/', numbers, name="numbers"), url(r'^about/', about, name="about"), url(r'^post_url/$', post_treasure, name='post_treasure') ] views.py from django.shortcuts import render from django.http import HttpResponse from .models import Treasure from .forms import TreasureForm def numbers(request): treasures = Treasure.objects.all() form = TreasureForm() return render(request, 'index4.html', {'treasures': treasures, 'form':form}) def about(request): return render(request, "about.html", {}) def q1(request): return HttpResponse("What is the average age of a dinosaur?") def post_treasure(request): form = TreasureForm(request.POST) if form.is_valid(): treasure = Treasure(name = form.cleaned_data['name'], value = form.cleaned_data['value'], material = form.cleaned_data['material'], location = form.cleaned_data['location'], img_url = form.cleaned_data['img_url']) treasure.save() return HttpResponseRedirect('/') forms.py from django import forms from .models import Treasure # class TreasureForm(forms.ModelForm): # class Meta: # model = Treasure # fields = ['name', 'value', 'location', 'material'] # if form.is_valid(): # form.save(commit = True) # return HttpResponseRedirect('/') class … -
multiple level authorization in django-mezzanine
i am a newbie of django/mezzanine I knew mezzanine provides the ability for public user must login to view some particular pages. But i want more specific when i create an staff user (not superuser) i want to define what pages this user can view. For example: UserA can view page: http://example.com/news and UserB can view page http://example.com/blogs and of course superuser can view both. -
Trouble installing aldryn_forms into django project
I've used the aldryn_forms plugin before on some other projects. Typically when I install it, it's at the beginning of the project. In this case, the library is being installed after the prokect was initially deployed. I sourced my virtualenv, ran pip install aldryn-forms, added the associated libs to the settings.py file and ran migrations, but I can't escape the 500 error and stack trace that is attached below. It seems to be an issue with the state of the DB, but I'm not savvy enough with sqlite3 or Django to debug this. [wsgi:error] [pid 158:tid 139929997891328] [client 10.0.0.5:46820] self.load_middleware() File "/usr/local/src/env-NewSSTProject/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 52, in load_middleware mw_instance = mw_class() File "/usr/local/src/env-NewSSTProject/local/lib/python2.7/site-packages/django/middleware/locale.py", line 24, in __init__ for url_pattern in get_resolver(None).url_patterns: File "/usr/local/src/env-NewSSTProject/local/lib/python2.7/site-packages/django/core/urlresolvers.py", line 401, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/usr/local/src/env-NewSSTProject/local/lib/python2.7/site-packages/django/core/urlresolvers.py", line 395, in urlconf_module self._urlconf_module = import_module(self.urlconf_name) File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/usr/local/src/NewSSTProject/NewSSTProject/urls.py", line 37, in <module> url(r'^', include('djangocms_forms.urls')), File "/usr/local/src/env-NewSSTProject/local/lib/python2.7/site-packages/django/conf/urls/__init__.py", line 33, in include urlconf_module = import_module(urlconf_module) File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/usr/local/src/env-NewSSTProject/local/lib/python2.7/site-packages/djangocms_forms/urls.py", line 7, in <module> from .views import FormSubmission File "/usr/local/src/env-NewSSTProject/local/lib/python2.7/site-packages/djangocms_forms/views.py", line 13, in <module> from .forms import FormBuilder File "/usr/local/src/env-NewSSTProject/local/lib/python2.7/site-packages/djangocms_forms/forms.py", line 386, in <module> class SubmissionExportForm(forms.Form): File "/usr/local/src/env-NewSSTProject/local/lib/python2.7/site-packages/djangocms_forms/forms.py", … -
django oscar invoice pdf generation
Hi I am trying to set up invoice generation for django oscar. I have found a useful link https://groups.google.com/forum/#!topic/django-oscar/sg1qtyuu32Q (two main links from this google groups are https://gist.github.com/elbaschid/8722203 and https://gist.github.com/elbaschid/8776935) but I am having an issue trying to set this up. I saved my templates as suggested in the link and the below is the code under OrderListView: def generate_packing_slips(self, request, orders): template = loader.get_template(self.packing_slip_template) main_pdf = pisaPDF() for order in orders: voucher_codes = [] for discount in order.discounts.all(): if discount.voucher_code: voucher_codes.append(discount.voucher_code) context = RequestContext(request, { 'order': order, 'STATIC_ROOT': settings.STATIC_ROOT, 'voucher_codes': voucher_codes, }) html = template.render(context) result = StringIO() order_pdf = pisa.pisaDocument(StringIO(html.encode("UTF-8")), result) if order_pdf.err: messages.error( self.request, _("An problem occured trying to generate the packing slip for " "order #%s") % order.number, ) else: main_pdf.addDocument(order_pdf) response = HttpResponse(main_pdf.getvalue(), mimetype='application/pdf') filename = self.get_packing_slip_filename(orders) response['Content-Disposition'] = 'attachment; filename=%s' % filename return response However this gives me an error of AttributeError at /dashboard/orders/ 'OrderListView' object has no attribute 'packing_slip_template' The path for the template is 'dashboard/orders/order_packing_slip.html' I also added a button on order_list.html by adding the below code: <button style="margin-right:10px" type="submit" class="btn w3-black w3-hover-dark-gray" name="action" value="generate_packing_slips" data-loading-text="{% trans 'Submitting...' %}">{% trans "Download" %}</button> I would be grateful if you have any suggestions for … -
ModelForm foreignkey field not loaded yet
I'm attempting to develop a work record tracker sort of app, very similar to a ticket tracker. Each 'ticket' can have multiple notes owned by employees (employees are tracked in a different app that has been installed into the ticket-tracker). i.e. MySite |___WorkRecords |__models.py |__views.py |__etc.. //standard app stuff |___emp #the uncreative name for the employee manager app |__ //standard stuff again... Within the models: WorkRecords.models.py class WorkRecord(models.Model): issuedate = models.DateField('date first issued', editable = False, default = timezone.now) owner = models.ForeignKey('emp.Employee', related_name='work_owner', on_delete=models.PROTECT) other_irrelevant_header_data... .... class WorkRecordNote(models.Model): ref_wr = models.ForeignKey(WorkRecord, on_delete=models.CASCADE) note_text = models.CharField(max_length=1000) author = models.ForeignKey('emp.Employee', related_name='note_author', on_delete=models.PROTECT) #Form class for the Work Record class EditWR(ModelForm): class Meta: model = WorkRecord fields = '__all__' emp.models.py class Employee(models.Model) data stuff At the moment, the models have all been migrated, but the data has not been input into the tables yet (MySQL tables are all there, matching models etc...but no data within tables yet) Now that I've gotten the models and tried working out modelform, I've tried makemigrations, but I'm getting an error traceback... ValueError: Cannot create form field for 'owner' yet, because its related model u'emp.Employee' has not been loaded yet I checked my mysite/settings.py to ensure that the … -
Django API list with pagination - Page is not JSON serializable
I am trying to create a Django API for a list with pagination but have this error TypeError: Object of type 'Page' is not JSON serializable The following is my API code: @api_view(['POST']) def employee_get_list_by_page(request): # ----- YAML below for Swagger ----- """ description: employee_get_list_by_page parameters: - name: token type: string required: true location: form - name: page type: string required: true location: form - name: page_limit type: string required: true location: form """ token = request.POST['token'] try: auth_employee = AuthEmployeeSessionToken.objects.get(token=token) except AuthEmployeeSessionToken.DoesNotExist: return Response("Invalid Token", status=status.HTTP_406_NOT_ACCEPTABLE) employee_list = Employee.objects.filter(company = auth_employee.employee.company.id) page = request.GET.get('page', request.POST['page']) paginator = Paginator(employee_list, request.POST['page_limit']) try: employees = paginator.page(page) except PageNotAnInteger: employees = paginator.page(request.POST['page']) except EmptyPage: employees = paginator.page(paginator.num_pages) return Response(employees,status=status.HTTP_200_OK) <-- passing employees probably cause this error that employees as Page is not JSON serializable. How do an API query for this list with pagination support ? Side issue which I want the JSON to list just the fields that I want. -
django similar to Select query with multiple tables
I am trying to perform query on database and export it to CSV. i need to join different models/tables and build a query set. class order(BaseModel): customer = models.ForeignKey(Customer, related_name='rmas', db_index=True) equipment = models.ForeignKey(Equipment, related_name='rmas', blank=True, null=True, db_index=True) class shipment(BaseModel): ordernum = models.ForeignKey(order, related_name='rmas', db_index=True) shipmentdate = models.DateTimeField(default=datetime.now, editable=False) class orderprocessshipment(BaseModel): ordernum = models.ForeignKey(order, related_name='rmas', db_index=True) status = models.TextField() i am try to do this : SELECT order.id, order.customer, shipment.shipmentdate, orderprocess.status FROM order , shipment, orderprocess WHERE order.id = ship.ordernum and order.id =orderprocess.ordernum I am trying to find a way get a queryset similar to the query above using any django method. -
User groups, and dififerent views / functions for each group
Desired Output: Employee and Client user types. If registering through the main website the user will automatically be a Client. Client type users get a different menu/dashboard/portal whatever you wanna call that. For examples. Clients can book an appointment. Then for employees that usertype is set manually in django admin. AFterwards when they log in, they get a different dashboard, say one that displays their schedule and they can put available hours. This user doesnt even need to have a registration page it can all be done in admin. From my limited understanding to bring this desired outcome to reality I must extend the userprofile? Or should I entirely create a custom userprofile using the AbstractUser abstraction? Also where does django groups come in. And is all this User model extending even necessary? Can django groups be used entirely for this project? class UserProfile(models.Model): user = models.ForeignKey(User) #define general fields class Client(models.Model): profile = models.ForeignKey(UserProfile) #freelancer specific fields class Meta: db_table = 'Client' class Employee(models.Model): profile = models.ForeignKey(UserProfile) #Employee specific fields class Meta: db_table = 'Employee' Thanks in advance!! -
Django haystack: elasticsearch how to delete by query
ElasticSearch offers a way to delete_by_query and I see that it is being called on the clear method of the backend with: self.conn.delete_by_query(index=self.index_name, doc_type='modelresult', body=query) where the query is something like this: {'query': {'query_string': {'query': "Model1 OR Model2"}}} Now, I don't know much about ElasticSearch and I created my Index like: class MyIndex(indexes.SearchIndex, indexes.Indexable): ... category = indexes.CharField(model_attr='category_id') ... And now I want to delete from my index all the documents that match category=5 and I tried something like: backend.conn.delete_by_query(index='haystack', doc_type='modelresult', body= {'query': {'match': {'category': '5'}}}) and it outputs something like this: {'_version': 4, 'created': False, '_id': '_delete_by_query', '_index': 'haystack', '_type': 'modelresult', '_shards': {'successful': 1, 'failed': 0, 'total': 2}} But it didn't delete it, I assume I need a better query, so what would it be? I also read that I can use the bulk method from ElasticSearch. Btw I also checked that I can get a "query" from a SearchQuerySet instance with: sqs.query.build_query() that gives: 'category:(5)' so it would be very helpful if I could use that query output for the delete_by_query method, but I don't know how to use it -
'WSGIRequest' object has no attribute method
I know this question has been asked many times, but I haven't found any solution that solved my problem. Basically, I have a method inside a class view in Django, and that method calls another method, which raises an AttributeError: 'WSGIRequest' object has no attribute 'send_email'. This is the code: class PartyListView(ListView): # ... # ... def approve_party(self, party_id): returnObj = {} # get the party by id party = party_repo.get_party_by_id(party_id) if party is None: returnObj['message'] = "The requested party doesn't exist." jsonObj = json.dumps(returnObj) return HttpResponse(jsonObj, status=404, content_type="application/json") # change the status to Approved party.party_status = Core.PartyStatus.Approved party.save() # email the party team on the approval self.send_email(True, party) # return a json success response returnObj['message'] = "The party has been approved." jsonObj = json.dumps(returnObj) return HttpResponse(jsonObj, status=200, content_type="application/json") def send_email(self, isApprovalEmail, party): username = self.request.user.username from_email = username + "@example.com" recipient_list = [party.host.student_email] cc = ['admin@example.com'] if isApprovalEmail: subject = "APPROVED Party Registration for {}".format(party.party_time) body = "approval email" email = EmailMessage(subject, body, from_email, recipient_list, cc=cc) email.send() else: subject = "REJECTED Party Registration for {}".format(party.party_time) body = "rejection email" email = EmailMessage(subject, body, from_email, recipient_list, cc=cc) email.send() # ... # ... I have tried the following things: Rearrange the … -
Django ajax returning null
I'm using Django to handle a form that sends a post request to a view and ajax is supposed to return that without refreshing the page. Here's my Jquery with ajax: $('.createFolder').on('submit', function(event){ event.preventDefault(); var folderName = $('#folderName').val(); $.ajax({ url: '{% url 'project:createFolder' %}', type: 'post', data: { 'folderName': folderName, csrfmiddlewaretoken: '{{ csrf_token }}' }, dataType: 'json', success: function(json) { alert(json); } }); }); Here's my view: class createFolder(TemplateView): template_name = "project/createFolder.html" def post(self, request): folderName = request.GET.get('folderName') return JsonResponse(folderName, safe=False) When running this the response I get displays "null". I'm not sure what is wrong here. Can anyone advise? Thanks -
TypeError: <lambda>() missing 1 required positional argument:
I'm trying to populate my Django project with some random data using factory_boy and faker. However, when I try to create an instance of my UserFactory object I'm getting the error TypeError: () missing 1 required positional argument: 'a'. It seems to have something to do with the fake_date and date_joined attributes and their lambda functions. A couple of the tutorials I've found have laid out using lambda functions in this way for the Factory objects but it isn't working for me. import datetime import factory import faker from dataStoreApp.models import Category, Goal, Transaction from django.contrib.auth.models import User fake = faker.Faker() class CategoryFactory(factory.django.DjangoModelFactory): class Meta: model = Category name = factory.Iterator(['Category1', 'Category2', 'Category3', 'Category4', 'Category5', ], cycle=False) class UserFactory(factory.django.DjangoModelFactory): FACTORY_HIDDEN_ARGS = ('fake_date', ) class Meta: model = User fake_date = factory.LazyAttribute( lambda a: datetime.datetime.now().strftime("%Y-%m-%d %H:%M")) date_joined = factory.LazyFunction(lambda a: a.fake_date) first_name = factory.LazyAttribute(lambda b: fake.first_name()) last_name = factory.LazyAttribute(lambda c: fake.last_name()) email = factory.LazyAttribute(lambda e: 'test' + '@test_email.com') class GoalFactory(factory.DjangoModelFactory): class Meta: model = Goal class TransactionFactory(factory.django.DjangoModelFactory): class Meta: model = Transaction When running in the python console I get the following errors: Traceback (most recent call last): File "<input>", line 1, in <module> File "C:\Program Files\Python36\lib\site-packages\factory\base.py", line 568, in create … -
django metismenu nav active on page change
I want to change the side menu highlighted field based on what page I am on. I've been working on this all day and cannot seem to solve the issue. HTML: <!--- Start Side Navigation ---> <nav class="navbar-default navbar-static-side" role="navigation"> <div class="sidebar-collapse"> <ul class="nav metismenu" id="side-menu"> <li class="nav-header"> <div class="dropdown profile-element"> {% if sma.active == True %} <span> <img alt="image" class="img-circle" height="80" width="80" src="{{ sma.profile_picture_object.thumbnail_url }}" /> </span> {% endif %} <a data-toggle="dropdown" class="dropdown-toggle" href="#" aria-expanded="true"> <span class="clear"> <span class="text-muted text-xs block"> <img src="small.png"> </span> </span> </a> </div> </li> <li class="active"> <a href="{% url 'website:dashboard' %}"> <i class="fa fa-linode"></i> <span class="nav-label">Dashboard</span> </a> </li> <li class=""> <a href="#"> <i class="fa fa-user-o"></i> <span class="nav-label">Accounts</span> <span class="fa arrow"></span> </a> <ul class="nav nav-second-level"> <li class=""> <a href="{% url 'website:accounts_detail' sma.id %}">Current Account</a> </li> <li> <a href="{% url 'website:accounts_edit' %}">Edit Account </a> </li> <li> <a href="{% url 'website:accounts_list'%}">Switch Account </a> </li> <li> <a href="{% url 'website:accounts_add' %}">Add Account </a> </li> </ul> </li> <li> <a href="#"> <i class="fa fa-sitemap"></i> <span class="nav-label">Ambassadors</span> <span class="fa arrow"></span> </a> <ul class="nav nav-second-level"> <li> <a href="{% url 'website:ambassadors_list_active' %}">Search </a> </li> <li> <a href="{% url 'website:ambassadors_list_requested' %}">Requested </a> </li> <li> <a href="{% url 'website:ambassadors_list_authorized' %}">Authorized </a> </li> </ul> </li> </ul> </div> …