Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: Get all objects from a specific user
I have a problem when trying to display all the Announce objects from a user. My problem is : Consider that I am logged in as a user with an id=1. When I go to /users/1/ it displays all my posts. But the problem is when I want to display all the posts from another user with id=2 by going to /users/2/, it still display all my Announce objects, and not the user with the id=2. models.py class Announce(models.Model): owner = models.ForeignKey('auth.User', related_name='announces') created_date = models.DateTimeField(auto_now_add=True) body = models.TextField(max_length=1000) views.py class UserAnnouncesList(ListView): model = Announce template_name = 'sewayoosite/user_announces_list.html' context_object_name = 'all_announces_by_user' def get_queryset(self): return Announce.objects.filter(owner=self.request.user) urls.py urlpatterns = [ url(r'users/(?P<pk>[0-9]+)/$', views.UserAnnouncesList.as_view(), name='user_announces_list'),] user_announces_list.html {% extends "account/base.html" %} {% block content %} {% for announce in all_announces_by_user %} <h1>{{announce.user.username}}</h1> <p>{{announce.body}}</p> {% endfor %} {% endblock content %} Do I have to use some kind of like : Announce.objects.get(pk=???) ? I appreciate your help! -
Use SAML2 auth with Weblate
I am trying to force Weblate running in docker to support SAML2 authentication (we have corporate ADFS). I found plugin for django. So I create own Dockerfile: from weblate/weblate RUN set -x \ && apt-get install --no-install-recommends -y xmlsec1 build-essential \ && pip install django_saml2_auth RUN (echo && echo 'execfile("/app/data/settings.override.py")') >> /app/etc/settings.py content of settings.override.py: INSTALLED_APPS = INSTALLED_APPS + ('django_saml2_auth',) SAML2_AUTH = { 'METADATA_AUTO_CONF_URL': 'https://adfs.homecredit.net/federationmetadata/2007-06/federationmetadata.xml', } I failed with setting of 'urls.py' as mantioned in plugin's manual (I cannot find this file inside docker container) - I am not python/django developer and don't know how to continue. Thanks for help. -
DRF IsAuthenticated not working
I have a ListView set permission set to IsAuthenticated, but when I hit the URL in Incognito window. I'm able to view the data. Though when I set the permission to IsAdmin. It works perfectly by showing me an error. Here is my serializer class BlogListSerializer(ModelSerializer): url = HyperlinkedIdentityField( view_name="blog_api:post_detail", lookup_field="slug" ) class Meta: model = Blog fields = [ 'url', 'title', 'category', 'date', 'publish', 'draft' ] Below is my view from rest_framework.permissions import IsAuthenticated class BlogListAPIView(ListAPIView): queryset = Blog.objects.filter(publish=True, draft=False) serializer_class = BlogListSerializer permission_classes = [IsAuthenticated] What possibly be wrong for this to happen? -
Django Invalid Syntax error def index(request) [on hold]
File "/home/david/Django-Development/csruipa/ruth/urls.py", line 3, in <module> from ruth import views File "/home/david/Django-Development/csruipa/ruth/views.py", line 4 def index(request) ^ SyntaxError: invalid syntax enter code here this is my urls.py from django.conf.urls import url from ruth import views urlpatterns = [ url(r'^$', views.index, name="index"), ] and this is the view.py from django.shortcuts import render from django.http import HttpResponse def index(request) return HttpResponse("Hello World") this is the main urls.py from django.conf.urls import include, url from django.contrib import admin urlpatterns = [ url(r'^ruth/', include('ruth.urls')), url(r'^admin/', admin.site.urls), ] I'm following django tutorial here https://docs.djangoproject.com/en/1.11/intro/tutorial01/ my error said it's on line 4 this line def index(request) and on urls.py on line 3 which is this from ruth import views on the main urls.py line 6 was the error which is this url(r'^ruth/', include('ruth.urls')), line I'm new to python, I need some help thanks. -
Intermittent Access-Control-Allow-Origin Issues with Django Rest Framework
I have a React frontend at foo.com and DRF backend at api.foo.com. If I refresh the page a bunch of times I end up with results that look like this: 5x -> loads successfully 1x -> 502 Error with /bar endpoint (preflight request issue with Access-Control-Allow-Origin) 7x -> loads successfully 2x -> 500 Error with OPTIONS 3x -> loads successfully 2x -> 500 Error with OPTIONS 1x -> 502 Error with /bazz endpoint (preflight request issue with Access-Control-Allow-Origin) 2x -> loads successfully 1x -> 502 Error with /user/1 endpoint (preflight request issue with Access-Control-Allow-Origin) 5x -> loads successfully I originally came upon a solution that said corsheaders.middleware.CorsMiddleware should be higher up in MIDDLEWARE_CLASSES. So I did that but I'm still getting the issue. Below are the relevant bits of code from settings.py. ALLOWED_HOSTS = ['*'] CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_CREDENTIALS = True ... INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'rest_framework', 'rest_framework.authtoken', 'rest_auth', 'rest_auth.registration', 'corsheaders', 'django_extensions', 'storages', 'raven.contrib.django.raven_compat', 'allauth', ... ] ... MIDDLEWARE_CLASSES = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'users.middleware.SetLastActivityMiddleware', 'raven.contrib.django.raven_compat.middleware.Sentry404CatchMiddleware', 'raven.contrib.django.raven_compat.middleware.SentryResponseErrorIdMiddleware', ] ... The site sits in a Docker container and uses uwsgi. Not sure if there's any other helpful information I can … -
Django - List blog posts in another view
I have got two Models: Member and Blog whic is called MyPosts. I have got a Member Detail page which looks like a Facebook profile page and I want to list user's posts there. How can I do that? My Member Model: class Member(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='members') member_name = models.CharField(max_length=120) member_adress = models.CharField(max_length=200) . . slug = models.SlugField(max_length=140, unique=True) etc. def __str__(self): return self.member_name def get_absolute_url(self): return reverse('memberships:dashboard') def _get_unique_slug(self): slug = slugify(self.member_name) unique_slug = slug num = 1 while Member.objects.filter(slug=unique_slug).exists(): unique_slug = '{}-{}'.format(slug, num) num += 1 return unique_slug def save(self, *args, **kwargs): if not self.slug: self.slug = self._get_unique_slug() super().save() My Blog Model: class MyPosts(models.Model): user = models.ForeignKey(Member, on_delete=models.CASCADE, blank=False, null=True, related_name='postcreator') title = models.CharField(max_length=120) content = models.TextField(max_length=240) publishing_date = models.DateTimeField(auto_now_add=True) update_date = models.DateTimeField(auto_now=True) slug = models.SlugField(max_length=140, unique=True, blank=False, null=True) def __str__(self): return self.title class Meta: ordering = ['-publishing_date', 'id'] My Detail Page View: def MemberDetailView(request,pk, slug): try: infos = Member.objects.get(pk=pk, slug=slug) except Member.DoesNotExist: raise Http404("Member does not exist") post_list = MyPosts.objects.filter(user=self.request.user.id) # this gives a self error return render(request, 'directory/member-detail.html', {'memberinfo':infos}, {'memberposts':post_list} ) How can I add my post view there to see them on the same "member-detail" page? -
calling clean() doesn't check the required fields and throws error in admin panel. however its validates the required fields when i remove clean()
This is my models.py, i am trying to call save function to create brand code and also checking the parent category of sub category should belongs to its original parent category not the other category. please help me out. class Brand(models.Model): category = models.ForeignKey(Category, related_name='category', limit_choices_to={'parent_category__isnull': True}) sub_category = models.ForeignKey(Category, related_name='sub_category', limit_choices_to={'parent_category__isnull': False}) brand_code = models.CharField(max_length=70, null=True, blank=True) brand_name = models.CharField(max_length=255) def __str__(self): return self.brand_name def create_brand_code(self): pass def clean(self): if not self.sub_category.parent_category == self.category: raise ValidationError("{} is not the sub category of {}".format(self.sub_category, self.category)) def save(self, *args, **kwargs): if not self.brand_code: if self.sub_category.parent_category == self.category: self.brand_code = self.create_brand_code() super(Brand, self).save(*args, **kwargs) -
Configuring django-easy-audit fails
I want to use django-easy-audit app for my models in admin, After installing it with pip and adding it to installed apps then when I try to migrate I get the following error: Operations to perform: Apply all migrations: easyaudit Running migrations: Rendering model states... DONE Applying easyaudit.0001_initial...Raven is not configured (logging is disabled). Please see the documentation for more information. raven.contrib.django.client.DjangoClient INFO base.py L170: Raven is not configured (logging is disabled). Please see the documentation for more information. .... six.reraise(dj_exc_type, dj_exc_value, traceback) File "/usr/local/lib/python2.7/site- packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) django.db.utils.ProgrammingError: there is no unique constraint matching given keys for referenced table "django_content_type" What could be going wrong here, I did not seem to resolve the issue. -
Deploy Django API + React app on Heroku
I'm developing an web application with React in the front-end and Django API REST in the back-end (mostly because in the future we're gonna create a mobile app). My question is, what is the best way to deploy this web app on heroku? Using two distincts heroku's app (one for React and one for Django), or to use Docker to deploy both app's in one single heroku app? (I've read a little about Docker, but i'm not sure how I would deploy it on heroku) Thanks and sorry for the English. -
Calculate time-difference from several db entries in Django/Python
I'm new to coding and Stackoverflow, if I missed something please let me know. I would like to get the time-difference for several database entries, I have 4 timestamps per day per user. I know how to generally get the difference betweeen two times =), but figuring out how to do this for several users and timestamps kind of blew my mind.... How do I iterate over a db Query(like all timestamps of a User) and get the values seperately to pass them to a view? Any advice is highly appreciated, thanks in advance. -
"I/O operation on closed file" error when trying to open uploaded file django 1.8
Unable to open uploaded file when using Django1.8, I am facing an error "ValueError: I/O operation on closed file". But this works well and good in Django 1.6: **Django1.8** >>>type(in_file) <class 'django.core.files.uploadedfile.TemporaryUploadedFile'> >>>in_file.closed **True** **Django1.6** >>>type(in_file) <class 'django.core.files.uploadedfile.TemporaryUploadedFile'> >>>in_file.closed **False** def save_to_file(in_file, dest_file, type='w'): try: with open(dest_file, type) as out_file: for line in in_file: out_file.write(line) except Exception as e: print "Error::--{}".format(e) -
Project created using cookiecutter-django not running
Its been a few months that I am trying to learn Django. In the same process (and while reading "Two Scoops of Django 1.11"), I came across Cookiecutter Django. It has helped me learn a few important things to keep in mind while creating a project. I tried to run the template provided by cookiecutter-django but failed. Here are the steps that I followed. Create a virtual environment named test and activate it. mkvirtualenv test Installed Cookiecutter. pip install coockiecutter Installed Cookiecutter Django, The project name was set to "Test Project" and other defaults settings were chosen. I am using PostgreSQL 9.6. cookiecutter https://github.com/pydanny/cookiecutter-django Create a database named "test_project" in PostgreSQL. Run python manage.py migrate The result was the error: django.db.utils.OperationalError: FATAL: role "dev" does not exist I have also tried making a user named test_project_user and granting it all the privileges to test_project database. I am still getting the same error. -
How do you override the way django displays DurationField as string?
In my form I am expecting the user to enter a two part time...HH:mm but when the update form is loaded the duration field value is returned as HH:mm:ss So when saving a value: duration: 13:00 When editing the form the initial data will be: duration 13:00:00 When saving that I get an ValidationError as that is not a format I want to accept. if ':' in duration: try: (hours, minutes,) = duration.split(':') except ValueError: self.add_error( 'duration', _("Invalid duration: {}".format(duration)) ) return duration Is there a way to only show the HH:mm format for all places I am showing the DurationField or is it better to just set it in the initial data of the form? -
How to convert the datetime.date to UTC date using python
I am using Highchart js in django. i am trying to send date in data =[[datetime.date(2017, 11, 30),21],[...]] formate from django but graph is not working. series: [{ name: 'Winter 2012-2013', data: [ [Date.UTC(1970, 9, 21), 0], [Date.UTC(1970, 10, 4), 0.28], [Date.UTC(1970, 10, 9), 0.25], ] }, {...}....] did some R&D and also tried with data =[[int(mydate.date.strftime('%s'))*1000,23],[....]] but its also not working -
Add and initialize custom field in Django ModelForm
I feel like I am missing some very basic point, but can't solve this. Let's say I have model like this one: class Person(models.Model): first_name = models.CharField(max_length=256, blank=True) # this is weird field, but needed for my usecase last_name = models.WeirdCustomField(max_length=256, blank=True) And there is a form for this, which I would like to customize a bit (comments): class PersonForm(forms.ModelForm): class Meta: model = Address # I want to override 'last_name' field, so exclude it here exclude = ['last_name'] # And add additional field my_field = ChoiceField(choices=list_of_choicec) last_name = forms.CharField() def __init__(self, *args, **kwargs): last_name = kwargs.pop('last_name', None) my_field = kwargs.pop('my_field', None) super(PersonForm, self).__init__(*args, **kwargs) self.fields['last_name'] = last_name self.fields['my_field'] = my_field Now, in the shell (after all imports...) person = Person.objects.get(first_name='Jacob') person.first_name # Prints 'Jacob', correct! form = PersonForm(instance=person, last_name='Smith', my_field='test123') form['first_name'].value() # -> 'Jacob', that's right form['last_name'].value() # -> nothing, I expected 'Smith' form['my_field'].value() # -> nothing, I would like to see 'test123' I think I dig Internet very deep, but could not find solutions for this kind of problem. -
Videos sent by android in bytes are not recieved by apache server..
I am using django==1.11 on the backend I am using apache2 server. I am receiving videos in bytes sent by android but I am getting an error "[wsgi:error] [pid 21270] The joined path is located outside of the base path component (/var/www)" Whereas when running the same server on port 8000 its working fine.. Even images with size more that 1 MB are not received by apache.. Can the issue be of Firewall or apache has some size limit issues?? Any suggestion as what might be the problem.. -
Resolving FK backwards relation when I have a model with two FKs to the same model
I'm having trouble wiring up a working queryset to obtain all the Messages that belong in a chat room. Two users, or Profiles, make up a Pair object, which should relate to a Room--representing a chat room between two people. Messages belong within a chat room. This is the view for a chat_room which I attempt to pre-populate with all the previously sent/saved messages: def chat_room(request, slug): # a failing queryset messages = reversed(request.user.profile.pairing_requester.get(requester=request.user.profile).room.get(occupants=).messages.order_by('-timestamp')[:50]) return render(request, "chat/room.html", { 'messages': messages, }) Going backwards, here are the related models (Message, Room, Pair, Profile): class Message(models.Model): room = models.ForeignKey(Room, related_name='messages') handle = models.TextField() message = models.TextField() timestamp = models.DateTimeField(default=timezone.now, db_index=True) def __unicode__(self): return '[{timestamp}] {handle}: {message}'.format(**self.as_dict()) @property def formatted_timestamp(self): return self.timestamp.strftime('%b %-d %-I:%M %p') class Room(models.Model): """ A room for people to chat in. """ # Unsure whether to have a single FK to Pair, or two directly to Profile occupants = models.ForeignKey(Pair, related_name='room') title = models.CharField(max_length=255) slug = models.SlugField() timestamp = models.DateTimeField(default=timezone.now, db_index=True) created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title class Pair(models.Model): requester = models.ForeignKey(Profile, related_name='pairing_requester') accepter = models.ForeignKey(Profile, related_name='pairing_accepter') class Profile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True, blank=True) From my view, how would I obtain all the messages that belong in … -
Filter ranges using Django Backend filter?
I am working on project using django rest framework in which i have to filter different parameters given by user.I am using django Filter backend. Here is my code: class FilterViewSet(viewsets.ModelViewSet): serializer_class = SearchSerializer #Filters on specific fields filter_backends = (DjangoFilterBackend,) filter_fields = ('property_zipcode','property_state', 'property_county', 'property_city','property_area',)#range between 100 to 500 or area less then 500. #range is pass by user as a property_area=300. def filter_queryset(self, queryset): if self.request.query_params.get('property_state', None): queryset = super(FilterViewSet, self).filter_queryset(self.get_queryset()) return queryset else: queryset = self.get_queryset() return queryset Everything is working fine. But now i have to filter property_area based on range like 100 sqft to 500 sqft. How i can achieve this using djangoFilter backend? -
Determine signal in receiver
I need to create Redirect object when page with certain attribute gets either removed or set disabled, so what it's saved I need to determine if it's disabled, or if it's deleted I need to create this Redirect anyway. @receiver([post_save, pre_delete], sender=MyModel, dispatch_uid='seo.models.add_redirect') def add_redirect(sender, instance, **kwargs): if instance.option and (instance.enabled == False or signal == pre_delete): Redirect.objects.create(site_id=1, from_url=instance.get_absolute_url()[1:], to_url=instance.category.get_absolute_url()) So how can I figure out which signal is emitted inside the handler? -
How to make Django Rest-Framework to respond 401 on a unauthenticated request?
I'm using the default django authentication, I have this APIView class: class MatchesViewSet(APIView): ... permission_classes = (permissions.IsAuthenticated,) ... def get(self, request, format=None): ... return JsonResponse(data) And this test methods: class MainTests(TestCase): def setUp(self): ... self.c = Client() ... def test_only_for_logged_in_users(self): r = self.c.get("/api/matches") self.assertEqual(r.status_code, 401) The problem is I am getting a HTTP_403_FORBIDDEN while I would like to get a HTTP_401_UNAUTHORIZED -
Django ManyToManyField : how to choose its place?
I have two possibilities concerning the ManyToManyField in django : putting it in the "parent" class : from django.db import models class Person(models.Model): pass class Group(models.Model): members = models.ManyToManyField(Person, related_name='group') putting it in the "child" class from django.db import models class Group(models.Model): pass class Person(models.Model): groups = models.ManyToManyField(Group, related_name='members') What is the difference between these two options ? Is there a reason to privilege one over the other ? -
DetailView for Django Formset
I'm using Django inlineformsets for the first time and I'm trying to work on my views. I've been able to create my Create and Update views but I'm lost on how to go about the Detail View. I basically have 2 models - SchoolMain and SchoolSub with SchoolSub having a fk relationship with SchoolMain. SchoolSub is my formset. My Create View is below - class SchoolSubCreate(LoginRequiredMixin,UserPassesTestMixin,generic.CreateView): model = SchoolMain fields = '__all__' def get_context_data(self, **kwargs): data = super(SchoolSubCreate, self).get_context_data(**kwargs) if self.request.POST: data['schoolsub'] = SchoolSubFormSet(self.request.POST) else: data['schoolsub'] = SchoolSubFormSet() def form_valid(self, form): context = self.get_context_data() schoolsub = context['schoolsub'] with transaction.atomic(): form.instance.user = self.request.user self.object = form.save() if schoolsub.is_valid(): schoolsub.instance = self.object schoolsub.save() return super(SchoolSubCreate, self).form_valid(form) I understand how to go about creating a general DetailView, but that is only able to get the object of my primary model i.e. the SchoolMain model. But I'm unable to access the objects in the formset. Would appreciate any help. Thanks. -
printing json data in format of key value pair in django
I am trying to print json data in format of key value pair so that i can render them in my html template. def ecpd(request): r= requests.get('http://jira.xxx.xxx.com/rest/api/2/issue/key-XXX',auth=HTTPBasicAuth('user','pass'),headers = {'Content-Type' : 'application/json'}) jsonDict = json.loads(r.content) return HttpResponse(jsonDict['fields']) as a response, I am only getting list of Keys in the "fields". like:customfield_10070customfield_10071customfield_10072customfield_10073customfield_13221customfield_10074customfield_13220customfield_10075. I need a key-value pair in dict format. -
Act like proxy user without login to that user account in django-python
The scenario is A and B are two users and A is assigned as a proxy user for B. So A can do stuff behalf of B based on permission assigned to A by B while giving proxy access. Now when A switches account as a proxy for B, A must be able to access functionality behalf of B with the same session. I do not want to log in with python code or not want to screw request.user. -
Setting up docker, gunicorn, nginx & django. Mounts denied
I know this has been discussed a lot and I tried to google but all post seem old or don't work. I'm trying to setup docker. I would like to start from the standard Python3 image, add gunicorn and nginx. It shouldn't be too hard. My Dockerfile looks like this: # Set the base image FROM python:3 ENV PYTHONUNBUFFERED 1 # Set variables for project name, and where to place files in container. ENV PROJECT=analyticme ENV CONTAINER_HOME=/opt ENV CONTAINER_PROJECT=$CONTAINER_HOME/$PROJECT RUN mkdir /code WORKDIR /code ADD requirements.txt /code/ RUN pip install -r requirements.txt ADD . /code/ This should just start a python3 image and install my requirements. My docker-compose.yml looks like this: version: '3' services: nginx: image: nginx:latest container_name: NGINX ports: - "8000:8000" volumes: - ./src:/src - ./config/nginx:/etc/nginx/conf.d - /www/static:/static depends_on: - web web: build: . container_name: ANALYTICMEDJANGO command: bash -c "python3 manage.py makemigrations && python manage.py migrate && gunicorn analyticme.wsgi -b 0.0.0.0:8000" depends_on: - db volumes: - ./src:/src - /static:/static expose: - "8000" db: image: postgres:latest container_name: PSQLDATABASE Which ideally starts 3 services, an nginx image, my django app and my database.. It should also run the migrations, however ideally I would get those things out of my docker-compose file …