Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
LOGIN_REDIRECT_URL to a specific View
Is there a way to specify a view in the LOGIN_REDIRECT_URL setting in settings.py? I am using django-allauth for registration and logging in. What i am trying to do is as follows: When the user is logged in, determine if the user is_user_A or is_user_B (is_user_A being default). If is_user_A -> redirect to is_user_A-dashboard.html If is_user_B -> redirect to is_user_B-dashboard.html My code is as follows: views.py def logged_in(request): if request.user.is_user_A: return render(request, "is_user_A-dashboard.html") if request.user.is_user_B: return render(request, "is_user_B-dashboard.html") settings.py LOGIN_REDIRECT_URL = '/' -
If time is more and less the one day in django app
I have django app and problems with set correct conditions for dates: I want to check if it's more than 24 hours (1 day) before event - show days I want to check if it's less than 24 hours (1 day) before event - show hours and minutes Check if event is between date_from and date_to Here are my filters: Task 1 @register.filter(name='if_more_then_24') def if_more_then_24(time): return time + datetime.timedelta(hours=24) > timezone.now() Task 2 @register.filter(name='if_less_then_24') def if_less_then_24(time): return time + datetime.timedelta(hours=24) < timezone.now() Task 3 @register.filter(name='now_online') def now_online(time): return time < timezone.now() @register.filter(name='not_online') def not_online(time): return time > timezone.now() But code didn't work. -
Programmatically launch a new website
I'm building a new Saas platform using Django, which will help businesses from a certain industry create their own e-commerce stores. Still have to choose between Heroku or AWS for hosting (open to other suggestions). The app will create the module for serving content through a web server. The part where I am stuck is after a user has uploaded their products, the web app is generated and the IP address with their DNS provider, how can I launch a website with code? Which Paas platforms allow for it? My apologies if this is not a very smart question to ask. -
Using Django-postman tags in other html pages
SO far I've installed django-postman and it works so fine and successfully updated the default template just fine but now i want to use the django-postman tags in someother pages such as the navbar ... but i can't get it to work here is a look at my <li class="dropdown messages-menu"> <a href="#" class="dropdown-toggle" data-toggle="dropdown"> <i class="fa fa-envelope-o"></i> <span class="label label-success">4</span> </a> <ul class="dropdown-menu"> <li class="header">You have 4 messages</li> <li> <!-- inner menu: contains the actual data --> <ul class="menu"> <li><!-- start message --> <a href="#"> <div class="pull-left"> <img src="{{ user.user.photo.url }}" class="img-circle" alt="User photo"> </div> {% block pm_sender_cell %} <h4 class="mailbox-name">{{ message.obfuscated_sender|or_me:user }}{% if message.count %} ({{ message.count }}){% endif %}</h4>{% endblock %} <small><i class="fa fa-clock-o"></i> 5 min</small> <p>Message Excerpt</p> </a> </li><!-- end message --> ... </ul> </li> <li class="footer"><a href="#">See All Messages</a></li> </ul> </li> my question is how can i make django-postman tags work on all my pages not only in /messages/inbox -
How to use a custom Oracle sequence for Django Model PK?
I'am integrating Django with a table inside an existing Oracle database, which has a sequence already created and its PK (Numeric) defined. What I want to achieve is to be able to create new rows for this table using the currently defined sequence. How can I do that? -
How to access {% url "name" %} inside 'include' tag
I can't figure out how to get value of {% url "name" %} inside another {% %} tag. In my case its include {% include "file" with next={% url "name" %} %} This doesn't work. Do you know what to do? I would surround the {% include.. by {% with but it would cause the same problem. -
How to Extract distinct Month Name from Database
i have a model with this structure: class Transacao(models.Model): TIPO_TRANSACAO = ( ('D', 'Debito'), ('C', 'Credito'), ) nome = models.CharField(null=False, max_length=20) tipo = models.CharField(max_length=1, choices=TIPO_TRANSACAO, default='D') valor = models.DecimalField(max_digits=20, decimal_places=2, default=0) data = models.DateField(auto_now=False) I would like to retrieve the Month's name for every Transaction, ordered by the 'date' field. Any clue on that? -
How To get just only the added this object when many to many table is updated
from django.contrib.auth.models import User from django.db.models.signals import post_save, m2m_changed from django.dispatch import receiver # Create your models here. class FollowersModel(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1, related_name='usr') follow = models.ManyToManyField(User, related_name="whom") my_followers = models.ManyToManyField(User, related_name='my_followers') update = models.DateTimeField(auto_now=True) timestamp = models.DateTimeField(auto_now_add=True) def __unicode__(self): return str(self.user) @receiver(m2m_changed, sender=FollowersModel.follow.through) def follow_by_follow_add_or_remove(sender, **kwargs): if kwargs.get('action') == 'post_add': print kwargs.get('instance').follow.all() In this example when I print kwargs.get('instance').follow.all() then I can get the whole lists of follow label but I just want to get only the added one, I mean I am searching kind of print kwargs.get('instance').follow.this(), just like jquery we do 'this.append()' only the added one -
boto3 django transfer.upload_file is breaking image, incomplete transfer
I am using boto3 library for transferring user uploaded image on my web application to S3 bucket, i am using transfer.upload_file but strangely part of the image gets vanished in uploaded file, though file seems perfect on instance but not in S3 bucket, any help would be really great. -
How Do I Make A Django (Python) Project Use Only A Specific Interpreter?
I am trying to set up a Django project. Initially I had Python 3.5 installed for a data analysis project I worked on. So while Python 3.5 works in tandem with matplot, pandas, scipy etc, the Django tutorial recommended I use 2.7 for the Django project as MySQL support for Python 3.5 is only third-party. I am also required to download Microsoft Visual C++ 14.0 anytime I try pip install mysqlclient for 3.5. Unfortunately my internet connection/data is quite limited. The thing is, I have installed 2.7 and it resides in C:\Python27. Python 3.5 is installed in C:\Users\XXXX\AppData\Local\Programs\Python\Python35-32 I have created a project directory - django-admin startproject myproject. I have installed the MySQLDb package to C:\Python27. But each time I attempt from command promptC:\Users\XXXX\Documents\WebDev\seedstars> python manage.py runserver, I get this error message: Traceback (most recent call last): File "C:\Users\XXXX\AppData\Local\Programs\Python\Python35-32\lib\site- packages\django\db\backends\mysql\base.py", line 25, in <module> import MySQLdb as Database ImportError: No module named 'MySQLdb' I tried setting my Python interpreter in PyCharm to Python 2.7. Each time I do this - python manage.py runserver, it reverts back to the error above. Please, how do I set this Django project to only "listen" to the Python2.7 interpreter, at cmd? Thanks. -
Moving a django instal to a new server and I'm getting a 403 error
I'm trying to move a django installation to a new server with a different IP. I'm setting up as a development initially to check everything works before going live and switching from the original site. I'm getting the following when I try to login as admin: CSRF verification failed. Request aborted. It's an exact copy of the other version except for domain name. I can log into the other site. Is there any reason that moving a django site would cause this? Thanks for your help -
Proper way of passing query from form to url in Django class based view
I want to learn a proper way of passing query from form to url in Django class based view. I want to retrieve form data in ListView to make query on the model. I'm currently using this, but i feel that there's a better way. class SearchFormView(FormView): form_class = SearchForm ... def form_valid(self, form): return HttpResponseRedirect('?'+urllib.parse.urlencode(form.data)) -
Django1.8 and Python 2.7: Radio button stores the first option whatever is my choice
I'm using Django 1.8 and python 2.7 In my template I have a radio button. <div class="form-group"> <label class="col-md-4 control-label" for="radios">Liquids:</label> <div class="col-md-4"> <label class="radio-inline" for="radios"> <input type="radio" name="liquids" id="liquids" value="1" disabled> With cough </label> <label class="radio-inline" for="radios"> <input type="radio" name="liquids" id="liquids" value="0" > No cough </label> </div> </div> When I push the submit button whatever is my choice, the first option is taken as selected. Do you know how to fix this? Also, when I render the template having filled values with selected the 2nd option, the radio button for the first option is selected in template. -
Substract 2 time fields in a ModelForm
I am trying to build a small logBook for pilots, where a user inputs the take off time and the time he landed and the forms returns below that duration in the form: 02:34 hrs i.e 2 hours 34 minutes. on the models.py side this is how I set it up: take_off_time = models.TimeField() land_time = models.TimeField() tot_time_field = models.DurationField() model.Duration doesn't seem to be the answer here... On the forms.py so far I simply rendered the model. So the questions are: What could i use instead of durationField? How can I take the inputs and render the calculation? I have tried in the models.py a simple: def get_total_time(self): self.tot_time_field = self.land_time - self.take_off_time return self.tot_time and then use tot_time in the form but I am not sure this is correct. -
Django CSRF verification failed. Request aborted even with @csrf_exempt
This is my view.py I am getting to get a response from a Payment Gateway but m getting an 403 Forbidden CSRF verification failed. Request aborted. after Payment I exempted CSRF Token for the view but still its showing same Error from django.views.decorators.csrf import csrf_exempt @csrf_exempt def resp(request, encResp): print " RESPONSE WITH CSRF EXEMPT " ''' Please put in the 32 bit alphanumeric key in quotes provided by CCAvenues. ''' workingKey = WorkingKey decResp = decrypt(encResp,workingKey) data = '<table border=1 cellspacing=2 cellpadding=2><tr><td>' data = data + decResp.replace('=','</td><td>') data = data.replace('&','</td></tr><tr><td>') data = data + '</td></tr></table>' html = '''\ <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Response Handler</title> </head> <body> <center> <font size="4" color="blue"><b>Response Page</b></font> <br> $response </center> <br> </body> </html> ''' fin = Template(html, csrfContext).safe_substitute(response=data) return HttpResponse(fin) I read many solutions on stackoverflow but still cant get it right -
uploading image to django rest model
I am trying to upload image to Images folder which under the media directory. I am using following APIView on my views.py; class FileUploadView(APIView): parser_classes = (FileUploadParser,) def post(self, request, format='jpg'): up_file = request.FILES['file'] destination = open('C:\\Users\\cano\\Desktop\\workspace\\campusBackend\\campusBackend\\media\\Images', 'wb+') for chunk in up_file.chunks(): destination.write(chunk) destination.close() return Response(up_file.name, status.HTTP_201_CREATED) However, when I sent request, it gives me the following error; PermissionError: [Errno 13] Permission denied: 'C:\Users\cano\Desktop\workspace\campusBackend\campusBackend\media\Images' [12/Dec/2016 15:10:45] "POST /imageUpload HTTP/1.1" 500 19170 I have already added MEDIA_ROOT and MEDIA_URL in settings.py; MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' -
Create one index per Django model in Haystack
I got basic Haystack working with Django as per the Getting Started of Haystack's docs. with Elasticsearch. I have two Django models: Product and Store, and have created corresponding SearchIndex classes for them. When I run the python manage.py rebuild_index command, only one index is being built and that contains documents of both my Product and Store objects. How do I get Haystack to create separate indices in Elasticsearch, one for Product and one for Store? -
How to redirect from one view to another?
I have an x view that redirects me to some_name.html page. This view needs to create a class that it is importing from other python file. This view calls a specific function (algorithm) that has some logic in it. lets say this func return a dictionary. I want that view 'x' will redirect me to negotioate.html page with this dynamic return dictionary. When the user gets the output he should choose from 3 options and basically trigger the algorithm again. Meaning, I want in each of those trigger to display the user the algo output but without reidrecting me to other page, but refreshing the current one. -
Django - Multiple users assign different names for the same object
I'm trying to add attribute to relationship. I have a model Scheduler, Product and User. There are multiple Scheduler objects in database. Each can have multiple products. And each product has some of those schedulers. The user can choose which scheduler to use with a product. I want user to be able to name this scheduler (note that one scheduler can be used by many products by multiple users). Use case: User creates a product and choose from allowed schedulers. When they choose the scheduler they can assign some name to this scheduler. For user1, the scheduler with id=5 has name='My scheduler - everyday' For user2, the same scheduler (id=5) has name='Everyday schedule' class Product(models.Model): user = models.ForeignKey(User, null=False, blank=False) scheduler = models.ForeignKey('Scheduler', null=True, blank=True, related_name='products') class Scheduler(models.Model): weekhours = models.ManyToManyField('WeekHour', related_name='schedulers') identificator = models.TextField(null=True,blank=True) Is it possible to do that in some simple way? -
How to move Django media files
I need to move a django site from one server to another. How do I move the media files so that the new site serves the media files previously loaded in the old location -
commenting system for Django 1.10
I am new to Django, I don't know a lot of them. I am trying to build a comment system for a blog in Django 1.10. Can anyone help me please ?? Best Regards -
Django logs in apache vhost error file, how to fix
I've a django running with WSGI and it sends logs to the error file that i setup in the vhost of apache. the logging configuration is the following 'django': { 'handlers': ['logfile'], 'level': 'INFO', 'propagate': True, }, 'django.requests': { 'handlers': ['slack_error'], 'level': 'ERROR', 'propagate': False, }, 'django.requests': { 'handlers': ['logfile'], 'level': 'INFO', 'propagate': True, }, and this 'version': 1, 'disable_existing_loggers': True, 'formatters': { 'standard': { 'format': "[%(asctime)s] %(levelname)s [%(name)s.%(funcName)s:%(lineno)s] %(message)s", 'datefmt': "%d/%b/%Y %H:%M:%S" }, 'onlymsg': { 'format': '%(message)s' }, }, 'handlers': { 'logfile': { 'level': 'INFO', 'class': 'logging.handlers.RotatingFileHandler', 'filename': "/var/log/web.log", 'maxBytes': 5000000, 'backupCount': 3, 'formatter': 'standard', }, 'slack_chino_error': { 'level': 'ERROR', 'class': 'handler.AdminSlackHandler', 'formatter': 'onlymsg', 'slack_url': 'https://hooks.slack.com/...', 'channel': '#error_notification', 'username': SERVER_NAME }, apache vhost is the follwing # LOG Possible values include: debug, info, notice, warn, error, crit, alert, emerg. CustomLog /var/log/web_access.log combined ErrorLog /var/log/web_error.log LogLevel warn Now if i open the web_error.log file it's full of django logs [Mon Dec 12 12:16:20.054977 2016] [wsgi:error] [pid 13255:tid 139989789542144] GET console.views.generic.generic_view [Mon Dec 12 12:18:11.222981 2016] [wsgi:error] [pid 13255:tid 139991418357504] GET console.views.user_info.UserInfo and I think the reason is beacuse of the [wsgi:error] which I don't know why it saying so, or for other reasons that I don't know. any help on … -
Can someone translate this to django query
SELECT a.title, COUNT(r.id) FROM myblog_category a JOIN myblog_post r on a.id=r.category_id GROUP BY a.title How to spell this in django orm query? Which options should i use from queryset? -
Django setup_environ alternative
I used this code with setup_environ, I upgraded django and scrapy and it doesn't work anymore. Could you please help me to adapt this code : def setup_django_env(path): import imp, os from django.core.management import setup_environ f, filename, desc = imp.find_module('settings', [path]) project = imp.load_module('settings', f, filename, desc) setup_environ(project) # Add django project to sys.path import sys sys.path.append(os.path.abspath(os.path.join(path, os.path.pardir))) setup_django_env('/home/myproject/project') -
Django admin dependent foreign key
So i have a model for example Sport and this sport have Type and Type have subtype so i made a 3 models: class Sport(models.Model): name = models.CharField(_('Name of Sport'), blank=False, max_length=255) class SportType(models.Model): name = models.CharField(_('Sport Type'), blank=False, max_length=255) class SportSubType(models.Model): name = models.CharField(_('Sub Category Name'), blank=False, max_length=255) sport_style = models.ForeignKey(SportType, on_delete=models.CASCADE) Now in django admin: class StyleSubInline(admin.StackedInline): model = SportSubType extra = 1 class SportStyleAdmin(admin.ModelAdmin): model = SportType inlines = [StyleSubInline] admin.site.register(Sport) admin.site.register(SportType, SportStyleAdmin) But problem is that i want these two fields in Sport admin, that they are related when choose SportType i get ability to chose its Sub types, how should i solve this?