Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Template Comma Filter
I am trying to adapt to my Django project image slider. But I cannot implement the comma tags. Here is an original HTML code: <section id="slider" class="fullheight nomargin" data-background-delay="3500" data-background-fade="1000" data-background=" imagefile1.jpg ,imagefile2.jpg ,imagefile3.jpg "> <!-- Backstretch Navigation --> <a class="bs-next" href="#"></a> <a class="bs-prev" href="#"></a> <div class="display-table"> <div class="display-table-cell vertical-align-middle"> <div class="container text-center"> <div class="rounded-logo wow fadeIn" data-wow-delay="0.4s"> <img src="demo_files/images/packs/hotel/logo.png" alt=""> </div> <h1 class="weight-300 margin-top-30 margin-bottom-0 wow fadeIn" data-wow-delay="0.6s">SMARTY HOTELS</h1> </div> </div> </div> <span class="raster overlay dark-3 z-index-0"><!-- dark|light overlay [0 to 9 opacity] --></span> </section> ` And here is mine Django template {% if carousel_items %} {% for carousel_item in carousel_items %} {% image carousel_item.image width-1000 as carouselimagedata %} <section id="slider" class="{% if forloop.first %}fullheight nomargin{% endif %}" data-background-delay="3500" data-background-fade="1000" data-background="{{ carouselimagedata.url }}" > <!-- Backstretch Navigation --> <div class="display-table"> <div class="display-table-cell vertical-align-middle"> <div class="container text-center"> <div class="rounded-logo wow fadeIn" data-wow-delay="0.4s"> <img src="{% static 'images/logo.png' %}" alt=""> </div> {% if carousel_item.caption %} <h1 class="weight-300 margin-top-30 margin-bottom-0 wow fadeIn" data-wow-delay="0.6s">{{ carousel_item.caption }}</h1> {% endif %} </div> </div> </div> <span class="raster overlay dark-3 z-index-0"><!-- dark|light overlay [0 to 9 opacity] --></span> </section> {% endfor %} {% endif %} With this code images not showing as a slider. I was searching adding … -
how to use uwsgi restart django
I have a wsgi.ini file in my project, and I use uwsgi wsgi.ini to run my project.But when I change the django code,I want to restart the project instead kill uwsgi then reload it. The uwsgi official document provide the following methods: # using kill to send the signal kill -HUP `cat /tmp/project-master.pid` # or the convenience option --reload uwsgi --reload /tmp/project-master.pid # or if uwsgi was started with touch-reload=/tmp/somefile touch /tmp/somefile But I don't have a project-master.pid file in /tmp catalog in my system(centOS). my question: how to use uwsgi restart django instead of kill it then start it? if use uwsgi official document provided method,how to create a .pid file and what content should in this file? -
logging file does not exist when running in celery
first, I'm sorry about my low level english I create a website for study I create send SMS feature using django + redis + celery tasks/send_buy_sms.py from celery import Task from items.utils import SendSMS class SendBuyMessageTask(Task): def run(self, buyer_nickname, buyer_phone, saler_phone, selected_bookname): sms = SendSMS() sms.send_sms(buyer_nickname, buyer_phone, saler_phone, selected_bookname) items/utils.py from wef.decorators import log_decorator import os import requests import json class SendSMS(): @log_decorator def send_sms(self, buyer_nickname, buyer_phone, saler_phone, selected_bookname): appid = [...] apikey = [...] sender = '...' receivers = [saler_phone, ] content = '...' url = os.environ.get("URL") params = { 'sender': sender, 'receivers': receivers, 'content': content, } headers = {...} r = '...' return params when I send sms using my code it has no problem [2017-09-12 17:20:43,532: WARNING/Worker-6] Task success and I want make log file and insert log "success send SMS" when user click "send sms button" wef/wef/decorators.py from django.utils import timezone import logging def log_decorator(func): logging.basicConfig(filename='../../sendsms.log', level=logging.INFO) def wrap_func(self, *args, **kwargs): time_stamp = timezone.localtime(timezone.now()).strftime('%Y-%m-%d %H:%M') logging.info('[{}] success send SMS'.format(time_stamp)) print(logging) return func(self, *args, **kwargs) return wrap_func but when I click 'send sms' button task is Ok , but log file doesn't created... So I want to know 'what is the problem?' I change my code create … -
Error: Reverse for 'detail' not found. 'detail' is not a valid view function or pattern name
Django version: 1.11.4 Python: 3.6.1 I want to add a line to my html file: <a class="pure-button" href="{% url 'detail' id=post.id %}">Read More </a> views.py: def detail(request, id): try: post = Article.objects.get(id=int(id)) except Article.DoesNotExist: raise Http404 return render(request, 'post.html', {'post':post}) url.py: from django.conf.urls import url,include from django.contrib import admin import article.views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^(\d+)', article.views.detail), url(r'^', article.views.home), ] I met the following errors: NoReverseMatch at / Reverse for 'detail' not found. 'detail' is not a valid view function or pattern name. Request Method: GET Request URL: http://localhost:8000/ Django Version: 1.11.4 Exception Type: NoReverseMatch Exception Value: Reverse for 'detail' not found. 'detail' is not a valid view function or pattern name. Who can help me? Many thanks! -
Questionnaire App, creating list models
I am trying to create a questionnaire app. Each question in the questionnaire have multiple possible answers to choose and the user can answer by chosing the answer that suits him Ex : If a debutant django debutant ask you for help what do you do ? 1) I help him no matter what 2) I give him direction to solve his problem 3) I pass on that one no time but if nobody answer I swear to answer later 4) Nobody helped me, so I won't help either User answer : 1 and 2 Now I designed my model the following : from django.db import models from registration.models import MyUser # Create your models here. class Questionnaire(models.Model): question = models.CharField(max_length=600) possible_answer_number = models.IntegerField() multiple_answer = models.BooleanField(default=False) def __str__(self): return self.question class Answers(models.Model): question_id = models.ForeignKey('Questionnaire', on_delete=models.CASCADE) answer = models.CharField(max_length = 600) def __str__(self): return self.answer class Test(models.Model): user = models.ForeignKey('registration.MyUser') created_at = models.TimeField(auto_now_add=True) closed = models.BooleanField(default=False) class UserAnswer(models.Model): test_id = models.ForeignKey('Test') question = models.ForeignKey('Questionnaire') answer = models.ForeignKey('Answers') I am not sure if it the best way to structure my models .. I guessed that the best way would be to have list answer for each question how can I … -
Django edit auth user profile
I'm new to Django and writing an application in Django 1.11. I want to create a Profile update page. I have created an app accounts to manage all profile related activities and created a class from django.contrib.auth.models import User # Create your views here. from django.views.generic import TemplateView, UpdateView class ProfileView(TemplateView): template_name = 'accounts/profile.html' class ChangePasswordView(TemplateView): template_name = 'accounts/change_password.html' class UpdateProfile(UpdateView): model = User fields = ['first_name', 'last_name'] template_name = 'accounts/update.html' and in myapp/accounts/urls.py from django.conf.urls import url from . import views app_name = 'accounts' urlpatterns = [ url(r'^$', views.ProfileView.as_view(), name='profile'), url(r'^profile/', views.ProfileView.as_view(), name='profile'), url(r'^change_password/', views.ChangePasswordView.as_view(), name='change_password'), url(r'^update/', views.UpdateProfile.as_view(), name='update'), url(r'^setting/', views.SettingView.as_view(), name='setting') ] When I access 127.0.0.1:8000/accounts/update, It gives AttributeError at /accounts/update/ Generic detail view UpdateProfile must be called with either an object pk or a slug. Since, I want the logged in user to edit his/her profile information. I don't want to pass pk in the url. How to create profile update page in Django 1.11? -
How can I put each model City&Prefecture&Area&User?
I wanna put data of list to City&Prefecture&Area&User model ? I wrote book3 = xlrd.open_workbook('./data/excel1.xlsx') sheet3 = book3.sheet_by_index(0) data_dict = OrderedDict() tag_list = sheet3.row_values(0) tag_list1_user_id = tag_list[9] fourrows = [] for row_index in range(7, sheet3.nrows): row = sheet3.row_values(row_index) if len(fourrows) == 5: fourrows=[] fourrows.append(row) fourrows_transpose = list(map(list, zip(*fourrows))) print(fourrows_transpose) val3 = sheet3.cell_value(rowx=0, colx=9) user3 = Companyransaction.objects.filter(user_id=val3) if user3: user3.update(XXXXX) models.py is class Area(models.Model): name = models.CharField(max_length=20, verbose_name='エリア名', null=True) class User(models.Model): user_id = models.CharField(max_length=200,null=True) area = models.ForeignKey('Area',null=True, blank=True) class Prefecture(models.Model): name = models.CharField(max_length=20, verbose_name='prefecture') area = models.ForeignKey('Area', null=True, blank=True) class City(models.Model): name = models.CharField(max_length=20, verbose_name='city') prefecture = models.ForeignKey('Prefecture', null=True, blank=True) class Price(models.Model): name = models.CharField(max_length=20, verbose_name='price') PRICE_RANGE = ( ('a', 'u500'), ('b', '500-1000'), ('c', 'u1000'), ) price_range = models.CharField(max_length=1, choices=PRICE_RANGE) city = models.ForeignKey('City', null=True, blank=True) In print(fourrows_transpose),it is shown [['America', '', '', '', ''], ['', '', 'u1000', '500~1000', 'd500'], ['NY', 'City A', '×', '×', '×'], ['', 'City B', '×', '×', '×'], ['', 'City C', '×', '×', '×'], ['', 'City D', '×', '×', '×'], ['', 'City E', '×', '×', '×']] I wanna put 'America' to Prefecture's area and City A to City's name and × to Price's name . So,i wanna put these data tp user3.update(XXXXX).What should I write to XXX?How can … -
Multiple Django functions on class-based view
I'm looking for using Multiple Django functions in the same Class and display these functions on the same template. Both functions are in my Django Template, but none work and I don't know why. First function : This function lets to search a person in my Database based on 3 criteria : firstname, lastname and birthcity. Then I display the query result in my array. Second function : This function is a simple Django form. This is my first Django Class : class SocieteFormulaire(TemplateView) : template_name= "Societe.html" model = Societe def get_context_data(self, **kwargs): request = self.request if 'recherche' in request.GET: query_Lastname_ID = request.GET.get('q1LastnameID') query_Firstname_ID = request.GET.get('q1FirstnameID') query_BirthCity_ID = request.GET.get('q1BirthCityID') sort_params = {} set_if_not_none(sort_params, 'Lastname__icontains', query_Lastname_ID) set_if_not_none(sort_params, 'Firstname__icontains', query_Firstname_ID) set_if_not_none(sort_params, 'BirthCity__icontains', query_BirthCity_ID) query_list = Societe_Recherche.Recherche_Filter(Societe, sort_params) context = { "query_Lastname_ID" : query_Lastname_ID, "query_Firstname_ID" : query_Firstname_ID, "query_BirthCityID" : query_Birthcity_ID, "query_list" : query_list, } return context def get_context_data(self, **kwarg) : success = False request = self.request if request.method == 'POST': form = IndividuFormulaire(request.POST or None, request.FILES or None) if form.is_valid() : post = form.save(commit=False) for element in settings.BDD : post.save(using=element, force_insert=True) messages.success(request, 'Le formulaire a été enregistré !') return HttpResponseRedirect(reverse('IndividuResume', kwargs={'id': post.id})) else: messages.error(request, "Le formulaire est invalide !") else: form = IndividuFormulaire() … -
convert a date string to datetime compatible to postgresql
I have a date string in the format, "dd/mm/yyyy" e.g="23/2/2017" How can I convert this to a valid format, so that I can save this value in Datetime field of postgresql. I tried using datetime package, but not getting. -
Add property to instance method Django instance
I am now rewriting the legacy project. This ProductNode instance image will be rendered in the Django HTML template and serve by webserver. Since the author of the code has gone from company. I am now contributing the concept of previous project and reuse it as a model, but not entirely. I have read Adding attributes to instance methods in Python But could not see how does it related to my case class ProductNode(models.Model): ... def image_img(self): if self.image: return u'<img src="%s" width="75" height="75" />' % (self.image.url) else: return '(No image)' image_img.short_description = 'Image' image_img.allow_tags = True Questions: 1. image_img is an object method. What is the benefit of adding the property? 2. What kind of situation I need to use this technique? 3. If I do not like to follow this. What is an alternative way? -
How to fix FCM ERR_UNSAFE_REDIRECT?
I have implemented Firebase Cloud Messaging into my Web Project, but when it trys to initialize the ServiceWorker it says The script resource is behind a redirect, which is disallowed. Failed to load resource: net::ERR_UNSAFE_REDIRECT The firebase-cloudmessaging-sw.js is in the same location as the calling overview.html. Here is my Path-Structure: And this is the Code: <script src="https://www.gstatic.com/firebasejs/4.3.0/firebase-messaging.js"></script> <script> // [FIREBASE SECTION FOR NOTIFICATION RECEIVING AND REGISTRATION TOKEN HANDLING] var config = { apiKey: "AIzaSyBozYVItD4eCeZdvqFSrT4171ip-dLj_7A", apiKey: "AIzaSyBozYVItD4eCeZdvqFSrT4171ip-dLj_7A", authDomain: "pillbox-884a9.firebaseapp.com", databaseURL: "https://pillbox-884a9.firebaseio.com", projectId: "pillbox-884a9", storageBucket: "pillbox-884a9.appspot.com", messagingSenderId: "451885250400" }; firebase.initializeApp(config); const messaging = firebase.messaging(); messaging.requestPermission() .then(function() { console.log('Notification permission granted.'); messaging.getToken() .then(function(currentToken) { if (currentToken) { sendTokenToServer(currentToken); } else { console.log('No Instance ID token available. Request permission to generate one.'); } }) .catch(function(err) { console.log('An error occurred while retrieving token. ', err); }); }) .catch(function(err) { console.log('Unable to get permission to notify.', err); }); function sendTokenToServer(refreshedToken) { $.ajax({ type: "POST", url: "/chat/devicekey/", data: {"devid": refreshedToken}, success: function (response) { }, error: function (jqXHR, textStatus, errorThrown) { alert("Error while saving Registration Token!"); } }); } messaging.onTokenRefresh(function() { messaging.getToken() .then(function(refreshedToken) { console.log('Token refreshed.'); sendTokenToServer(refreshedToken); }) .catch(function(err) { console.log('Unable to retrieve refreshed token ', err); }); }); </script> I read, that its a Path problem, … -
Method GET not allowed in DRF ViewSet when trying to retrieve single resource
I am new Python and Django. I have created ViewSet as follows: api/views.py class UserDetails(ViewSet): """ CREATE, SELECT, UPDATE OR DELETE """ def retrive(self, request, pk): user = self.get_object(pk) print(user.query) user = TestSerializer(user) return Response(user.data) def list(self, request): users = TestTB.objects.all() print(users.query) serializer = TestSerializer(users, many=True) return Response(serializer.data) def create(self, request): serializer = TestSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) def update(self, request, pk): user = self.get_object(pk) serializer = TestSerializer(user, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) def destroy(self, request, pk): user = self.get_object(pk) user.delete() return Response(status=status.HTTP_204_NO_CONTENT) def get_object(self, pk): try: return TestTB.objects.get(pk=pk) except TestTB.DoesNotExist: raise Http404 api/urls.py router = routers.DefaultRouter() router.register(r'users', UserDetails, base_name='user-details') urlpatterns = router.urls This works fine with POST request to create new resource, GET request to get all resources, PUT request to update resource and DELETE request to delete resource. But how can I retrieve single resource? When I make request like http://127.0.0.1:8000/api/users/1/ than it shows error - { "detail": "Method \"GET\" not allowed." } It means that retrieve() method in UserDetails is never called. I know I am missing something, but not able to figure out what. -
Automatically Update Django Profile when creating user
I am fairly new to Django and am hoping that this is as easy as I think it should be. I have written a custom Django app that uses SaltStack as a back end for spinning up AWS instances. When an instance comes up, it adds the user who created it using their SSH key. I need to give each user a UID and GID so we can create user accounts on linux hosts for them. Right now, this requires that an admin go in for each new user created and manually update these fields in the admin interface before a user can use the tool. What I am hoping is that when a user is created, there is a way for Django to search through the profiles for the UID/GIDs that have already been used, increment by one, and assign it to the newly created user automatically. Here is my Profile model: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) linux_username = models.CharField(max_length=50, blank=True) linux_uid = models.CharField(max_length=10, blank=True) linux_gid = models.CharField(max_length=10, blank=True) linux_ssh_authkey = models.TextField(max_length=1000, blank=True) @receiver(post_save, sender=User) def update_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.created(user=instance) instance.profile.save() I hope this makes sense--when a user signs up, they choose a linux username … -
store multiple value in database by taking single value at a time from webpage in django
1)webpage contains one field named: Enter symptom:-|______________| and two button named next and none of these 2)whenever user click "next" after entering value then fetch data from "disease" database and match with inserted value 3)show related values that stored in database as a list, now user has to select from this list 4)while doing this process, all the inserted value are going to be stored into the "PatientHistory database" 5)whenever user click "none of these", result will be displayed result: Show disease by matching all user entered symptoms in database Problem: I take one field in "PatientHistory" database which can store multiple value(using tag field) but according to my process value will be goes into database one by one as user insert into above field So, how can I manage it?? Here's my code: models.py class TaggedSymptoms(TaggedItemBase): content_object = models.ForeignKey("Disease") class Disease(models.Model): did = models.AutoField(verbose_name='Disease Id', primary_key=True,default=0) dName = models.CharField(max_length=100) symptoms = TaggableManager(through=TaggedSymptoms) #it has values like v1,v2,v3,v4 symptoms.rel.related_name = "+" class PatientHistory(models.Model): phid = models.AutoField(verbose_name='History Id', primary_key=True,default=0) searchBy = models.CharField(max_length=5) dateOfSearch = models.DateField(auto_now=True) timeOfSearch = models.TimeField(auto_now=True) forms.py class DiseaseForm(ModelForm): dName = forms.CharField(help_text="Enter disease") symptoms = TagField(help_text="Enter symptoms separated by comma") class Meta: model = Disease fields = "__all__" class … -
I wanna get list content by 4 rows
I wanna parse excel and make lists by 4 rows. Now I wrote book3 = xlrd.open_workbook('./data/excel1.xlsx') sheet3 = book3.sheet_by_index(0) tag_list = sheet3.row_values(0) user_id = tag_list[9] for row_index in range(7, sheet3.nrows): row = sheet3.row_values(row_index) print(row) In print(row),it is shown ['', '', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M, 'N', 'O', '', '', '', ''] ['', 'u1000', '×', '×', '×', '×', '×', '×', '×', '×', '×', '×', '×', '×', '×', '×', '×', '', '', '', ''] ['', '500~1000', '×', '×', '×', '×', '×', '×', '×', '×', '×', '×', '×', '×', '×', '×', '×', '', '', '', ''] ['', 'd500', '×', '×', '×', '×', '×', '×', '×', '×', '×', '×', '×', '×', '×', '×', '×', '', '', '', ''] ・・・・・ Now I wanna get these lists by 4 ones like [ ['', '', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M, 'N', 'O', '', '', '', ''] ['', 'u1000', '×', '×', '×', '×', '×', '×', '×', '×', '×', '×', '×', '×', '×', '×', '×', '', '', '', ''] ['', '500~1000', '×', '×', '×', '×', '×', '×', '×', '×', '×', '×', '×', '×', '×', '×', '×', '', '', '', ''] ['', 'd500', '×', … -
nginx serving django static and media files 403 forbidden
First i try to find a solution from other questions, but they can't working for me, so i create a new one. The detail are below: 1 I try change user in the nginx.conf #user www-data; user me; worker_processes 4; pid /run/nginx.pid; .... 2 Add and link a conf on sites-available and sites-enabled server { add_header Access-Control-Allow-Origin *.mysite.com; add_header Access-Control-Allow-Headers X-Requested-With; add_header Access-Control-Allow-Methods GET,POST,OPTIONS; listen 80; server_name mysite.com; access_log /var/log/nginx/hitek.access.log; error_log /var/log/nginx/hitek.error.log; location / { proxy_pass http://127.0.0.1:8010; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } location ~ ^/media/ { #alias /var/www/html/mysite/media; alias /home/me/website/mysite/media; #alias /home/www-data/website/website/mysite/media; expires 1h; access_log off; } location ~ ^/static/ { #alias /var/www/html/mysite/collected_static; alias /home/me/website/mysite/collected_static; #alias /home/www-data/website/website/mysite/collected_static; expires 1h; access_log off; include /etc/nginx/mime.types; } } You can see 4 line comment, i try copy the collected_static and media folders this place ,but failure. Of course i change permission on this folders. ~/website$ ls -alt drwxrwxrwx 8 me me 4096 Sep 11 14:43 mysite drwxr-xr-x 6 me me 4096 Sep 8 14:30 .. drwxrwxrwx 4 me me 4096 Sep 7 11:41 . Who can answer it? thank. -
Django ImportError from django.core.management
I have tried everything to make it work #!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "leke.settings") try: from django.core.management import execute_from_command_line except ImportError: # The above import may fail for some other reason. Ensure that the # issue is really that Django is missing to avoid masking other # exceptions on Python 2. try: import django except ImportError: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) raise execute_from_command_line(sys.argv) Please Help That's the error I have been getting from the manager.py . Thanks -
Django foreign key reference name conflict
Location App Model: class States(models.Model): state_name = models.CharField(max_length=200, unique=True) update_time = models.DateTimeField(auto_now=True, auto_now_add=False) create_time = models.DateTimeField(auto_now=False, auto_now_add=True) def __str__(self): return self.state_name class Districts(models.Model): state = models.ForeignKey(States, on_delete=models.CASCADE) dis_name = models.CharField(max_length=200, unique=True) update_time = models.DateTimeField(auto_now=True, auto_now_add=False) create_time = models.DateTimeField(auto_now=False, auto_now_add=True) def __str__(self): return self.dis_name class Places(models.Model): district = models.ForeignKey(Districts, on_delete=models.CASCADE) place_name = models.CharField(max_length=200, unique=True,) pin_no = models.IntegerField(null=True) update_time = models.DateTimeField(auto_now=True, auto_now_add=False) create_time = models.DateTimeField(auto_now=False, auto_now_add=True) def __str__(self): return self.place_name Suppose, i want to map some info with District name. but in admin panel it shows all district name. (but the conflict is two states have some same district name) i want to use this way: working app model: from location.models import States, Districts, Places class Info(models.Model): dis_name = models.ForeignKey(Districts, on_delete=models.CASCADE) info_name = models.CharField(max_length=500) sort_name = models.CharField(max_length=50) in Admin.py class InfoAdmin(admin.ModelAdmin): list_display = ("dis_name", "info_name", "sort_name") ordering = ('id',) But in admin Panel it shows all district name. So what should i do. for avoid conflict. -
Getting Previous URL in Django Form
So i'm trying to build something, so that users would be able to report something on site. Here's the model, class Report(models.Model): reporting_url = models.URLField() message = models.TextField() Here's the view, def report(request): url_report = ??? if request.method == 'POST': form = ReportForm(request.POST or None) if form.is_valid(): new_form = form.save(commit=False) new_form.reporting_url = url_report new_form.save() I can't use something like, url_report = request.get_full_path() since I need to create/edit several views & repeat things in that case. When I'm using something like, url_report = request.META.get('HTTP_REFERER') it's returning the URL of same page from where the from is written. I'm using something like, <a href="{% url 'contact:report' %}">Report</a> to reach the Report form from several different apps/html_pages How can I get the URL of previous page from where user has pressed the "Report" button? Please help me with this code! -
Is there a python base gallery web app can check photo in the form of file hierachy of folders?
I find two GitHub django projects: https://github.com/jdriscoll/django-photologue https://github.com/VelinGeorgiev/django-photo-gallery But I need a web-based python web to browser my server's local photo paths. -
Django: Class Based View accessing URL variables
My urls.py has an entry: urlpatterns = [ url(r'^results/(?P<query>).+', views.ResultsView.as_view(), name="results"), ] which matches to the corresponding Class Based View: class ResultsView(TemplateView): template_name = os.path.join(APPNAME, "results.html") def dispatch(self, request, *args, **kwargs): query = kwargs['query'] print("HERE: " + str(json.dumps(kwargs, indent=1))) print(self.kwargs['query']) print(self.kwargs.get('query')) print(kwargs['query']) print(kwargs.get('query')) if query is None: return redirect('/') return super(ResultsView, self).dispatch(request, *args, **kwargs) def get_context_data(self, **kwargs): context = super(ResultsView, self).get_context_data(**kwargs) print("HERE: " + str(json.dumps(kwargs, indent=1))) print(self.kwargs['query']) print(self.kwargs.get('query')) print(kwargs['query']) print(kwargs.get('query')) ... # This is just here to test if 'query' is set def get(self, request, query): print(query) I'm trying to get the value of the query variable that is set in urls.py. However, after trying various solutions I found on other SO posts (as you can see from all the print statements), nothing is working. I'm fairly sure my urls.py is set up properly, because the request resolves to the correct page (results/), but all attempts to print the query entry of the dict return an empty string, and json.dumps(kwargs, indent=1)) prints this: HERE: { "query": "" } What am I doing wrong? -
rollback is not working in django using commit_manually
I am looking to import data from csv file. I need a atomic transaction.I am using django version 1.5.1. I am not able to revert transaction if an exception occurs. @transaction.commit_manually def import_user_csv(request): if request.method == 'POST' and request.FILES.has_key('csv_file'): csv_file = request.FILES['csv_file'] try: for i, row in enumerate(csv.reader(csv_file, delimiter=',')): if i == 0: continue else: createduser, created = User.objects.get_or_create( username=row[0], full_name=row[1] ) _, userrolecreated = UserOption.objects.get_or_create( user_id = createduser.id, user_role = "Employee" ) except: transaction.rollback() print ("Exception occured........") #raise else: transaction.commit() -
How fix error in unit test? | AssertionError
I am trying to write unit-test to my create function in Django project. This is my first experience creating of unit-tests. Why I cant create new data? From error I understand that there is no articles in test database. Where I did mistake? tests.py: class ArticleViewTestCase(TestCase): def test_article_create(self): self.client.login(username='user', password="password") response = self.client.get('/article/create/') self.assertEquals(response.status_code, 200) response = self.client.post('/article/create/', { 'head': 'TEST', 'body': 'TEST', 'location': 1, 'public': 1, 'idx': 0, 'image': 'article/images/2017/09/11/planet.jpg' }, follow=True) self.assertEquals(response.status_code, 200) <-- 200 = 200 Correct all_articles = Article.objects.all() self.assertEquals(len(all_articles), 1) ERROR: FAIL: test_article_create (slider.tests.ArticleViewTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/home/nurzhan/CA/article/tests.py", line 24, in test_article_create self.assertEquals(len(all_slides), 1) AssertionError: 0 != 1 -
Class variable of Django coding style
class ProductNode(models.Model, AbstractSequence): ... attribute = JSONField() def __str__(self): return f'{self.name}' def image_img(self): if self.image: return u'<img src="%s" width="75" height="75" />' % (self.image.url) else: return '(No image)' image_img.short_description = 'Image' image_img.allow_tags = True Hi I am now rewriting the legacy project. I found this coding style. I have no idea what is the purpose and benefit of doing this? -
Video output on browser created using python
I am working on a project with Python and I wonder if it is possible to display an output video embedded in a web page. Consider the code on the following section: Playing video from file. My idea was to replace cv2.imshow('frame',gray), to another command, maybe something with Django (other frameworks can be suggested!). Does anyone have any reference for me to start? PS.: each frame will be generated during execution, so it's not an option to save the video and upload it...