Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ImproperlyConfigured: Error loading psycopg2 module: No module named cffi
I developed a platform with django + wsgi + pypy + postgresql + postgis, everything works fine in development environment, but in production it sends error 500 and in the apache log it says ImproperlyConfigured: Error loading psycopg2 module: No module named cffi my config apache: <VirtualHost *:80> ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined WSGIScriptAlias / /home/user/plataform/project/project/wsgi.py WSGIDaemonProcess project python-path=/home/user/plataform/project:/home/user/env/site-packages WSGIProcessGroup project WSGIPassAuthorization On <Directory /home/user/plataform/project/project> <Files wsgi.py> Require all granted </Files> </Directory> Alias /media /home/user/plataform/project/media/ Alias /static /home/user/plataform/project/static/ <Directory /home/user/plataform/project/static> Options Indexes FollowSymLinks AllowOverride None Require all granted </Directory> <Directory /home/user/plataform/project/media> Require all granted </Directory> my pip freeze cffi==1.6.0 Django==1.11.7 django-cors-headers==2.1.0 django-filter==1.1.0 djangorestframework==3.7.3 greenlet==0.4.9 Markdown==2.6.9 olefile==0.44 Pillow==4.3.0 psycopg2cffi==2.7.7 python-stdnum==1.7 pytz==2017.3 readline==6.2.4.1 six==1.11.0 uWSGI==2.0.15 Log Apache: [Tue Dec 12 11:15:49.727998 2017] [wsgi:warn] [pid 4975:tid 139854422423424] mod_wsgi: Compiled for Python/2.7.11. [Tue Dec 12 11:15:49.728151 2017] [wsgi:warn] [pid 4975:tid 139854422423424] mod_wsgi: Runtime using Python/2.7.12. [Tue Dec 12 11:15:49.729853 2017] [mpm_event:notice] [pid 4975:tid 139854422423424] AH00489: Apache/2.4.18 (Ubuntu) mod_wsgi/4.3.0 Python/2.7.12 configured -- resuming normal operations [Tue Dec 12 11:15:49.729893 2017] [core:notice] [pid 4975:tid 139854422423424] AH00094: Command line: '/usr/sbin/apache2' [Tue Dec 12 11:15:59.608678 2017] [wsgi:error] [pid 4978:tid 139854259615488] [remote ::1:30039] mod_wsgi (pid=4978): Target WSGI script '/home/user/plataform/project/project/wsgi.py' cannot be loaded as Python module. [Tue Dec 12 11:15:59.608785 … -
Avoid concurrent access to same queue element
I'm reviewing/refactoring a queue that's going to be used internally by up to 20 people simultaneously but as of now, multiple people can access the first element ( We tried it locally clicking on the link at the same time. ) The flux is similar to this: views.py [GET] def list_operator(request, id): if request.POST: utilitary = Utilitary(id) pool = ThreadPool(processes=1) async_result = pool.apply_async(utilitary.recover_people, (id, )) return_val = async_result.get() person = People.objects.get(pk=return_val) return redirect('people:people_update', person.pk) utilitary.py This file has the method recover_people which performs around 4-5 queries (where people have flag_allocated=False) across multiple tables and sorts a list, to return the first element. The final step is this one: for person in people: p_address = People_Address.objects.get(person_id=person.id) p_schedule = Schedules.objects.get(schedules_state=p_address.p_state) if datetime.now() > parse_time(p_schedule.schedules_hour): person = People.objects.get(pk=person.id) person.flag_allocated = True person.date_of_allocation = datetime.now() person.save() return person.pk Perhaps something in the Utilitary method's logic is wrong? Or I should be expecting this problem with this amount of people simultaneously calling this method? Could using a cache help? I'm sorry, I'm new to django and mvc. -
Django application not running with Gunicorn and Supervisor
I am trying to run a Django application from gunicorn and supervisord. I have configured bash script to run application from gunicorn which is working fine and I am able to see the GUI but when I was trying to start this application from supervisorctl. I am not able to see the GUI. However, Gunicorn processes are running. gunicorn_start2 #!/bin/bash export ANALYTICS_ENV="dev" NAME="analytics" # Name of the application DJANGODIR=/home/ubuntu/code/current/analytics/analytics/analysis/ # Django project directory SOCKFILE=/home/ubuntu/code/current/analytics/analytics/run/gunicorn.sock # we will communicte using this unix socket USER=ubuntu # the user to run as GROUP=ubuntu # the group to run as NUM_WORKERS=3 # how many worker processes should Gunicorn spawn DJANGO_SETTINGS_MODULE=analytics.settings # which settings file should Django use DJANGO_WSGI_MODULE=analytics.wsgi # WSGI module name echo "Starting $NAME as `whoami`" # Activate the virtual environment cd $DJANGODIR echo $DJANGODIR source /home/ubuntu/code/current/analytics/analytics/bin/activate export DJANGO_SETTINGS_MODULE=$DJANGO_SETTINGS_MODULE #export PYTHONPATH=$DJANGODIR:$PYTHONPATH #export PYTHONPATH=/home/ubuntu/code/analytics/bin/python # Create the run directory if it doesn't exist RUNDIR=$(dirname $SOCKFILE) test -d $RUNDIR || mkdir -p $RUNDIR # Start your Django Unicorn # Programs meant to be run under supervisor should not daemonize themselves (do not use --daemon) exec /home/ubuntu/code/current/analytics/bin/gunicorn ${DJANGO_WSGI_MODULE}:application \ --name $NAME \ --workers $NUM_WORKERS \ --user=$USER --group=$GROUP \ --bind=unix:$SOCKFILE \ --log-level=all \ --log-file=- gunicorn_start.conf [program:analytics] command … -
Como puedo hacer para que servicio Rest con DRF me retorne un archivo csv como respuesta.
Estoy intentado que mi servicio rest con DRF me devuelva un archivo csv descargable. y me codigo es el siguiente : class OperationsReportOrders(APIView): def post(self, request): if request.method == "POST": #Aqui va toda la logica donde obtengo toda la data que necesito para mi csv y lo almaceno en file_rows file_rows.append(row) # Creo file_rows donde se encuentra toda la data a escribir en csv #Escribo el archivo CSV with open('orders.csv', 'wb') as myfile: wr = csv.writer(myfile, quoting=csv.QUOTE_ALL) wr.writerows(file_rows) #Armo el response csv_file = open('orders.csv', 'rb') response = HttpResponse(FileWrapper(csv_file), content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="%s"' % 'orders.csv' return response else: return Response("Metodo no autorizado", status=status.HTTP_405_METHOD_NOT_ALLOWED) Mi Defaul render class esta asi: 'DEFAULT_RENDERER_CLASSES': ( 'rest_framework.renderers.JSONRenderer', ), Luego le agrego otro render: 'DEFAULT_RENDERER_CLASSES': ( 'rest_framework.renderers.JSONRenderer', 'rest_framework_csv.renderers.CSVRenderer', ), y a mi clase le agrego: renderer_classes = (r.CSVRenderer, ) pero al momento de hacer un request con con Content-Type igual A text/csv Me retorna la siguiente: { "detail": "Unsupported media type \"text/csv\" in request." } -
maintain HTTP Response headers after redirect from django application using apache
I am trying to do something like this Django set headers on redirect() The solution I see here to set 'token' it in cookie.However I don't want to keep it in a cookie as I think cookie might still be there in browser in case user does not logged out. I am using Apache web server . Is there any configuration in apache through which I can retain my 'token' which I set in HTTP headers? -
template doesnt exist "django 2.0"
please can anyone help me i cant figure out what is the error while rendering template in djano 2.0 i created a app and and in the views.py section i added all thoe code lines of manange.py imported urls(directly in the views ) tried to run the server (python views.py runserver) here is my complete code from views.py import os import sys from django.conf import settings DEBUG = os.environ.get('DEBUG', 'on') == 'on' SECRET_KEY = os.environ.get('SECRET_KEY', os.urandom(32)) ALLOWED_HOSTS = os.environ.get( 'localhost','127.0.0.1').split(',') BASE_DIR = os.path.dirname(__file__) settings.configure( DEBUG=DEBUG, SECRET_KEY=SECRET_KEY, ALLOWED_HOSTS=ALLOWED_HOSTS, ROOT_URLCONF=__name__, MIDDLEWARE_CLASSES=( 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ), ) INSTALLED_APPS=( 'django.contrib.staticfiles', 'django.contrib.contenttypes', 'django.contrib.auth', ), TEMPLATE_DIRS=( os.path.join(BASE_DIR, 'templates'), ), STATICFILES_DIRS=( os.path.join(BASE_DIR, 'static'), ), STATIC_URL='/static/', #############################views & urls###############################s from django import forms from django.urls import path,include from django.core.cache import cache from django.core.wsgi import get_wsgi_application from django.http import HttpResponse, HttpResponseBadRequest from django.shortcuts import render from django.views.decorators.http import etag # Create your views here. application = get_wsgi_application() def home(request): return render(request,'index.html') urlpatterns=[ path('',home,name='home'), ] ###################################### ############################################# if __name__ == "__main__": from django.core.management import execute_from_command_line execute_from_command_line(sys.argv) and i tried placing templates in the same directory where views exist and also in outside of the app folder i should be getting a basic template as explained in the book lightweight django … -
Django checking if an individual field has an error and not run clean()?
Is there a way to check if an inidividual field has not passed validation in django's clean() method for a form. I don't want to have to manually be checking if a required field is there: def clean(): cleaned_data = super().clean() half_day = cleaned_data.get('half_day') start_date = cleaned_data.get('start_date') end_date = cleaned_data.get('end_date') leave_type = cleaned_data.get('leave_type') extra_info = cleaned_data.get('extra_info') if start_date and end_date: if half_day: if start_date != end_date: self.add_error( 'half_day', 'Start and end date must be the same' ) -
Django Application running on AWS ECS Cluster and behind the Squid Proxy
I have a Django Python app running on AWS ECS Cluster and it's running behind the Squid Proxy. The application need to access AWS SSM to get the parameter and it always fails I think because of the proxy. The application cannot use the proxy setting that I have set in the UserData #cloud-boothook # Configure Yum, the Docker daemon, and the ECS agent to use an HTTP proxy # Specify proxy host, port number, and ECS cluster name to use PROXY_HOST=10.0.0.131 PROXY_PORT=3128 CLUSTER_NAME=proxy-test # Set Yum HTTP proxy if [ ! -f /var/lib/cloud/instance/sem/config_yum_http_proxy ]; then echo "proxy=http://$PROXY_HOST:$PROXY_PORT" >> /etc/yum.conf echo "$$: $(date +%s.%N | cut -b1-13)" > /var/lib/cloud/instance/sem/config_yum_http_proxy fi # Set Docker HTTP proxy if [ ! -f /var/lib/cloud/instance/sem/config_docker_http_proxy ]; then echo "export HTTP_PROXY=http://$PROXY_HOST:$PROXY_PORT/" >> /etc/sysconfig/docker echo "export NO_PROXY=169.254.169.254" >> /etc/sysconfig/docker echo "$$: $(date +%s.%N | cut -b1-13)" > /var/lib/cloud/instance/sem/config_docker_http_proxy fi # Set ECS agent HTTP proxy if [ ! -f /var/lib/cloud/instance/sem/config_ecs-agent_http_proxy ]; then echo "ECS_CLUSTER=$CLUSTER_NAME" >> /etc/ecs/ecs.config echo "HTTP_PROXY=$PROXY_HOST:$PROXY_PORT" >> /etc/ecs/ecs.config echo "NO_PROXY=169.254.169.254,169.254.170.2,/var/run/docker.sock" >> /etc/ecs/ecs.config echo "$$: $(date +%s.%N | cut -b1-13)" > /var/lib/cloud/instance/sem/config_ecs-agent_http_proxy fi # Set ecs-init HTTP proxy if [ ! -f /var/lib/cloud/instance/sem/config_ecs-init_http_proxy ]; then echo "env HTTP_PROXY=$PROXY_HOST:$PROXY_PORT" >> /etc/init/ecs.override echo "env NO_PROXY=169.254.169.254,169.254.170.2,/var/run/docker.sock" >> /etc/init/ecs.override echo … -
Django: How to drop default sqlite database?
I need to drop my database since I want to use a customized user model in my project. I've used the default database that is used when following the django introduction tutorial. I connect to the database through the terminal with python manage.py dbshell. Then, I locate the database: sqlite> .databases main: /Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/workout/mydatabase And I proceed to delete the database: $ rm /Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/workout/mydatabase $ rm /Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/workout/mydatabase rm: /Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/workout/mydatabase: No such file or directory But the database still shows up in the database connection: sqlite> .databases main: /Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/workout/mydatabase And when I try to detach, I get an error: sqlite> detach database main; Error: cannot detach database main Is this a problem? -
Django: limit_choices_to to current objects id
Im using Django 1.11.6 and trying to limit the choices of projectLeader in my Project class to a list of AbstracUser which have the Projects id in their ManytoMany field workingproject. class Project in models.py of one app class Project (models.Model): projectLeader = models.ForeignKey('anmeldung.AbstractUser', blank=True, null=True, limit_choices_to={'workingproject': limit},) class AbstractUser in models.py of application named "anmeldung" class AbstractUser(AbstractBaseUser, PermissionsMixin): workingproject = models.ManyToManyField('szenario.Project', blank=True) For 'limit' i've used several things like self.id, obj.id but cant figure out whats correct. I'm quite new to Django and all the similar questions i've found didnt help me (could be i just didnt get the answers). -
How to serialize a django QuerySet and a django object in one call?
I am trying to retrieve my object and a query set from my model through an ajax call. What I want to get back is an object and a query set. So when i serialize the object its no problem but the QuerySet does not seem to be serialized by Django. I get an error "QuerySet has no attribute _meta". Here is my code: def followUp(request): fid = request.GET['fid'] fup = FollowUp.objects.get(answer=fid) Question = fup.question answers = Question.answer_set.all() context = { 'question': Question, 'answers' : answers } data = serializers.serialize('json', context) return JsonResponse(data, safe=False, content_type="application/json") Here if i just put 'Question' its no problem but as soon as i try to make a dict with 'answers' combined, it throws the error. Is there a way to serialize both of them or what should I do if not? Please Help! -
How to filtering tag using Django2.0 and django-taggit0.22.1
I have a problem which i can't resolve. I try to implements tags features in my blog project in Python/Django 2.0. I install django-taggit0.22.1. Ok i have a class Post with atributte tags = TaggableManager() I also have a few posts object with tags. For example in python manage.py shell I import my Post models and I do command: post = Post.objects.get(id=1) i have a post named "Post: Django 2.0" then i use tag = post.tags.all() "tag" variable show me this "QuerySet [<\Tag: django\>], <\Tag: programming\>, <\Tag: jazz\>" ok and then i want to filter my tags. I download all my published post published= Post.published.all() and finally i want do filter post by tags using this: published.filter(tags__name__in=['music']) I see this error: TypeError: get_path_info() takes 1 positional argument but 2 were given What is the main problem ? This filtering method i saw on https://pypi.python.org/pypi/django-taggit Can you help me? -
Multiple Inheritance Django mixins
I have an issue with getting Django view to work with two mixins that both override dispatch method. My view has the following signature: class SomeView(LoggingMixin, ResetUserLanguageMixin, generics.ListAPIView) The ResetUserLanguageMixin supposed to set the language in dispatch, but then set it back to what it was before the call in finally block. class ResetUserLanguageMixin(object): def dispatch(self, request, *args, **kwargs): cur_language = translation.get_language() try: response = super(ResetUserLanguageMixin, self).dispatch(request, *args, **kwargs) finally: translation.activate(cur_language) return response The issue is that generics.ListAPIView also has an implementation of dispatch that doesn't call super. The ResetUserLanguageMixin calls dispatch, where it sets the language, but also the finally block is called before the generics.ListAPIView dispatch is called. As a result incorrect language is used by generics.ListAPIView. The ideal situation would be that generics.ListAPIView dispatch is called from ResetUserLanguageMixin's dispatch before the finally block. Is this possible, and if so, how could it be accomplished? -
How to create schema from tree structure, create a api in django and generate a tree on browser?
Please generate schema using below image and generate api. Give me a perfect answer. -
Django 1.11 password reset not working
I've been researching about some other questions here about django password reset email not working and I tried it but I can't find a real solution. The problem is that I can send email through Django 1.11 without problem but it fails in password reset. It is just not sent. These are my url patterns: url(r'^password/reset/$', password_reset, {'template_name': 'registration/password_reset_form.html', 'email_template_name': 'registration/password_reset_email.html', 'post_reset_redirect': 'password-reset-done'}, name='password-reset'), url(r'^password/reset/done/$', password_reset_done, name='password-reset-done'), url(r'^password/reset/complete/$', password_reset_complete, {'template_name': 'registration/password_reset_complete.html'}, name='password_reset_complete'), url(r'^password/reset/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$', password_reset_confirm, {'template_name': 'registration/password_reset_confirm.html'}, name='password_reset_confirm'), And my email settings: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.sendgrid.net' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = os.environ['EMAIL_USER'] EMAIL_HOST_PASSWORD = os.environ['EMAIL_PASSWORD'] SERVER_EMAIL = EMAIL_HOST_USER DEFAULT_FROM_EMAIL = 'Team <noreply@whatever.com>' The templates exist and are working fine. I used the console email backend to test the email but it doesn't send anything and any error is shown at the console. Other views can send email without problem. -
foreign key appearing as char field
My foreign key that is event_id is being displayed as another attribute in my Expense class as Hall_name which is an attribute of Event class a char field. i don't know why because i have just did this. class Event(model.Model): event_hall=models.CharField(max_length=1) here are all my attributes but i let django make its own default primary key and it should be an integer. class Expense(models.Model) event_id=models.ForeignKey(Event) so why is it displaying it as event_hall in my foreign key? -
Django.fcgi using dynamic virtualenv
Is there a way to load the virtualenv in a dynamic way? #!/home/root/.virtualenvs/production/bin/python import os, sys ... I'd like the path to be #!/home/root/.virtualenvs/production/bin/python or #!/home/root/.virtualenvs/staging/bin/python depending if the folder name is staging or production I can get the folder name this way: _PROJECT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.insert(0, _PROJECT_DIR) sys.path.insert(0, os.path.dirname(_PROJECT_DIR)) _FOLDER_NAME = _PROJECT_DIR.split('/')[-1] But I have no idea if I can load the virtualenv in a dynamic way based on this. It's a deployment issue, I currently have to replace the path in staging environment because it's hardcoded for production. -
Different error importing file-wide and function-wide Django
I am trying to run some tests in my Django project, but I get two different errors with two different appoaches. If I do from cards_browser.models import Cards, Drawers, Timeframes at the top of the file among the other imports, I get: RuntimeError: Model class cards_browser.models.Cards doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. However, the app is in fact in INSTALLED_APPS, among others: 'vcc_merged.cards_browser', But if I import specific models for the specific model I'm testing like so def test_data_count(self): from cards_browser.models import Cards I get: django.db.utils.ProgrammingError: (1146, "Table 'test_vcc.feedback' doesn't exist") Now the second is a problem with Django if you have unmanaged models like I do, but I have a TestRunner file in Settings that is supposed to make the models Managed for the duration of the test, but that obviously fails to work, or I wouldn't be getting this error. Using Python 3.6.3 and Django 1.11.7 connected to MySQL 5.7 -
Django many to many relationship
I have a user model and a group model. from django.contrib.auth.models import AbstractUser class Group(models.Model): name = models.CharField(max_length=200) class User(AbstractUser): name = models.CharField(max_length=200) group = models.ManyToManyField('Group') I have a scenario in which a user can be an admin or just a member of a group. A group can have many admins as well as it can have many members. How can I define such a relation in Django and query things like "Admins of a group", "members of group", "groups where a user is an admin", "groups where a user is a member" -
RabbitMQ is getting flooded by connection and disconnection
I have a very weird issue where my rabbimq gets a flooded log like the one below continuously as in milliseconds =WARNING REPORT==== 12-Dec-2017::11:52:44 === closing AMQP connection <0.27756.1813> (10.0.1.44:57706 -> 10.0.1.33:5672, vhost: 'peter1_vhost', user: 'peter1'): client unexpectedly closed TCP connection =INFO REPORT==== 12-Dec-2017::11:52:44 === connection <0.27588.1813> (10.0.1.44:57710 -> 10.0.1.33:5672): user 'peter1' authenticated and granted access to vhost 'peter1_vhost' =WARNING REPORT==== 12-Dec-2017::11:52:44 === closing AMQP connection <0.27562.1813> (10.0.1.44:57708 -> 10.0.1.33:5672, vhost: 'peter1_vhost', user: 'peter1'): client unexpectedly closed TCP connection =INFO REPORT==== 12-Dec-2017::11:52:44 === accepting AMQP connection <0.28103.1813> (10.0.1.44:57714 -> 10.0.1.33:5672) =WARNING REPORT==== 12-Dec-2017::11:52:44 === closing AMQP connection <0.27588.1813> (10.0.1.44:57710 -> 10.0.1.33:5672, vhost: 'peter1_vhost', user: 'peter1'): client unexpectedly closed TCP connection =INFO REPORT==== 12-Dec-2017::11:52:44 === connection <0.28103.1813> (10.0.1.44:57714 -> 10.0.1.33:5672): user 'peter1' authenticated and granted access to vhost 'peter1_vhost' =INFO REPORT==== 12-Dec-2017::11:52:44 === accepting AMQP connection <0.28178.1813> (10.0.1.44:57716 -> 10.0.1.33:5672) =INFO REPORT==== 12-Dec-2017::11:52:44 === connection <0.28178.1813> (10.0.1.44:57716 -> 10.0.1.33:5672): user 'peter1' authenticated and granted access to vhost 'peter1_vhost' =INFO REPORT==== 12-Dec-2017::11:52:44 === accepting AMQP connection <0.27644.1813> (10.0.1.44:57718 -> 10.0.1.33:5672) =WARNING REPORT==== 12-Dec-2017::11:52:44 === closing AMQP connection <0.28178.1813> (10.0.1.44:57716 -> 10.0.1.33:5672, vhost: 'peter1_vhost', user: 'peter1'): client unexpectedly closed TCP connection =INFO REPORT==== 12-Dec-2017::11:52:44 === connection <0.27644.1813> (10.0.1.44:57718 -> 10.0.1.33:5672): user 'peter1' authenticated … -
Djnago error no reverse match [duplicate]
This question already has an answer here: NoReverseMatch at /posts/post/18/comment/ Django Error 1 answer I've been getting this error, and I couldn't seem to fix it. Here is a screenshot of it: error image Here my view's.py: from django.shortcuts import render, get_object_or_404, redirect from django.contrib import messages from django.contrib.auth.mixins import LoginRequiredMixin from posts.forms import PostForm, CommentForm from django.core.urlresolvers import reverse_lazy from django.http import Http404 from django.views import generic from braces.views import SelectRelatedMixin from . import forms from . import models from django.contrib.auth import get_user_model User = get_user_model() class PostList(SelectRelatedMixin, generic.ListView): model = models.Post select_related = ("user", "group") class UserPosts(generic.ListView): model = models.Post template_name = "posts/user_post_list.html" def get_queryset(self): try: self.post_user = User.objects.prefetch_related("posts").get( username__iexact=self.kwargs.get("username") ) except User.DoesNotExist: raise Http404 else: return self.post_user.posts.all() def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["post_user"] = self.post_user return context class PostDetail(SelectRelatedMixin, generic.DetailView): model = models.Post select_related = ("user", "group") def get_queryset(self): queryset = super().get_queryset() return queryset.filter( user__username__iexact=self.kwargs.get("username") ) class CreatePost(LoginRequiredMixin, SelectRelatedMixin, generic.CreateView): # form_class = forms.PostForm fields = ('message','group') model = models.Post # def get_form_kwargs(self): # kwargs = super().get_form_kwargs() # kwargs.update({"user": self.request.user}) # return kwargs def form_valid(self, form): self.object = form.save(commit=False) self.object.user = self.request.user self.object.save() return super().form_valid(form) class DeletePost(LoginRequiredMixin, SelectRelatedMixin, generic.DeleteView): model = models.Post select_related = ("user", "group") … -
How to set a variable from one class equals to a variable in another class in Django models.py?
I am a new in Django world and I want to link two classes from models.py so that i can set their variables equal to each other. Here is the models.py code: from django.db import models from django.core.urlresolvers import reverse # Create your models here. class file(models.Model): title = models.CharField(max_length=250) FILE_TYPE_CHOICES = ( ('audio','Audio'), ('games','Games'), ('videos','Videos'), ('applications','Applications'), ('books','Books/Docs'), ('others','Others') ) file_type = models.CharField(max_length=10,choices=FILE_TYPE_CHOICES,default='others') description = models.TextField(max_length=6000) #uploader_username = ??? def get_absolute_url(self): return reverse('one:user') def __str__(self): return self.title class user (models.Model): username= models.CharField(max_length=100) email=models.EmailField password= models.CharField(max_length = 100) user_files = models.ForeignKey(file, on_delete=models.CASCADE) Here I want to set uploader_username from file class equals tousername from user class. -
Django Rest Framework + Python
Hello everyone, I'm beginner in python and Django rest And I stuck when I fetch data. **Here is my API** :- http://127.0.0.1:8000/subjects/course/23/ I want a all subject data according to course which I select..When I hit this api if single data present working awesome but when inside course_id multiple subject present then gives me error such as : Exception Type: MultipleObjectsReturned Exception Value: get() returned more than one Subject -- it returned 2! Thanks in advance -
Is django-imagekit ready for Django 2.0?
Could you tell me whether django-imagekit is ready for Django 2.0? They doesn't seem to have announced that. But they mention "Test against Django 2.0" for their tox.ini. -
Which framework is best for Web Development using Python - Python Flask or Python Django?
Which framework is best for Web Development using Python - Python Flask or Python Django ? And which ever it is, Could you please provide me the best tutorial url.