Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: How can I make it display one to the many?
As a newbie, I do not know how to solve the following problem and hope you can help. My application is designed to provide a method for creating and displaying Quizzes. By providing the following schema (Example: 1), I wanted to allow quiz (admins) creators the flexibility to create quizzes with a variety of questions and answers. Also, I assumed that by normalizing as I attempted to do that I was making an efficient database schema. My problem is that due to the fact that a question value is created for each answer I am ending-up with multiple question results when displaying via Admin.py (Example: 2). How can I make it display one question to the many question answers? Do I need to change the database schema, is the a change to admin.py, or something else completely? Example 1: from django.db import models from autoslug import AutoSlugField from model_utils.models import TimeStampedModel class TimeStampedModel(models.Model): created = models.DateTimeField(auto_now_add=True) modified = models.DateTimeField(auto_now=True) class Meta: abstract = True class Quiz(TimeStampedModel): title = models.CharField("Title of Quiz", max_length=255) slug = AutoSlugField( "Quiz Address", unique=True, always_update=False, populate_from="title") description = models.TextField("Description", blank=True) def __str__(self): return self.title class Question(TimeStampedModel): quiz = models.ForeignKey("quizzes.Quiz") text = models.CharField("Question Text", max_length=255) def __str__(self): … -
django dev server not loading on google chrome
I am just beginning to learn django and i set up my first django server using python manage.py runserver 0.0.0.0:8000 command. Why is google chrome not loading localhost:8000/ for me even though Microsoft edge is? -
get empty request while posting
I was just trying to understand the connection between ajax request with django views but i am getting an error while toggling the switch on and off. I have a simple switch which is used for on and off. When user on the switch, django view should get on value through request.post but it is not able to get the data from my ajax request. What have i missed or done wrong? def toggle(request): status = {} if request.method=="POST": print('request', request.POST.get('toggle', '')) status['message'] = 'success' else: status['message'] = 'error' return HttpResponse(json.dumps(status), content_type="application/json") frontendForm class App extends Component { constructor() { super(); this.state = { toggled: true }; } getChildContext() { return { muiTheme: getMuiTheme(Style) }; } handleToggle = (event) => { // console.log(event.target.getAttribute('data-isToggled')); console.log(event.target.value); this.setState({ toggled: !this.state.toggled }); axios({ method: 'POST', url: '/toggle/', headers: { 'X-CSRFToken': CSRF_TOKEN, 'Content-Type': 'application/json' }, data:{ toggle:this.state.toggled }, }) .then(response => { console.log(response); }) .catch(error => { console.log(error); }); } render() { return ( <div className="automation" style={automationStyle}> <form> <Card style={{ padding: '5em' }}> <CardHeader title="Turn on/off light" titleStyle={{fontSize: '24px'}} /> <CardText> <Toggle label="On/Off" id="toggle" onToggle={this.handleToggle} data-isToggled={this.state.toggled} toggled={this.state.toggled} labelStyle={{ fontSize: '24px' }} labelPosition="right" className="toggle" /> </CardText> </Card> </form> </div> ); } } -
Task not executed in background with Celery and Django
I recently choose to use Celery to execute some tasks in background. I'm also using Django, so I followed this tutorial in the official documentation (http://docs.celeryproject.org/en/latest/django/first-steps-with-django.html). myApp/celery.py from __future__ import absolute_import import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myApp.settings') from django.conf import settings app = Celery('myApp') app.config_from_object('django.conf:settings') app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) myApp/__init__.py from __future__ import absolute_import from .celery import app as celery_app I decided to use Redis as broker so in my settings.py you can find : BROKER_URL = 'redis://localhost:6379' CELERY_RESULT_BACKEND = 'redis://localhost:6379' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' I defined a task in a file tasks.py in one of my packages that I have included into my INSTALLED_APPS in settings.py like recommended in the documentation to enable celery to detect every task. from celery import task @task(name="sum_task") def add(x, y): return x+y When I start the worker with : celery -A myApp worker -l info I can see that celery detect my task : [tasks] . myApp.celery.debug_task . sum_task Also successfully connected to my redis cache : [2016-10-24 12:29:49,273: INFO/MainProcess] Connected to redis://localhost:6379// [2016-10-24 12:29:49,602: INFO/MainProcess] mingle: searching for neighbors [2016-10-24 12:29:50,802: INFO/MainProcess] mingle: all alone So my first problem, is that celery … -
Custom response for request with query in Django REST
I have viewset, which return list of objects on the simple request and request with query. But in the cases when I use query each photo object has the same user_id and username fields. Is it possible to return list of photo objects without username and user_id in each object on request with query , but JSON like this: { "user_id: 1, "username": "user", "photos": [ {photo1...}, {photo2...}, ... ] } viewset: class PhotoViewSet(viewsets.ModelViewSet): queryset = Photo.objects.all() serializer_class = PhotoSerializer permission_classes = (IsOwnerOrReadOnly, permissions.IsAuthenticated) def get_queryset(self): queryset = Photo.objects.all() user_id = self.request.query_params.get('user_id', None) if user_id != None: return queryset.filter(user_id=user_id) return queryset def perform_create(self, serializer): serializer.save(user=self.request.user) serializer: class RelatedToUserModelSerializer(serializers.ModelSerializer): user_id = serializers.PrimaryKeyRelatedField(read_only=True) username = serializers.SerializerMethodField(read_only=True) def get_username(self, obj): return User.objects.get(id=obj.user_id).username class PhotoSerializer(RelatedToUserModelSerializer): album_id = serializers.PrimaryKeyRelatedField(read_only=True, required=False) albumname = serializers.SerializerMethodField(read_only=True, required=False) class Meta: model = Photo fields = ('id', 'name', 'image', 'creation_date', 'album_id', 'albumname', 'user_id', 'username') read_only_fields=('id', 'creation_date', 'album_id', 'albumname', 'user_id', 'username') def get_albumname(self, obj): if obj.album_id: return Album.objects.get(id=album_id).name else: return '' -
Using Vue with django
I've recently started on some social media web site using Django. Im using the default django template engine to fill my pages. But at this moment, I want to add javascript to make the site more dynamic. This means: The header and footer is the same on each page. The header should have a dropdown menu, a search form that searches when you're typing. My current django application has a base template that has the header and footer HTML, since every page should have this. The site consists of multiple pages, think of index page, profile page, register page. Each of these pages have some common but also a lot of different dynamic components. For example the register page should have form validation on the fly, but the profile page doesn't need this. The profile page should have a status feed with infinite scrolling. I want to use Vue to deal with the dynamic components, but I don't know how I should get started. The application should not be a SPA. How should I structure the Vue code? How should I bundle this. Using Gulp? Or maybe django-webpack-loader? I should still be able to use the Django template tags, for … -
Django: how to import static files dynamically from context variable?
I have a variable in my context called THEME. According to its value, django should load CSS files from one folder or another. This is how I've defined my context processor to read the variable THEME form the settings file: from django.conf import settings def theme(request): return {'theme': getattr(settings, "THEME", None)} I'm trying to build the css path dynamically like this: {% with 'myapp/css/'|add:THEME|add:'.custom_theme.css' as image_static %} {% static image_static %} {% endwith %} However, I'm getting this error: VariableDoesNotExist at /foo/bar/ Failed lookup for key [THEME] in u"[{'False': False, 'None': None, 'True': True}, {}, {}, ... I try another way: {% with 'myapp/css/'|add:request.THEME|add:'.custom_theme.css' as image_static %} {% static image_static %} {% endwith %} And I get this error: VariableDoesNotExist at /foo/bar/ Failed lookup for key [THEME] in u"<WSGIRequest: GET '/foo/bar/'>" Any idea on how can I build the load static path to the CSS dynamically based on the value of my context variable "THEME"? -
Adding a parent to django-mptt in Admin page throws an error
I had a model, which I changed to be MPTTModel, which looks like this class ServiceRequest(EntityBase, MPTTModel): parent = TreeForeignKey('self', null=True, blank=True, related_name='children', db_index=True) field1 = models.ForeignKey(SomeModel1, blank=True, null=True, verbose_name="model1") field2 = models.ForeignKey(SomeModel2, blank=True, null=True, verbose_name="model2") and I have this model as inline in Admin page. class ServiceRequestsInline(admin.StackedInline): model = ServiceRequest extra = 0 fieldsets = ( (None, { 'fields': ('parent', 'field1', 'field2',) }), ) readonly_fields = ('field2',) I can create a new model and save it. Then I'd like to create a new model and set it's parent to previously created model. When I do this and click "Save" i get this InvalidMove at /admin/app/requests/1/change/ A node may not be made a child of any of its descendants. Though, I can create the 2-nd model, save it without setting a parent and then edit, set parent to the 1-st and save it successfully. What do I do wrong? -
How to fetch property in the template Django 1.8?
I want to create functionality where it's clear whether the user liked every fetched post in template or not(so that I just check attribute post.liked which is True or False in for construction) I suggested that method in models.py might help: class Post(models.Model): who_liked = models.ForeignKey('UserProfile', related_name='who_liked_QUESTION', blank=True, null=True) def _is_it_liked(self, theuser): if self.who_liked == theuser: return True else: return False liked_bool = property(_is_it_liked) But I do not fully understand how should I fetch it then in template, considering that it's a function and I need to insert request.user as argument to the function and call it. Could you please explain how it works since documentation didn't help me much? -
how to add multiple images to the django
i am new to the django. i am trying to add multiple images to the django template like blog post. i am not getting how to do it. please help me. i am not getting how to save the image in single image filed and how to upload multiple image class UserProfile(models.Model): user = models.OneToOneField(User) phone_no= models.CharField(max_length=10,null=True) shop_name=models.CharField(max_length=244, null=True) shop_address=models.CharField(max_length=200,null=True) city=models.CharField(max_length=20,null=True) country=models.CharField(max_length=20,null=True) abn=models.CharField(max_length=11) website = models.CharField(max_length=200, blank=True, null=True) created_at = models.DateTimeField(default=datetime.now, blank=True) updated_at = models.DateTimeField(default=datetime.now, blank=True) Emg_no=models.CharField(max_length=10, null=True,blank=True) payment_date = models.DateTimeField(default=datetime.now, blank=True) area_code=models.CharField(null=True,blank=True,max_length=2) landline_number= models.CharField(null=True,blank=True,max_length=9) status=models.ForeignKey(Status,blank=True,null=True) user_image = models.ImageField(upload_to='user_image') def __str__(self): return self.user.first_name class Meta: db_table = 'registration_userprofile' -
How to display files from a folder in django
I have made a django app that has images in a folder.I have to create a dropdown menu as to which image it has to select.One has to provide the path to the folder and this image should be displayed on the html page. -
Get a URL's Kwargs
Given a URL for example: url(r'^article/(?P<article_id>\d+)/review/(?P<review_id>\d+)/rate/$', views.rate_reviewer, name='review_rate_reviewer') Is there a way in django that I could get a list of the Kwargs this URL required eg. ['article_id', 'review_id']? -
Django Login Custom Auth works locally but not on production server
I implemented a custom Authentication Backend for my Django Project. If I run Django locally, accessing the productive database, everything works properly. But if I run the same Django App on the production server, It fails. Here is my custom Authentication: import hashlib import logging from django.contrib.auth.models import User from QAServer import error_codes from QAServer import exceptions from QAServer.DataAccess.UserDAO import UserDAO from QAServer.couchbase_util import ConnectionUtil import constants as c logger = logging.getLogger(__name__) class CouchbaseBackend(object): _workaround_delimiter = "login+" def authenticate(self, username=None, password=None): # ## workaround to suppress 401 responses when login+ is provided in username # ## -> otherwise problem with browser behaviour! if username.find(CouchbaseBackend._workaround_delimiter) >= 0: split = username.split(CouchbaseBackend._workaround_delimiter) username = split[1] salt, user = self.get_user(username) if salt: pass_hash = hashlib.sha512(password + salt).hexdigest() else: pass_hash = hashlib.sha256(password).hexdigest() logger.debug(user.details) # ## authentication fallback if user.password == pass_hash: logger.debug(user.details) return user else: logger.info("### wrong password for user %s ###" % username) raise exceptions.PermissionError(error_code=error_codes.INVALID_CREDENTIALS_PROVIDED) def get_user(self, username): try: con = ConnectionUtil.get_prod_instance() dao = UserDAO(con) cb_user = dao.find_by_username(username) return self.convert_to_django_user(cb_user) except User.DoesNotExist as e: logger.error("### Get User Error (Couchbase Backend Authentication) ###") logger.error(e) logger.error("#########################################################") return None @staticmethod def convert_to_django_user(cb_user): user_name = cb_user[c.USERNAME] email = cb_user[c.EMAIL] password = cb_user[c.PASSWORD] salt = cb_user.get(c.SALT, None) user = … -
Python: Invalid HTTP basic authentication header with long base64 string
I tried to login my django-rest-framework test client via HTTP Basic authentication to gain a REST-API token. But had to find out that it fails once my randomly generated username and password is too long: def login_client(self): uid = uuid.uuid4().hex user = User.objects.create(username=uid, email="{}@foo.de".format(uid)) user.set_password(uid) user.save() self.client.credentials(HTTP_AUTHORIZATION=self.get_knox_auth_header(uid, uid)) response = self.client.post(reverse("knox_login")) print response.content.data["token"] def get_knox_auth_header(self, username, password): return "Basic {}".format("{}:{}".format(username, password).encode("base64")) Header looks like: Basic MTAyZDc2OTJjY2E5NGY0NmFmNThkODNmNDc5NTc6MTAyZDc2OTJjY2E5NGY0NmFmNThkODNmNDc5 NTc= Response: {"detail":"Invalid basic header. Credentials string should not contain spaces."} -
django translation with format() does not work
models.py: class Reservation(models.Model): class Period: MORNING = 'morning' EVENING = 'evening' @classmethod def choices(cls): return ( (cls.MORNING, _('Morning')), (cls.EVENING, '{} until {:%I %p}'.format(_('Evening'), datetime.time(16)), ) period = models.CharField(max_length=10, choices=Period.choices(),) The 'period' field uses one of the choices from the inner class method - Period.choices() In my template I use {{ reservation.get_period_display }} to display the custom label I want to display. Now, the translation is working properly for the first choice (cls.MORNING)., output: الصباح. For the second choice (cls.EVENING), translation is not simply happening., output: "Evening until 04 PM" Can anyone suggest me what is wrong with the format specifier, and why translation/localization is not working. N.B: The translation and i18n is setup properly and other places in my project is correctly showing translated values. -
IntegrityError:NOT NULL constraint failed: chatapp_chat.message
I'm writing chat application in Django and after subbing my message I get error: IntegrityError at /chatapp/post/ NOT NULL constraint failed: chatapp_chat.message This is my models.py: from django.db import models from django.contrib.auth.models import User class Chat(models.Model): created = models.DateTimeField(auto_now_add=True) user = models.ForeignKey(User, blank=True, null=True) message = models.CharField(max_length=200) def __unicode__(self): return self.message This is my view.py def home(request): c = Chat.objects.all() return render(request, "chatapp/home.html", {'home': 'active', 'chat': c}) def post(request): if request.method == "POST": msg = request.POST.get('msgbox', None) c = Chat(user=request.user, message=msg) if msg != '': c.save() return JsonResponse({ 'msg': msg, 'user': c.user.username }) else: return HttpResponse('Request must be POST.') def messages(request): c = Chat.objects.all() return render(request, 'chatapp/messages.html', {'chat': c}) And .html <body> <div class="panel-heading">Chat Box</div> <div id="msg-list-div" class="panel-body"> <ul id="msg-list" class="list-group"> {% for obj in chat %} {% if obj.user == request.user %} <li class="text-right list-group-item">{{ obj.message }}</li> {% else %} <li class="text-left list-group-item">{{ obj.message }}</li> {% endif %} {% empty %} <li class="text-right list-group-item">No messages yet!</li> {% endfor %} <script> var chatlist = document.getElementById('msg-list-div'); chatlist.scrollTop = chatlist.scrollHeight; </script> </ul> </div> <form id="chat-form" method="post" action="/chatapp/post/"> {% csrf_token %} <div id="chat-bottom" class="input-group"> <input type="text" id="chat-msg" name="chat-msg" class="form-control"/> <span class="input-group-btn"> <input class="btn btn-default" id="send" type="submit" value="Send"/> </span> I've searched through lot of … -
Rotate image in template before upload in Django
May be somebody faced with such issue and found good solution. I need rotate image in template before upload and save the record. I can rotate image view in template using JavaScript but it doesn't give any results, because image saves in original rotation. I saw several sites with such kind of feature and it's really useful. -
Is it possible with docker to run more than one app on port 80 on the same computer?
My thought is this. I might not even need docker to solve the issue. Perhaps, I can just run nginx as a reverse proxy running on port 80, the default for web applications and somehow direct them to different applications, using different programming stacks. In other words, a Java EE server, a Node.js server, a Django app and some PHP apps. In this scenario, nginx would serve the requests to the appropriate applications. Is that possible? Second scenario is having different IP addresses attached to docker images, so that each IP address can have a different application running on port 80 - the default port. If this does not work, I guess I would need a different VPS server for each environment that I want to serve on port 80. I have both a Linux development server which could serve low traffic sites but I also purchase VPS hosting monthly. I'd like to avoid having to purchase separate vps server accounts for each stack, e.g. Java EE, Node.js, Python/Django with Gunicorn, and PHP apps. Thanks in advance for any help/advice, Bruce -
Show text only in b tags with regex
I have QuerySet with output: <b>Author</b> Work <b>Author</b> Work <b>Author</b> Work <b>Author</b> Work <b>Author</b> Work I want to have an array only with Autor. Below is my code but doesn't works: author_list = self.texts.filter(code='OPEN') for i in author_list: aa = [re.match(r'<b>(.*)</b> ', str(i.text_en))] return aa -
how to import models to oscar.partner app's strategy module correctly?
I have defined declared my own Strategy to Select a Stock and a price as described in http://django-oscar.readthedocs.io/en/releases-1.1/topics/prices_and_availability.html Everything worked fine until I had the need to import a custom model class that I created in the catalogue app. My goal was to access this custom model for the price selection strategy. in /apps/partner/strategy I tried to import the model like this: CountrySpecificProductInformation = get_model('catalogue', 'CountrySpecificProductInformation') this call raises a Model not Registered exception: File "/home/matyas/virtenvs/oscar/local/lib/python2.7/site-packages/oscar/core/loading.py", line 250, in get_model return apps.get_registered_model(app_label, model_name) File "/home/matyas/virtenvs/oscar/local/lib/python2.7/site-packages/django/apps/registry.py", line 260, in get_registered_model "Model '%s.%s' not registered." % (app_label, model_name)) LookupError: Model 'catalogue.CountrySpecificProductInformation' not registered. my Installed apps settings look like this: INSTALLED_APPS = ['...'] + oscar.get_core_apps(['apps.catalogue', 'apps.promotions', 'apps.dashboard', 'apps.dashboard.catalogue', 'apps.partner', 'apps.payment', 'apps.dashboard.partners', 'apps.shipping', 'apps.checkout', 'apps.search']) I am using django-oscar 1.3 with Django 1.9.9 -
How to deploy django with certain database name, django, fabric, mezzanine
I'm making web service using django, fabric, mezzanine and confronted with problem related to setting database name. I'm beginner in this field. the status is like bellow ProjectName: WebService Database I want to use: WebService_DB3 How can I declare Database name I want to use? Without any changes fabric tries to use database: WebService. If you need any additional information please let me know. Thanks! -
DRF and RBAC: How to dynamically select the view for an endpoint?
I'm implementing role-based access control in a system with a few user types: staff, publisher, and advertiser. Each user type has a different set of object filtering and field restriction rules. To increase security and decrease spaghetti (at the cost of some extra boilerplate), I'm creating separate serializers and views for each user type, which inherit from unrestricted base classes: class BaseItemSerializer(serializers.ModelSerializer): class Meta: model = Item fields = '__all__' class BaseItemList(generics.ListCreateAPIView): queryset = Item.objects.all() And then implement restrictions and extra filtering: class AdvertiserItemSerializer(BaseItemSerializer): class Meta(BaseItemSerializer.Meta): fields = ('b', 'c',) class AdvertiserItemList(BaseItemList): permission_classes = (AdvertiserPermission,) This works great... Except for URLs. I don't want to have multiple endpoints for a single resource type – it's not RESTful, and pushes implementation details into the client side. Is there any performant, non-hacky way to dynamically select the view for a URL in DRF? See also: The non-performant, hacky way: How to programatically call a Django Rest Framework view within another view? Similar concept – but too simple for my requirements – that uses methods: https://computerlab.io/2016/08/17/django-rest-framework-roles/ -
Django two-factor authentication, require 2FA on specific views
I am implementing Django two-factor-auth on my website and I would love to have some views protected by two-FA, and some other not. In order to do so, I use the decorator @otp_required which works great, but unfortunately asks the users to input their credentials again (to handle user sessions, I use the registration module). Would you be able to give me a good to way to hack the form in order to just ask the user to input the token (skipping a step of the form, basically) ? Thanks a lot, -
Django foreignkey, retrieving the value
I was trying get the value from a foreignkey but it throws a type error please give me a solution. class LenderInvestment(models.Model): user = models.ForeignKey(User) investment = models.DecimalField(max_digits=15, decimal_places=2, default=1000000) initial_capital = models.DecimalField(max_digits=12, decimal_places=2, **optional) date_stamp = models.DateField(default=datetime.date.today) def __unicode__(self): return str(self.initial_capital) class LoanDisbursement(models.Model): user = models.ForeignKey(User) initial_capital = models.ForeignKey(LenderInvestment, **optional) loan_applicant = models.ForeignKey(LoanApplication) money_disbursed = models.DecimalField(max_digits=10, decimal_places=2) pay_slip = models.FileField(_('Upload depostited payslip'), upload_to=upload_location2, storage=FileSystemStorage(location=settings.PROTECTED_ROOT)) date_stamp = models.DateField(default=datetime.date.today) def __unicode__(self): return str(self.user) def loan_disbursement_receiver(sender, instance, *args, **kwargs): initial_capital = instance.initial_capital[0] money_disbursed = instance.money_disbursed initial_capital -= Decimal(money_disbursed) instance.initial_capital = initial_capital pre_save.connect(loan_disbursement_receiver, sender=LoanDisbursement) The error says indexing not allowed, how I can take the first index value of the initial_capital? Thank you in advance. -
Passing group name of a user in context and accessing in template in django
I have used mixins with class-based views in my django app. I also have created a group named Instructors to allow only user belonging to this group to have certain permissions which are to edit, add and delete a course object. In the ManageCourseList View which is responsible for rendering the courses created by the current user, I tried to override the get_context_data method to pass an additional 'group_list' argument which contains the groups the user belongs to. I tried to access it in the template ManageCourseList view renders. The problem is though the current user belongs to Instructors group but still it renders the else condition data. Please help,My files: Views.py from django.shortcuts import render from django.core.urlresolvers import reverse_lazy from django.views.generic.list import ListView from django.views.generic.edit import CreateView,UpdateView,DeleteView from django.contrib.auth.mixins import LoginRequiredMixin,PermissionRequiredMixin from .models import Course class OwnerMixin(object): def get_queryset(self): qs = super(OwnerMixin,self).get_queryset() return qs.filter(owner=self.request.user) class OwnerEditMixin(object): def form_valid(self,form): form.instance.owner = self.request.user return super(OwnerEditMixin, self).form_valid(form) class OwnerCourseMixin(OwnerMixin,LoginRequiredMixin): model = Course fields = ['subject','title','slug','overview'] # why use this attribute? success_url = reverse_lazy('courses:manage_course_list') # use of it? class OwnerCourseEditMixin(OwnerCourseMixin,OwnerEditMixin): fields = ['subject','title','slug','overview'] success_url = reverse_lazy('courses:manage_course_list') template_name = 'courses/manage/course/form.html' class ManageCourseListView(OwnerCourseMixin,ListView): template_name = 'courses/manage/course/list.html' def get_context_data(self, **kwargs): context = super(ManageCourseListView,self).get_context_data(**kwargs) context['group_list'] = self.request.user.groups.all() …