Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django multiple active item carousel
I am pulling the products from database and trying to display them in multiple frames/items of carousel on a screen rather than a single item using for loop. This is what my carousel looks like at present, as you will notice only one item is displayed, but i want it to display 4 items at one slide and next four on clicking arrow button and so on. click here to see my carousel image. my Django code looks like this-- <div id="recommended-item-carousel" class="carousel slide" data-ride="carousel"> <div class="carousel-inner"> {% for prod in pro %} <div class="item{% if forloop.first %} active{% endif %}"> <div class="col-sm-3"> <div class="product-image-wrapper1"> <div class="single-products"> <div class="productinfo text-center"> <!--sample image, same for all--><img src="{% static 'header/images/home/2508__14291.1437672247.200.200.jpg' %}" alt="" /> <h2>{{prod.productname}}</h2> <p>{{prod.producttype}}</p> <a href="#" class="btn btn-default add-to-cart"><i class="fa fa-shopping-cart"></i>Add to cart</a> </div> </div> </div> </div> </div> {% endfor %} </div> <a class="left recommended-item-control" href="#recommended-item-carousel" data-slide="prev"> <i class="fa fa-angle-left"></i> </a> <a class="right recommended-item-control" href="#recommended-item-carousel" data-slide="next"> <i class="fa fa-angle-right"></i> </a> </div> -
Upgraded from Django 1.8 to 1.1 and TemplateDoesNotExist error
I upgraded my Django version from 1.8 to 1.10 and I had to remove the patterns() in various files in my site_packages folder. I was getting errors like this: File "C:\Python27\lib\site-packages\import_export\admin.py", line 266, in get_urls my_urls = patterns( NameError: global name 'patterns' is not defined So, per the depreciation guidelines, I changed the code to this in the admin.py file. my_urls = [ url(r'^process_import/$', self.admin_site.admin_view(self.process_import), name='%s_%s_process_import' % info), url(r'^import/$', self.admin_site.admin_view(self.import_action), name='%s_%s_import' % info), ] return my_urls + urls I repeated this 3 times in the site_packages folder. However I'm now getting a TemplateDoesNotExist error: Environment: Request Method: GET Request URL: http://127.0.0.1:8000/view_shifts/ Django Version: 1.10.8 Python Version: 2.7.13 Installed Applications: ['django.contrib.auth', 'django.contrib.admin', 'django.contrib.contenttypes', 'django.contrib.messages', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.staticfiles', 'bootstrapform', 'pinax_theme_bootstrap', 'account', 'metron', 'pinax.eventlog', 'table', 'import_export', 'django_tables2', 'django_filters', 'wordcloud', 'mathfilters', 'capes_mantle', 'shift', 'usereval', 'finance'] Installed Middleware: ['django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Template loader postmortem Django tried loading these templates, in this order: Using engine : This engine did not provide a list of tried templates. Traceback: File "C:\Python27\lib\site-packages\django\core\handlers\exception.py" in inner 42. response = get_response(request) File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in _legacy_get_response 249. response = self._get_response(request) File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) … -
AttributeError: module 'django.contrib.auth.views' has no attribute 'login'
I got error on my django rest framework, I am running it on windows 10 OS. this is the entire error: Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "c:\django\django\django\core\management\__init__.py", line 371, in execute_from_command_line utility.execute() File "c:\django\django\django\core\management\__init__.py", line 365, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "c:\django\django\django\core\management\base.py", line 288, in run_from_argv self.execute(*args, **cmd_options) File "c:\django\django\django\core\management\base.py", line 332, in execute self.check() File "c:\django\django\django\core\management\base.py", line 364, in check include_deployment_checks=include_deployment_checks, File "c:\django\django\django\core\management\commands\migrate.py", line 58, in _run_checks issues.extend(super()._run_checks(**kwargs)) File "c:\django\django\django\core\management\base.py", line 351, in _run_checks return checks.run_checks(**kwargs) File "c:\django\django\django\core\checks\registry.py", line 73, in run_checks new_errors = check(app_configs=app_configs) File "c:\django\django\django\core\checks\urls.py", line 13, in check_url_config return check_resolver(resolver) File "c:\django\django\django\core\checks\urls.py", line 23, in check_resolver return check_method() File "c:\django\django\django\urls\resolvers.py", line 385, in check for pattern in self.url_patterns: File "c:\django\django\django\utils\functional.py", line 37, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "c:\django\django\django\urls\resolvers.py", line 524, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "c:\django\django\django\utils\functional.py", line 37, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "c:\django\django\django\urls\resolvers.py", line 517, in urlconf_module return import_module(self.urlconf_name) File "C:\Users\user\AppData\Local\Programs\Python\Python36-32\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen … -
Exclude one choice in a dropdown
Currently I have a drop down list, that is accessible for staff/admin personnel, as part of a ticketing system. In this list however, I'd like to deactivate one of the attributes ("needs review"), if the ticket is already "dealt with". My initial thoughts were to somehow solve this by setting in the settings.py (as a flag), but this is not advised. views.py formOrder_minimal = OrderModelForm_minimal_partII(request.POST) # allows change status, staff-only #formOrder_minimal = OrderModelForm_minimal(instance=order) # allows change status forms.py ''' def get_choices_needsReview(): order = Order.objects.get(id=id) print "order: {0}".format(order) if order.status == 2: # "erledigt" print "order is erledigt, now somewhere else" class OrderModelForm_minimal_partII(forms.ModelForm): def __init__(self, *args, **kwargs): super(OrderModelForm_minimal_partII, self).__init__(*args, **kwargs) self.fields['my_choice_field'] = forms.ChoiceField( choices=get_choices_needsReview() class Meta: model = Order exclude = ('nrVoting','created', 'deadline', 'customer') ''' class OrderModelForm_minimal(forms.ModelForm): """ mmh. dirty. allows status-edit in frontend. """ class Meta: model = Order exclude = ('nrVoting','created', 'deadline', 'customer') models.py class Order(models.Model): from .CHOICES import STATUS_CHOICES, dSTATUS_CHOICES, STATUS_CHOICES_ALREADY_DEALT, dSTATUS_CHOICES_ALREADY_DEALT customer = models.ForeignKey(Customer) created = models.DateTimeField(blank=True) lastUpdate = models.DateTimeField(blank=True, editable=False) user = models.ForeignKey(User,editable=False,blank=True,null=True) ip = models.CharField(editable=False,blank=True, max_length=78, verbose_name='IP') version = models.IntegerField(default=1, editable=False) deadline = models.DateField(blank=True,null=True) nrVoting = models.IntegerField(default=0) if settings.DISABLE_NEEDSREVIEW_ON_STATUS_PLANNING==True: status = models.IntegerField(choices=STATUS_CHOICES_ALREADY_DEALT, default=-1) else: status = models.IntegerField(choices=STATUS_CHOICES, default=-1) CHOICES.py STATUS_CHOICES = (-10, 'still not assigned'), … -
How to add version controlling functionality in a blog made with Django?
It will be a shared blog, many people can contribute to each blog post, i want to add a version controlling functionality, whenever anyone make any changes there would be a little line saying who edited that.like bottom: Sample Header by Alpha, Beta, Gama, omega This is a sample body text, this is cool, this is awesome. ----added by alpha on 27/10/17 : 6.05 Stackoverflow is awesome, it helped me a lot. ----added by beta blockers on 27/10/17: 8.09 Like this..is it possible? -
Filter on JSONField array
I have a book model class Book(): ... tags: JSONField() I have some records: Book(..., tags: ['Tech', 'Business']) Book(..., tags: ['Marketing']) I want to filter out the books those have tag 'Tech' or 'Business' query = Q ( Q(tags__contains='Tech') | Q(tags__contains='Business') ) I've tried to used contains, contained_by, has_key, has_any_keys but got no luck. The result is always empty. -
Does not match background image url on s3 with django
My django project was integrate with AWS S3, It perfectly working on my project, but that was in COMPRESS_ENABLED = False state, Issue: my style.css have lot of images set in background url property in classes, and finally collectstatic and compressed those files, the problem starting from there, if enabled compress. Then we get the files from cache folder, so the background image url was wrong, because the url under cache folder. Example: True - https://domain1.s3.amazonaws.com/img/location/location.jpg False - https://domain1.s3.amazonaws.com/css/style/img/location/location.jpg path of style.css - https://domain1.s3.amazonaws.com/css/style/style.css Regards, AJayan c -
create object with one to one attribute django
I want to create object with set attributes in create function. This is my profile model: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE,related_name='profile') employees = models.ManyToManyField(User, blank=True, null=True, related_name='boss') FatherName = models.CharField(max_length=20,default='',blank=True) NationalCode = models.CharField(max_length=20, default='') birth_date = jmodels.jDateField(null=True, blank=True) PhoneNumber = models.CharField(max_length=20,default='',unique=True) and when I create object emp = User.objects.create(first_name=FirstName, last_name=LastName, username=phonenumber,user__PhoneNumber=phonenumber) error is invalid keyword argument for this function. How can I set PhoneNumber value in Profile model when I try to create User model? tanks all -
How can I authenticate user both in websockets and REST using Django and Angular 4?
I would like to authenticate user both in websockets and REST using Django and Angular 4. I have created registration based on REST API. User after creating an account and log in can send messages to backend using websockets. My question is how can I know that the user authenticated by REST API (I use Tokens) is the same user who sends messages? I don't think that sending Token in every websocket message would be a good solution. Do you have any ideas? consumers.py: Something like this? def msg_consumer(message): text = message.content.get('text') Message.objects.create( message=text, ) Group("chat").send({'text': text}) channel_session_user_from_http def ws_connect(message): # Accept the connection message.reply_channel.send({"accept": True}) # Add to the chat group Group("chat").add(message.reply_channel) message.reply_channel.send({ "text": json.dumps({ 'message': 'Welcome' }) }) @channel_session_user def ws_receive(message): message.reply_channel.send({"accept": True}) print("Backend received message: " + message.content['text']) Message.objects.create( message = message.content['text'], ) Channel("chat").send({ "text": json.dumps({ 'message': 'Next message' }) }) @channel_session_user def ws_disconnect(message): Group("chat").discard(message.reply_channel) -
docker compose cannot connect postgresql database with django
my django app cannot connect to postgresql. I'm using Dockerfile for django and build using docker-compose with postgres official image. docker-compose.yml version: '2' services: db: image: eg_postgresql expose: - 5432 environment: - POSTGRES_PASSWORD=docker - POSTGRES_USER=docker - POSTGRES_DB=postgres web: build: . command: python3 manage.py runserver 0.0.0.0:8000 volumes: - .:/test_application ports: - "8000:8000" links: - "db:db" environment: - DATABASE_URL=postgres://docker:docker@db:5432/postgres - DJANGO_SECRET_KEY=x7-g-xu^h5k%h8860!7ksn=@)7q9frn9_l6tmefvf)y=0)d!uh output: conn = _connect(dsn, connection_factory=connection_factory, **kwasync) django.db.utils.OperationalError: could not connect to server: Connection refused Is the server running on host "localhost" (127.0.0.1) and accepting TCP/IP connections on port 5432? could not connect to server: Cannot assign requested address Is the server running on host "localhost" (::1) and accepting TCP/IP connections on port 5432? docker-compose ps ubuntu@ip-172-31-7-117:~/dj1/helloworld$ sudo docker-compose ps Name Command State Ports ---------------------------------------------------------------------------------- helloworld_db_1 /usr/lib/postgresql/9.3/bi ... Up 5432/tcp helloworld_web_1 python3 manage.py runserve ... Up 0.0.0.0:8000->8000/tcp in app settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'postgres', 'USER': 'docker', 'PASSWORD': 'docker', 'HOST': 'db', 'PORT': '5432', } } I tried in many ways to connect but the issue is same... -
Django Oauth2 Toolkit read access token from request body not headers
I have setup an OAuth2 provider using Django Oauth Toolkit, and it works fine. The issue is that the Client which is making requests to my API does not pass the access token in the headers (No "AUTHORIZATION : BEARER XXXXXXX"). Instead, the access token is passed in JSON data. How can I change the toolkit's behaviour to read the access token from the data ? -
Does pm2 support Django to make it forever application
I was trying to use pm2 to make the Django application run forever however I was unable to do that. Can any one help me out. Does pm2 really supports django -
How to apply filter after the retrieve methods?
I'm currently overriding the list method of the ModelViewSet and using filter_fields but I realized that the filter is applied before the list, so my list method is not being filtered by the query param. Is it possible to apply this filter after the list method? class AccountViewSet(viewsets.ModelViewSet): serializer_class = AccountSerializer filter_fields = ('country__name') filter_backends = (django_filters.rest_framework.DjangoFilterBackend,) queryset = Account.objects.all() def list(self, request): if request.user.is_superuser: queryset = Account.objects.all() else: bank_user = BankUser.objects.get(user=request.user) queryset = Account.objects.filter(bank=bank_user.bank) serializer = self.get_serializer(queryset, many=True) return Response(serializer.data) When I do request using this URL http://localhost:8000/api/account/?country__name=Germany, it returns all the accounts filtered by bank but not by country. -
django convert Html to pdf, better library than pdfkit?
I am working on task using django and this task is to allow users to download a pdf document with there user informations. So I am using django template to fill in the user info with the render context. Then I convert the html into pdf using pdfkit and whtmltopdf. But this library is not good enough to take into account some of the css files. So the displayed pdf is not really good. Is there a more powerful library to do this ? Or any other idea to carry out this task ? -
ProgrammingError in Django: object has no attribute, even though attribute is in object
I am working in Django, and have a model that needs to contain the field "age" (seen below) class Result(models.Model): group = models.ForeignKey(Group, null=True) lifter = models.ForeignKey("Lifter", null=True) body_weight = models.FloatField(verbose_name='Kroppsvekt', null=True) age_group = models.CharField(max_length=20, verbose_name='Kategori', choices=AgeGroup.choices(), null=True) weight_class = models.CharField(max_length=10, verbose_name='Vektklasse', null=True) age = calculate_age(lifter.birth_date) total_lift = models.IntegerField(verbose_name='Total poeng', blank=True, null=True) The age is calculated with a method in utils.py, called "calculate_age": def calculate_age(born): today = date.today() return today.year - born.year((today.month, today.day < (born.month,born.day)) The lifter.birth_date passed to the calculate_age method comes from this model (in the same class as the Result-model) class Lifter(Person): birth_date = models.DateField(verbose_name='Fødselsdato', null=True) gender = models.CharField(max_length=10, verbose_name='Kjønn', choices=Gender.choices(), null=True) However, I get the error 'ForeignKey' object has no attribute "birth_date". I have tried tweaking the code to get rid of it, but nothing seems to be working. Does anyone know why I might be getting this error? Thank you for your time! -
OSError [Errno 2] No such file or directory
Output : OSError at /treedump/ [Errno 2] No such file or directory Request Method: GET Request URL: http://xxx.xxx.xxx.xxx/ekmmsc/treedump/ Django Version: 1.10.7 Exception Type: OSError Exception Value: [Errno 2] No such file or directory Exception Location: /usr/local/lib/python2.7/site-packages/Django-1.10.7-py2.7.egg/django/utils/_os.py in abspathu, line 31 Python Executable: /usr/local/bin/python Python Version: 2.7.6 TreeDump Views from django.shortcuts import render import time from . import scripts # Create your views here. y=time.strftime("%d_%m_%Y") print (y) l=y.split("_") date=l[0]+l[1]+str((int(l[2])%100)) def index(request): num_visits=request.session.get('num_visits', 0) request.session['num_visits'] = num_visits+1 return render( request, 'index.html', context={'num_visits':num_visits}, ) def printx(request): if(request.GET.get('mybtn')): strx= "HELLO required Executed" time.sleep(5) return render(request,'printx.html', context = {'strx':strx},) import os from django.conf import settings from django.http import HttpResponse,Http404 def download(request): scripts.tree70dump() file_path ='/data1/ekmmsc/webapp/ekmmsc/treedump/DumpFiles'+"EKM_TREE70DUMP_"+date+".zip" if os.path.exists(file_path): with open(file_path, 'rb') as fh: response = HttpResponse(fh.read(), content_type="application/vnd.ms-excel") response['Content-Disposition'] = 'inline; filename=' + os.path.basename(file_path) return response raise Http404("Does not exist") Please help.... -
Error: No module
Made a pull from GIT. But the new setup does not run while there are 2 other setups of the same project on the same server and all 3 are running under virtual env. Using runserver for the new setup throws this error.Error: No module named service_centre Have checked the setting.py files on both the other setups its same as the one for the new one with just the project and template directory paths changed. Thanks in advance. -
Django: How to handle exception if something wrong in database credential which is specified in setting.py file.
I am using MySQL as a database in Django application. I want to throw an exception if something went wrong in database credential setting in setting.py. For example: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'customuser2', 'USER': 'john', 'PASSWORD': 'xyzabc', 'HOST': 'xxx.xxx.xx.x', 'PORT': 'xxxx', } } So if I entered wrong host or a port name, there will be an error in application. is there any way to throw the exception? -
Calling some functions if Generic View is success
I use generic views/class-based views in my project and I want to call some functions if view is done successfully. I use for this def get_success_url() method. But I can't reach the model in that function. How can I get rid of this, or are there any other way to do this? My codes: class MyModelUpdate(UpdateView): model = MyModel fields = ['details'] def get_success_url(self, **kwargs): add_log(form.model, 2, 1, request.POST.user) return reverse_lazy('model-detail', kwargs = {'pk' : self.kwargs['model_id'] }) -
Django - correct way to convert list to combined OR for Q object
I have QueryDict with list 'value': ['1', '2', '3', '4', '5'] - number of elements is unknown. I need convert this list to filter model using OR condition: Poll.objects.get(Q(value__icontains=option[0]) | Q(value__icontains=option[1])) In SQL: AND (value LIKE '%1%' OR value LIKE '%2%') How to achieve this correct and easy way ? -
Django Foreign Key of Auth.User - column "user_id" does not exist
I have looked at all relevant resources but I'm unable to make any headway. Situation: I am building a simulation model using Django and am looking to store simulation data as well as sets of parameter data. Many sets of simulation data should be linked to each user, and many sets of parameter data can be linked to each simulation. Thus, I have tried to model this under 'models.py' of my Django app. from django.db import models from django.conf import settings # Create your models here. class Simulation(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, ) date = models.DateTimeField() # Each simulation has only one graph # Graphing parameters hill_num = models.CharField(max_length=3) div_type = models.CharField(max_length=10) s3_url = models.CharField(max_length=256) def __str__(self): return str(self.sim_id) class Parameter(models.Model): # Each simulation can have many sets of simulation parameters simulation = models.ForeignKey('Simulation', on_delete=models.CASCADE) lsp = models.PositiveIntegerField() plots = models.PositiveIntegerField() pioneer = models.BooleanField() neutral = models.BooleanField() # for pioneers p_max = models.PositiveIntegerField() p_num = models.PositiveIntegerField() p_start = models.PositiveIntegerField() # for non-pioneers np_max = models.PositiveIntegerField() np_num = models.PositiveIntegerField() np_start = models.PositiveIntegerField() def __str__(self): return str(self.param_id) ./manage.py makemigrations works but when I try to populate the database with python manage.py loadtestdata auth.User:10 divexplorer.Simulation:40 divexplorer.Parameter:300, it throws this error: auth.User(pk=72): JshtkqSzw3 auth.User(pk=73): … -
Django 1.11 enter_transaction_management alternative
We are using django as our main backend, we use django-nose as our unit test framework. We have recently upgraded from django 1.3 to 1.11, a huge change, we are facing the following issue. When we are django 1.3, the unit tests ran fine, but with django 1.11, it's throwing the below error. transaction.enter_transaction_management(using=db) AttributeError: 'module' object has no attribute 'enter_transaction_management' We found that there is an opened issue going on in django-nose github. I thought of two solutions for this problem. 1. As I can understand that enter_transaction_management and managed functions are deprecated/removed in django 1.11, were there any replacements or alternatives provided in 1.11??? 2. What are the good alternatives to django-nose?? Please help These are the github issues. https://github.com/django-nose/django-nose/issues/226 https://github.com/django-nose/django-nose/issues/289 https://github.com/django-nose/django-nose/pull/258 -
Accessing friends without taggable_friends permission using django and Facebook API
I am using Facebook Sdk in Django 1.11.5. I have tried hard but could not get the permission to access the friend profile using the facebook Graph API as facebook didn't approved my request for accessing the taggable_friend. I would like to know whether it is possible to access my profile and then get the friend profile without using the facebook API. I am not talking about illegal Facebook Scraping. What I am talking about is that whether I can access my profile using the app and my credential and then access the friends section of my facebook. Is it at all possible to enter or login facebook with the App ID and secret ket and access_token with simple permission of public_profiles and email and then login the facebook and extract the friend list from the profile friends tab. Can anyone suggest an idea for this concept? I am using Python 2.7 -
django: rest-auth and allauth for Facebook registration API requires CSRF token
Using allauth and django-rest-auth to create a facebook login api. I've followed the both packages documentations and using example from rest-auth doc. I've followed all the steps and I can successfully use this API from DRF browse-able API view and it is successfully performing the registration. When I try this API from somewhere else like postman it asks for CSRF token. I tried to use csrf_exempt decorator but that doesn't seem to be effective on this url. Here is my url config: url(r'^rest-auth/facebook/$', csrf_exempt(FacebookLogin.as_view()), name='fb_login'), Rest of the things are same as they mentioned in the documentation for django-rest-auth. I can't figure out what am I missing, or where should I look for a fix. Any help to diagnose the issue would be appreciated. -
Need a calculated value in models in Django
I want a calculated value in models.py. Below is the file models.py. I manage to get the price as expected but the price doesn't appear as one of the field. What I mean is, when I enter delivery_price and support_price, the price field should be calculated and be shown in the below page itself (attached image). Is this possible or am I getting something wrong? delivery_price = models.DecimalField(max_digits=10, decimal_places=0,default=0) support_price = models.DecimalField(max_digits=10, decimal_places=0,default=0) #def get_price(self): # "Returns the price." # return (self.delivery_price + self.support_price) #price = property(get_price) price = models.DecimalField(max_digits=10, decimal_places=0,editable=False) def save(self, *args, **kwargs): self.price = self.delivery_price + self.support_price super(Product, self).save(*args, **kwargs)