Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Use HTTP session in Django Channels
I have the following problem. I have an django web application and i need to upload csv files and then stream them using django-channels. I decided to save the path of the uploaded csv file in the http session. From django-channels documentation I understood that i can access http session object inside a websocket, but using the following code returns an object which does not have the file path added earlier. @http_session def ws_connect(message): print("Connected on data websocket") print(message.http_session.__dict__) Group("data").add(message.reply_channel) Result of printing the http session is: {'modified': False, 'accessed': False, '_SessionBase__session_key': '92zcls0hxqlk1352xwja6tvytjebjfw7', 'serializer': <class 'django.core.signing.JSONSerializer'>} My question is, can I really access the HTTP session in websockets? Or should i consider another way of doing this? -
Django: can't override get_FOO_display()
I have a field called status. I want to pluralize status, so I write def get_status_display(self): return dict(STATUS_CHOICES).get(self.status) + 's' In template I write {{ object.get_status_display }} But this function is not invoked. What am I doing wrong? -
How do simple connect thousand differents schemas connections using postgresql, django and pgbouncer
I need a simple way to connect 10000 customers using the same app but connection string differents. schema changes only. Using postgresql + django Database customer schemas : c1, c2, c3, c4 ... c10000 How do django to change schema dynamically in settings ? I will get the schema name in other connection with other database. -
How to implement "email_user" method in custom user model?
Trying to use django-registration module with custom user model that extends AbstractBaseUser. This is a form, I use for the registration: from django.contrib.auth import get_user_model from registration.forms import RegistrationForm class UserCreateForm(RegistrationForm): class Meta: fields = ("username", "email", "password1", "password2") model = get_user_model() This is the view: class Register(RegistrationView): form_class = forms.UserCreateForm This is my registration url: url(r'^accounts/register/$', views.Register.as_view(), name='registration_register'), Django successfully sends confirmation email, but browser throws an error 'User' object has no attribute 'email_user' Edit: I understand I have to implement email_user method in my custom user model. How can I do this? -
How to use django-taggit from view file
I want the user to be able to tag his post. So, he would enter words in the text field, and separate them with ",". When he is done, he presses save and all the tags he entered will be saved to that post. I am using django-taggit, but when the user enters his words in the field they do not get saved with the post. But when I do that from the django-admin site it works perfect. Here is my code: models.py: class Post(models.Model): STATUS_CHOICES = ( ('draft', 'Draft'), ('published', 'Published'), ) title = models.CharField(max_length=250) slug = models.SlugField(max_length=250, unique_for_date='publish') author = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='blog_posts') body = RichTextUploadingField() publish = models.DateTimeField(default=timezone.now) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='draft') objects = models.Manager() # The default manager published = PublishedManager() # Our custom manager tags = TaggableManager() category = models.ForeignKey(BlogCategory, related_name='post_category') header_photo = models.ImageField(upload_to = 'users/%Y/%m/%d', null = True, blank = True, width_field="width_field", height_field="height_field" ) width_field = models.IntegerField(default = 0, null = True) height_field = models.IntegerField(default=0, null = True) forms.py: class CreatePostForm(forms.ModelForm): class Meta: model = Post fields = ('title', 'status', 'header_photo', 'body', 'tags') views.py: @login_required(login_url='account_login') def create_post(request): if request.method == 'POST': post_form = CreatePostForm(data=request.POST, files=request.FILES) if post_form.is_valid(): new_post … -
How to call process_template_response in Django 1.10+ middleware
This new style middleware is driving me to distraction. I want to do some things before the view and then alter the context when the template is rendered (depending on the pre-run results). Before this was simple. An object with process_view and process_template_response methods. Here's my new simple 1.10-compliant middleware: import re class ControlMiddleware(object): ''' Middleware to stuff variables into request and context ''' RE_CONTROL = re.compile(r'^/control/') def __init__(self, get_response): self.get_response = get_response def __call__(self, request): request.is_control = self.RE_CONTROL.match(request.path) if request.is_control: print('CONTROL MIDDLEWARE') return self.get_response(request) def process_template_response(self, request, response): print('CONTROL process_template_response') if request.is_control: print('CONTROL process_template_response') response.context_data.update({ 'is_manager': True, }) return response __call__ is being called and the request variable is set, but process_template_response isn't called. What am I doing wrong? How do I get process_template_response to run? -
how to do calculation inside for loop in django template
I have to do some calculation in django template inside for loop, but it it is not parsing python code inside for loop and giving error {% for ticket in tickets_in_cart %} <div class="davis-date-time"> <h3>{{ ticket.performance_id__event_start_date|date:"M d" }}</h3> <p>{{ ticket.performance_id__timing }}</p> </div> <div class="davis-date-time"> <h3>{{ ticket.performance_id__city }}</h3> <p>{{ ticket.performance_id__venue }}</p> </div> {% singleAmount = ticket.tickets_count*ticket.tickets_amount %} {% finalAmount += singleAmount %} {% endfor %} I have to do this because i need to print this finalAmount variable value outside of the for loop. -
Append object to a cached django queryset
Suppose that we have a queryset and we cache it. Then a new object is created. Is there a way to get the cached queryset and append the new object (or another queryset) to it? (For example deserialize the queryset, append the object, serialize the new queryset and cache it. Or maybe work directly to the serialized objects) I'm thinking that this way you can avoid the process of querying again the database to create and cache a whole new queryset while in reality only one (or a few) objects should be appended to it. Is there a point in this thought? -
Converting DateTimeField in Django to Unix time
In a Django project of mine, I'm using DateTimeField in a model. This essentially has python datetime.datetime instances. What's the fastest way convert this to time since epoch (in seconds)? -
I want to use existing mssql database.i use inspectdb command but it's not working
DATABASES = { 'default': { 'NAME': 'xxxx', 'ENGINE': 'sqlserver_ado', 'HOST': '102.35.140.54\SQLEXPRESS', 'USER': 'xxxx', 'PASSWORD': 'xxxxx', 'PORT' : '1434', 'OPTIONS': { 'provider': 'SQLNCLI11', } } } This is my database configuration i fired 'python manage.py inspectdb' and get error. D:\Python_Workspace\oracle>python manage.py migrate Traceback (most recent call last): File "manage.py", line 22, in execute_from_command_line(sys.argv) File "C:\Python35\lib\site-packages\django\core\management__init__.py", line 367, in execute_from_command_line utility.execute() File "C:\Python35\lib\site-packages\django\core\management__init__.py", line 359, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Python35\lib\site-packages\django\core\management\base.py", line 294, in run_from_argv self.execute(*args, **cmd_options) File "C:\Python35\lib\site-packages\django\core\management\base.py", line 345, in execute output = self.handle(*args, **options) File "C:\Python35\lib\site-packages\django\core\management\commands\migrate.py", line 83, in handle executor = MigrationExecutor(connection, self.migration_progress_callback) File "C:\Python35\lib\site-packages\django\db\migrations\executor.py", line 20, in init self.loader = MigrationLoader(self.connection) File "C:\Python35\lib\site-packages\django\db\migrations\loader.py", line 52, in init self.build_graph() File "C:\Python35\lib\site-packages\django\db\migrations\loader.py", line 203, in build_graph self.applied_migrations = recorder.applied_migrations() File "C:\Python35\lib\site-packages\django\db\migrations\recorder.py", line 65, in applied_migrations self.ensure_schema() File "C:\Python35\lib\site-packages\django\db\migrations\recorder.py", line 52, in ensure_schema if self.Migration._meta.db_table in self.connection.introspection.table_names(self.connection.cursor()): File "C:\Python35\lib\site-packages\django\db\backends\base\base.py", line 231, in cursor cursor = self.make_debug_cursor(self._cursor()) File "C:\Python35\lib\site-packages\django\db\backends\base\base.py", line 204, in _cursor self.ensure_connection() File "C:\Python35\lib\site-packages\django\db\backends\base\base.py", line 199, in ensure_connection self.connect() File "C:\Python35\lib\site-packages\django\db\backends\base\base.py", line 170, in connect conn_params = self.get_connection_params() File "C:\Python35\lib\site-packages\sqlserver_ado\base.py", line 225, in get_connection_params 'connection_string': make_connection_string(settings_dict), File "C:\Python35\lib\site-packages\sqlserver_ado\base.py", line 56, in make_connection_string raise ImproperlyConfigured("When using DATABASE PORT, DATABASE HOST must be an IP address.") django.core.exceptions.ImproperlyConfigured: When using DATABASE PORT, DATABASE … -
Django directory upload get sub-directory names
I am writing a django app to upload a directory of files with forms. This is the form I am using which allows upload of directory: class FileFieldForm(forms.Form): file_field = forms.FileField(widget=forms.ClearableFileInput(attrs= {'multiple': True, 'webkitdirectory': True, 'directory': True})) This is the raw post payload: ------WebKitFormBoundaryPbO3HkrKGbBwgD3sd1 Content-Disposition: form-data; name="csrfmiddlewaretoken" F575Bgl4U9dzgwePPeSW2ISZKk5c3CnRoqFasdasD0Hep6nD0LnAAObXbF92SUa96NbO2 ------WebKitFormBoundaryPbO3HkrKGbBwgDsd31 Content-Disposition: form-data; name="file_field"; filename="MainDir/SubDir1/1.jpg" Content-Type: image/jpeg ------WebKitFormBoundaryPbOasd3HkrKGbBwgD31 Content-Disposition: form-data; name="file_field"; filename="MainDir/SubDir2/2.jpg" Content-Type: image/jpeg This is the view to handle form: class FileFieldView(FormView): form_class = FileFieldForm template_name = 'upload.html' success_url = 'upload' def post(self, request, *args, **kwargs): form_class = self.get_form_class() form = self.get_form(form_class) files = request.FILES.getlist('file_field') if form.is_valid(): for f in files: pprint("Name of file is " + f._get_name() + ' ' + f.field_name, sys.stderr) new_file = FileModel(file=f) new_file.save() return self.form_valid(form) else: return self.form_invalid(form) Problem is that name of file object in django is without sub-directory names. I am assuming one of the middleware handling request is parsing and removing subdirectory names from filename. Is there way I can get the original filename that has directory and sub-directory names? -
How to make a query using a database function with Django ORM?
I want to query the database using a WHERE clause like this in Django ORM: WHERE LOWER(col_name) = %s or WHERE LOWER(col_name) = LOWER(%s) How can I do this using QuerySet API? -
DRF PUT request on unique model field
I have the following model: class Movie(models.Model): name = models.CharField(max_length=800, unique=True) imdb_rating = models.IntegerField(null=True) movie_choice = ( ('Act', 'Action'), ........... ) movie_type = models.CharField(max_length=3, choices=movie_choice) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Hiren(models.Model): movie = models.ForeignKey(Movie) watched_full = models.BooleanField(default=True) rating = models.IntegerField() source = models.CharField(max_length=500, null=True) watched_at = models.DateField() quality_choice = ( .................. ) video_quality = models.CharField(max_length=3, choices=quality_choice) created_at = models.DateField(auto_now_add=True) updated_at = models.DateField(auto_now=True) and serializer: class MovieSerializer(serializers.ModelSerializer): class Meta: model = Movie fields = '__all__' class HirenSerializer(serializers.ModelSerializer): movie = MovieSerializer() class Meta: model = Hiren fields = ('movie', 'id', 'watched_full', 'rating', 'source', 'video_quality', 'watched_at') def update(self, instance, validated_data): instance.movie.name = validated_data.get('movie', {}).get('name') instance.movie.imdb_rating = validated_data.get('movie', {}).get('imdb_rating') instance.movie.movie_type = validated_data.get('movie', {}).get('movie_type') instance.watched_full = validated_data.get('watched_full', instance.watched_full) instance.rating = validated_data.get('rating', instance.rating) instance.source = validated_data.get('source', instance.source) instance.video_quality = validated_data.get('video_quality', instance.video_quality) instance.watched_at = validated_data.get('watched_at', instance.watched_at) instance.movie.save() instance.save() return instance When I try to send a put request without changing name field from Movie model it throws an error { "movie": { "name": [ "movie with this name already exists." ] } } However, I can perfectly update any other field if I change the name field's value each time. -
Query for enum value in GraphQL
Suppose I have a model like this class Order(models.Model): STATES = [ (1, 'Initiate'), (2, "Brief"), (3, "Planning"), (4, "Price Negotiate"), (5, "Executing"), (6, "Pending"), (7, "Completed"), (8, "Canceled"), (9, "Failed"), (10, "Paid"), ] state = models.PositiveSmallIntegerField( choices=STATES, default=1 ) When I pair this model with its Graphene object type companion class OrderNode(graphene_django.DjangoObjectType): class Meta: model = Order interfaces = (relay.Node,) An enum type with name OrderState! is created. I am concerned with How can I query for the enums How can I manage enums in React with Apollo client For the first question, I have this query { customer(id: "Q3VzdG9tZXJOb2RlOjE=") { name orders { edges { node { state } } } } } It gives me a weird state value like A_1 and A_2. I was expecting it to give me some meaningful value like "Initiate". How can I get the value of the kv pair enum? For the second question, if I want to present to user a list of possible value for this enum, how can I do so? -
python 3.5 - django 1.10 - mysqlclient windows 7 installation error
I have very disturbing me problem with configuring mysql in django. I did it with python 3.5 and django 1.10 on ubuntu x64 but I can't do this on windows 7. I tried almost everything, I hope almost: installed python 3.5 installed pip for python upgrade everything what I can upgrade installed django installed visual studio 2015 for python 3.5 installed mysql server and workbench installed all connectors for mysql C, python, odbc installed vs C++ redistutable 2013 installed mingw download mysqlclient 1.3.9 trying to edit some files with information from stack more more stress and do things what I could do So I had a lot of errors what I could pass and now I have one error (hope last) that I can't do anything with it. when I use command: python setup.py install in folder with mysqlclient 1.3.9 I got error: C:\Program Files (x86)\MySQL\MySQL Connector C 6.1\include_mingw.h(49): fatal error C1189: #error: ERROR: You must use a GNU Compiler. I thought that it is problem with compiler from Visual Studio, so I try to use mingw as default gcc, it helped but with another error: ValueError: Unknown MS Compiler version 1900 I can't help myself with it and I … -
How to add Template to Django Oscar e-commerce framework
Im start using oscar e-commerce framework for django. I setup sandbox, the backend part works prefectly out of the box. Now i want to change the default theme to a bootstrap template that i found. Is there is any simple way to do such things on oscar? -
Creating a for loop with results based on another table
I have two lists of objects, buildnumbers and partrequestnumbers. Both list contain buildnumbers, and what I am trying to achieve is a html list of the buildnumbers with their associated parturequestnumbers, the link being the buildnumber. So far I have had a look at numpy arrays and a few for loop suggestions without achieving what I am trying to achieve. My current for loop just loops through all of the numbers... Django Views: def manufacturelist(request, mug=None, slug=None): if not request.user.is_staff or not request.user.is_superuser: raise Http404 partrequests = PartRequestNumbers.objects.order_by('-id')[:10] latest_preparebuild_list = PrepareBuild.objects.order_by('-pub_date')[:10] buildpr = zip(latest_preparebuild_list, partrequests) print buildpr buildpr.sort() prsorted = [partrequests for build, pr in buildpr] print prsorted context = { "latest_preparebuild_list": latest_preparebuild_list, "partrequests": partrequests, } return render(request, "buildpage/manufacturelist.html", context) HTML: {% if latest_preparebuild_list %} <ul> {% for preparebuild in latest_preparebuild_list %} <li><a class = "subtitle" >{{ preparebuild.buildno }}: </a><a style= "float: right" href="/buildpage/{{ preparebuild.part_request }}/manufacturebuild">{{ partrequests.part_request }}</a><p style= "float: right">{{ preparebuild.build_status }}</p></li> {% for partrequest in partrequests %} <center><a href="/buildpage/{{ partrequest.part_request }}/manufacturebuild">{{ partrequest.part_request }}&nbsp;&nbsp;</a></center> {% endfor %} {% endfor %} </ul> {% else %} <p>No builds are available.</p> {% endif %} -
how to check logged in user in context processors file in django
I am using context processors for showing total products in cart and other details in my project's header and footer. This is my file for context processors file "custom_context.py" from models import Event, Ticket_Cart_details def get_base_content(request): music_events = Event.objects.all().filter(category='music', status = True).values('id','event_title').order_by('-id')[:4] sports_events = Event.objects.all().filter(category='sports', status = True).values('id','event_title').order_by('-id')[:4] experience_events = Event.objects.all().filter(category='experience', status = True).values('id','event_title').order_by('-id')[:4] lifestyle_events = Event.objects.all().filter(category='lifestyle', status = True).values('id','event_title').order_by('-id')[:4] The above code does not contain any information about logged in user now i have to write a code in which i have to get data of logged in user. from models import Event, Ticket_Cart_details def get_base_content(request): music_events = Event.objects.all().filter(category='music', status = True).values('id','event_title').order_by('-id')[:4] sports_events = Event.objects.all().filter(category='sports', status = True).values('id','event_title').order_by('-id')[:4] experience_events = Event.objects.all().filter(category='experience', status = True).values('id','event_title').order_by('-id')[:4] lifestyle_events = Event.objects.all().filter(category='lifestyle', status = True).values('id','event_title').order_by('-id')[:4] if request.user.is_authenticated(): current_cart_products = Ticket_Cart_details.objects.all().filter(user_id=request.user.id, session_id=request.session.session_key) current_cart_products = Ticket_Cart_details.objects.all().filter(session_id=request.session.session_key) In the above code "request" will not work, so how can i get records of logged in user using this -
Django Generic Relation with proxy models not working
I am trying to filter the result of WebsiteEdit model based on review_status in admin. Here are the models: class SubmitLog(TimeStampedModel): QUEUED = 0 CANCELLED = 1 FINISHED = 2 content_type = models.ForeignKey( ContentType, limit_choices_to={"model__in": CONTENT_TYPE_OPTIONS}, related_name='submit_log_content_type') object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') review_status = models.PositiveSmallIntegerField( choices=SUBMIT_STATUS_OPTIONS, default=QUEUED, verbose_name="status") class Meta: unique_together = ('content_type', 'object_id',) def __unicode__(self): return unicode(self.id) class Website(models.Model): website = models.ForeignKey( 'websites.WebsiteIndex', related_name='website', null=True, blank=True) site_url = SiteURLField() slug = models.CharField(max_length=200) is_edit = models.BooleanField(default=False) review_log = GenericRelation( SubmitLog, related_query_name='website') class WebsiteEdit(Website): review_log = GenericRelation( SubmitLog, related_query_name='website_edit', for_concrete_model=False) class Meta: proxy = True Admin Filter: class SubmitStatusFilter(admin.SimpleListFilter): title = _('Status') # Parameter for the filter that will be used in the URL query. parameter_name = 'status' def lookups(self, request, model_admin): return SubmitReviewLog.SUBMISSION_STATUS_OPTIONS def queryset(self, request, queryset): if self.value() is not None: qs = queryset.filter(review_log__review_status=self.value()) return qs This filter is working for concrete model in admin but not working for proxy model. for_concrete_model=False is also set in proxy model. How to filter results for proxy model ? -
Python Function with arbitrary parenthesis (and arguments)
I want something like this def Print(Something): print all in Something Print("This") Print("This")("Also")("This") output should be : This This Also This No matter how many parenthesis or arguments are there it should show all the arguments. -
How to extend the time scale of django connection.queries output?
Currently I have this output: from django.db import connection print connection.queries Output: [{'time': '0.000', ... I wanted to output to be like: [{'time': '0.000000', ... Is it possible. If yes how? If not why not? Most of my SQL Queries get executed in 0.000 time frame. Basically I want to implement this feature so that when I set up my DEBUG True in settings.py and make necessary changes I want to be able to see the SQL Execution times of small time fraction also in my log. -
django oscar wrong order while loading models of forked apps
I have a strange problem where one of the forked apps model is loaded after the one from oscar insted other forked apps are loaded in the correct order; this is causing a RuntimeError because our app tries to register a model that is already registered. I have checked the get_core_apps() return value and the oscar model is overridden by our custom UserAddress model. does AbrstractUserAdders require some additional work or different procedure? for all our cusom models we have followed this guide but only the custom UserAddress has problems at load time. -
How can we get a model instance not by model pk in DRF
I would like to get a model instance from my record in django-rest-framework (DRF) api. On default we can get an instance of model by a particular pk /api/animal/1/ But how can we get an instance with another model property supposed the animal model may have a herd_id property? I am using this viewset to handle the crud. class AnimalViewSet(viewsets.ModelViewSet): """ This viewset automatically provides `list`, `create`, `retrieve`, `update` and `destroy` actions. """ queryset = Animal.objects.all() serializer_class = AnimalSerializer -
Loading script files when creating a pyinstaller exe of a Django application
I am trying to package a django application which also contains script files(angularJS). When I create an exe , its not able to load the static files(404 error). I tried python manage.py collectstatic and its copying the files from the correct location. But when I run the exe, its not able to load the files. My settings.py file BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) STATIC_URL = '/res/' STATIC_ROOT = os.path.join(BASE_DIR, "res") STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'Rule/res'), ) My spec file: added_files = [ ('Rule\\templates\\*.html','Rule\\templates'), ('Rule\\migrations','Rule\\migrations'), ('Rule\\res\\scripts\\*.js','Rule\\res\\scripts'), ] Its able to load the templates, but not the script files. I am loading the script files in my html file like this: {% block js %} <script src='{% static "scripts/app.js" %}' ></script> <script src='{% static "scripts/angular.js" %}'></script> <script src='{% static "scripts/angular-ui-router.js" %}'></script> <script src='{% static "scripts/angular-route.min.js" %}'></script> <script src="{% static "scripts/ui-grid.min.js" %}"></script> {% endblock %} Please help me if I am missing something.Thanks -
How to sort a dictionary in django?
i'm a rookie in programming and i ran into a problem in django. So i'm trying to sort a dictionary based on the value. I've tryed several methods seen here, but thing is nothing works for me. It worked to make the dictionary but i don't know why it's not sorting. So 'scoruri' is the dictionary: when using it in html it's showing like this {User: alex_py: 6, User: ion: 3, User: lil: 1, User: sss: 1, User: ddd: 1, User: bbb: 7}, 'result' is the score for each 'user'(key). When i'm printing the type of scoruri it prints 6 times (type 'dict') It may be possible that each key:value in scoruri to be actually a dictionary so i'm having a dictionary of dictionaries? Below are the methods i've tryed to sort. views.py def home(request): data = dict() data['users'] = User.objects.all() data['scoruri'] = dict() if request.method == "POST": for key in request.POST: if 'nota_' in key: nota_acordata = Punctaj.objects.filter(acordat_de=request.user, acordat_catre__id=key.split('_')[1]).first() if nota_acordata: nota_acordata.nota = request.POST.get(key) nota_acordata.save() else: Punctaj.objects.create(acordat_de=request.user, acordat_catre_id=key.split('_')[1], nota=request.POST.get(key)) messages.success(request, "Successfully Voted") return redirect('home') for user in data['users']: suma = Punctaj.objects.filter(acordat_catre=user).aggregate(punctaj=Sum('nota')).get("punctaj") count = Punctaj.objects.filter(acordat_catre=user).count() if not suma: result = 0 else: result = int(suma)/count data['scoruri'][user] = result # sorted(data['scoruri'].items()) …