Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django form how to show logged in user only?
I have a django model "Post" that has a field: author = models.ForeignKey('auth.User') I also have a PostForm in forms.py with author as a field and Post as the model. I want to only show the user logged in and not all superusers. https://gyazo.com/fb8884391bdf8284065175fbcdc16f75 Is there a painless way of doing so? If not what is my best option? -
Django nested query PostgreSQL
class Route(app_core_base_model.AbstractDefaultModel): code = models.PositiveIntegerField( verbose_name=_('code'), default=0, editable=True) slug = models.SlugField( verbose_name=_('slug'), unique=True, max_length=255, blank=True, null=True, editable=True, db_index=True) class Route(app_core_base_model.AbstractDefaultModel): code = models.PositiveIntegerField( verbose_name=_('code'), default=0, editable=True) slug = models.SlugField( verbose_name=_('slug'), unique=True, max_length=255, blank=True, null=True, editable=True, db_index=True) class StopPoint(app_core_base_model.AbstractDefaultModel): route = models.ForeignKey( Route, verbose_name=_('route')) station = models.ForeignKey( app_core_models.Station, verbose_name=_('station')) arrival_time = models.TimeField( verbose_name=_('arrival time'), blank=True, null=True, editable=True) departure_time = models.TimeField( verbose_name=_('departure time'), blank=True, null=True, editable=True) class Station(app_core_base_model.AbstractDefaultModel): name = models.CharField( verbose_name=_('name station'), max_length=255, blank=True, null=True, editable=True) slug = models.SlugField( verbose_name=_('slug'), unique=True, max_length=255, blank=True, null=True, editable=True, db_index=True) I have 3 models I can not make a request that will be able to choose all flights that pass through the point of arrival and the point of departure. How can I find all routes that are passing through and the point of departure to the arrival point? -
Django: Cannot set values on a ManyToManyField which specifies an intermediary model
I have a problem with a CreateView in my Django app, I want to create a Sesion but the sessions can only be created by a GroupMember leader of that Group. Here are my models: class Group(models.Model): # The code class GroupMember(models.Model): member = models.ForeignKey(Volunteer) group = models.ForeignKey(Group) leader = models.BooleanField(default=False) class Session(models.Model): name = models.CharField(max_length=250) group = models.ForeignKey(Group) assistants = models.ManyToManyField(GroupMember, through='SessionAssistant') hours = models.FloatField(default=1) day = models.DateTimeField(default=datetime.now) class SessionAssistant(models.Model): assistant = models.ForeignKey(GroupMember) session = models.ForeignKey(Session) rol = models.CharField(max_length=250) assist = models.BooleanField(default=True) Also I want when I create a Sesision I can assign de rols of my assistants, here is my view: class CreateSession(CreateView): model = Session template_name = "session_form.html" fields = ['name', 'hours', 'day', 'assistants', ] success_url = '/' def form_valid(self, form): group = Group.objects.get(id=self.kwargs['pk']) form.instance.group = group return super(CreateSession, self).form_valid(form) -
Iterating models fields and updating them in Django
I have a model named UserInfo. class UserInfo(models.Model): username = models.CharField(max_length=240 , default = "" , blank = False , null = False) first_name = models.CharField(max_length=240 , default = "" , blank = False , null = False) last_name = models.CharField(max_length=240 , default="" , blank = False , null = False) address = models.CharField(max_length=500 , default="" , blank = False , null = False) email = models.CharField(max_length=240 , default="" , blank = False , null = False) phoneNumber = models.CharField(max_length=240 , default="" , blank = False , null = False) pincode = models.CharField(max_length=240 , default="" , blank = False , null = False) I also have a UserInfoFormthat has these fields. class UserInfoForm(forms.ModelForm): class Meta: model = UserInfo fields = [] for field in UserInfo._meta.get_fields(): #automatically update fields from userinfo model fields.append(field.name) exclude = ['username'] What is want is to iterate over the fields of UserInfo model and update with data in UserInfoForm, rather than hardcoding it all. I have tried this: obj = UserInfo.objects.get(email = request.user.email) if obj.username == request.user.username: #basically a test to see if the same person is updating his profile, or is someone else using this email id for field in UserInfo._meta.get_fields(): fieldname = field.name fieldvalue … -
DateField in Django missing Hours, Minutes, Seconds
I have a Date field in an oracle 12c legacy table which has data like 18-JAN-14 12 34 59. In my django 1.10 app I have a corresponding model with a field time = models.DateField(blank=True, null=True). The problem is when I examine an instance of the model I get something like datetime.date(2014, 1, 18)....what happened to the hours, minutes, and seconds? Thanks! -
when i use object name i get 'DeferredAttribute' object has no attribute 'get'
i'm new for django. i'm really confused with views filters. this is my models.py class Author(models.Model): title = models.CharField(max_length=30) user=models.ForeignKey(User) age= models.CharField(max_length=2) post= models.ManyToManyField(Article) def __str__(self): return self.title def __str__(self): return self.post def __str__(self): return self.age class Meta: ordering = ('title','user',) my views.py def posting(request): details = Author.age.get(pk=request.user.id) return render(request,'home.html' , {'detail':details}) Now i need to get the current logged in user (age or title or post).when i execute the code i get the above error. how can i filter the particular object of logged in user kindly suggest me some docs for views filter Thanks for advance !! -
RQ: redis.exceptions.ResponseError: Command # 3 ... of pipeline caused error: OOM command not allowed when used memory > 'maxmemory'
I am running a background task in my django app with RQ, as it is supposed to be one of the simplest ways to get the job done. The task consists in checking in some APIs if any information has been updated and inserting any new information in my own database. Until a few days ago, it was working fine, but I am now getting an error that I am not able to solve. From the last lines of the error message: OOM command not allowed when used memory > 'maxmemory' I thought at the beginning that I was passing too much data to the worker. However, I have eventually reduced the data passed to a single dictionary with 5 key-value pairs and I am still getting the error (see the complete message at the bottom). Until last week, however, I was passing more than 20 dictionaries, each of them with more elements and it was just working fine. I have checked here and here, but it does not seem to be the same problem as mine. Any idea of why I am getting this error and how to solve it? Error message: Internal Server Error: /en/results/ Traceback (most recent … -
inheritance of login_required decorator on dispatch of a class based view
I have multiple views all inheriting from a base view. All views require the login_required decorator. I would like to add this as a method decorator to dispatch of the base view and then not have to add the decorator to every child view. I was not able to achieve this. Is this generally not possible? What am I missing? What don't I know? Here is a somewhat broken down version of my code: class CoreView(CoreMixin,TemplateView): pass class BaseView(CoreView): @method_decorator(login_required) def dispatch(self, request, *args, **kwargs): return super(BaseView, self).dispatch(request, *args, **kwargs) class MyView(BaseView): def dispatch(self, request, *args, **kwargs): "Do Stuff" I have tried to do my research but could not find an answer. BTW: I am currently using django 1.8 and python 2.7. -
How would I connect a React Native app to Django?
I'm teaching myself React Native at the moment. I'm familiar with connecting Django to a regular HTML & CSS project. For example, if the user wants to create a username/password for a website and hits the Submit button, I'm aware on how to access the database and how it goes to database. But what about to a React Native project? Is it possible? How would I go about doing this? I've literally looked everywhere and haven't found a concrete answer. -
DjangoRestFramwork creating Duplicate values on post request
When I create a new record there are now new Cost Center and Role in Org valued being created too, existing values are not being selected. If the Role in Org or Cost Center does not exist an error should be returned, new values should not be created. Following is my Serializer class SectorSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Sector fields = ('sector',) class RegionSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Region fields = ('region',) class RoleSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Role fields = ('role',) class DepartmentSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Department fields = ('department',) class CompanySerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Company fields = ('name',) class CitySerializer(serializers.HyperlinkedModelSerializer): class Meta: model = City fields = ('name',) class CostCenterSerializer(serializers.HyperlinkedModelSerializer): city = CitySerializer(read_only=False) region = RegionSerializer(read_only=False) company = CompanySerializer(read_only=False) class Meta: model = CostCenter fields = ('cost_center', 'city', 'region', 'company') class RoleInOrgSerializer(serializers.HyperlinkedModelSerializer): department = DepartmentSerializer(read_only=False) sector = SectorSerializer(read_only=False) role = RoleSerializer(read_only=False) class Meta: model = RoleInOrg fields = ('department', 'sector', 'role') Following are the corresponding models class CostCenter(models.Model): cost_center = models.CharField(max_length=100, null=True) city = models.ForeignKey(City, null=True) region = models.ForeignKey(Region, null=False) company = models.ForeignKey(Company, null=False) concat_cost_center = models.CharField(max_length=100, null=True, blank=True) class RoleInOrg(models.Model): department = models.ForeignKey(Department, null=False) sector = models.ForeignKey(Sector, null=False) role = models.ForeignKey(Role, null=False) role_in_org = models.CharField(max_length=150, … -
How to translate choicefields
In my Django Project I have a choicefield in Constance for the employee-type like that: CONSTANCE_ADDITIONAL_FIELDS = { 'employee_type': ['django.forms.fields.ChoiceField', { 'widget': 'django.forms.Select', 'choices': (("---", "---"), ("Expert", "Expert"), ("Beginner", "Beginner"), ("CEO", "CEO")) }], I can pass it to the template. {% if show_employee and show_employee|length > 3%} {% blocktrans %} This is the title: {{ show_empolyee}} {% endblocktrans %}{% endif %} But I cannot translate it that way. The django.po file looks like that: msgid "%(show_employee)s " msgstr "" Any solution for this? -
AttributeError at / 'NoneType' object has no attribute 'startswith'
After configured django-debug-toolbar, I ended up with this error: Traceback: File "/home/muhammad/.local/lib/python2.7/site-packages/django/core/handlers/exception.py" in inner 41. response = get_response(request) File "/home/muhammad/.local/lib/python2.7/site-packages/django/utils/deprecation.py" in call 142. response = self.process_response(request, response) File "/home/muhammad/.local/lib/python2.7/site-packages/debug_toolbar/middleware.py" in process_response 132. panel.generate_stats(request, response) File "/home/muhammad/.local/lib/python2.7/site-packages/debug_toolbar/panels/staticfiles.py" in generate_stats 128. 'staticfiles_finders': self.get_staticfiles_finders(), File "/home/muhammad/.local/lib/python2.7/site-packages/debug_toolbar/panels/staticfiles.py" in get_staticfiles_finders 139. for path, finder_storage in finder.list([]): File "/home/muhammad/PycharmProjects/proyekakhir/django_assets/finders.py" in list 52. output = bundle.resolve_output(env) File "/usr/local/lib/python2.7/dist-packages/webassets/bundle.py" in resolve_output 326. output = ctx.resolver.resolve_output_to_path(ctx, self.output, self) File "/usr/local/lib/python2.7/dist-packages/webassets/env.py" in resolve_output_to_path 260. return path.join(ctx.directory, target) File "/usr/lib/python2.7/posixpath.py" in join 68. if b.startswith('/'): Exception Type: AttributeError at / Exception Value: 'NoneType' object has no attribute 'startswith' What's going wrong here? -
Using Latexify in Django
I want to share the mathematical contents through web and for this I am using latex and I found latexify which would convert the latex commands in to normal fonts in python (Django) framework, but I got really confused how to get start there? Please, help me if anyone have solution. -
Setting up docker-compose.yml to run celery worker and celery beat for a django project with redis as broker
I have setup django project using django cookiecutter. The project scaffolding is excellent. I also opted to use docker along with it. Now I am struggling with getting celery v4.0.x working in the whole setup. This is my docker-compose.yml version: '2' volumes: postgres_data_dev: {} postgres_backup_dev: {} services: postgres: build: ./compose/postgres volumes: - postgres_data_dev:/var/lib/postgresql/data - postgres_backup_dev:/backups environment: - POSTGRES_USER=application django: build: context: . dockerfile: ./compose/django/development/Dockerfile depends_on: - postgres environment: - POSTGRES_USER=application - USE_DOCKER=yes volumes: - .:/app - /tmp/ links: - postgres - redis expose: - "8000" env_file: - ./dev.env restart: - "on-failure" nginx: build: context: . dockerfile: ./compose/nginx/development/Dockerfile depends_on: - django ports: - "0.0.0.0:80:80" links: - django volumes_from: - django redis: image: redis:latest hostname: redis celeryworker: build: context: . dockerfile: ./compose/django/development/Dockerfile env_file: ./dev.env depends_on: - postgres - redis command: celery -A application.taskapp worker -l INFO restart: "on-failure" celerybeat: build: context: . dockerfile: ./compose/django/development/Dockerfile env_file: ./dev.env depends_on: - postgres - redis command: celery -A application.taskapp beat -l INFO Quite honestly I feel there seems to be some tiny issue with config for celerybeat/celeryworker service. It would be nice if someone can point it out. -
How should I proceed with showing dynamic w.r.t. user logged in in django?
I am able to authenticate user via inheriting AbstractUser class and return a JSON response, how should I design my backend using django rest framework such that a unique URL returns different information from a single class based view according to user logged in? -
How to get the value of an individual radio button in a Django template?
Is there a way for a template to examine the value of an individual radio button? I know how to get other attributes: {% for button in myform.radio_select %} {{button.tag}} {{button.choice_label}} {{button.id_for_label}} {% endfor %} But how do I get the value? I tried the obvious {{button.value}} and the less obvious {{button.tag.value}} but they did not work. -
allauth social login error during gmail verification
settings.py SOCIALACCOUNT_PROVIDERS = { 'google': { 'SCOPE': ['profile', 'email'], 'AUTH_PARAMS': {'access_type': 'online'}, }, 'facebook': { 'METHOD': 'oauth2', 'SCOPE': ['email', 'public_profile', 'user_friends'], 'AUTH_PARAMS': {'auth_type': 'reauthenticate'}, 'FIELDS': [ 'id', 'email', 'name', 'first_name', 'last_name', 'timezone', 'gender', 'updated_time'], 'EXCHANGE_TOKEN': True, 'LOCALE_FUNC': lambda request: 'kr_KR', 'VERIFIED_EMAIL': False, 'VERSION': 'v2.4' }, } the problem is I'm directed to choose account option using allauth. But after i choose account its redirects to a page **socila network login failure Authorized JavaScript origins http://localhost:8000 Authorized redirect URIs http://localhost:8000/accounts/google/login/callback/ What am I doing wrong?? -
Using Django CreateView to set multiple object levels in a database
I'm fairly new to Django and trying to set up a form for submission to my database. My models are: class Site(models.Model): name = models.CharField(max_length=32) site_number = models.CharField(max_length=32 , primary_key=True) def __str__(self): return self.name class Project(models.Model): project_site = models.ManyToManyField(Site) name = models.CharField(max_length=100) def __str__(self): return self.name class Context(models.Model): site = models.ForeignKey(Site) project = models.ForeignKey(Project) name = models.CharField(max_length=32) def __str__(self): return self.name class Artifact(models.Model): context = models.ForeignKey(Context) def __str__(self): return self.pk I'm trying to create a form for the Artifact. I want the user to be able to select a Site and Project and then select a Context affiliated with the selected Site and Project. Is it possible to do all of this on one page? Should this be separated into multiple pages after I query the database for the affiliated Contexts? I'm having trouble conceptualizing how to do this. -
Python/Django : while trying to connect Django with database, get error - ValueError: invalid literal for int() with base 10: '0b1'
After updating oracle database information in settings.py file, i tried to run manage.py inspectdb command and i am getting error below. Any help in figuring out the issue is greatly appreciated. After updating oracle database information in settings.py file, i tried to run manage.py inspectdb command and i am getting error below. Any help in figuring out the issue is greatly appreciated. Microsoft Windows [Version 10.0.10586] (c) 2015 Microsoft Corporation. All rights reserved. C:\Users\aupadhyay\Desktop\myproj>python manage.py inspectdb > klog_batch_dev1_user/models.py Traceback (most recent call last): File "manage.py", line 22, in execute_from_command_line(sys.argv) File "C:\Users\aupadhyay\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django-1.10.5-py3.5.egg\django\core\management__init__.py", line 367, in execute_f rom_command_line utility.execute() File "C:\Users\aupadhyay\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django-1.10.5-py3.5.egg\django\core\management__init__.py", line 341, in execute django.setup() File "C:\Users\aupadhyay\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django-1.10.5-py3.5.egg\django__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\aupadhyay\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django-1.10.5-py3.5.egg\django\apps\registry.py", line 108, in populate app_config.import_models(all_models) File "C:\Users\aupadhyay\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django-1.10.5-py3.5.egg\django\apps\config.py", line 199, in import_models self.models_module = import_module(models_module_name) File "C:\Users\aupadhyay\AppData\Local\Programs\Python\Python35-32\lib\importlib__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "", line 986, in _gcd_import File "", line 969, in _find_and_load File "", line 958, in _find_and_load_unlocked File "", line 673, in _load_unlocked File "", line 665, in exec_module File "", line 222, in _call_with_frames_removed File "C:\Users\aupadhyay\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django-1.10.5-py3.5.egg\django\contrib\auth\models.py", line 4, in from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "C:\Users\aupadhyay\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django-1.10.5-py3.5.egg\django\contrib\auth\base_user.py", line 52, in class AbstractBaseUser(models.Model): File "C:\Users\aupadhyay\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django-1.10.5-py3.5.egg\django\db\models\base.py", line 119, in new new_class.add_to_class('_meta', Options(meta, app_label)) File … -
Retrieve extra fields in Kibana
I'm loggin from my Django app to a Logstash handler as so : logging.log(logging.INFO, 'Account balance', {'account': a.name, 'platform': a.platform, 'currency': currency, 'amount': balance['result']['currency']}) I would like to aggregate and play with this data from Kibana. I've a lot of other log formats and would like to have a way to display and visualize this data without explicitly writing a filter for each possibility. Is there a versatile way to get those 'fields' value and get them in Kibana? -
Djangdo 'HttpRequest' object has no attribute '_stream'
I create an instance of HttpRequest to test my restful "PUT" method. In oder to set the request body like {"active":true}, I write: from django.http import HttpRequest request=HttpRequest() request.method='PUT' request.content_type='application/json' request.POST["active"]=True response=views.job(request,job_name='TestJob') The last line calls the "PUT" method and brings the error. Why has my 'HttpRequest' object no attribute '_stream'? How can I set the attribute? -
Python similar method in multiple classes
I'm trying to re-factor my Django app. Here is the repeated code i found annoying : class EducationInfoViewSet(viewsets.ModelViewSet): queryset = pf.education_info.objects.all() serializer_class = EducationInfoSerializer permission_classes = (VisionUserPermissions, ) def get_queryset(self): model = pf.education_info identity = self.request.query_params.get('username',None) queryset = model.objects.all() user = User.objects.none() if identity is not None: user = User.objects.get(username=identity) student = get_object_or_404(dbd.user_type, username=user) queryset = model.objects.filter(username=student) if not permission_check(self.request,user): return User.objects.none() return queryset class FamilyInfoViewSet(viewsets.ModelViewSet): queryset = pf.family_info.objects.all() serializer_class = FamilyInfoSerializer permission_classes = (VisionUserPermissions, ) def get_queryset(self): model = pf.family_info identity = self.request.query_params.get('username',None) queryset = model.objects.all() user = User.objects.none() if identity is not None: user = User.objects.get(username=identity) student = get_object_or_404(dbd.user_type, username=user) queryset = model.objects.filter(username=student) if not permission_check(self.request,user): return User.objects.none() return queryset So my "get_queryset" functions are identical other than one variable, and i have multiple classes like these two. How should I implement this without repeating myself? Thanks in advance! -
ImportError: No module named rest_framework
I'm using python 2.7.13 and have a django server 1.11.2. i did pip install djangorestframework and my pip freeze has: ... djangorestframework==3.6.3 ... when i run the django server it gives me: File "/usr/local/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) ImportError: No module named rest_framework I'm using ubuntu gnome 16.04.2 -
How to serve a static file in a Django app only to logged-in users?
I need to serve a particular static asset only to users logged into my Django site. I'm serving static assets through Apache. For various reasons I’m not interested in standing up a full CMS — I just need to make sure non-qualified site visitors cannot download this particular file. This is really low traffic site so failing all else I can hardcode a urlpattern & serve it as a template. But there's gotta be a smarter way to do this, right? -
Delete a record if it is not confirmed, else mark it for deletion: django
I have a simple model: class VIP(models.Model): member=models.ForeignUser(User,related_name='user_task') confirmed=models.CharField(max_length=3,default='No') requested_deletion=models.DateField(null=True,blank=True) What I want is if the user wants to be deleted from the table, he should be deleted completely if confirmed=No. Else for reqeusted_deletion to be set today. May be I am overthinking this but I feel my approach is a resource waster since I am hitting the database twice. It might be the only way but i wanna know of possibilities. In my views.py: status=Task.objects.values('confirmed').get(member=request.user) if status['confirmed']=='No': #delete fully s=Task.objects.get(member=request.user) s.delete() Is there another way or it is that one only?