Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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> … -
For loop issue writing multiple lines to database
The for loop below has an issue when writing to the database. Only the first record is coming through, i believe it's because report_name_sc = reportlist is writing the query set to the database. How can I get it to write a single line for each report_id? checkedlist = request.GET.getlist('report_id') reportlist = QvReportList.objects.filter(report_id__in= checkedlist, active = 1).values_list('report_name_sc',flat = True) for i in checkedlist: requestsave = QVFormAccessRequest(ntname_id = owner.formattedusername, first_name = owner.first_name, last_name = owner.last_name, coid = owner.coid, facility = owner.facility, title = owner.title ,report_id = i, report_name_sc = reportlist, accesslevel_id = '7', phi = '1', access_beg_date = '2017-01-01', access_end_date = '2017-01-31') requestsave.save() -
loading staticfiles in django template causes server error 500
I have a base.html file extended by the index.html one. In base I load some static files in the section, and other in the bottom of the file. I am trying to use the template tag for loading static files: {% load static %} However, depending where I put it, this works or fails. When the tag is on the begining of the base (first line), this always does not work. It works only when it is on the body section of the base.html and on the begining (just after extend tag) of the index.html. Where is the correct place to put it ? Should it be called only once ? -
Django Image Grid Gallery
I am trying to setup a grid gallery in my Django website similar to pinterest.com. I have the following HTML code: <div class="row text-center text-lg-left"> <div class="col-lg-3 col-md-4 col-xs-6"> <a href="#" class="d-block mb-4 h-100"> {% for img in imgs %} <img src="/static/img/{{ img }}" class="img-thumbnail" alt=""> {% endfor %} </a> </div> </div> Here is my views.py def gallery(request): path = "C:/Users/fela/Pictures/" img_list = os.listdir(path) return render(request, 'gallery.html', {'imgs': img_list}) The above code shows the result line by line instead of next to each other. It displays one result (image) per line (https://image.ibb.co/bVAE9b/result_2.png). The expected result should be similar to pinterest, it should be next to each other to fill up the screen. I have tried using bootstrap 4 and bootstrap 3 with same results. -
decrypting token from url
i'm trying to create a url from with a token by combining an id and a date then create a url and send it to a mail. When clicking the link i should be able to decrypt and get the values. However i keep getting an cryptography.fernet.InvalidToken. I'm not sure what i'm doing wrong here? token generator class class ExpiringTokenGenerator(object): FERNET_KEY = Fernet.generate_key() fernet = Fernet(FERNET_KEY) EXPIRATION_DAYS = 1 def _get_time(self): """Returns a string with the current UTC time""" return datetime.utcnow().strftime('%Y-%m-%d %H-%M-%S') def _parse_time(self, d): """Parses a string produced by _get_time and returns a datetime object""" return datetime.strptime(d, '%Y-%m-%d %H-%M-%S') def generate_token(self, text): """Generates an encrypted token""" full_text = bytes(str(text) + '|' + self._get_time(), encoding='utf-8') token = self.fernet.encrypt(full_text) return token def get_token_value(self, token): """Gets a value from an encrypted token. Returns None if the token is invalid or has expired. """ value = self.fernet.decrypt(bytes(token.strip("/"), encoding='utf-8')) return value transaction_activation_token = ExpiringTokenGenerator() sending the email message = render_to_string('transaction_active_email.html', { 'email':serializer.data['user']['email'], 'domain':current_site.domain, 'uid': force_bytes(serializer.data['user']['id']), 'token': transaction_activation_token.generate_token(serializer.data['user']['id']), }) mail_subject = 'Gennemfør transaktion!' to_email = serializer.data['user']['email'] email = EmailMessage(mail_subject, message, to=[to_email]) email.send() view def activate_transaction(request, token): value = transaction_activation_token.get_token_value(token) print(value) redirect("/") -
Django ImageField save to locations
I'm able to upload photos to the media folder just fine. My problem is I can't save them to a specific folder on upload. I want the image to be saved in a unique folder based on an id being passed into the django view. Below is the code that throws the following error: views.py", line 90, in orderdetails settings.MEDIA_ROOT + '/orders/' + str(orderid) + '/' + image) TypeError: coercing to Unicode: need string or buffer, InMemoryUploadedFile found if request.method == 'POST': # Loop through our files in the files list uploaded if not os.path.exists(settings.MEDIA_ROOT + '/orders/' + str(orderid)): os.makedirs(settings.MEDIA_ROOT + '/orders/' + str(orderid)) for image in request.FILES.getlist('files[]'): # Create a new entry in our database new_image = UploadedImages(client_order=client, image=image.name) # Save the image using the model's ImageField settings filename, ext = os.path.splitext(image.name) new_image.image.save("%s-%s%s" % (filename, datetime.datetime.now(), ext), settings.MEDIA_ROOT + '/orders/' + str(orderid) + '/' + image) new_image.save() If i just use image it saves just find in the media folder. Which is the code below. I know I set a folder inside my model with upload_to. Even with that I'm unsure how to set it to a folder based off of the ordierid. if request.method == 'POST': # Loop … -
Trying to create user types: 'Client' and 'Employee'. Would like all users who register on site to be Clients, who see different page than employee
I'm reading through these docs on Django: https://docs.djangoproject.com/en/1.11/topics/auth/customizing/#extending-user I'm just not sure which route to go. They suggest using a custom user model like so: from django.contrib.auth.models import AbstractUser class User(AbstractUser): pass Doing so, what would the procedure be to make two different user types. Should I have something like this: class Client(AbstractUser): pass class Employee(AbstractUser): pass But then how would new registered users be 'clients' when they sign up? And how would I make it so they see a different part of the site than employees? Really, i'm just looking for some guidance in how I should approach this. Any help would really be appreciated! Thanks!