Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Passing environment variables from apache via mod_wsgi to use in django 1.11 settings
Found a few versions of this question, such as Django get environment variables from apache, however the advice I've found so far doesn't seem to work with the latest LTS django (1.11). I have an apache configuration which holds a number of environment variables, not limited to connection credentials for the DB. Im using this to make my code portable between dev/prod etc. My apache conf just uses SetEnv to pass in some variables. I've tried two different styles of approach to use these variables, both seem to suffer from the same issue; it needs to read the settings file before we can write to the environment, and the settings file requires values from the environment. My two variants are; import os import django from django.core.handlers.wsgi import WSGIHandler from django.core.wsgi import get_wsgi_application _application = get_wsgi_application() def application(environ, start_response): for key in [keys...]: if environ.get(key): os.environ[key] = environ.get(key) return _application(environ, start_response) and import os import django from django.core.handlers.wsgi import WSGIHandler class WSGIEnvironment(WSGIHandler): def __call__(self, environ, start_response): for key in [keys...]: if environ.has_key(key): print "Key: %s = %s" % (key,environ[key]) os.environ[key] = environ[key] return super(WSGIEnvironment, self).__call__(environ, start_response) os.environ.setdefault("DJANGO_SETTINGS_MODULE", 'apiClient.settings') django.setup(set_prefix=False) application = WSGIEnvironment() Either way im trying to use the values in … -
Django cannot assign value, must be another instance
So I am simply trying to add LectureCategory in my Lecture model, I want the user to be only able to select between Classes or Seminars. If I put choices in both models, I can see them on django admin, but I get the error: Cannot assign "'0'": "Lecture.lecture_category" must be a "LectureCategory" instance. If I dont put choices in second model, then in admin panel will show 0 or 1, instead of my values. Any suggestion ? class LectureCategory(models.Model): lecture_category = models.IntegerField(choices=((0, "Classes "), (1, "Seminars"), )) def __str__(self): return str(self.lecture_category) class Lecture(models.Model): course = models.ForeignKey('Course', on_delete=models.CASCADE, default='', related_name='lectures', null=True, ) lecture_category = models.ForeignKey('LectureCategory', on_delete=models.CASCADE, default='', related_name='categories', choices=((0, "Classes "), (1, "Seminars"), ) ) -
How to create Django Model with Many-To-Many Parents-Children Relationship?
I already know, that I can achieve ForeignKey Parent-Children relationship within the same model, that allows to create relations with 1 parent = multiple children. But how can I accomplish Many-To-Many relationship within the same model ? At this moment I wrote and tested this: class Person(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) parents = models.ManyToManyField( 'self', blank=True ) And it works, but not as I expected. What it does is: john = Person.objects.get(id=1) sam = Person.objects.get(id=2) >>> john.parents.all() <QuerySet [<Person: Alex>, <Person: Peter>, <Person: Sam>]> >>> sam.parents.all() <QuerySet [<Person: John>]> As you can see, Sam was supposed to be child of John, not his child and parent at the same time. What I want is to get John when I'm retrieving sam.parents.all() But not to get Sam when I'm retrieving john.parents.all() Is there a way to accomplish what I want ? Or that's not gonna work with this logic at least ? Do I have to create second separate model withing the same app ? -
Confusion about timezones oracle and django
I have django app running on ubuntu-14.04 and database is oracle. The timezones are as follow django- settings - TIME_ZONE = 'UTC' ubuntu - Asia/Kolkata oracle dbtimezone - UTC oracle sessiontimezone - Asia/Kolkata #this is via sqldeveloper While storing datetimes into db I am doing following. datetime.datetime.now(timezone.utc) Error I get is time can not be past. I don't want to change the code line. I can set the timezone of my Ubuntu or oracle as that is my development env. -
TypeError in django restapi
I was making a RESTFull API on Django. but when I run the server getting type error and I am not going the my desired url. although I have connected all classes with URLs -
Simplest way to periodically run a function from Django app on Elastic Beanstalk
Within my app i have a function which I want to run every hour to collect data and populate a database (I have an RDS database linked to my Elastic Beankstalk app). This is the function I want to want (a static method defined in my Data model): @staticmethod def get_data(): page = requests.get(....) soup = BeautifulSoup(page, 'lxml') ..... site_data = Data.objects.create(...) site_data.save() From reading it seems I want to use either Celery or a cron job. I am unfamiliar with either of these and it seems quite complicated using them with AWS. This post here seems most relvant but I am unsure how I would apply the suggestion to my example. Would I need to create a management command as mentioned and what would this look like with my example? As this is new to me it would help a lot it someone could point me down the right path. -
Django JSONWebTokenAuthentication not working for views
I am using rest_framework_jwt.authentication.JSONWebTokenAuthentication for my REST APIs . This is working fine for authentication but for my Skill view , I am able to hit the REST endpoint even though I am not passing any authentication token . How can i make my Skill API authenticated . Also I am new to Django so In the User view I do have a class , but for my Skill view i didnt found a correct example to have a class . Please help me with this . I have following view file : from rest_framework.permissions import IsAuthenticated @api_view(['GET']) def skill_collection(request): if request.method == 'GET': skills = Skill.objects.all() serializer = SkillSerializer(skills, many=True) return Response(serializer.data) @api_view(['GET']) def skill_element(request, pk): try: skill = Skill.objects.get(pk=pk) except Skill.DoesNotExist: return HttpResponse(status=404) if request.method == 'GET': serializer = SkillSerializer(skill) return Response(serializer.data) Url file : urlpatterns = [ path('admin/', admin.site.urls), url(r'^rest-auth/', include('rest_auth.urls')), url(r'^rest-auth/registration/', include('rest_auth.registration.urls')), url(r'^rest-auth/login/', include('rest_auth.registration.urls')), url(r'^refresh-token/', refresh_jwt_token), url(r'^user/$', DetailsView.as_view(), name='rest_user_details'), url(r'^', include('api.urls')), url(r'^api/v1/skills/$', wantedly_app_views.skill_collection), url(r'^api/v1/skills/(?P<pk>[0-9]+)$', wantedly_app_views.skill_element) ] -
Filter table based on function in django
I have a table which has a column A I want to filter table after applying some operation on A and filter the result of the operation with some value. What I want is something like this: MyTable.objects.filter(some_function(F('A'))=some_constant) Basically I want to calculate value of column A for each row based on some_function and filter the result of the function with some value. Any different approach for the solution is much appreciated. -
Is mongoengine is compatible to django 1.11.4 and latest mongodb?
I'm trying to find out any documentation for the compatibility of mongoengine with Django 1.11.4. Official Doc -
django form queryset multiple same field filter
Greeting, im trying to filter my user field queryset based on 3 department id, I'm able to filter a single department but when i try to filter multiple time its not working, can anyone help me with this thanks. below is my code : form.py class EditProjectForm(forms.ModelForm): prefix = 'edit_form' class Meta: model = Model_A fields = '__all__' def __init__(self, user, *args, **kwargs): super(EditProjectForm, self).__init__(*args, **kwargs) self.fields['user'].queryset = Employee.objects.filter(department__id=18).filter(department__id=19).filter(department__id=20) -
Django rest framework API calling to another API
I have 2 django project API. What i am trying to do is django 1 api call to django 2 api to create and appointment (to do a get and post method) These are the 2 things i am currently 1. Djangp api 1 will do a get request to django api 2 to get a 200OK response first(for now is just doing testing for 200 status code). Django api 1 will do a post request to django api 2 to create an appointment, getting a queue number if success. I found an answer here: Calling a REST API from django view It is working for now but is it a good solution ? -
Filter the StringRelatedField data in Django rest framework
I'm trying to query two tables data with StringRelatedField method, it's working fine but it throws list of data. But i need to filter the data with some conditions. ex: Top most, recently created . Manually writing extra code it's possible but i need to do that by serializer itself. Can anyone help me with that thing. Below i added sample code. Models.py class User(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) first_name = models.CharField(max_length=50) class UserLog(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) user_id = models.ForeignKey(User, related_name='user_log', on_delete=models.CASCADE) Serilizer.py class UserDetailsSerializer(serializers.ModelSerializer): user_log = serializers.StringRelatedField(many=True) class Meta: model = User fields = ('id', 'first_name', 'user_log') -
Celery: Global SoftTimeLimitExceeded Handler function
I want to actually execute a function whenever a celery task exceeds it's allotted global soft time limit. I tried using on_faiure but it won't work as it works only upon FAILED tasks. Any suggestions? Thank You -
Django Beginner Forms, not able to get loop forms
I have a model name Fightmma and a model named Fightmmacard. Commentform works for Fightcard but not for Fightmma. Each fightcard is made of fights. When I comment on any fight, the last fight on the card gets the comment. My Commentform looks for the content type and the id. I am not able to pass the correct fight id to the Commentform properly. In my views it loop though the fights but the id is stored for the last fight only. My python isn't that great but I've been trying for 12 hours All help appreciated. models.py from __future__ import unicode_literals from django.db import models from django.core.urlresolvers import reverse from datetime import date from django.contrib.auth.models import User #Blog author or commenter from django.contrib.contenttypes.fields import GenericForeignKey from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes.fields import GenericRelation class CommentManager(models.Manager): def filter_by_instance(self, instance): content_type = ContentType.objects.get_for_model(instance.__class__) obj_id = instance.id qs = super(CommentManager, self).filter(content_type=content_type, object_id= obj_id) return qs class Comment(models.Model): author = models.ForeignKey(User) body = models.TextField(blank=True) post_date = models.DateTimeField(auto_now_add=True) content_type = models.ForeignKey(ContentType) object_id = models.PositiveIntegerField() content_object = GenericForeignKey() objects = CommentManager() class Meta: ordering = ["-post_date"] def __str__(self): """ String for representing the Model object. """ len_title=75 if len(self.body)>len_title: titlestring=self.body[:len_title] + '...' else: titlestring=self.body return … -
Customize Users inside Django Admin
I want to add some fields in Users section, apart from the predefined ones. I want to add a section called "Objectives" and also another called "Tests". How can I do this? -
Alternative to path() in Django 1.11
I have the following code in my URLs.py from django.conf.urls import url, include, path from django.contrib import admin urlpatterns = [ path('moraimono/', include('moraimono.urls')), path('admin/', admin.site.urls), however I found that path() is only included in Django 2.0 and I am using Django 1.11b1. How can I modify this code to make it work in Django 1.11b1 -
Djangae AppEngine misbehaves with IAP
Everything works fine when I use the Djangae appengine with Datastore (Django with datastore support) back-end but when I enable the Google Identity Aware Protocol (Google IAP) everything starts failing. When I checked the logs, It says that there was an IntegrityError in djangae_gaedatastoreuser on the field email_lower IntegrityError: Unique constraint violation for kind djangae_gaedatastoreuser on fields: email_lower The datastore kind has two empty entries in the email_lower field. Even the google.appengine.api.users module starts misbehaving. On first attempt to login, I can login to the AppEngine normally but I cannot logout of the appengine as a google account user, I see that I have logged out of my Google account(that's great but). When I try logging in, I see that no authentication was required to login (Google Sign In). When I login from another browser instance, It shows DatabaseError: save with update_fields did not affect any rows. Can someone please explain why this is happening and what I must do to avoid this. -
How to modify python source code using ubuntu on putty?
I am now running Ubuntu using putty, and try to modify a Django project using virtualenv. But I don't know how to open the source code. Please how to open source code and modify Thank you -
Django: Is it possible to run django without Nginx, gunicorn?
What I want to do is to run my django project on my desktop(Ubuntu 16.04) computer at my home. I have a Wi-Fi-router and use port-forwarding function to access other computer at my home by ssh. It also supports one free DDNS so I have a my own domain. Let say domain name is THIS_IS_MY_DOMAIN This is my idea : Run django on my desktop Set DEBUG=False, ALLOWED_HOST=["*",] in settings.py Run django by python super_crawler/manage.py runserver 0.0.0.0:8002 Port-forwarding on my Router : 8002(external) -> 8002(internal) When I run my django application, it shows like this in terminal: python manage.py runserver 0.0.0.0:8002 Performing system checks... System check identified no issues (0 silenced). January 19, 2018 - 17:38:03 Django version 1.11.8, using settings 'config.settings.production' Starting development server at http://0.0.0.0:8002/ Quit the server with CONTROL-C. Now I access some pages via other computer's browser with other network(from outside), and it shows like this: THIS_IS_MY_DOMAIN:8002/ => Not Found. The requested URL / was not found on this server. THIS_IS_MY_DOMAIN:8002/admin/ => Server Error (500) On my desktop, Nginx was off. I wonder whether I can run django ON MY DESKTOP in any other way. Must I use nginx, gunicorn? Edit Actually if I set DEBUG=True, … -
code in save_model executed on second save, not first
i defined a save_model in my UserAdmin to change object level permissions for users. class UserAdmin(BaseUserAdmin): def save_model(self, request, obj, form, change): obj.save() allprojects = Project.objects.all() projects = obj.workingproject.all() remove_perm("view_project", obj, allprojects) assign_perm("view_project", obj, projects) obj.save() remove_perm and assign_perm are shortcuts from django-guardian, workingproject is a M2M field of user. The problem: when selecting different projects and saving the permissions are not changed, but pressing the save button a second time makes the changes as wanted. What am i doing wrong? -
pika.exceptions.ConnectionClosed - asgi_rabbitmq + django + pika
I am getting this issue in my django project. this is the traceback: Traceback (most recent call last): File "/usr/local/lib/python3.6/site-packages/channels/worker.py", line 119, in run consumer(message, **kwargs) File "/usr/local/lib/python3.6/site-packages/channels/handler.py", line 360, in __call__ message.reply_channel.send(reply_message, immediately=True) File "/usr/local/lib/python3.6/site-packages/channels/channel.py", line 44, in send self.channel_layer.send(self.name, content) File "/usr/local/lib/python3.6/site-packages/asgi_rabbitmq/core.py", line 812, in send return future.result() File "/usr/local/lib/python3.6/concurrent/futures/_base.py", line 432, in result return self.__get_result() File "/usr/local/lib/python3.6/concurrent/futures/_base.py", line 384, in __get_result raise self._exception File "/usr/local/lib/python3.6/site-packages/channels/worker.py", line 119, in run consumer(message, **kwargs) File "/usr/local/lib/python3.6/site-packages/channels/handler.py", line 360, in __call__ message.reply_channel.send(reply_message, immediately=True) File "/usr/local/lib/python3.6/site-packages/channels/channel.py", line 44, in send self.channel_layer.send(self.name, content) File "/usr/local/lib/python3.6/site-packages/asgi_rabbitmq/core.py", line 812, in send return future.result() File "/usr/local/lib/python3.6/concurrent/futures/_base.py", line 432, in result return self.__get_result() File "/usr/local/lib/python3.6/concurrent/futures/_base.py", line 384, in __get_result raise self._exception File "/usr/local/lib/python3.6/site-packages/channels/worker.py", line 119, in run consumer(message, **kwargs) File "/build/apps/core/decorators.py", line 74, in inner return func(message, user=user, *args, **kwargs) File "/build/apps/core/consumers.py", line 110, in ws_message handler(action, message, user) File "/build/apps/core/consumers.py", line 35, in subscribe_handler Group('games').add(message.reply_channel) File "/usr/local/lib/python3.6/site-packages/channels/channel.py", line 70, in add self.channel_layer.group_add(self.name, channel) File "/usr/local/lib/python3.6/site-packages/asgi_rabbitmq/core.py", line 839, in group_add return future.result() File "/usr/local/lib/python3.6/concurrent/futures/_base.py", line 432, in result return self.__get_result() File "/usr/local/lib/python3.6/concurrent/futures/_base.py", line 384, in __get_result raise self._exception pika.exceptions.ConnectionClosed and this is what I use: asgi-rabbitmq==0.5.5 pika==0.11.2 and this is the log from rabbitmq: =WARNING REPORT==== 19-Jan-2018::09:35:40 … -
Django: Structure to import file
I have a general question about project structure in Django. I have several apps on my website. Let's say App A & App B I have now an API code which I want to import in both apps. I couldn't find a page answering me this question so I want to ask you here. Where in the project folder should I store this SOMEAPI.py file to import it in both app? -
Get multiple querysets for a particular month in Django MonthArchiveView?
The date range parameter seems to be added to the default queryset of model. I want querysets for multiple models returned. Would this have to be done in context data and with having to manually acquire the daterange? Surely there is a way to return multiple querysets for the selected range. Maybe there is generic way to apply such filtering to an existing queryset? What I am doing currently: I get the main queryset in get_queryset def get_queryset(self): entries = Entry.objects.filter(user=self.request.user) Then to get paid holidays in the get_context_data I acquire the date range in a terrible way (I think) def get_context_data(self, **kwargs): #jump through hoops to get the date range context_data = super().get_context_data(**kwargs) current_month_date = date(int(self.get_year()), int(self.get_month()), 1) current_month_datetime = datetime.combine(current_month_date, datetime.min.time()) start_month_date = self._get_current_month(current_month_datetime).date() end_month_date = get_last_day_of_month(current_month_date) context_data['total_working_days'] = PaidHoliday.calculate_total_days( start_month_date, end_month_date ) -
Error 1054 from database when I am trying to access model in admin panel
So I was trying to modify my models a bit and now I can't get rid of this error. I tried to delete all my data, but it doesn't help. I think it has to do with my database, but before, everything used to work fine. I get this error: (1054, "Unknown column 'courses_course.course_category_id' in 'field list'") And here are my models: class StudyProgramme(models.Model): department = models.ForeignKey('Department', on_delete=models.CASCADE) name = models.CharField(max_length=50) studies_type = models.IntegerField(choices=((0, "Bachelor Studies"), (1, "Master Studies"), (2, "PhD Studies"), (3, "Integrated Studies"))) duration = models.PositiveSmallIntegerField(validators=[MaxValueValidator(99)]) class Meta: verbose_name = "Study Programme" verbose_name_plural = 'Study Programmes' def __str__(self): return self.name class Course(models.Model): study_programme = models.ForeignKey('StudyProgramme', on_delete=models.CASCADE) course_category = models.ForeignKey('CourseCategory', on_delete=models.CASCADE, default='', related_name='categories') name = models.CharField(max_length=50) ects = models.PositiveSmallIntegerField(validators=[MaxValueValidator(99)]) description = models.TextField() year = models.PositiveSmallIntegerField(validators=[MaxValueValidator(99)]) semester = models.IntegerField(choices=((1, "1"), (2, "2"), ), default=None) slug = models.SlugField(max_length=140, unique=True) def __str__(self): return self.name def _get_unique_slug(self): slug = slugify(self.name) unique_slug = slug num = 1 while Course.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() class CourseCategory(models.Model): course_category = models.CharField(max_length=50, unique=True) def __str__(self): return self.course_category class Lecture(models.Model): course = models.ForeignKey('Course', on_delete=models.CASCADE, default='', related_name='lectures') lecture_title = models.CharField(max_length=100) content = models.TextField() link … -
django - Custom redirect after login
In my app I try to redirect after submitting a form, but it seems to does not work. Here is my urls.py from django.conf.urls import url from po_contest_app import views urlpatterns = [ # url(r'^admin/', admin.site.urls), url(r'^$', views.home, name='home'), url(r'^signup/$', views.graduate_signup, name='signup'), url(r'^signup/success/$', views.signup_success, name='signup_success') ] and views.py. The actual problem is in graduate_signup view. After receiving POST request I want to create a User and then save additional info about it. For that purpose I use User Profile approach as described here: def graduate_signup(request): if request.method == 'POST': form = GraduateSignUpForm(request.POST) print('POST has been received') if form.is_valid(): user = form.save() user.refresh_from_db() # load the profile instance created by the signal user.graduate.birth_date = form.cleaned_data.get('birth_date') user.save() print('user is signed up') raw_password = form.cleaned_data.get('password1') user = authenticate(username=user.username, password=raw_password) login(request, user) print('user is signed in') return redirect('signup_success') else: print('form has some errors') print(form.errors) else: form = GraduateSignUpForm() return render(request, 'graduate_signup.html', {'form': form}) def signup_success(request): return render(request, 'signup_finished.html') After submitting form in browser, I can see logs in Django console: System check identified no issues (0 silenced). January 19, 2018 - 08:05:32 Django version 1.11.7, using settings 'po_contest.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. [19/Jan/2018 08:05:34] "GET / HTTP/1.1" 200 …