Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
'Unicode' object has no attribute 'items'
I am using Cassandra DB and Django Framework, I was trying to get the partial information of a particular user from the database and tried to compare it to the user input but instead of returning an output, it showed me a "Unicode object has no attribute items" error This is the error details for your reference: AttributeError at /auth-user-session/ 'unicode' object has no attribute 'items' Request Method: POST Request URL: http://127.0.0.1:8000/auth-user-session/ Django Version: 1.10.5 Exception Type: AttributeError Exception Value: 'unicode' object has no attribute 'items' Exception Location: /usr/local/lib/python2.7/dist-packages/django/db/backends/base/operations.py in last_executed_query, line 215 Python Executable: /usr/bin/python Python Version: 2.7.12 Python Path: ['/home/chamber/Desktop/Emergency-Command-Center-SOFTDEV/Application/Emergency-Command-Center', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-x86_64-linux-gnu', '/usr/lib/python2.7/lib-tk', '/usr/lib/python2.7/lib-old', '/usr/lib/python2.7/lib-dynload', '/home/chamber/.local/lib/python2.7/site-packages', '/usr/local/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages/PILcompat', '/usr/lib/python2.7/dist-packages/ubuntu-sso-client'] Server time: Tue, 14 Mar 2017 08:08:05 +0000 This is the code: views.py def LoginAuthPageView(request): if request.method == 'POST': form = Login(request.POST) if form.is_valid(): username = form.data['username'] password = form.data['password'] cursor = connection.cursor() result = cursor.execute("SELECT salt, password FROM emergency_command_center.auth_user_model WHERE username = ?", username) pword_hash = hashlib.sha512(password + result['salt']).hexdigest() if(pword_hash == result['password']): return HttpResponse(pword_hash) Am I doing something wrong? -
django encode UnicodeEncodeError
I have a problem in django project. UnicodeEncodeError at /contact/1/view 'ascii' codec can't decode byte 0xd0 in position 28: ordinal not in range(128) in Traceback: views.py in single_contact 'vcard_str': unicode(VCard(contact)), and all view def single_contact(request, pk): contact = Contact.objects.get(pk = pk) if contact.group.user != request.user.profile: raise Http404 if request.method=="GET": emails = Email.objects.filter(contact = contact) hash = '' if emails: email = emails[0] hash = get_hash(email.email) addresses = Address.objects.filter(contact = contact) if addresses: address = addresses[0] phones = PhoneNumber.objects.filter(contact=contact) return render(request, 'dashboard/addressbook/single_contact.html', RequestContext(request, { 'contact':contact, 'emails':emails, 'hash':hash, 'addresses':addresses, 'phones':phones, 'vcard_str': unicode(VCard(contact)), })) elif request.method=="POST": contact.delete() return HttpResponseRedirect(reverse('addressbook_index')) else: raise Http404 but if i change sting 'vcard_str': unicode(VCard(contact)), to 'vcard_str': VCard(contact).encode("utf-8") i got another error: AttributeError at /contact/1/view 'VCard' object has no attribute 'encode' what i'm doing wrong ? how can i fix this? -
How to code a 5 second timer in django?
Task: (in Django - pycharm webpage) File/webpage-1:: ~ Needs to have 1 textbox where user can enter any number. Let's keep it 50 initially. ~ Needs to have submit button named OK. (Now when the user clicks OK button, it shall be redirected to file2/webpage-2) file2/webpage-2 :: Displays 50 After 5 seconds displays 51, again after 5 seconds displays 52 ... And further. Its keeps on incrementing the counter after 5 second delay. I Presently am unfamiliar with Python and django, also applied sleep method as suggested in stack overflow but all in vain. Currently working on django installation and its tutorials. -
Django HTML Array Form Passing
I have the following HTML form I am submitting to Django using post: input id="array" type="text" class="arrayinput" name="array[]" placeholder="Thing 1"> input id="array" type="text" class="arrayinput" name="array[]" placeholder="Thing 2"> input id="array" type="text" class="arrayinput" name="array[]" placeholder="Thing 3"> And in the model of this form I have: array = ArrayField(CharField(max_length=255, blank=True, null=True)) However when I submit this array, it tells me that the form is missing the field array. I assume this is because the field is called "array[]" but obviously I cannot name a python variable this. On the other hand, I cannot find any way to make a HTML array that has the functionality I need. -
How to add custom benefit in django-oscar?
Django-oscar provides multibuy benefit type. class MultibuyDiscountBenefit(Benefit): _description = _("Cheapest product from %(range)s is free") Now, I can add Buy 1 get 1 free offer with this benefit. I have a little custom requirement here. I want to add 'Buy 1 get 50% off on second' offer. To do so, I need to add custom benefit. I checked docs for adding custom benefit. And as per doc says..A custom benefit can be used by creating a benefit class and registering it so it is available to be used.. Following docs, I created my custom benefit for that. class MultiBuyCustom(Benefit): class Meta: proxy = True @property def description(self): """ Describe what the benefit does. This is used in the dashboard when selecting benefits for offers. """ return "But 1 and get 50% off" Here I don't know how to register this custom benefit to using in dashboard.? I need this benefit in the dropdown at dashboard while creating the offer. Any help would be greatly appreciated. -
Django, Is a directory error, when setting up templates folder inside app
I have a Django v1.10 project wherein I have following structure project --app ----templates --templates Basically, I have my app specific templates within them and base templates in outer templates folder which is sub directory of project. Let say, I have a file called base.html in templates folder which is in project. When I try to extend it in my app/templates/anytemplate.html I get an error as follows: IsADirectoryError: [Errno 21] Is a directory: '/project/templates' My initial google search brought me to this page on google groups, which is exactly my case. Is there a different way to set it up. Also, the way I extend base.html in anytemplate.html is as follows: {% extends 'base/base.html' %} -
Error creating django application: Pycharm MAC
Click here for error prompt image[This is the error occurs when I create a new django application on mac, I have given all the permission for the respective folder, any help will be appreciated] -
django encode UnicodeEncodeError at /
I have a problem in django project. UnicodeEncodeError at /contact/1/view 'ascii' codec can't decode byte 0xd0 in position 28: ordinal not in range(128) in Traceback: views.py in single_contact 'vcard_str': unicode(VCard(contact)), and all view def single_contact(request, pk): contact = Contact.objects.get(pk = pk) if contact.group.user != request.user.profile: raise Http404 if request.method=="GET": emails = Email.objects.filter(contact = contact) hash = '' if emails: email = emails[0] hash = get_hash(email.email) addresses = Address.objects.filter(contact = contact) if addresses: address = addresses[0] phones = PhoneNumber.objects.filter(contact=contact) return render(request, 'dashboard/addressbook/single_contact.html', RequestContext(request, { 'contact':contact, 'emails':emails, 'hash':hash, 'addresses':addresses, 'phones':phones, 'vcard_str': unicode(VCard(contact)), })) elif request.method=="POST": contact.delete() return HttpResponseRedirect(reverse('addressbook_index')) else: raise Http404 what im doing wrong? how can i fix this ? -
(Python 3.6.0 Django 1.10.6) how to fix python manage.py runserver
Everytime i run the python manage.py runserver on powershell the python application forces to stopped. How to fix this? -
Sorl-thumbnail generates black lines and undesired crops
I'm using Sorl Thumbnail 12.4a1, Pillow 4.0.0 in a django project It works fine for most images but for some of them I run into unexpected behaviour. The original image is portrait jpg 765x1110 After running this code: get_thumbnail('/media/ryzsUIKZVUc.jpg', '464', upscale=False) I receive a 464x320 image with black background on it's left and right and cropped on top and bottom this is the original: https://www.dropbox.com/s/ia7906ec19xjhro/ryzsUIKZVUc.jpg?dl=0 and this is the result: https://www.dropbox.com/s/adgut5zkw4xln6e/62b2439654a00312defafddb862eda9b.jpg?dl=0 p.s. tried to upload the original here as an image but it was automatically converted to portrait.. could it mean something? -
Not data is retrieved form Database
I am using Django 1.8.6 and python 3.6. I am quite new to django and python, trying to make a blog .I am not able retrieve the data form database. Even though it is in there in data base my model.py class Post(models.Model): STATUS_CHOICES = (('draft', 'Draft'), ('published','Published'), ) title = models.CharField(max_length=250) slug = models.SlugField(max_length=250, unique_for_date='publish') author = models.ForeignKey( User, blank=True, null=True, ) body = models.TextField() publish = models.DateTimeField(default=timezone.now) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) status = models.CharField( max_length=10, choices=STATUS_CHOICES, default='draft') objects = models.Manager() # The default manager published = PublishedManager() # custom manager class Meta: ordering = ('-publish', ) def __str__(self): return self.title def get_absolute_url(self): return reverse( 'blog:post_detail', args=[ self.publish.year, self.publish.strftime('%m'), self.publish.strftime('%d'), self.slug ]) view which handles this model is def post_detail(request, year, month, day, post): post = get_list_or_404( Post, slug=post, status='published', publish__year=year, publish__month=month, publish__day=day) return render(request, 'blog/post/detail.html', {'post': post}) when us the html template for getting data <p>Published {{ post.pulish }} by {{ post.author }}</p> The output is just " Published by" But when I use just {{ posts }} I getting output [<Post: this is Me>] "this is Me " is the title of post saved in database Thanks in advance for your time and effort.It would β¦ -
Multiple views in same page
In my django blog project i have multiple views to handle multiple task view 1 ----> renders a form for creating a new post (includes title, content) view 2 ----> renders a form for searching different blog posts based on the title view 3 ----> displays trending blog posts of other users how can I render all this in the same profile.html page? Can I use a view 4 which includes all the 3 views and let it render the profile.html page? -
How to use git to implement a simple versioning system?
I wish to create an interface where the user can list, upload and modify existing files. The user should also be able see the past snapshots of their files and permanently revert to a past snapshot if they so desire. My use case is similar to this. I am thinking of something like GitHub.com, but with a very simple interface that anyone will be able to understand (e.g. web interface only, one branch only, ...) What are the options available to create this kind of simple versioning system? Or should I need to integrate git into my Django project? (pointers on how to do this would be appreciated. It's my first time doing this.) -
Django won't serve some static files
I'm not sure what's happening but for some reasons django won't serve some scripts, and give me a not found error, despise the directory displayed being correct, while others in the same directory has no issue serving. Here is my file directory structure mysite/ βββ imagenes β βββ migrations β β βββ __pycache__ β βββ __pycache__ β βββ recibo β βββ static β β βββ css β β βββ js β βββ templates β βββ imagenes βββ media β βββ recibos β βββ 2017 β βββ 03 β βββ 10 βββ mysite β βββ __pycache__ β βββ static β βββ sitioI βββ static β βββ css β βββ js β βββ jquery-file-upload βββ templates βββ registration Here are my setting: STATIC_ROOT = os.path.join(BASE_DIR, "static") STATIC_URL = '/static/' STATICFILES_DIR= [ os.path.join(BASE_DIR, "static"), ] the static files used in upload.html, out of which only lightbox.css and lightbox.js are served: {% extends 'imagenes/base.html' %} {% load static %} {% block style %} <link rel="stlyesheet" href="{% static 'css/lightbox.css' %}"> {% endblock %} . . . {% block scripts %} <script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.1.1.min.js"></script> <script src="{% static 'js/lightbox.js' %}" ></script> <script src="{% static 'js/jquery-file-upload/vendor/jquery.ui.widget.js' %}"></script> <script src="{% static 'js/jquery-file-upload/jquery.iframe-transport.js' %}"></script> <script src="{% static 'js/jquery-file-upload/jquery.fileupload.js' %}"></script> <script src="{% β¦ -
Django automatic logout not working
For the automatic logout middleware code is below..Its not showing an error but its not logging out after 2 minutes..where have i gone wrong??? class AutoLogout(object): def init(self, get_response): self.get_response = get_response def __call__(self, request): if (request.COOKIES == None): return try: if datetime.now() - request.session['last_touch'] > timedelta(0, settings.AUTO_LOGOUT_DELAY * 60, 0): logout(request) del request.session['last_touch'] return self.get_response(request) else: request.session['last_touch'] = datetime.now() return self.get_response(request) except KeyError: # KeyError thrown if last touch doesn't exist, so set it. request.session['last_touch'] = datetime.now() return self.get_response(request) -
Incorrectly crope the picture
Got code for crope image x = int(request.POST.get('x')) y = int(request.POST.get('y')) h = int(request.POST.get('h')) w = int(request.POST.get('w')) user = RegModel.objects.get(id=request.user.id) user.cropping.delete(save=True) picture_copy = ContentFile(user.image.read()) new_picture_name = user.image.name.split("/")[-1] user.cropping.save(new_picture_name, picture_copy) image = Image.open(user.cropping) cropped_image = image.crop((x, y, w + x, h + y)) resized_image = cropped_image.resize((200, 200), Image.ANTIALIAS) resized_image.save(user.cropping.path) In my template jquery set parameters for crope image x, y, width, height and that i send it to server. Jquery show for me how will look croped image but after croped image on server backend imge look incorrectly. Where my falt? -
Images not rendering in Django in pages with forms
Forewarning, I am very new to Django and Python in general. So my images render perfectly with all my other urls. But lets say I have a blog and when I edit a blog post, the url would be as follows: http://127.0.0.1:8000/post/14/edit/ Or for adding a comment: http://127.0.0.1:8000/post/3/comment/ And the images would not render for those urls. The pattern seems kind of obvious but I still don't know what the issue is. Now, if I was just creating a new post, with the url: http://127.0.0.1:8000/post/new/ The images render fine. Is this a caching issue or what? I've tried clearing my cache and it will work for a little bit and then fail to render later. Any suggestions? Thanks in advance! -
Attempting to deploy to Heroku using Django: Error R10 (Boot timeout)
I am able to successfully run my application locally in production mode. My Procfile currently uses gunicorn to run the application: web: gunicorn weirwood.wsgi I have attempted adding ${PORT} and $PORT to the end of the line as suggested by some members to no avail. Python runtime version is 3.6~. I built the application using Django and my modules are bundled using webpack if that helps. Below is the error log: 2017-03-14T03:20:09.362878+00:00 app[web.1]: webpack: bundle is now VALID. 2017-03-14T03:20:09.362878+00:00 app[web.1]: [353] ./assets/js/simpleMap.js 2.24 kB {0} [built] 2017-03-14T03:20:59.804195+00:00 heroku[web.1]: Error R10 (Boot timeout) -> Web process failed to bind to $PORT within 60 seconds of launch 2017-03-14T03:20:59.804195+00:00 heroku[web.1]: Stopping process with SIGKILL 2017-03-14T03:20:59.959643+00:00 heroku[web.1]: State changed from starting to crashed 2017-03-14T03:20:59.949409+00:00 heroku[web.1]: Process exited with status 137 2017-03-14T03:32:57.987295+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=stuff.herokuapp.com request_id=2cb0fd4e-a2a4-42b1-8152-99f0ba6384a3 fwd="98.259.126.70" dyno= connect= service= status=503 bytes= protocol=https -
How to Query Django
Good nigth,I have a problem that I do not know how to solve it. I have three models in my application: class Hecho(models.Model): codigo = models.CharField(max_length=1) hecho = models.CharField(max_length=100) class Beneficiario(models.Model): tipoDocumento = models.CharField(max_length=150) numeroDocumento = models.IntegerField() nombre = models.CharField(max_length=150) class HechoBeneficiario(models.Model): beneficiario = models.ForeignKey(Beneficiario) hecho = models.ForeignKey(HechoVictimizante) As you can see the model HechoBeneficiario relates the other two models. My problem is like using the Beneficiario model can I get the model Hecho and paint this in a template? -
Django React Ajax Method not Found Err:404
urls.py urlpatterns = [ url(r'^producttype/$', views.producttype, name='producttype'), url(r'^createnewproducttype/', views.createnewproducttype, name='createnewproducttype'), ] views.py def createnewproducttype(request): print("here") producttype = json.loads(request.body) obj = ProductType() obj.desc = producttype["desc"] obj.status = producttype["status"] print("before save") obj.save(); print("after save") return HttpResponse('') ajax $.ajax({ "url": "/products/producttype/createnewproducttype/", "data" : {'producttype':JSON.stringify(producttype)}, "type" : 'POST', beforeSend: function(xhr, settings) { function getCookie(name) { var cookieValue = null; if (document.cookie && document.cookie != '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = jQuery.trim(cookies[i]); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) == (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } console.log(cookieValue); return cookieValue; } if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) { // Only send the token to relative URLs i.e. locally. xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken')); } }, success: function(data){ alert("success"); }, error:function(XMLHttpRequest, textStatus, errorThrown){ console.log(XMLHttpRequest); console.log(textStatus); console.log(errorThrown); } }) Ajax is made inside .js file using ReactJs. The Url producttype is found. But if I use the createnewproducttype url. It returns method no found. Im am just noob both in React and Django so I have no idea what is the reason behind the error. -
Host django app and mediawiki on same server
I want to host a django app alongside a media wiki on the same server (same ec2 instance) in such a way that my domain example.com points to my django app and a subdomain like wiki.example.com points to the media wiki server. I want to do this with nginx as I have deployed my django app using the instructions on this link: http://michal.karzynski.pl/blog/2013/06/09/django-nginx-gunicorn-virtualenv-supervisor/ Essentially, I want to add mediawiki for my website and it should be accessible via wiki.example.com How do I go about it? -
What is the best approach to handle user registration through invitation?
I want to implement the feature where users are not given to signup account directly. A request invitation button will be there. When user clicks for request invitation with an email address, a link will be send with token and when user clicks on that link, the user will be redirected to signup page. What i come up with is this tutorial on invitation but its a outdated one and it says it is not well suited for production purpose. from django.contrib.auth.models import User class Invite(models.Model): user = models.OneToOneField(User) cookie = models.SlugField() token = models.SlugField() def __unicode__(self): return u"%s %s's invite" % (self.user.first_name, self.user.last_name) @models.permalink def get_absolute_url(self): return ('invites.views.confirm_invite', [self.token]) class InviteMiddleware(object): def process_request(self, req): if req.path == '/i.auth': return None if not req.user.is_authenticated(): if 'token' in req.COOKIES: return redirect('invites.views.login_user') return None def process_response(self, req, resp): if req.user.is_authenticated(): if req.user.is_staff: return resp if 'token' in req.COOKIES: token = req.COOKIES['token'] else: invite = Invite.objects.get(user=req.user) token = invite.cookie resp.set_cookie('token', token, max_age=1209600) return resp class InviteForm(forms.Form): username = forms.CharField(max_length=20) first_name = forms.CharField(max_length=40) last_name = forms.CharField(max_length=40) email = forms.EmailField() def invite_user(req): if req.method == 'POST': form = InviteForm(req.POST) if form.is_valid(): user = User.objects.create_user(form.cleaned_data['username'], form.cleaned_data['email'], '**') user.first_name = form.cleaned_data['first_name'] user.last_name = form.cleaned_data['last_name'] user.is_active = False β¦ -
Website that builds a graphic representation of visitors' choices building a product
I'm trying to build a website that will create a visual representation of a product based on the users' choices. Take for example, wreathed. On the first screen, the user would be presented with three options. When the make their choice, the base would be displayed. On the second screen, they would choose a bow and its placement, which would also be displayed. On so on... I'm currently learning Python/Django, so hopefully this would utilize a complementary framework/language. I understand the logic, just am not sure where to head to look for tying in the graphical aspect. I'm a quick learner, and learn best by doing, examples, tutorials, etc. Any help pointing me in the right direction would be greatly appreciated. Thanks! -
Redirect to "next" after python-social-auth login
In my settings.py I have the following: LOGIN_URL = 'Eapp:login' LOGOUT_URL = 'Eapp:logout' LOGIN_REDIRECT_URL = 'Eapp:login' And in my template I've got the following <a href="{% url 'social:begin' 'facebook' %}?next={{request.path}}"> Next takes it to the correct url but it's followed by #_=_ Which is what I'm trying to get rid of. -
cannot import name views - django
I am using Visual Studio 2013, and, Python Tools for VS 2013 to get started with a Django website. It gives the following error, Full traceback, Performing system checks... Traceback (most recent call last): File "C:\Users\my_username\documents\visual studio 2013\Projects\DjangoWebProject1\DjangoWebProject1\manage.py", line 17, in <module> execute_from_command_line(sys.argv) File "C:\Python27\lib\site-packages\django\core\management\__init__.py", line 367, in execute_from_command_line utility.execute() File "C:\Python27\lib\site-packages\django\core\management\__init__.py", line 359, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Python27\lib\site-packages\django\core\management\base.py", line 294, in run_from_argv self.execute(*args, **cmd_options) File "C:\Python27\lib\site-packages\django\core\management\commands\runserver.py", line 58, in execute super(Command, self).execute(*args, **options) File "C:\Python27\lib\site-packages\django\core\management\base.py", line 345, in execute output = self.handle(*args, **options) File "C:\Python27\lib\site-packages\django\core\management\commands\runserver.py", line 97, in handle self.run(**options) File "C:\Python27\lib\site-packages\django\core\management\commands\runserver.py", line 108, in run self.inner_run(None, **options) File "C:\Python27\lib\site-packages\django\core\management\commands\runserver.py", line 121, in inner_run self.check(display_num_errors=True) File "C:\Python27\lib\site-packages\django\core\management\base.py", line 374, in check include_deployment_checks=include_deployment_checks, File "C:\Python27\lib\site-packages\django\core\management\base.py", line 361, in _run_checks return checks.run_checks(**kwargs) File "C:\Python27\lib\site-packages\django\core\checks\registry.py", line 81, in run_checks new_errors = check(app_configs=app_configs) File "C:\Python27\lib\site-packages\django\core\checks\urls.py", line 14, in check_url_config return check_resolver(resolver) File "C:\Python27\lib\site-packages\django\core\checks\urls.py", line 24, in check_resolver for pattern in resolver.url_patterns: File "C:\Python27\lib\site-packages\django\utils\functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Python27\lib\site-packages\django\urls\resolvers.py", line 313, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "C:\Python27\lib\site-packages\django\utils\functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Python27\lib\site-packages\django\urls\resolvers.py", line 306, in urlconf_module return import_module(self.urlconf_name) File "C:\Python27\lib\importlib\__init__.py", line 37, in import_module __import__(name) File "C:\Users\my_username\documents\visual studio 2013\Projects\DjangoWebProject1\DjangoWebProject1\DjangoWebProject1\urls.py", β¦