Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
DjangoREST using DELETE and UPDATE with serializers
So I followed the Quickstart Guide on the DjangoREST framewok site and ended up with the following code: serializers.py: class UserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = User fields = ('url', 'username', 'email', 'groups') class GroupSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Group fields = ('url', 'name') views.py: class UserViewSet(viewsets.ModelViewSet): """ API endpoint that allows users to be viewed or edited. """ queryset = User.objects.all().order_by('-date_joined') serializer_class = UserSerializer class GroupViewSet(viewsets.ModelViewSet): """ API endpoint that allows groups to be viewed or edited. """ queryset = Group.objects.all() serializer_class = GroupSerializer urls.py: router = routers.DefaultRouter() router.register(r'users', views.UserViewSet) router.register(r'groups', views.GroupViewSet) router.register(r'rooms', views.RoomViewSet) router.register(r'devices', views.DeviceViewSet) router.register(r'deviceTypes', views.DeviceTypeViewSet) # Wire up our API using automatic URL routing. # Additionally, we include login URLs for the browsable API. urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^', include(router.urls)), url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')) ] Now this all works fine, but I cant find out how to DELETE or UPDATE a user or a group, seems I can only add users and groups and view them. So my question is: How can I modify this code to make it possible to delete/update users and groups? -
How to customize static_placeholder html code in django cms
I want to customise the HTML for static_placeholder. Html Code: <ul class="top_list"> <li class="spc"><span class="ion-ios-telephone"></span> Call us: {% static_placeholder 'call_us' %}</li> <li class="spc"><span class="ion-android-mail"></span> Mail us: <a href="mailto:{% static_placeholder 'mail_us' %}">{% static_placeholder 'mail_us' %}</a> </li> </ul> <div class="cms-plugin cms-plugin-1"><p>+91-95578XXXXX</p></div> this what cms is rendering as the theme is expecting <span> and cms is rendering <div> layout is distorted . -
assertContains with html special characters
I want to search for a string in a django template response but the string includes html special characters(e.g:'>') Is there anyway to decode this type of strings so that django assertContains works as well? -
Server responds by "text/html" to a "text/css" request
PROBLEM: When I try to access the web page (localhost/mysite/admin), all goes well, except the CSS files which my server can't deliver !! I got a 500 Internal Server Error By investigating the problem, I found that the server returns a text/html instead of text/css Apache 2.4.23 / mod_wsgi 4.5.5 / Python 3.4.2 / Django 1.8 on Linux Debian (64-bit) Additional informations: This is my settings.py file """ Django settings for mysite project. Generated by 'django-admin startproject' using Django 1.8. For more information on this file, see https://docs.djangoproject.com/en/1.8/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.8/ref/settings/ """ # Build paths inside the project like this: os.path.join(BASE_DIR, ...) import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '##################################################' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'polls' ) MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.security.SecurityMiddleware', ) ROOT_URLCONF = 'mysite.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR,'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ … -
Modify read only nested fields in DRF
I realize the title sounds silly but I want to be able to change the references to the Group objects for my User instances. But I do not want them to be able to create new groups or edit existing groups. I think what I want is a read only nested field. However, if I set it to read_only=True I do not get the data in my serializers validated data. If I set it to read_only=False then it tries to create a new Group instead of just changing the references. class GroupSerializer(serializers.ModelSerializer): permissions = PermissionSerializer(many=True) class Meta: model = Group fields = ( 'pk', 'name', 'permissions', ) class UserSerializer(serializers.ModelSerializer): groups = GroupSerializer(many=True) .... class Meta: model = User exclude = ( .... ) def update(self, instance, validated_data): print(validated_data) return instance def validate_groups(self, value): print("validating groups") .... return value With read_only=True nothing happens at all. I get the user back on my PATCH request but the user is exactly the same. With read_only=False I get a validation error returned to me {'groups': [{'name': ['group with this name already exists.']}]} I have also tried overriding the create and update method on the GroupSerializer but with no change. -
Dynamic update instance on Django REST Framework
Hi I'm trying to update dynamically using custom method update Django REST Framework like this: serializers.py class ArtistSerializer(serializers.Serializer): id = serializers.IntegerField(required=False) name = serializers.CharField(max_length=100, required=True) def create(self, validated_data): Personnels.objects.create(**self.validated_data) def update(self, instance, validated_data): # for k,v in self.validated_data.iteritems(): # instance['k'] = self.validated_data.get(k, instance[k]) # instance.name = self.validated_data.get('name', instance.name) instance['name'] = self.validated_data.get('name', instance.name) instance.save() return instance views.py @api_view(['PUT']) def artist_serialization_specific(request, artist_id): if request.method == "PUT": # Example of updating an object via manual serialization # return HttpResponse(artist_id) personnel = Personnels.objects.get(id=artist_id) x = ArtistSerializer(personnel, data={"name":"John Doe"}) if x.is_valid(): x.update(personnel, x.validated_data) else: print x.errors return Response(x.data, status=status.HTTP_200_OK) However I get this error: Internal Server Error: /forms/artists/serialization/3/ Traceback (most recent call last): File "/Users/deanarmada/.virtualenvs/django-cassandra/lib/python2.7/site-packages/django/core/handlers/exception.py", line 39, in inner response = get_response(request) File "/Users/deanarmada/.virtualenvs/django-cassandra/lib/python2.7/site-packages/django/core/handlers/base.py", line 249, in _legacy_get_response response = self._get_response(request) File "/Users/deanarmada/.virtualenvs/django-cassandra/lib/python2.7/site-packages/django/core/handlers/base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "/Users/deanarmada/.virtualenvs/django-cassandra/lib/python2.7/site-packages/django/core/handlers/base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/deanarmada/.virtualenvs/django-cassandra/lib/python2.7/site-packages/django/views/decorators/csrf.py", line 58, in wrapped_view return view_func(*args, **kwargs) File "/Users/deanarmada/.virtualenvs/django-cassandra/lib/python2.7/site-packages/django/views/generic/base.py", line 68, in view return self.dispatch(request, *args, **kwargs) File "/Users/deanarmada/.virtualenvs/django-cassandra/lib/python2.7/site-packages/rest_framework/views.py", line 474, in dispatch response = self.handle_exception(exc) File "/Users/deanarmada/.virtualenvs/django-cassandra/lib/python2.7/site-packages/rest_framework/views.py", line 434, in handle_exception self.raise_uncaught_exception(exc) File "/Users/deanarmada/.virtualenvs/django-cassandra/lib/python2.7/site-packages/rest_framework/views.py", line 471, in dispatch response = handler(request, *args, **kwargs) File "/Users/deanarmada/.virtualenvs/django-cassandra/lib/python2.7/site-packages/rest_framework/decorators.py", line 52, in handler return … -
How to aggregate QuerySet based on property of model?
For example some model: class Foo(models.Model): a = models.FloatField() b = models.FloatField() @property def c(self): return self.a / self.b And we want to find minimal value in QuerySet: bar = Foo.objects.aggregate(Min('c')) But this doesn't work, because c not in database and can't be fetched from db. How to get minimum value c of Foo? -
Python-social-auth with Django - NoneType error upon authenticating user (Facebook)
Hi trying to write a part of an app which allows an authenticated user invite their friends via a unique link to join their social account (at first, facebook only) to an event they have created. Im trying to use python-social-auth to handle the Facebook authentication and token obtaining. I'm using the following view to allow the user to auth but the trouble comes when they auth a second time, and thus trying ti create another user again (this is not usual, but i want to get rid of the error in case the user forgets that they authed, plus i want to understand whats happening as I'm new to Django!) Provide unauthenticated user with a facebook login button def authme(request, uuid): link = get_object_or_404(AuthLink, uuid=uuid) e = link.event # Cycle through social auth providers social_type = link.get_social_type_display() link.authlink = reverse('social:begin', args=[social_type]) + '?next=' + request.path try: social_user = UserSocialAuth.objects.get(user=request.user, provider=social_type) except TypeError: social_user = None if not 'event_id' in request.session or not request.session['event_id'] == e.pk: request.session['event_id'] = e.pk context = { 'event': e, 'link': link } # Make sure user has an attached social account elif not social_user == None: # See if the user already has an account … -
Django when I ran server(manage.py) nothing shows up?
I am working on Django web framework , Its been almost one year. Today I ran into strange problem. when I run my manage.py runserver command on Django and try to see result in browser nothings shows up page is blank. Till yesterday it was fine. I am absolutely blank what to do.I though Due to Java script problem but even 127.0.0.1:8000/admin page is not showing. I tried to change the port number ,used private browsing mode on browser both firefox and chrome still it shows nothing. What is the problme? I tired to google it sstill I couldnot find solution of my problme. Need your help. Thanks -
How would Auth work between Django and Discourse (working together)
I need a modern looking forum solution that is self hosted (to go with a django project) The only reasonable thing I can see using is discourse, but that gives me a problem... How can I take care of auth between the two? It will need to be slightly deeper than just auth because I will need a few User tables in my django site as well. I have been reading about some SSO options, but I am unclear on how to appraoch the problem down the road. here is the process that I have roughly in my head... Let me know if it sounds coherent... Use Discourse auth (since it already has social auth and profiles and a lot of user tables. Make some SSO hook for django so that it will accept the Discourse login Upon account creation of the Discourse User, I will send (from the discourse instance) an API request that will create a user in my django instance with the proper user tables for my django site. Does this sound like a good idea? -
How do I use modules in Django?
I'm trying to display a graph on a webpage. I can get the graph to show up with a simple example that only uses functions defined within the function. However, I want to be able to expand it further. In my original code, I have one main "graphing" function that uses the functions of other modules so that it stays organized. When I try import these modules, which exist as files within the Django app folder, it says there is no module with that name. How do I fix this? Error: File "/Users/andrewho/Desktop/website/charts/views.py", line 48, in import graphing ImportError: No module named 'graphing' I clearly have a file in the app folder called, graphing.py, so why does it give me this error? -
Apache & mod_wsgi settings for Django Python Project
I am trying to setup my django-python project on Google Compute Engine Debian8 VM. I made few config changes in /etc/apache2/sites-available/000-default.conf & /etc/apache2/sites-available/default-ssl.conf files Then tried to restart the server. And I got following Errors. Uninstalling & reinstalling the apache2 too is not fixing this error. Any suggestions to fix this issue ? Command: sudo service apache2 restart Error: Job for apache2.service failed. See 'systemctl status apache2.service' and 'journalctl -xn' for details. Command: sudo systemctl status apache2.service -l Error: Starting LSB: Apache2 web server... Starting web server: apache2 failed! The apache2 configtest failed. ... (warning). Output of config test was: apache2: Syntax error on line 140 of /etc/apache2/apache2.conf: Syntax error on line 1 of /etc/apache2/mods-enabled/wsgi.load: Cannot load /usr/lib/apache2/modules/mod_wsgi.so into server: /usr/lib/apache2/modules/mod_wsgi.so: cannot open shared object file: No such file or directory Action 'configtest' failed. The Apache error log may have more information. apache2.service: control process exited, code=exited status=1 Failed to start LSB: Apache2 web server. Unit apache2.service entered failed state. Thanks, -
How run subprocess in Python 3 on windows for convert video?
I have a little problem, I have trying for a lot time converted a video with FFMPEG in python 3 like this: The model, class Video(models.Model): name = models.CharField(max_length=200, null=False) state = models.CharField(max_length=30, null=False) user_email = models.CharField(max_length=30, null=False) uploadDate = models.DateTimeField(null=False) message = models.CharField(max_length=200, null=False) original_video = models.FileField(upload_to='video', null=True) converted = models.BooleanField(default=False) And the code of converted. video = Video.objects.filter(id=param_id).get() pathConverted = 'C:\\Users\\diego\\Documents\\GitHub\\convertido.mp4' cmd = ['ffmpeg', '-i ', video.original_video.path, ' -b 1500k -vcodec ibx264 -g 30', pathConverted] print('Ejecutando... ', ' '.join(cmd)) try: proc = subprocess.run(cmd, shell=True, check=True) proc.subprocess.wait() except subprocess.CalledProcessError as e: raise RuntimeError("command '{}' return with error (code {}): {}".format(e.cmd, e.returncode, e.output)) The error is this. raise RuntimeError("command '{}' return with error (code {}): {}".format(e.cmd, e.returncode, e.output)) RuntimeError: command '['ffmpeg', '-i ', 'C:\\Users\\diego\\Documents\\GitHub\\video1.avi', ' -b 1500k -vcodec libx264 -g 30', 'C:\\Users\\diego\\Documents\\GitHub\\convertido.mp4']' return with error (code 1): None And also I have tried this: video = Video.objects.filter(id=1).get() pathConverted = 'C:\\Users\\diego\\Documents\\GitHub\\convertido.mp4' cmd = ['ffmpeg', '-i ', video.original_video.path, ' -b 1500k -vcodec libx264 -g 30', pathConverted] print('Ejecutando... ', ' '.join(cmd)) proc = subprocess.Popen(cmd,stdout=subprocess.PIPE,stderr=subprocess.STDOUT) proc.subprocess.wait() In this case the error is: FileNotFoundError: [WinError 2] No such file or directory But when I copy the path and paste this in CMD on windows for … -
Django Abstract User Error in Using Permission
I am making a custom user model using AbstractUser in django.contrib.auth.models. everything was working fine. and when i wanted to make some changes in user_permissions of my SiteUser then django gave error that SiteUser has no attribute named 'user_permissions' then I thought of extending PermissionMixin in django.contrib.auth.models to my SiteUser class to make changes in 'user_permissions' but now It is throwing error like - project.SiteUser.user_permissions: (fields.E304) Reverse accessor for 'SiteUser.user_permissions' clashes with reverse accessor for 'SiteUser.user_permissions'. HINT: Add or change a related_name argument to the definition for 'SiteUser.user_permissions' or 'SiteUser.user_permissions'. project.SiteUser.user_permissions: (fields.E304) Reverse accessor for 'SiteUser.user_permissions' clashes with reverse accessor for 'SiteUser.user_permissions'. HINT: Add or change a related_name argument to the definition for 'SiteUser.user_permissions' or 'SiteUser.user_permissions'. project.SiteUser.user_permissions: (fields.E331) Field specifies a many-to-many relation through model 'project.SiteUser_user_permissions', which has not been installed. P.S. - I have used AUTH_USER_MODEL='project.CustomUser' -
Openshift 3 (DevPreview) Django Postgresql build error
I am trying to setup Django + Postgresql in Openshift 3 (Dev Preview) The following is the database setup in my settings.py file import os DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': os.getenv('POSTGRESQL_DATABASE'), 'USER': os.getenv('POSTGRESQL_USER'), 'PASSWORD': os.getenv('POSTGRESQL_PASSWORD'), 'HOST': os.getenv('POSTGRESQL_SERVICE_HOST'), 'PORT': os.getenv('POSTGRESQL_SERVICE_PORT'), } } I get the following error during code build. I did try displaying the env variables using printenv command and i can see them in the shell. Can anyone point out if something is wrong with my setup ? File "./manage.py", line 10, in <module> execute_from_command_line(sys.argv) <br> File "/opt/app-root/src/.local/lib/python3.5/site-packages/django/core/management/__init__.py", line 354, in execute_from_command_line utility.execute() File "/opt/app-root/src/.local/lib/python3.5/site-packages/django/core/management/__init__.py", line 346, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/opt/app-root/src/.local/lib/python3.5/site-packages/django/core/management/commands/test.py", line 30, in run_from_argv super(Command, self).run_from_argv(argv) File "/opt/app-root/src/.local/lib/python3.5/site-packages/django/core/management/base.py", line 394, in run_from_argv self.execute(*args, **cmd_options) File "/opt/app-root/src/.local/lib/python3.5/site-packages/django/core/management/commands/test.py", line 74, in execute super(Command, self).execute(*args, **options) File "/opt/app-root/src/.local/lib/python3.5/site-packages/django/core/management/base.py", line 445, in execute output = self.handle(*args, **options) File "/opt/app-root/src/.local/lib/python3.5/site-packages/django/core/management/commands/test.py", line 90, in handle failures = test_runner.run_tests(test_labels) File "/opt/app-root/src/.local/lib/python3.5/site-packages/django/test/runner.py", line 210, in run_tests old_config = self.setup_databases() File "/opt/app-root/src/.local/lib/python3.5/site-packages/django/test/runner.py", line 166, in setup_databases **kwargs File "/opt/app-root/src/.local/lib/python3.5/site-packages/django/test/runner.py", line 370, in setup_databases serialize=connection.settings_dict.get("TEST", {}).get("SERIALIZE", True), File "/opt/app-root/src/.local/lib/python3.5/site-packages/django/db/backends/base/creation.py", line 336, in create_test_db test_database_name = self._get_test_db_name() File "/opt/app-root/src/.local/lib/python3.5/site-packages/django/db/backends/base/creation.py", line 434, in _get_test_db_name return TEST_DATABASE_PREFIX + self.connection.settings_dict['NAME'] TypeError: Can't convert 'NoneType' object to str implicitly -
Django Admin: Determine correct image upload path
I am new to Django and I am currently having problems in showing uploaded images in Django Admin. I have followed many posted Q and A here in stackoverflow but of those worked in my problem. I hope any active of the coding ninja here could help me with this problem. Here is the detailed view of the problem: I have defined the MEDIA_ROOT and MEDIA_URL in settings.py BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) MEDIA_URL = os.path.join(BASE_DIR, "media") MEDIA_URL = "/media/ This is my upload model in model.py: from django.utils.html import mark_safe class ImageDetails(models.Model): image = models.ImageField(null=True) def image_img(self): if self.image: return mark_safe('<img src="%s" height="125px" width="125px"/>' % (self.image.url)) else: return '(No image found)' image_img.short_description = 'Thumbnail' In my Application urls.py: urlpatterns = [ url(r'^inputImage', views.inputImage, name='inputImage'), url(r'', views.index), ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) In my admin.py: class ImageDetailsAdmin(admin.ModelAdmin): fields = ["image"] #for file upload list_display = ("image_img",) admin.site.register(ImageDetails, ImageDetailsAdmin) The image was successfully stored at ProjectDIR/media. The HTML returns the url: http://127.0.0.1:8000/media/imagename.jpg at img tag. But the page fails to load the image. I am using Django version 1.10 -
request.session.get('last_visit') yields None all the time
I am recently into session and cookies. I comprehend session and cookies well in theory but i have one issue in understanding the code of session. It is about getting the last_visit by the user. The code is if request.session.get('last_visit'): # The session has a value for the last visit last_visit_time = request.session.get('last_visit') visits = request.session.get('visits', 0) if (datetime.now() - datetime.strptime(last_visit_time[:-7], "%Y-%m-%d %H:%M:%S")).days > 0: request.session['visits'] = visits + 1 request.session['last_visit'] = str(datetime.now()) else: # The get returns None, and the session does not have a value for the last visit. request.session['last_visit'] = str(datetime.now()) request.session['visits'] = 1 When i tried to understand what request.session.get('last_visit') does, i get None all the time. What i don't understand is the key 'last_visit'. Is it default object inside session? If it is default in the session object then why it shows None every time in my terminal. Please someone make me understand the object passed inside get(). -
Django template bootstrap_form Internal Server Error
I have a template that I am trying to use in a jQuery modal popup in django. In the html for my homepage, I have these links in the navbar: <a class="navbar-brand show-modal" href="{% url 'signup' %}" title="Register" data-tooltip> register </a> <a class="navbar-brand show-modal" href="{% url 'login' %}" title="Login" data-tooltip> login </a> In my template routed to url 'signup' I've loaded bootstrap via {% load bootstrap3 %}, and I have this within the form element: <div class="modal-body"> <div id="form-error"></div> {% bootstrap_form singupForm layout='inline' %} </div> But when I click on the signup link, the modal popup comes up with no content and there's an Internal Server Error in the javascript console. I do the same thing in the login template and the modal comes up just fine. Also, if I change the template to use {{ signupForm.as_p }} instead, I get the form in the modal (but no bootstrap styling). How do I debug this error? Or does anyone know what's going on? -
Django Error :"ImportError No module named djangoproject01"
y have a problen using the command "python manage.py makemigrations" it prints me an error "ImportError: No module named djangoproyect01", idon't have any idea what would it be, thanks for the help enter image description here -
Django 1.8 deep reverse relationship lookup
I have three models: class Product(models.Model): idproduct=models.AutoField(primary_key=True) productname=models.CharField(max_length=100, blank=False, null=False) product_state=models.BooleanField(default=True) class ProductInventory(models.Model): idinventory=models.AutoField(primary_key=True) product_idproduct=models.ForeignKey(Product) storage_idstorage=models.ForeignKey(Storage) class Sale(models.Model): idsale=models.AutoField(primary_key=True) sale_date = models.DateTimeField(default=timezone.now) inventory_idinventory=models.ForeignKey(ProductInventory) What I want to do is to get all the products that has been sold in this month, I have tried this: thisdate=datetime.today() products=Product.objects.filter(product_state=1,productinventory__sale__sale_date__month=thisdate.month).values('pk','productname','productinventory__sale__sale_date') But first, it gives me "nested lookup is not supported" so I taked off the month filter, but after that it gives me a FieldError: Cannot resolve keyword 'sale' into field How can I do this? -
Django FilePathField Best Practice
I've looked over the questions in SO and none can explain the proper usage of Django's FilePathField. The Django documentation about it is a little short. A web search does not yield good tutorials about it as well. To add do non uploaded files must be collected to the static directory,reside inside apps where they are used, or at the project level? -
Django Queryset filter between two decimal fields stored in a database table
I don't know if this can be done using querysets, but I have the next models: class TipoCliente(models.Model): idtipo_cliente = models.AutoField(db_column='idTipo_cliente', primary_key=True) # Field name made lowercase. nombre_tipocliente = models.CharField(db_column='nombre_tipoCliente', max_length=45, blank=True, null=True) # Field name made lowercase. estado_tipocliente = models.BooleanField(db_column='estado_tipoCliente', default=True) # Field name made lowercase. comprasminimas_cliente=models.DecimalField(max_digits=12, decimal_places=2, blank=True, null=True) class Cliente(models.Model): idcliente = models.AutoField(db_column='idCliente', primary_key=True) # Field name made lowercase. persona_idpersona = models.ForeignKey('Persona', db_column='Persona_idPersona') # Field name made lowercase. nit_cliente = models.CharField(max_length=13, blank=True, null=True) tipo_cliente_idtipo_cliente = models.ForeignKey('TipoCliente', db_column='Tipo_cliente_idTipo_cliente') # Field name made lowercase. estado_cliente = models.BooleanField(default=True) class Venta(models.Model): idventa = models.AutoField(db_column='idVenta', primary_key=True) # Field name made lowercase. cliente_idcliente = models.ForeignKey(Cliente, db_column='Cliente_idCliente') # Field name made lowercase. fecha_venta = models.DateTimeField(default=timezone.now) total_venta = models.DecimalField(max_digits=12, decimal_places=2, blank=True, null=True) estado_venta = models.BooleanField(default=True) es_cotizacion = models.BooleanField(default=False) fecha_registro_cliente = models.DateField(default=timezone.now) TipoCliente (client type if we translate it) has an attribute comprasminimas_cliente which stores a minimum sales amount for clients clasification, so, suppose the clasifications are: [nombre_tipocliente] = [comprasminimas_cliente] Client A = 3000.00 Client B = 6000.00 Client C = 10000.00 What I want to do is to suggest a new clasification acording to a SUM of total_venta (sale total), so, if aggregate(total_ventas=SUM('venta__total_venta')) is equal to 7000 I want to show Client B, if it … -
Django Generic Views :How does DetailView automatically provides the variable to the template ??
In the following code, How does the template details.html knows that album is passed to it by views.py although we have never returned or defined any context_object_name in DetailsView class in views.py. Please explain how are the various things getting connected here. details.html {% extends 'music/base.html' %} {% block title %}AlbumDetails{% endblock %} {% block body %} <img src="{{ album.album_logo }}" style="width: 250px;"> <h1>{{ album.album_title }}</h1> <h3>{{ album.artist }}</h3> {% for song in album.song_set.all %} {{ song.song_title }} {% if song.is_favourite %} <img src="http://i.imgur.com/b9b13Rd.png" /> {% endif %} <br> {% endfor %} {% endblock %} views.py from django.views import generic from .models import Album class IndexView(generic.ListView): template_name = 'music/index.html' context_object_name = 'album_list' def get_queryset(self): return Album.objects.all() class DetailsView(generic.DetailView): model = Album template_name = 'music/details.html' urls.py from django.conf.urls import url from . import views app_name = 'music' urlpatterns = [ # /music/ url(r'^$', views.IndexView.as_view(), name='index'), # /music/album_id/ url(r'^(?P<pk>[0-9]+)/$', views.DetailsView.as_view(), name='details'), ] Thanks in advance !! -
Is it possible to use Django models module only in my project?
I am developing a small independent python application which uses Celery. I have built this using django framework but my application is back end only. This means that the users do not need to visit my site and my application is built only for the purpose of receiving tasks queue from celery and performing operations on the database. In order to perform operations on the database, I need to use Django modules. What I am trying to do is eliminate the rest of my django application and use ONLY celery and django models modules (including the dependencies required to run these). In short, my simple celery application will be running receiving instructions from my redis broker and perform operations in database using django models. Is is possible to do this? If so, how? Here is my project structure: myproject/ --manage.py --myproject/ ----celery.py ----models.py ----settings.py ----tasks.py ----urls.py ----wsgi.py Here is my settings.py: -
ImportError : cannot import name timezone pythonanywhere
sorry if I do not format this correctly I am attempting to collectstatic in the bash console to get my CSS running on a django app on pythonanywhere and it gives me the following. 23:49 ~/mysite/mysite $ python manage.py collectstatic Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 429, in execute_from_command_line utility.execute() File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 379, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 191, in run_from_argv self.execute(*args, **options.__dict__) File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 219, in execute self.validate() File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 249, in validate num_errors = get_validation_errors(s, app) File "/usr/local/lib/python2.7/dist-packages/django/core/management/validation.py", line 35, in get_validation_errors for (app_name, error) in get_app_errors().items(): File "/usr/local/lib/python2.7/dist-packages/django/db/models/loading.py", line 146, in get_app_errors self._populate() File "/usr/local/lib/python2.7/dist-packages/django/db/models/loading.py", line 64, in _populate self.load_app(app_name) File "/usr/local/lib/python2.7/dist-packages/django/db/models/loading.py", line 78, in load_app models = import_module('.models', app_name) File "/usr/local/lib/python2.7/dist-packages/django/utils/importlib.py", line 35, in import_module __import__(name) File "/home/nikk2009/mysite/mysite/polls/models.py", line 4, in <module> from django.utils import timezone ImportError: cannot import name timezone 23:49 ~/mysite/mysite $ Here is the .py where timezone is imported import datetime from django.db import models from django.utils import timezone # Create your models here. class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') def __str__(self): return self.question_text def was_published_recently(self): now = timezone.now() return self.pub_date >= timezone.now() - datetime.timedelta(days=1)<= now was_published_recently.admin_order_field …