Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django-How to put a model under a model directory in admin dashboard?
This is my django admin dashboard: my django admin dashboard I want to put my "Days" model into the "Input outputs" model. So it will be like... Patients Records Input outputs Days How cam I do this?? -
Python Django: If you change the data type of an attribute in a model and then migrate, does the sql lite database drop data in that column?
Python Django: If you change the data type of an attribute in a model and then migrate, does the sql lite database drop data in that column? -
Ajax call not returning the correct data
I am trying to get data from my django views and using the data to update the DOM however i do not get the correct data in the first place. When i print out the json_data in my console for my django app i do see the full html string coming back. However at the front end's console i only see the response coming back as the query DJANGO VIEW: def bloglist_search_ajax(request): query = request.GET.get('q') qs = Blog.objects.search(query) html_food_search = render_to_string('blogs/blog_food_listing_partial.html', {'object_list': qs}, request=request) json_data = { 'html_food_search': html_food_search } print(json_data) return JsonResponse(json_data) DJANGO URLS path('ajax/call', bloglist_search_ajax, name='ajax'), FORM <form method="GET" action="{% url 'blogs:ajax' %}" class="form-inline foodsearchform" > <i class="fa fa-search ml-4 fa-1x" aria-hidden="true"></i> <input name="q" value="{{request.GET.q}}" style="height:45px" class="form-control form-control-sm ml-3 w-50" type="text" placeholder=" Blogs Search" aria-label="Search"> <button type="submit" class="btn btn-primary">Search</button> </form> JQUERY CODE $(document).ready(function(){ var blogForm = $('.foodsearchform') blogForm.submit(function(event){ event.preventDefault(); console.log('Form not sending') var thisForm = $(this) var actionEndpoint = thisForm.attr('action'); console.log(actionEndpoint) var httpMethod = thisForm.attr('method'); console.log(httpMethod) var formData = thisForm.serialize(); console.log(formData) $.ajax({ url: actionEndpoint, method: httpMethod, data: formData, success: function(data){ // console.log(data) // data contains whatever u sent from django var foodlist = $('.foodlist') if (data.product_added) { foodlist.html(data.html_food_search) } }, error: function(errorData) { console.log(errorData) } }) }); }); … -
get_object_or_404(Profile, user=request.user) Error
I am trying to create a shopping cart for my website, but in my function "add_to_cart" when I try to request the user profile model in the beginning of function it tells me 'User' object has no attribute 'profile' add_to_cart is the first method in Checkout views.py under #get the user profile Error AttributeError at /checkout/add-to-cart/2/ 'User' object has no attribute 'profile' Request Method: GET Request URL: http://127.0.0.1:8000/checkout/add-to-cart/2/ Django Version: 1.11 Exception Type: AttributeError Exception Value: 'User' object has no attribute 'profile' If I remove the related_name for user in Profile, then I receive this error: Error from removal of related_name Request Method: GET Request URL: http://127.0.0.1:8000/checkout/add-to-cart/2/ Django Version: 1.11 Exception Type: AttributeError Exception Value: 'Product' object has no attribute 'all' Checkout views.py from django.conf import settings from django.contrib.auth.mixins import LoginRequiredMixin from django.contrib.auth.decorators import login_required from django.urls import reverse from django.shortcuts import render, redirect, get_object_or_404 from users.models import User, Profile, userStripe from portal.models import Product #from manaland.helper import get_reference_code from checkout.extras import generate_order_id from checkout.models import OrderItem, Order from django.views import generic from django.views.generic import CreateView import stripe stripe.api_key = settings.STRIPE_SECRET_KEY def add_to_cart(request, **kwargs): #get the user Profile user_Profile = get_object_or_404(Profile, user=request.user) #filter products for id product = Product.objects.filter(id=kwargs.get('item_id', "")).first() … -
Django-Channels 2 not persisting session data set in `connect`
channels==2.1.2 | channels-redis==2.2.1 | daphne==2.2.0 | Django==1.11.6 I've upgraded to Channels 2 specifically for the ability to access and modify the session from within a consumer (and access it in a view), but that doesn't seem to be working. Basically, I want to identify AnonymousUsers and send them messages (each his own, not all of them together). Here's my routing.py file: application = ProtocolTypeRouter({ # (http->django views is added by default) 'websocket': AuthMiddlewareStack( URLRouter( core.routing.websocket_urlpatterns ) ), }) Here's my consumers.py file: class ChatConsumer(WebsocketConsumer): def connect(self): if self.scope['user'].is_authenticated: user_id = str(self.scope['user'].id) self.scope['session']['user_identifier']= user_id self.group_name = user_id else: user_id = str(self.scope['user']) + str(uuid.uuid4()) self.scope['session']['user_identifier'] = user_id self.group_name = user_id self.scope['session'].save() print(f" in consumer: {self.scope['session']['user_identifier']}") # Join room group async_to_sync(self.channel_layer.group_add)( self.group_name, self.channel_name ) self.accept() And in the view where I need to use send, I'm trying to get the group_name (user_identifier) from the session in case of an AnonymousUser: def get_spotify_link(request): if request.user.is_authenticated: user_identifier = str(request.user.id) else: user_identifier = request.session['user_identifier'] print(f"in get_spotify_link: {user_identifier}") However, I'm intermittently (well, 99% of time) getting KeyError: 'user_identifier'. Internal Server Error: /get_spotify_link/ Traceback (most recent call last): File "/Users/myusername/.virtualenvs/bap_dev/lib/python3.6/site-packages/django/core/handlers/exception.py", line 41, in inner response = get_response(request) File "/Users/myusername/.virtualenvs/bap_dev/lib/python3.6/site-packages/django/core/handlers/base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File … -
View Set - filter objects
I have a problem with filtering objects in View Set... I am trying to show objects only where field 'point' is null. I always get error: NameError: name 'null' is not defined Could you please HELP ME ? My code: class CompanyMapSerializer(serializers.ModelSerializer): class Meta: model = Company fields = ('name', 'point', 'url', 'pk') extra_kwargs = { 'url': {'view_name': 'api:company-detail'}, } def to_representation(self, instance): ret = super(CompanyMapSerializer, self).to_representation(instance) ret['point'] = { 'latitude': instance.point.x, 'longitude': instance.point.y } return ret And view set code: class CompanyMapViewSet(viewsets.ModelViewSet): queryset = Company.objects.filter(point = null) serializer_class = CompanyMapSerializer PageNumberPagination.page_size = 10000 Please help me. -
Error running WSGI application , ModuleNotFoundError: No module named 'mysite' , while deploying django project in pythonanywhere
I am trying to deploy my Django project through project using pythonanywhere but I am getting problem and am really stuck. Can anyone help me with that. The image attached in the path to my setting.py file. Path to settings.py . The WSGI.py configuration on Webttab is path = '/home/technewsandblog/blog/blog_project/mysite' if path not in sys.path: sys.path.append(path) os.environ['DJANGO_SETTINGS_MODULE'] = 'mysite.settings' # then: from django.core.wsgi import get_wsgi_application application = get_wsgi_application() and The Error shows after I reload is Error running WSGI application 2018-07-08 20:30:23,383: ModuleNotFoundError: No module named 'mysite' 2018-07-08 20:30:23,383: File "/var/www/technewsandblog_pythonanywhere_com_wsgi.py", line 18, in 2018-07-08 20:30:23,383: application = get_wsgi_application() 2018-07-08 20:30:23,384: 2018-07-08 20:30:23,384: File "/home/technewsandblog/.virtualenvs/myDjangoEnv/lib/python3.6/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application 2018-07-08 20:30:23,384: django.setup(set_prefix=False) 2018-07-08 20:30:23,384: 2018-07-08 20:30:23,384: File "/home/technewsandblog/.virtualenvs/myDjangoEnv/lib/python3.6/site-packages/django/init.py", line 19, in setup 2018-07-08 20:30:23,384: configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) 2018-07-08 20:30:23,384: 2018-07-08 20:30:23,385: File "/home/technewsandblog/.virtualenvs/myDjangoEnv/lib/python3.6/site-packages/django/conf/init.py", line 56, in getattr 2018-07-08 20:30:23,385: self._setup(name) 2018-07-08 20:30:23,385: 2018-07-08 20:30:23,385: File "/home/technewsandblog/.virtualenvs/myDjangoEnv/lib/python3.6/site-packages/django/conf/init.py", line 43, in _setup 2018-07-08 20:30:23,385: self._wrapped = Settings(settings_module) 2018-07-08 20:30:23,385: 2018-07-08 20:30:23,386: File "/home/technewsandblog/.virtualenvs/myDjangoEnv/lib/python3.6/site-packages/django/conf/init.py", line 106, in init 2018-07-08 20:30:23,386: mod = importlib.import_module(self.SETTINGS_MODULE) What should I do? Can anyone please help me to deploy this project. Thank you. -
How to perform an F() query with datetime field?
I want to do a query based on two fields of a model, a date, offset by an int, used as a timedelta model.objects.filter(last_date__gte=datetime.now()-timedelta(days=F('interval'))) I am using Django 2.0 and db.sqlite3 I found some sources source 1 and source 2 but they were not helpful. some suggested to use duration field, but I want the interval to be entered in days desperately, whenever I use duration field , the admin needs to enter that in [days hh:mm:ss] in admin forms. And some gave a method model.objects.filter(last_date__gte=datetime.now()-timedelta(days=1)*F('interval')) which isn't working in db.sqlite3 and returning errors. Please suggest me some solution,like admin using duration field and entering only days or some solution with integer field of days. -
Base64ImageField returns full path only when parameter context={"request": request} added to it - Is there any other way
I currently have a Base64ImageField which works totally fine. The only problem I am having is sometimes it returns back an incomplete path. It skips the domain name but the rest of the path is fine.The reason its skipping the domain name is because I do not pass in the parameter context={"request": request} during serialization.The reason for that is because sometimes I do not have access to the request object.In other words this works fine jsonObject = Serializer(model_instance,context={"request": request}).data and this one skips the domain name from the image field jsonObject = Serializer(model_instance).data My question is how can I make it return the full path using the second example when I do not have to the request object ? Or is there any way for me to obtain the request object. When its not available ? I have this serializer in my code class Serializer_Employer_TX(ModelSerializer): user = Serializer_User() employer_image = Base64ImageField(max_length=None, use_url=True, required=False) class Meta: model = modelEmployer fields = [ 'user', 'employer_zip', 'employer_image', ] -
tastypie group by value
Using tastypie. I have the following simple model: class Autocomplete(models.Model): tablename = models.CharField(max_length=50, blank=True) # fieldname = models.CharField(max_length=25, blank=True) # value = models.CharField(max_length=50, blank=True) # class Meta: managed = False db_table = 'autocomplete' And the following ModelResource: class AutocompleteResource(ModelResource): counter = fields.CharField() class Meta: queryset = Autocomplete.objects.values('fieldname').annotate(counter=Count('fieldname')) resource_name = 'autocomplete' My goal is to group by the fieldname and return a result like this: fieldname | counter -----------+------- somefield1 | 177 somefield2 | 13926 somefield3 | 7331 Instead, tastypie throws back the following: error_message: "invalid literal for int() with base 10: ''", I'm probably missing something very basic here. Is it looking for the id but can't find it, because the values() call has removed it? How can I return a result that has different fields than the original model? I've spent way too much trying to figure this out, hope you guys can point me in the right direction. Thank you! -
Django + WSGI: No HTTP_COOKIE in environ
I've followed numerous examples, but the only one that does not return errors are the implementations of the two functions below. There doesn't seem to be an HTTP_COOKIE key in the environ. The request value only gets set with POST and GET. Think something is wrong with my setup, because none of the common usage patterns I've seen online like request.POST don't work. This is on the Django 1.11 development server, so if there will be differences between this and production (apache, nginx, lighttp) please let me know. I'm using the standard wsgi.py (I think), not django-wsgi if that is a separate module (out of my depth). view.py def index(environ, start_response, request): print request print environ.keys() template = loader.get_template('index.html') response = HttpResponse(template.render(None)) response.set_cookie('name1', 'test-cookie') response.set_cookie('name2', 'test-cookie') return response wsgi.py: def application(environ, start_response): try: request_body_size = int(environ.get('CONTENT_LENGTH', 0)) except (ValueError): request_body_size = 0 request_body = environ['wsgi.input'].read(request_body_size) request = parse_qs(request_body) start_response('200 OK', [('Content-Type', 'text/html')]) return omicron.view.index(environ, start_response, request) OUTPUT: request: {} environ.keys(): ['RUN_MAIN', 'HTTP_REFERER', 'XDG_GREETER_DATA_DIR', 'QT4_IM_MODULE', 'SERVER_SOFTWARE', 'UPSTART_EVENTS', 'SCRIPT_NAME', 'XDG_SESSION_TYPE', 'REQUEST_METHOD', 'CONTENT_LENGTH', 'SERVER_PROTOCOL', 'HOME', 'DISPLAY', 'LANG', 'SHELL', 'PATH_INFO', 'XDG_DATA_DIRS', 'QT_LINUX_ACCESSIBILITY_ALWAYS_ON', 'MANDATORY_PATH', 'COMPIZ_CONFIG_PROFILE', 'UPSTART_INSTANCE', 'JOB', 'SESSION', 'LIBGL_ALWAYS_SOFTWARE', 'SERVER_PORT', 'CLUTTER_IM_MODULE', 'XMODIFIERS', 'GTK2_MODULES', 'HTTP_PRAGMA', 'XDG_RUNTIME_DIR', 'COMPIZ_BIN_PATH', 'VTE_VERSION', 'HTTP_CACHE_CONTROL', 'HTTP_CONNECTION', 'HTTP_HOST', 'wsgi.version', 'XDG_CURRENT_DESKTOP', 'XDG_SESSION_ID', 'DBUS_SESSION_BUS_ADDRESS', 'GNOME_KEYRING_PID', … -
Python TypeError: 'bool' object is not callable
How i can fix this problem.it is on script im using or it is on the Python.Im using Debian OS And trying to install this code https://github.com/rkubik/paypark Traceback (most recent call last): File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 2309, in __call__ return self.wsgi_app(environ, start_response) File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 2295, in wsgi_app response = self.handle_exception(e) File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1741, in handle_exception reraise(exc_type, exc_value, tb) File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 2292, in wsgi_app response = self.full_dispatch_request() File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1815, in full_dispatch_request rv = self.handle_user_exception(e) File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1718, in handle_user_exception reraise(exc_type, exc_value, tb) File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1813, in full_dispatch_request rv = self.dispatch_request() File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1799, in dispatch_request return self.view_functions[rule.endpoint](**req.view_args) File "/var/paypark/paypark/frontend/auth.py", line 14, in auth_login if current_user.is_authenticated() or form.validate_on_submit(): TypeError: 'bool' object is not callable -
How do I get text from the database to keep my paragraphs separated on my blogging website?
I'm using Django and SQLite to build my personal blog site. Let's say I save my 'title' and the 'content of blog' into my database, and in the body of my content has multiple paragraphs and maybe an image. The problem I'm having is that when I display my data from my DB to the browser, it shows my content as a single paragraph and no images displayed instead of the way I originally intended. Whats the solution to this issue when using Django -
Using a Model @property decorator to check the count of manytomany
How do you set a model decorator (in Django) to count ManyToManyFields (and other verifiable conditions)? Django Model: class Cake(models.Model): cake_layer = models.ManyToManyField(CakeLayer, related_name="cake_layer") cream_layer = models.ManyToManyField(CreamLayer, related_name="cream_layer") @property def at_least_one_cake_layer(self): if self.cake_layer_set.count = 0: raise AssertionError("At last one cake layer is needed to be a cake") @property def at_least_two_layers(self): total_layer_count = 0 total_layer_count += self.cream_layer_set.count total_layer_count += self.cream_layer_set.count if total_layer_count <= 1: raise AssertionError("A proper Cake needs two layers, even if they are just two cake layers!") Is it as simple as being able to do a query in the model itself? (I have only been using queries in templates and views, and am unsure of how to properly (if at all) access the model's attributes if they are yet another Model. please note: If this code should work, please let me know, but so you know where I am coming from: I am re-writing an app schema from what I've learned, and am trying to abstract some things to remove duplication, and am stepping into Generic Foreign Key (GFK)/Multiple Table Inheritance/ ManyToMany architecture, and am trying different things out, and am sure if the approach I want to try is viable I am trying to avoid using GFKs, … -
Dynamic Django apps
I searched for a long time how to create a "plugin" framework in Django, without success. You can add some support for plugins, but having apps with full support for models, urls etc. is a hard thing. Let's start from the beginning. I started an application using django that is wanted to be extended by plugins in the future. I don't know which features vendors will add to that application, so they must be able to add database models too. If I now say, let a plugin be a django app, I have the problem that django apps are not loaded dynamically during startup. I have to manually and hardcodedly add the app into my settings.py, add the urls to urls.py etc. I now created a simple plugin system that * searches for django apps in a plugins/ directory, and includes them into the "INSTALLED_APPS" dict, by adding that code INTO settings.py directly * adds Interfaces that can be implemented by plugins to automatically add e.g. urls into the root urls.py by collecting that implementations automatically. Everything works, but one thing: I'd like to add a "shadowed" Plugin model to my database that holds the metadata of the installed plugins. … -
Django Vue.js - Different default values for multiselect list
I am trying to render different default values for dropdown multiselect list (based on Vue.js), but explicitly changing v-model to particular structure does not make the job. Default code looks like this: <div class="" id="input_element"> <div id="multiselect"> <multiselect name="socialMediaType" ref="multiselect" v-model="value" :options="options" :multiple="true" track-by="library" :custom-label="customLabel" @close="isOpen = false" @open="isOpen = true" > </multiselect> </div> </div> And used : new Vue( { components: { Multiselect: window.VueMultiselect.default }, data: { isOpen: false, value: { language: 'Snapchat', library: 'Snapchat' }, options: [ {% for val, name in social_media_platforms %} { language: '{{ val }}', library: '{{ name }}' }, {% endfor %} ] }, methods: { customLabel (option) { return `${option.language}` }, toggle () { this.$refs.multiselect.$el.focus() setTimeout(() => { this.$refs.multiselect.$refs.search.blur() }, 400) } } }).$mount('.multiselect_platform') Data is being rendered by Django template language. Each time the result is the same: As a default, it renders "Snapchat". I want to manipulate attribute, because I am generating many multiselect lists with different default values -
Django giving error on terminal:unable to load CA private key
I'm trying to sign a certificate using the private key. But everytime django just gives this error on the terminal, not on the interface. unable to load CA private key 140032149018488:error:06065064:digital envelope routines:EVP_DecryptFinal_ex:bad decrypt:evp_enc.c:594: 140032149018488:error:0906A065:PEM routines:PEM_do_header:bad decrypt:pem_lib.c:488: Whereas on the interface it shows success status. This comes when i try to execute the following through python subprocess: tempdirname = 'temp_cert/' dirname = 'certs/' configdirname = 'config/' cmd = [ 'openssl', 'ca', '-create_serial', '-config', configdirname + 'openssl.cnf', '-cert', configdirname + 'private/ca.root.pem', '-keyfile', configdirname + 'private/ca.key.pem', '-passin', 'pass:"thsjfasdfljkasdffasf"', '-in', tempdirname + keyname + '.csr', '-out', tempdirname + certname ] r = subprocess.Popen(cmd, stdin=subprocess.PIPE, shell=False) out, err = r.communicate('\n'.encode()) r.stdin.close() here is the excerpt from my openssl.cnf file: [ CA_default ] # Directory and file locations. dir = /var/www/html/libreswan-upgraded certs = /var/www/html/libreswan-upgraded/temp_cert new_certs_dir = $certs database = $certs/index.txt serial = $certs/serial RANDFILE = $certs/.rand # The root key and root certificate. private_key = $dir/config/private/ca.key.pem certificate = $dir/config/private/ca.root.pem Whereas when i execute the equivalent command in terminal it gets executed successfully. eg. openssl ca -create_serial -config config/openssl.cnf -cert config/private/ca.root.pem -keyfile config/private/ca.key.pem -in temp_cert/7ym2zupqo9.csr -out temp_cert/7ym2zupqo9.pem this command works great and don't give any error of anything. Why is this error coming with django? I'm … -
django-admin.py' is not recognized as an internal or external command
I have installed Django on my computer with the help oh anaconda and used command "conda install -c anaconda django" for the same. Now when I was supposed to work on Django so I typed "django -admin --version" inorder to get information about it's version, what I found was "django-admin.py' is not recognized as an internal or external command" as it's output". I am referring to this online tutorial https://www.youtube.com/watch?v=qgGIqRFvFFk&index=1&list=PL6gx4Cwl9DGBlmzzFcLgDhKTTfNLfX1IK -
"Posts matching query does not exist." error while navigating to "admin page" in django?
I am learning Django and working on making a simple blog website. Now the whole project is working fine but whenever I navigate to the admin panel it shows the error "Posts matching query does not exist.". Let me know which part of the code you want to see(i'm confused which file has the error) -
Django send mail from docker container
I have a Django application and when I run it locally it all works fine. But in production that runs in a docker container it can not send mail anymore I get the error Traceback (most recent call last): File "/app/training/schema.py", line 167, in mutate fail_silently=False, File "/app/.heroku/python/lib/python3.6/site-packages/django/core/mail/__init__.py", line 60, in send_mail return mail.send() File "/app/.heroku/python/lib/python3.6/site-packages/django/core/mail/message.py", line 294, in send return self.get_connection(fail_silently).send_messages([self]) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/mail/backends/smtp.py", line 103, in send_messages new_conn_created = self.open() File "/app/.heroku/python/lib/python3.6/site-packages/django/core/mail/backends/smtp.py", line 63, in open self.connection = self.connection_class(self.host, self.port, **connection_params) File "/app/.heroku/python/lib/python3.6/smtplib.py", line 251, in __init__ (code, msg) = self.connect(host, port) File "/app/.heroku/python/lib/python3.6/smtplib.py", line 336, in connect self.sock = self._get_socket(host, port, self.timeout) File "/app/.heroku/python/lib/python3.6/smtplib.py", line 307, in _get_socket self.source_address) File "/app/.heroku/python/lib/python3.6/socket.py", line 724, in create_connection raise err File "/app/.heroku/python/lib/python3.6/socket.py", line 713, in create_connection sock.connect(sa) OSError: [Errno 99] Cannot assign requested address I am using these settings: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = 'me@gmail.com' EMAIL_HOST_PASSWORD = 'password' EMAIL_PORT = 587 Does someone know what I am doing wrong? -
Why is Celery periodic task not working? (Django)
It returns no errors, however when running celery -A mysite beat -l info & celery -A mysite worker -l info the task doesn't happen. When trying the same structure in another Django project it works fine. Help please! My code: mysite/settings.py (Only CELERY part) BROKER_URL = 'redis://localhost:6379' CELERY_RESULT_BACKEND = 'redis://localhost:6379' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' CELERY_TIMEZONE = 'Africa/Nairobi' mysite/init.py from __future__ import absolute_import from .celery import app as celery_app mysite/celery.py from __future__ import absolute_import import os from celery import Celery from django.conf import settings os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite.settings') app = Celery('mysite') app.config_from_object('django.conf:settings') app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) personal/tasks.py from celery.task.schedules import crontab from celery.decorators import periodic_task from celery.utils.log import get_task_logger logger = get_task_logger(__name__) @periodic_task( run_every=(crontab(minute='*/1')), name="task_deleteFiles", ignore_result=True ) def task_deleteFiles(): logger.info("Files Deleted") PS: If necessary I can post the outputs from Celery -
How To Model Mapping Table in Django
I'm building a Django app that needs to represent which students are in which classes. If I were doing this in SQL I'd have three tables. One for classes, one for students, and then a third table which would be enrollments, for mapping students and classes together. In Django I could do this with three models. But is there a "Djangonic" way to represent a mapping between two classes? -
django check email address is live or not
I am working on a django project and need to verify email address is live. Suppose a user send registration request with email - pankajsharma00008@gmail.com it will check if this email is registered on gmail or not. Here it is not only for gmail but it can be any email service provider like Yahoo, hotmail, etc. There are thousands of email service providers, how can I check if email address is registered on that mail service. Is there any app for django to check valid mails? -
PYTHONHOME and PYTHONPATH for Django in Heroku
This is a follow-up question for this. No module named PIL in heroku though it is installed I got help from Heroku website here. https://help.heroku.com/BWJ7QYTF/why-am-i-seeing-importerror-no-module-named-site-when-deploying-a-python-app But from the terminal, when I type heroku config I only get the DATABASE_URL. How do I set these variables? -
Validation error not working with pytest: Django
I'm using Django 2.0 I have a model with two datetime fields class AmountGiven(models.Model): amount = models.FloatField(help_text='Amount given to the contact') _given_date = models.DateTimeField( db_column='given_date', default=datetime.now, ) promised_return_date = models.DateTimeField( blank=True, default=None, null=True, ) @property def given_date(self): return self._given_date @given_date.setter def given_date(self, value): self._given_date = value def clean(self): print(self.given_date) if self.given_date: if self.given_date.date() > datetime.today().date(): raise ValidationError({ 'given_date': _('The given date was in the future') }) if self.given_date and self.promised_return_date: if self.given_date > self.promised_return_date: raise ValidationError({ 'promised_return_date': _('Promised return date can not be earlier than given date') }) I have to perform following validations on given_date and promised_return_date given_date is not in future if promised_return_date i. promised_return_date is not in past to given_date I'm using mixer to generate model data test_models.py @pytest.mark.django_db class TestAmountGiven(TestCase): def test_model_add_amount_given_in_future(self): amount_given_in_future_1_day = mixer.blend( 'transactions.AmountGiven', given_date=datetime.now(get_localzone()) + timedelta(days=1), promised_return_date=datetime.now(get_localzone()) + timedelta(days=300) ) self.assertRaises(ValidationError, amount_given_in_future_1_day.clean) assert str(amount_given_in_future_1_day) == str(amount_given_in_future_1_day.amount), \ '__str__ should return amount string' But this test is returning no ValidationError or any error.