Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Tablename with ID "Some_ID" doesn't exist. Perhaps it was deleted? Django Sqlite
I have database with many tables; three of those which are interlinked via primary and foreign keys are "Vendor_Details" , "Channel_Details" and "MSO_Details" models.py class Vendor_Details(models.Model): class Meta: verbose_name_plural = "Vendor_Details" vendor_name = models.CharField(primary_key = True,max_length=50) mso_id = models.CharField(unique = True, max_length=20) class Channel_Details(models.Model): class Meta: verbose_name_plural = "Channel_Details" channel_id = models.CharField(primary_key = True, max_length=20) vendor_name = models.ForeignKey(Vendor_Details, on_delete=models.CASCADE) channel_logo = models.CharField(max_length=50) channel_name = models.CharField(max_length=50) class MSO_Details(models.Model): class Meta: verbose_name_plural = "MSO_Details" mso_id = models.ForeignKey(Vendor_Details, on_delete=models.CASCADE) channel_id = models.ForeignKey(Channel_Details, on_delete=models.CASCADE) channel_number = models.PositiveIntegerField() So, Channel_Details is linked to Vendor_Details with vendor_name and MSO_Details is linked with Vendor_Details and Channel_Details with mso_id and channel_id respectively. Now, I am inside Django's Administrator's MSO_Details table and trying to click on edit icon of CHANNEL ID column i get a new window opens with message Channel_ details with ID "CH6" doesn't exist. Perhaps it was deleted? May be this is because channel_id is primary key of reference table and DB will not allow the changes? But then the message should had been something different. How can i handle this situation? I clicked on edit for CH_006 and message shows CH6. I am confused whats going on here, what is django's DB refering to here? … -
Django OneToOneField initialization
I'm building a django-based application that receives some information from client-computers (e.g. memory) and saves it into the database. For that I created the following model: class Machine(models.Model): uuid = models.UUIDField('UUID', primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField('Name', max_length=256) memory = models.OneToOneField('Memory', on_delete=models.CASCADE, null=True) def save_data(self, data): if not self.memory: memory = Memory() memory.save() self.memory = memory self.save() self.memory.total = data['memory_total'] self.memory.used = data['memory_used'] self.memory.cached = data['memory_total'] self.memory.save() Now for the Memory, I have the following model: class Memory(models.Model): total = models.IntegerField(default=0) used = models.IntegerField(default=0) cached = models.IntegerField(default=0) To save data to the machine-model when I receive it from the client, I call the save_data()-method. There I test if there is already a self.memory object, and if not I create it first before adding the data. Now, even tho it's working as intended I was wondering if there was a better, more clean way to achieve this. Would it be possible to initialize all my OneToOne-Fields to an empty instance of the referenced type so I needn't do the if not every time? -
creating Django models one to one 'ish' relation to (read-only) legacy table
I'm working with default postgres database and a legacy database (MSSQL) which is read only (ro to me, data does change). Understanding that there will be no keys or RI, is it possible to create a one-to-one 'like' relationship between a table in the read only legacy database and the default django database? The MSSQL database has unmanaged models in the django project - Basically I want to reference objects in these models from regular models in django applications (with underlying django-managed tables). Any suggestions on how to accomplish this or something with the same utility? Thanks in advance! -
Django: defining a model to make a template
I am new to creating models in Django and I want to make a model, which allows you to fill in the title, some texts for on the template and the path to this template. I am trying to get the answer off of the Django Example Project, but I just don't understand the models, is there anybody who can help me on how to write such a model? My code in the models.py class Project(models.Model): project_name = models.Charfield(max_length=20) project_title = models.Charfield(max_length=100) project_information = models.Charfield(max_length=400) where project_name is the link to the template I don't know if this is a correct begin or that it should be something completely different. -
How to throw ValidationError for DjangoAdmin when it's a ModelAdmin w/change_view
I have a model class Group(models.Model): active = models.BooleanField(null=False, blank=False, default=True) and its admin page class GroupAdmin(admin.ModelAdmin): change_form_template = "admin/group/group.html" def change_view(self, request, object_id, form_url='', extra_context=None): extra_context = extra_context or {} extra_context['group_data'] = self.get_info(object_id) return super(GroupAdmin, self).change_view( request, object_id, form_url, extra_context=extra_context, ) which requires the change_view template. Notably, this is not an AdminForm, because of the change_view template. How do I throw a validation error when active is False, and have it show up on Django admin? When I throw it on Group.save() on the Model, it breaks the page, instead of not-saving and telling the user to fix the error. Is there a way to do this using ValidationError? Is it by somehow integrating an AdminForm? This question is similar but recommends Messages, but I'd like to know if there's another way: Raise django admin validation error from a custom view -
Paypal sent warning emails for IPN
I have integrated Paypal in my Django(1.10) app using Django-paypal package. Everything works fine even payments processing perfectly well and I'm receiving IPNs from PayPal in Django admin. But PayPal send this email to me as: Hello XXXXXXXXXX, Please check your server that handles PayPal Instant Payment Notifications (IPN). IPNs sent to the following URL(s) are failing: https://XXXXXXXXXX/paypal/ipn/ If you do not recognize this URL, you may be using a service provider that is using IPN on your behalf. Please contact your service provider with the above information. If this problem continues, IPNs may be disabled for your account. Thank you for your prompt attention to this issue. Thanks, PayPal ---------------------------------------------------------------- PROTECT YOUR PASSWORD NEVER give your password to anyone, including PayPal employees. Protect yourself against fraudulent websites by opening a new web browser (e.g. Internet Explorer or Firefox) and typing in the PayPal URL every time you log in to your account. Please do not reply to this email. We are unable to respond to inquiries sent to this address. For immediate answers to your questions, visit our Help Centre by clicking "Help" located on any PayPal page or email. PayPal is committed to your privacy, learn more about … -
Creating TestCaseMixin for Django, is that a safe method?
I want to speed up my Class Based Views tests. I wrote this small test-mixin. It seems to work pretty well and is actually doing all i need. Question to more experienced players here. Is that a method safe, without any actual drawbacks? ................................................................................................................................................................ class TemplateResponseTestMixin(object): """ Basic test checking if correct response, template, form, is rendered for the given view. Can be used for any CBV that inherits from TemplateResponseMixin. """ # required view_class = None url_name = '' # optional (all below) template_name = '' form_class = None csrf_token = True get_status_code = 200 post_status_code = 405 def setUp(self): self.client = Client() ############# # SHORTCUTS # ############# def get_response(self): """ returns response for given view """ return self.client.get(reverse(self.url_name)) ######### # TESTS # ######### def test_view_used(self): """ check if correct view is used to render response """ resp = self.get_response() self.assertIsInstance(resp.context['view'], self.view_class) if template_name: def test_template_used(self): """ check if correct template is used to render response """ resp = self.get_response() self.assertTemplateUsed(resp, self.template_name) if form_class: def test_form_used(self): """ check if correct form is used to render response """ resp = self.get_response() self.assertIsInstance(resp.context['form'], self.form_class) if csrf_token: def test_if_csrf_token_is_used(self): """ check if csrf_token is used to render response """ resp = self.get_response() … -
How to appear two times in the django template?
I have two times: {{maine.job_time}} and {{maine.transport_time}}, I can add them using {% load mathfilters%}. That works well. I want to check now if the result of {{aine.job_time | add: maine.transport_time}} is equal to "3:00:00" displays OK. But my condition does not work. Can you help me solve this problem? Thank you Here is my Django template: {% extends 'blog/base.html' %} {% load mathfilters %} {% block content %} {% if semain %} <div class="container"> <table class="table table-bordered" > <thead> <tr> <th> {{ dim }} </th> </tr> </thead> <tr> <td> {% for maine in SemaineView %} {% if maine.date|date:"D" == "dim" %} <p class='postcontent' ><strong>job:</strong> {{ maine.job_time}}</p> <p class='postcontent' ><strong>transport:</strong> {{ maine.transport_time }}</p> <p class='postcontent' ><strong>Total:</strong> {{ maine.job_time|add:maine.transport_time }}</p> {% if maine.job_time|add:maine.transport_time== "3:00:00" %} <h1> ok </h1> {% else %} <h1> Non </h1> {% endif %} {% endif %} {% endfor %} {{ tr }} </td> </tr> </table> </div> {% endif %} {% endblock %} -
Django: render form field label without explicitly calling it
I have a form like this: class RoomForm(forms.Form): city = forms.CharField(max_length=100) country = forms.CharField(max_length=100) arrival_date = forms.DateField(widget=forms.DateInput(attrs= { 'class':'datepicker' })) departure_date = forms.DateField(widget=forms.DateInput(attrs= { 'class':'datepicker' })) I am its country field to the template like this: {{ form.country }} However the field gets diplayed without a label, even if I specify it in the form class like this: country = forms.CharField(max_length=100, label='Country') So in order to render the label to the template I have to do like this: {{ form.country.label }}{{ form.country }} Is there a way to only write {{ form.country }} and still have the label rendered to template? -
django-livereload-server not working 404 Not Found
I'm using Django 2.0.2, and I want to reload my static files live. i followed these instructions: https://github.com/tjwalch/django-livereload-server yet when I do python manage.py livereload and access localhost:35729 i get 404: Not Found -
Django-cms bulk update redirect urls
I need to make a simple change to the redirect url on a large number of published pages. How can I do that, either programmatically or through the admin? I've tried changing it through the shell and can access the Page objects with: from cms.models import Page pages = Page.objects.all() however there is no redirect field on the objects. Any help on where to look is much appreciated. Thanks. -
Django: annotate() does not work
Let Post be a model. I need to write a query which has a "constant" field type whose value is the string "X" for every object. I try to do the following: >>> Post.objects.all().annotate(type="X") Traceback (most recent call last): File "<console>", line 1, in <module> File "/home/porton/.virtualenv/opus/lib/python3.6/site-packages/django/db/models/query.py", line 929, in annotate clone.query.add_annotation(annotation, alias, is_summary=False) File "/home/porton/.virtualenv/opus/lib/python3.6/site-packages/django/db/models/sql/query.py", line 982, in add_annotation annotation = annotation.resolve_expression(self, allow_joins=True, reuse=None, AttributeError: 'str' object has no attribute 'resolve_expression' Why the error and how to solve my problem? Note that I need this for distinguishing different kinds of results when I .union() several queries together: q1 = paybills.models.PaymentSuccess.objects.all().annotate(type='PaymentSuccess').values('created', 'type') q2 = paybills.models.SubscriptionSuccess.objects.all().annotate(type='SubscriptionSuccess').values('created', 'type') q3 = paybills.models.SubscriptionPayment.objects.all().annotate(type='SubscriptionPayment').values('created', 'type') q4 = paybills.models.UnsubscriptionSuccess.objects.all().annotate(type='UnsubscriptionSuccess').values('created', 'type') q = q1.union(q2, q3, q4, all=True).order_by('-created') -
Google Flexible Environment django deploy with:Invalid Cloud SQL name: gcloud beta sql instances describe
I am deploying Django app to Google Flexible Environment using the following command gcloud app deploy But I get this error Updating service [default] (this may take several minutes)...failed. ERROR: (gcloud.app.deploy) Error Response: [13] Invalid Cloud SQL name: gcloud beta sql instances describe What could be the problem? -
heroku collecting static fails django python settings
My heroku build keeps failing while collecting static. My static files code in my settings.py file is such: Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(file))) angular distro root ANGULAR_APP_DIR = os.path.join(BASE_DIR, 'frontend/dist') # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.11/howto/static-files/ STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(ANGULAR_APP_DIR), os.path.join(BASE_DIR, 'static'), ] is it better to not have django collect static if I have already have? Or are they separate? -
Django: making queries based on foreign key field data?
These are my models: class Symbol: name = models.CharField(max_length=100) class Price: symbol = models.ForeignKey(Symbol) date = models.DateField() open = models.DecimalField( max_digits=15, # total digits including floating point decimal_places=2, ) What I want to query is "get all symbols whose any one of dailyprice's open == 0". Is that possible? -
Django - adding a filter to a prefetch gives one record with nested results
When I add a filter to a prefetch I no longer receive 70 results I receive 1 but with all the results nested into the parent object for example, I have to use: site_data[0][0].sitesupernet_set.all()[0].subnet_type.monitoring instead of site_data[0].sitesupernet_set.all()[0].subnet_type.monitoring when I do not have the filter and I just prefetch the table it works fine. why would the filter create a single parent object? This is the query that returns 1 object with 70 objects in it site_data = Site.objects.filter(is_live=True).filter( Q(site_type__site_type='Showroom') | Q(site_type__site_type='Transport Office')| Q(site_type__site_type='Other')) \ .prefetch_related( Prefetch( 'sitesupernet_set', queryset=SiteSupernet.objects.filter(subnet_type__monitoring=True) ) ), this query returns 70 objects site_data = Site.objects.filter(is_live=True).filter( Q(site_type__site_type='Showroom') | Q(site_type__site_type='Transport Office')| Q(site_type__site_type='Other')) \ .prefetch_related('sitesupernet_set') -
django Rest Framework - ViewSet with custom list view and URL parameter
I have the following setup: I want to list all holidays of a specific year. That's why I leave out the default list view and implement my own like this: class HolidayViewSet(mixins.RetrieveModelMixin, GenericViewSet): @list_route() def year(self, request, year=get_today().year): public_holidays = self.get_queryset().filter(date__year=year) page = self.paginate_queryset(public_holidays) if page is not None: serializer = self.get_serializer(page, many=True) return self.get_paginated_response(serializer.data) serializer = self.get_serializer(public_holidays, many=True) return Response(serializer.data) If I use the default /holiday/year/ I get a result for the current year. But whe I try to pass a parameter, I'll get a 404. The 404 page (in debug mode) even shows me the correct URL pattern: api/v1/ ^holiday/year/$ [name='holiday-year'] api/v1/ ^holiday/year\.(?P<format>[a-z0-9]+)/?$ [name='holiday-year'] In the documentation this aspect is unfortunately not covered. Any ideas why my route to holiday/year/2017 is not working? Thanks! Ron -
Can't run Apache2 with virtualenv
I'm making a website based on Django, on the server was installed a Python 3.5, but my project requires a Python 3.6. I decided to use virtualenv. I successfuly installed needed version of Python but I can't make it works with Apatche2 using virtualenv. Website is able to run only on Python 2.7, otherwise (when I change sth in VirtualHost settings) nothing happens, page is loading for a long time without any error. Here is my VirtualHost config with my try to run on Python 3.6. <VirtualHost *:443> ServerName <site_adress>:443 ServerAdmin admin@<site_adress> DocumentRoot /var/www/html/MMServer ErrorLog /var/www/logs/error.log CustomLog /var/www/logs/custom.log combined SSLEngine on SSLCertificateFile /etc/apache2/ssl/mm.cert SSLCertificateKeyFile /etc/apache2/ssl/mm.key Alias /static/ /var/www/html/MMServer/static/ <Directory /var/www/html/MMServer/static> Require all granted </Directory> WSGIDaemonProcess MMServer python-path=/var/www/html/MMServer python-home=/var/www/html/venv WSGIProcessGroup MMServer WSGIScriptAlias / /var/www/html/MMServer/mm_server/wsgi.py <Directory /var/www/html/MMServer/mm_server> <Files wsgi.py> Require all granted </Files> </Directory> </VirtualHost> Below is my wsgi.py file: import os import sys def application(environ, start_response): start_response('200 OK',[('Content-type','text/html')]) return [sys.version] Only one thing what I can get this way (while WSGIDaemonProcess and WSGIProcessGroup is deleted) is: 2.7.13 (default, Nov 24 2017, 17:33:09) [GCC 6.3.0 20170516] -
compare two time and if it elapse one day : unsupported operand type
guys im trying to compare two time .the times are current time and saved time in db. i want if it elapse one day if statment run id did somthing like this : but i have error unsupported operand type(s) for -: 'datetime.datetime' and 'str' am i doing right for this porpose ? how can i fix the error? obj = UserViewControll.objects.filter(visited_ip= ip) if(obj.exists()): get_dic = obj.values()[0] start = datetime.datetime.now() now = str(start) dbtime = get_dic['visited_datetime'] elapsed = dbtime - now if elapsed > datetime.timedelta(days=1): obj.update(view_count=F('view_count')+1) return -
Mocking a function
i try to figure how to mock a function in a helper.py that use in several methods for a unit test. I try with patch, @patch('project.helpers.function_0', new=lambda: True) but didn't work. How is the correct way to do this? Thank you. -
Django cleaned form data as list instead of string
I have a form with a multiple select field, e.g.: FRUIT_CHOICES = ( ('apple', 'apple'), ('orange', 'orange'), ) fruits = forms.CharField(label='fruit type', widget=forms.CheckboxSelectMultiple(choices=FRUIT_CHOICES)) When a user checks both 'apples' and 'oranges' and submits the form, and the form is validated, it produces a string, which is formatted to look like a list: form.is_valid() type(form.cleaned_data['fruits']) >>> <class 'str'> print(form.cleaned_data['fruits']) >>> ['apple', 'orange'] Now if I want to use the values 'apple' and 'orange' in my view, i'll have to create some type of regex to remove them from the string. This seems like a cumbersome solution. If there a way to get this data as a list straight from the form object? -
Creating a Django-Filter based on multiple inputs/fields
I would like to add a custom filter to sort my query set by location. I'm using the following answer to sort results by distance e.g. by calling: qs = Model.objects.nearby(lat, long, radius) Currently, my template.html has 3 inputs (2 hidden) which get populated by Google Maps Autocomplete: <input type="hidden" id="Lat" name="Lat" value="{{ form.Lat.value }}"/> <input type="hidden" id="Lng" name="Lng" value="{{ form.Lng.value }}"/> <input name="Radius" value="{{ form.Radius.value }}" /> I also have other fields which I'm filtering on, so I decided to use Django-Filter library. I would like to create a custom method to be able to filter by location in addition to other filters. The first solution which I created is: views.py if request.method == 'GET': form = LocationForm(request.GET) if form.is_valid(): # process the form and return nearby results results = Model.objects.nearby(lat, long, r) else: # initialise the form results = Model.objects.all() # add my filter f = ModelFilter(request.GET, queryset=results) return render(request, 'template.html', {'filter': f, 'form':form}) However, this creates 2 filters on top of each other. I'm not sure how to move my location filtering into the filter. Another solution is to create avoid using the form altogether (but then I'm losing validation and I can't seem to be able … -
Referencing Django's versioned static resources
When I run python manage.py collectstatic, it makes a copy of each image, JavaScript, and CSS file with a hash in the filename: Post-processed 'css/theme.css' as 'css/theme.afeb1fc222a9.css' Post-processed 'css/custom.css' as 'css/custom.585e1b29ff9a.css' ... I'm assuming this is just a way of making a versioned filename for better caching; the client or CDN can be told to cache this file indefinitely, because if I make a change, the hash will differ, and I'll just reference the new version by the new name. However, I'm not clear on how I'm supposed to reference this URL. The documentation on serving static files just says, In your templates, either hardcode the url like /static/my_app/example.jpg or, preferably, use the static template tag to build the URL for the given relative path by using the configured STATICFILES_STORAGE storage (this makes it much easier when you want to switch to a content delivery network (CDN) for serving static files). I went through my templates and dutifully switched every static resource (including the CSS files) from a hardcoded URL to a `{% static "..." %}" template tag, assuming it would map to the versioned filename where appropriate. But it doesn't. I'm also using WhiteNoise for serving the resources, and … -
Problems with win32com.client and Django
When I try to convert a .docx or doc document to a .txt in Django using win32com.client, I get this problem, Exception Value: (-2147221008, 'CoInitialize has not been called.', None, None) but when I try to convert the document without using Django I have not any problem this is the code I use to convert the documents doc = win32com.client.GetObject(DOC_FILEPATH) text = doc.Range().Text with open(FILETXT, "wb") as f: f.write(text.encode("utf-8")) Why do I get that exception value? -
Django: Having 2 cookie sessions but app gets logged out when the admin app gets logged in (viceversa)
I want to have 2 sessions, one for my application (myapp.com) and one for the admin (myapp.com/admin). With this, I can have access to both in different tabs of my web client without logging in every time I want to use one of them. It is very irritating. I have created a new session middleware to control that. import time from importlib import import_module from django.conf import settings from django.contrib.sessions.backends.base import UpdateError from django.core.exceptions import SuspiciousOperation from django.utils.cache import patch_vary_headers from django.utils.deprecation import MiddlewareMixin from django.utils.http import http_date class AdminCookieSessionMiddleware(MiddlewareMixin): def __init__(self, get_response=None): self.get_response = get_response engine = import_module(settings.SESSION_ENGINE) self.SessionStore = engine.SessionStore def cookie_name(self, request): parts = request.path.split('/') if len(parts) > 1 and parts[1].startswith('admin'): return settings.ADMIN_SESSION_COOKIE_NAME return settings.SESSION_COOKIE_NAME def cookie_path(self, request): parts = request.path.split('/') if len(parts) > 1 and parts[1].startswith('admin'): return settings.ADMIN_SESSION_COOKIE_PATH return settings.SESSION_COOKIE_PATH def process_request(self, request): session_key = request.COOKIES.get(self.cookie_name(request)) request.session = self.SessionStore(session_key) def process_response(self, request, response): """ If request.session was modified, or if the configuration is to save the session every time, save the changes and set a session cookie or delete the session cookie if the session has been emptied. """ try: accessed = request.session.accessed modified = request.session.modified empty = request.session.is_empty() except AttributeError: pass else: # First check …