Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I send channels 2.x group message from celery 3 task?
I need to postpone sending channels message. Here is my code: # consumers.py class ChatConsumer(WebsocketConsumer): def chat_message(self, event): self.send(text_data=json.dumps(event['message'])) def connect(self): self.channel_layer.group_add(self.room_name, self.channel_name) self.accept() def receive(self, text_data=None, bytes_data=None): send_message_task.apply_async( args=( self.room_name, {'type': 'chat_message', 'message': 'the message'} ), countdown=10 ) # tasks.py @shared_task def send_message_task(room_name, message): layer = get_channel_layer() layer.group_send(room_name, message) The task is being executed and I can't see any errors but message is not being sent. It works only if I send it from consumer class method. I also tried using AsyncWebsocketConsumer and sending with AsyncToSync(layer.group_send). It errors with "You cannot use AsyncToSync in the same thread as an async event loop - just await the async function directly." Then I tried declaring send_message_task as async and using await. Nothing happens again (with no errors) and I'm not sure if the task is executed at all. Here are versions: Django==1.11.13 redis==2.10.5 django-celery==3.2.2 channels==2.1.2 channels_redis==2.2.1 Settings: REDIS_HOST = os.getenv('REDIS_HOST', '127.0.0.1') BROKER_URL = 'redis://{}:6379/0'.format(REDIS_HOST) CHANNEL_LAYERS = { "default": { "BACKEND": "channels_redis.core.RedisChannelLayer", "CONFIG": { "hosts": ['redis://{}:6379/1'.format(REDIS_HOST)], }, }, } Any ideas? -
Load an html5 canvas into a PIL Image with Django and save it in new File
I test this example : question source : Load an html5 canvas into a PIL Image with Django import re datauri = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUg AAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8 /w38GIAXDIBKE0DHxgl jNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==' imgstr = re.search(r'base64,(.*)', datauri).group(1) output = open('output.png', 'wb') output.write(imgstr.decode('base64')) output.close() but I have an error on this line: output.write(imgstr.decode('base64')) here is the error: File "C:\django_projects\intranet\intranet\capture\views.py", line 19, in enregistre_image output.write(imgstr.decode('base64')) AttributeError: 'str' object has no attribute 'decode' could you tell me what I'm doing wrong thank you Christophe -
Extract metadata from database using python?
I have looked for an answer to this question, but very was able to find very little. I want to extract the names of the tables, references between them, column names so I can graphically visualize that information. I need to this in a Django project. Since I am a newbie to python I would like to know if there is some kind of API to do this type of thing. -
Error when using set tag in jinja template ('set'. Did you forget to register or load this tag?)
Basically i want to count variable inside a loop in HTML page. For that i want to use set tag as explained in this example: How to increment a variable on a for loop in jinja template? When i use the set tag in my html page i get this error: Django Version: 2.0.5 Exception Type: TemplateSyntaxError Exception Value: Invalid block tag on line 98: 'set'. Did you forget to register or load this tag? I can't really find another way to do this. Thank you. -
Json Database. I want to get a number from a json string and put it into a database.
I am making a PWA for a friend. the database has users and the users have json strings associated with them. I know that I can just ask the database for that user's Json in html or js, but I want to know if its possible to have the database look at that json String, and automatically divvy out the details in it to the database say every hour. I know there is a simpler way of just putting the json string in the database under the user, then just parsing it when the user logs into the page and asks for it. just wondering if I can skip a step and just make the database auto update the json string into the DB itself. -
How to send an email after User post the form?
i am beginner and used steps for sending email from https://docs.djangoproject.com/en/2.0/topics/email/ but i didn't accomplished to send email. i want to send an email automatically using django email after a user submit the form . i am having a booking form and having email field in it after user post the form i want to send a email "Thankyou for your booking / your booking is placed ". for eg first name : Abubakar Last name :Afzal email : any@gmail.com i want to take any@gmail.com and send email to it . after user post the form . settings.py EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_HOST_USER = 'my@gmail.com' EMAIL_HOST_PASSWORD = 'mypassword' EMAIL_USE_TLS = True View.py class BookingView(FormView): template_name = 'buggy_app/booking.html' form_class = BookingForm models = Booking def form_valid(self, form): car_id = self.request.GET.get('car', '') car = Car.objects.get(id=car_id) car.is_available_car = False car.save() form.save() return super(BookingView, self).form_valid(form) success_url = reverse_lazy('index') Forms.py class BookingForm(ModelForm): class Meta: model = Booking widgets = { times_pick': TimePickerInput(), } fields = ('first_name','last_name','email','book_car','contact_number','times_pick',) -
Correct way to pass a link to an email template in django
So I want to add a link to a specific page of my app in my email template, but this page changes based on the different values I pass on to my template through my view,so i tried to pass the name of the url into the template like the following but it doesn't work. Can someone please show me the right way to do something like this? views.py html_message = loader.render_to_string( 'catalog/email_template.html', {'body_message': body_message, 'user': user_obj_to.get_full_name(), 'link': link }, ) send_mail( email_subject, body_message, sender_email, [receiver_email], fail_silently=False, html_message=html_message ) email_template.html <p style="font-family: sans-serif; font-size: 20px; font-weight: normal; margin: 0; Margin-bottom: 15px;">Dear {{ user }}</p> <p style="font-family: sans-serif; font-size: 14px; font-weight: normal; margin: 0; Margin-bottom: 15px;">{{ body_message }} <a href="{% url '{{ link|safe }}' %}">link</a></p> -
404 error issue with Path() pattern.
path('add', views.TopicCreate.as_view(), name='add-topic') ] When i try to run it, it gives me 404 error saying it didn't match any of the patterns. even though it says that there's matching url pattern right there. home/ [name='index'] home/ <int:topic_id> [name='details'] home/ add [name='topic-add'] admin/ The current path, home/add/, didn't match any of these. -
I am trying to import the model Product from another app in my django project
enter image description hereThis is my screenshot having the directory structure in it.but while getting the Product model attribute and print it shows me the empty Querry set like Here is my Ecom/settings.py """ Django settings for Ecom project. Generated by 'django-admin startproject' using Django 2.0.6. For more information on this file, see https://docs.djangoproject.com/en/2.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.0/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) 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/2.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'r*4jisk#c^4gl0-#x_x_sm%f9t-t4#n@j$ea_6sep@1&aobl-k' # 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', 'home', 'product', 'search', 'cart' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'Ecom.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'Ecom.wsgi.application' # Database # https://docs.djangoproject.com/en/2.0/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # … -
Have a variable in a Template that can be increased or decreased
I need a 'counter' (not forloop) in a Django template that increases and decreases based on some actions, something lik In a semi-pseudo code I need something like: {% with col=0 %} {% for d in d_list %} {% if forloop.counter|divisibleby:4 %} # increase/add col=col+1 {% endif %} {% ifchanged d.data} col=col-1 {end ifchanged} {% endfor %} {% if col ==4 %} do something {% endif %} ... {% endwith %} -
Django: get foreign key´s value instead of id
I´m trying to use foreign key values in a template. When I try to show it, I get the value on screen correctly. {% for x in dataset %} <p> {{ x.fieldname }} {% endfor %} But when I try to use it for comparisons it uses the id, not the value. {% for x in dataset %} {% if x.fieldname == "The name I want" %} <p> {{ x.fieldname }} {% endif %} {% endfor %} I´ve been looking some posts relateing serializers with this, but (in my little knowledge) I understand serializers are to send or receive data from outside the application. As the is only tu use the values within the application, is there another way to get the actual value for comparisons? Should I use the serializers approach? Thanks! -
Mysql replication/sync cloud and remote server(local server)
I am building a application using(Django-Mysql-Vuejs) for a customer who have around 20 stores across the country the application needs to work even when the internet is not available. so we decided to deploy the application on each store setting up a local server. I have set the primary key on each table to make the data unique so it will not conflict between each store. Now the same application is deployed also in the cloud what i actually need to do is i need to move all the data in each store to cloud database so that the management team can view all the data at a single database. what will be the right solution to deploy it i am using mysql database. Note:i have a table called emp this can be updated by the management using the cloud application for example if any employee is added by management in cloud this data needs to be moved to particular store not to all the store. I need few tables from the cloud to replicate to the store and also all the tables from the store needs to sync to cloud. -
enumerate instances within queryset by group
Let's say I have a model which can be subdivided into groups Gender: Class: Item M 1 1 F 2 2 M 1 3 M 2 4 if I make a queryset in Django from this model, is there a compact way to annotate it with a kind of a 'counter' within each group? so if I do a query: q = MyModel.objects.all().order_by('class','gender') the result would be: Gender: Class: Item Counter (Id in Class) M 1 1 1 M 1 3 2 F 2 2 1 M 2 4 2 -
multiprocessing error in django
I am trying to start multiprocessing from a django application. But it continously throws error File "C:\Users\souradipta.roy\tensorflow2\lib\site-packages\django\db\models\base.py", line 100, in new app_config = apps.get_containing_app_config(module) File "C:\Users\souradipta.roy\tensorflow2\lib\site-packages\django\apps\registry.py", line 244, in get_containing_app_config self.check_apps_ready() File "C:\Users\souradipta.roy\tensorflow2\lib\site-packages\django\apps\registry.py", line 127, in check_apps_ready raise AppRegistryNotReady("Apps aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. Sometimes it also says django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet. The code snippet that starts multiprocesing is as below def process_content_sources(self,use_case_ids): content_sources = ModelFunctionCalls().get_content_source(use_case_ids) print("start_time...."+str(time.time())) django.db.connections.close_all() #process_executor = concurrent.futures.ProcessPoolExecutor(max_workers=5) for contnt_source in content_sources: print('contnt_source',contnt_source) # self.process_each_content_source(contnt_source) multiprocessing.Process(target=self.process_each_content_source, args=(contnt_source,)).start() -
Loading template from an external URL in django
I have an HTML template stored in a VPS. I want to use this template for rendering in Django, is there a way to do this? I know its better to have the template in the same project directory as Django, but I am just curious to know how can I render a template which is not in our project folder and we know its url. Thanks -
Django: keep owning side unique when adding object with different ManyToMany field
I have two fields, one being Symbol and the other Source. They have a ManyToMany relationship, since each Symbol can appear in multiple Sources and each Source can have multiple Symbols. Symbols are unique, too. So far so good. Now I want to allow the user to bulk add a CSV of Symbol -> Source mappings. There is, however, the chance that a Symbol appears twice in one or more of these CSVs, which I believe will violate the UNIQUE constraint. I could of course check while iterating through every row in the CSV whether the character is already in the database. But wouldn't that cause a load of database calls? Is there a more efficient way? class Source(models.Model): title = models.CharField(max_length=200, unique=True) author = models.CharField(max_length=200) offset = models.IntegerField(default=0) def __str__(self): return self.title + " by " + self.author class Meta: ordering = ('title',) class Symbol(models.Model): name = models.CharField(max_length=1, unique=True) location = models.ManyToManyField(Source, through='CharInSource') def __str__(self): return self.name class Meta: ordering = ('name',) class SymbolInSource(models.Model): source = models.ForeignKey(Source, on_delete=models.CASCADE) symbol = models.ForeignKey(Symbol, on_delete=models.CASCADE) page = models.IntegerField() def __str__(self): return "p" + str(self.page) -
How to set the server and port in the Visual Studio Django Web Project template
I created a Django web project in Visual Studio 2017. In the context menu of the project icon in the Solution Explorer view, in the "Python" entry, I can select, among other actions, "Start server" and "Start debug server". A cmd window opens and shows that it is sourcing the correct config settings and then attempts to start the server at localhost, port 8000. Here is where it fails on my machine since that port is taken. How do change that port (and server address) for using the context menu? (I do know how to change it for starting runserver on the command line or via the Debug configuration.) -
How to restrict date and time in django bootstrap datetimepicker plus?
i am newbie using jquery stuff and date time picker. i am using https://github.com/monim67/django-bootstrap-datepicker-plus in my django forms . User cannot pick date more then next two days and cannot select time from 18:00 to 8:00 . how to manage all this . i had used jquery in it but didn't accomplished for eg today is 22june user can select date till 24june time user can see is from 8:00 to 17:00 Forms.py class BookingForm(ModelForm): class Meta: model = Booking widgets = { 'times_pick': DateTimePickerInput(), } fields = ('booking_name','rental_price','book_car','customer_name','times_pick',) can anyone tell me how to use jquery to customize it like i told before. please help me out -
Package similar to django-sql-explorer but for django-orm queries?
I need/want to be able to write reusable queries in an exact fashion already supported by django-sql-explorer, but I want to write regular django-orm expressions, rather than raw SQL. Is there anything out there that supports something like this? -
GeoDjango - django-leaflet map not showing marker
I have two questions with django-leaflet. Following the official documents, my HTML file looks like this: <html> {% load leaflet_tags %} <head> {% leaflet_js %} {% leaflet_css %} <style> #myMap { width:100%; height:100% } </style> </head> <body> <script type="text/javascript"> function map_init_basic (map, options) { L.marker([lat, lng]).adddTo(Map); } </script> {% leaflet_map "myMap" callback="window.map_init_basic" %} </body> The map shows up but the marker doesn't show up. I don't know what's wrong. Am I missing some kind of tags to load? 2. When I add <!DOCTYPE html> the map only shows for 50% of the div height. When I remove it it takes up the whole browser. Can someone explain me why it happens like that? Thanks. -
Running Django Commands on a different server
Right now I have a django website. I manage to programmatically populate the database using django commands and everything works fine. I now want to have a dedicated server for populating the database programmatically but I do not want to give up using django commands as thei are very powerful in my opinion. I am using aws elastic beanstalk and an rds db instance, so I know that I could simply create my scripts (the ones I use to populate the db) in pure python, but I am wondering if there is a nice way to do the same using Django. I thought of simply setting up a new Django project that connects to the same RDS database, but this would mean that I need to copy all the models/settings every time a make a change to my main website... I did not really seem ideal. Any thoughts? -
list_display not showing email_verified field in ModelAdmin Django
I am list displaying the following fields in Django ModelAdmin. list_display = ['username', 'email_verified', 'cert_password', 'key_name'] in this list the items - username, cert_password and key_name belongs to a a model ModelName and the item email_verified belongs to other model ModelName2. But I want to display them all to admin in ModelAdmin so for that I created a function def email_verified as below: class UserAdmin(admin.ModelAdmin): list_display = ['username', 'email_verified', 'cert_password', 'key_name'] def email_verified(self): return ModelName2.email_verified actions = [my_action_here] So, when I returned ModelName2.email_verified its showing <django.db.models.query_utils.DeferredAttribute object at 0x7efcca3b9910> in the Admin interface through ModelAdmin. So, I tried through the following: class UserAdmin(admin.ModelAdmin): list_display = ['username', 'email_verified', 'cert_password', 'key_name'] def email_verified(self,obj): return ModalName2.objects.get().email_verified actions = [my_action_here] But in this case I got the error - get() returned more than one ModalName2 So, how can I do it. I want to display the value of email_verified in the ModalAdmin (Admin Interface) in the table with the respective username and other fields. eg. What I want - Username | Email_Verified | cert_password | Key_name abcuser | 1 | asdf | asdf bhdjs | 1 | lkj | ljk asdff | 0 | lkjsd | ljl How to do it? I am using … -
Two foreign keys of same class Django
How to access the two foreign key's of same class class Countries(models.Model): name = models.CharField(max_length=200,null=True) class bookings(models.Model): Pickup = models.ForeignKey(Countries,on_delete=models.CASCADE,null=True) Dropoff = models.ForeignKey(Countries,on_delete=models.CASCADE,null=True) ERROR reverse accessor of Pickup clashes with reverse accessser for Dropoff -
Separate multiple 'for loops' in multiple sections by multiple dividers
I have a hierarchy (multiple trees); For ex: A1 is child of A, B2 is child of B I need to split the children in 4 columns and each column grouped in 5 rows; Notice how the parent name(A) is not repeated in the 4 columns packet, but if is moving in another packet(B) is repeated; A B --- ---- ---- --- A1 A6 A11 B1 A2 A7 A12 B2 A3 A8 B3 A4 A9 B4 A5 A10 B5 --------------- B C -- -- B6 C1 B7 C2 B8 C3 C4 The loops: {% for d in list %} <a href="#">{{ d.name }}</a> {% for c in d.children %} <a href="#">{{ c.name }}</a> {% endfor %} {% endfor %} Will look like this( reduced the number for space reasons): <div class="row"> <a href="#">Parent1</a> <div class="col"> <a href="#">{{ d.name }}</a> <a href="#">{{ d.name }}</a> <a href="#">{{ d.name }}</a> </div> <div class="col"> <noparent> <a href="#">{{ d.name }}</a> <a href="#">{{ d.name }}</a> <a href="#">{{ d.name }}</a> </div> <div class="col"> <noparent> <a href="#">{{ d.name }}</a> <a href="#">{{ d.name }}</a> <a href="#">{{ d.name }}</a> </div> </div> <div class="col"> <a href="#">Parent2</a> <a href="#">{{ d.name }}</a> <a href="#">{{ d.name }}</a> <a href="#">{{ d.name }}</a> </div> </div> <div … -
Split datetime field in date, hours and minutes
I have a model which has a datetime field. The user should enter the date, the hours and the minutes in 3 separate fields. What is the best way to do this? Should I create a custom form field or a custom widget or is there a better way?