Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django: how to update the html once the celery asynchronous task is completed
I have a django view without using celery background task. It does some long calculation and then it renders a template. Now i want to use celery to make the long calculation in background. But the template i made need the context values from the that long calculation. How will the template load intially saying "work in progress and later on update the html when the context values of the template are ready and show the proper html. I heard of two solutions: 1) to use ajax to ping the server to check the task is completed or not and then show the content dynamically 2) dont use celery at all, create another view and url for the calculations and load the html inside main template using AJAX. which is better, because in both cases while ajax is requesting i have to show a loading indicator. -
How to send an email with bold string using Django
My Django app sends an email as follows: mail_subject='Hi' to_email='xyz@gmail.com' message=render_to_string('app1/xyz.html',{ 'user':User1,'var1':'BLUE'}) email = EmailMessage(mail_subject, message, to=[to_email]) email.send(); xyz.html looks like below: I would like for the following string to be bold <strong>{{var1}}</strong> but it just shows as <strong>BLUE</strong> in the email. I would like to see BLUE -
Django: queryset permissions based on object field
Assume that I have the following models: from django.db import models class Environment(models.Model): name = models.CharField(max_length=30, unique=True) class Device(models.Model): # (some other fields) environment = models.ForeignKey(Environment, on_delete=models.CASCADE) There are also two "permission levels": root: users with this level can edit and delete Devices regular_user: users with this level can view Devices Each user for specified Environment should have either root or regular_user permission level, ie. in environment A he can be root and in environment B - regular_user. For specifying that user has a certain permission level for selected environment, I use the solution described here (<permission_level_name>:<environment_id>, eg.: root:1). This can be a subject to change if it will help to resolve the problem. User accesses data via Django REST Framework-based API. How to prevent user with root permission level in environment A to edit (via API) Devices that are in environment B, where he has regular_user permission level? Solutions like django-guardian allow to assign permissions per Device instance and Django Permissions allow to assign permissions per Model but what I am looking for is permission system based on property of Device instance. -
configuring Django Channels for windows in production
Please, I need to configure Django Channels on redis-channel-layer on windows IIS in production. It is running very well in development. I have installed redis, daphne. I have set the IIS as proxy server with URL Rewrite pointing the Inbound to localhost 6379 to redis-layer channels. I used python manage.py runworker. and also started the daphne server with the daphne command. They all ran very well, but there is no websocket handshake for my url. -
Django app on heroku doesn't load staticfiles from S3 bucket
When I run heroku run python manage.py collectstatic it does upload staticfiles to AWS S3, however when I run django in production, my static files do not load to the page. To be honest i dont know why do i have bad request, since i already did collectstatic to S3. My AWS settings @ settings.py AWS_ACCESS_KEY_ID = os.environ.get('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = os.environ.get('AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = os.environ.get('AWS_STORAGE_BUCKET_NAME') STATIC_URL = 'https://' + AWS_STORAGE_BUCKET_NAME + '.s3.amazonaws.com/' AWS_URL = os.environ.get('AWS_URL') STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' ADMIN_MEDIA_PREFIX = STATIC_URL + 'admin/' STATIC_URL = "https://" + AWS_STORAGE_BUCKET_NAME + ".s3.amazonaws.com/" MEDIA_URL = STATIC_URL + "media/" STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'),) STATIC_ROOT = 'staticfiles' STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', ) -
Fetch rows from Mysql and display it in html using Django
I am fairly new to Django. I want to know how to fetch rows from mysql and get it in views.py and send it to html where it will be displayed. My views.py: def fetchDate1(request): query = request.session.get('query') date1 = request.session.get('date1'); db = pymysql.connect(host="localhost", # your host user="root", # username passwd="=", # password db="Golden") # name of the database # Create a Cursor object to execute queries. cur = db.cursor() # Select data from table using SQL query. stmt = "SELECT * FROM golden_response WHERE query LIKE '%s' AND DATE(updated_at) = '%s' " % ( query.replace("'", r"\'"), date1) cur.execute(stmt) if cur.rowcount is None: return None else: rows = cur.fetchall() row_headers = [x[0] for x in cur.description] # this will extract row headers json_data = [] for result in rows: json_data.append(dict(zip(row_headers, result))) return json.dumps(json_data) I don't know where I am going wrong. Have also saved required configuration in settings.py. However when i try to run my program : ProgrammingError: (1146, "Table 'Golden.django_session' doesn't exist") Please help!! -
Scalability in Python, Django and Tastypie
I am building a web-service which might be heavily loaded by users in future, So I need to understand clearly how the scalability works. I use Python + Django, and Tastypie as a RES-API framework. The question is: Who of this technologies is responsible for creation of thread(s) for each user ? Is new thread generated for each http request, or it is managed by "session" for the user ? I didn't find this information in google or in Tastypie documenScalability in Python, Django and Tastypie.tation. -
making Django slug and id working together?
I want my URL contain both id and slug like Stackoverflow, but slug is not working probably and instead of being like this www.example.com/games/155/far-cry-5 the URL is like this www.example.com/games/155/<bound%20method%20Game.slug%20of%20<Game:%20Far%20Cry%205>> my models.py : class Game(models.Model): name = models.CharField(max_length=140) def slug(self): return slugify(self.name) def get_absolute_url(self): return reverse('core:gamedetail', kwargs={'pk': self.id, 'slug': self.slug}) my views.py : class GameDetail(DetailView): model = Game template_name = 'core/game_detail.html' context_object_name = 'game_detail' My urls.py : path('<int:pk>/<slug>', views.GameDetail.as_view(), name='gamedetail') thanks -
python how to display variables in the url
I have created y,x a map using leaflet and defined default zoom, x, y as variables: How can I create my url based on this parameters ? var center_x = 42.21526; var center_y = 20.74148; var map_zoom = 13; var map = L.map('map', { center: [center_x , center_y], zoom: map_zoom }); url(r'^$', MapView.as_view(template_name="index.html")), -
Dockerized Nginx, Domain not working properly
I managed to dockerized my django app. With docker-compose I can run django,postgresql and nginx but Nginx not working well. I can access my app and it works fine but when I tried to connect to my domain, always work at port 8000. I want to run my app at testapp.org but I can only access wtih testapp.org. How can I solve this? What changed do I need to use in my configuration file? Did I missed something? docker-compose: version: '3' services: db: container_name: db.postgres image: postgres:10 environment: - POSTGRES_DB=testdb - POSTGRES_USER=test - POSTGRES_PASSWORD=password ports: - '5432:5432' volumes: - ./pgdata:/var/lib/postgresql/data web: restart: always build: . image: djangoapp command: bash -c "python manage.py makemigrations && python manage.py migrate && gunicorn fatihkocnet.wsgi -b 0.0.0.0:8000" depends_on: - db volumes: - ./fatihkocnet:/fatihkocnet - ./config/nginx:/etc/nginx/conf.d expose: - "8000" nginx: restart: always image: nginx:latest ports: - "8000:8000" volumes: - ./fatihkocnet:/fatihkocnet - ./config/nginx:/etc/nginx/conf.d depends_on: - web nginx/test.conf upstream web { ip_hash; server web:8000; } # portal server { location / { proxy_pass http://web; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; } listen 8000; server_name testapp.org; } -
Image not uploading in Django
I have uploaded an image in admin portal but it is not rendering in html template how can i solve this? below are the source codes! models.py from django.db import models from django.contrib.auth import get_user_model from PIL import Image class Question(models.Model): question_relation=models.ForeignKey('Answer',related_name='ques',on_delete=models.CASCADE) question_image=models.ImageField(upload_to='media/') text=models.TextField(blank=True,max_length=100) def __str__(self): return str(self.question_relation) html file <div style="margin-left:35%;margin-right:35%"> <img src="{{question.question_image.url}}" alt=""> i have included these in my urls.py urlpatterns += staticfiles_urlpatterns() urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) on checking the inspect element in img src it appears as (unknown). i dont know why it is not able to pick up the url of image settings.py MEDIA_URL="/media/" MEDIA_ROOT=os.path.join(BASE_DIR,'levels/media') -
Class refactoring advice
I have a class that prepares new team, based on data that Slack sends me. I'm bothering that this class became tigthly coupled to three Django models such as SlackTeam, SlackBot and SlackUser. Is there a way to refactor this? Should I move some code from initialize method to separate methods? How can I make this class easy to test? class TeamInitializer: def __init__(self, access_data): self.team_id = access_data['team_id'] self.team_name = access_data['team_name'] self.bot_user_id = access_data['bot']['bot_user_id'] self.bot_access_token = access_data['bot']['bot_access_token'] self.user_id = access_data['user_id'] self.access_token = access_data['access_token'] def create_team(self): team, _ = SlackTeam.update_or_create( {'id': self.team_id, 'name': self.team_name}) return team def create_bot(self, team): bot, _ = SlackBot.update_or_create( self.bot_user_id, self.bot_access_token, team) return bot def initialize(self): team = self.create_team() self.create_bot(team) client = get_client_by_team_id(self.team_id) team_info = get_team_info(client) team.update_info(team_info) users = get_users_list(client) team.update_members(users) initiator = SlackUser.get_by_ids(self.team_id, self.user_id) initiator.access_token = self.access_token initiator.save(update_fields=['access_token']) team.initiator = initiator team.save(update_fields=['initiator']) return team -
How to store json from request directly into mongo database
I would like to store json from request body directly into mongo collection without creation of specific model in django. I cannot create it because specific fields in json may change and new ones can be introduced, so I would like rather to store it as it is without this abstraction layer. Is it possible? -
fetching data using query from a particular table and showing it in admin side of django
hey am working on Django framework project ,see i want to fetch data from particular table and show it in the admin side,can anyone help me out. Am having a company model which i have registered in admin using admin.site.register(Company,Company_Admin) now i want to just get all the company after querying it from company table and just show the result in admin side class Company(models.Model): name=models.CharField(default=None,max_length=200) description=models.TextField(default=None) url=models.CharField(max_length=200) published=models.BooleanField() createdOn=models.DateTimeField(default=datetime.utcnow) updatedOn=models.DateTimeField(default=datetime.utcnow) keywords=models.ManyToManyField(Keyword) def __unicode__(self): return self.text class CompanyAdmin(admin.ModelAdmin): list_display= ['name','url','description','published','createdOn','updatedOn'] list_filter = ['name'] search_fields = ['name'] filter_horizontal=('keywords',) admin.site.register(Company,CompanyAdmin) now i want to create a option in admin which will give show me all the companies which are published. -
How can i duplicate obj in response in obj in date range
I have a Model Event like this { "id": 1, "name": "Event1", "start_date": "2018-09-14 14:22:00", "end_date": "2018-09-15 14:22:00", } { "id": 2, "name": "Event2", "start_date": "2018-09-15 14:22:00", "end_date": "2018-09-15 15:22:00", } I need to return response group_by date and If Event duration (end_date, start_date) took 2 days so i need return him twice in two days. So response should look like this: { "2018-09-14": [ { "id": 1, "name": "Event1", "start_date": "2018-09-14 14:22:00", "end_date": "2018-09-15 14:22:00", }], "2018-09-15": [{ "id": 1, "name": "Event1", "start_date": "2018-09-14 14:22:00", "end_date": "2018-09-15 14:22:00", }, { "id": 2, "name": "Event2", "start_date": "2018-09-15 14:22:00", "end_date": "2018-09-15 15:22:00", }] } How can i do this? -
BooleanField acts strange In django v2.1
Hello Why is django BooleanField(default=False) return true when printed out in the console? eg: class Themodel(models.Model): status = models.BooleanField(default=False) doing: print(status) returns True Am I confused or is something wrong here? -
Transfer and application of heroku input data
I want to deploy one django python project in heroku, but have troubles in the transfer and application of the inputs data from the visitors. Sorry that if my question is kind of foolish or too easy. The web contains the topic and entries section for visitors to give inputs (the setting.py are provided as followed). def topics(request): topics = Topic.objects.filter(owner=request.user).order_by("date_added") context = {"topics": topics} return render(request, "learning_logs/topics.html", context) @login_required def topic(request, topic_id): topic = Topic.objects.get(id=topic_id) entries = topic.entry_set.order_by("-date_added") context = {"topic": topic, "entries": entries} return render(request, "learning_logs/topic.html", context) @login_required def new_topic(request): if request.method != "POST": form = TopicForm() else: form = TopicForm(request.POST) if form.is_valid(): new_topic = form.save(commit=False) new_topic.owner = request.user new_topic.save() form.save() return HttpResponseRedirect(reverse("learning_logs:topics")) context = {"form": form} return render(request, "learning_logs/new_topic.html", context) @login_required def new_entry(request, topic_id): topic = Topic.objects.get(id=topic_id) if request.method != "POST": form = EntryForm() else: form = EntryForm(data=request.POST) if form.is_valid(): new_entry = form.save(commit=False) new_entry.topic = topic new_entry.save() return HttpResponseRedirect(reverse("learning_logs:topic", args=[topic_id])) context = {"topic": topic, "form": form} return render(request, "learning_logs/new_entry.html", context) Here's the model.py for class Topic and Entry. class Topic(models.Model): text = models.CharField(max_length=200) date_added = models.DateTimeField(auto_now_add=True) owner = models.ForeignKey(User, on_delete=models.CASCADE) def _str_(self): return self.text class Entry(models.Model): topic = models.ForeignKey(Topic, on_delete=models.CASCADE, related_name="entries") text = models.TextField() date_added = models.DateTimeField(auto_now_add=True) … -
Passing django variables to javascript
I'm having a difficult time passing variables from the python backend to javascript. A lot of my variables look like this in javascript: if ('{{ user.has_paid_plan}}' == 'True') { isPayingUser = true; } else { isPayingUser = false; } It's ugly and I'm sure there's a much cleaner way to do this. How should this be done? -
How django implements single-user login
I use the session to record user login information and how to implement single-user login. -
Write django URL in 2.12
How to pass for /api/users?page=1&limit=10&name=James&sort=-age like this in URL.py file extract these parameters value in below class Class DetailsView(generics.RetrieveUpdateDestroyAPIView): serializer_class = UserDetailSerializer get these parameters value RetrieveUpdateDestroyAPIView class. -
Django Webtest create integration test for formset
I've got a page with a formset, that consists of three forms, each of them possessing a hidden input with a predefined value, and several textareas for the each one of the form. On the front end the formset is a single <form> tag with tabs inside. I can successfully retrieve data from the each form in the formset and post it to server. The problem goes that I need to write an integration test, where I could visit the page, fill out the form and submit it, to later check that form.cleaned_data has the correct and necessary values. Here go my templates edit.html <form action="{% url 'my_model/edit', my_model.pk" id="my_formset", method="post"> {% csrf_token %} {% for form in formset %} {# here we render hidden inputs #} {% for hidden in form.hidden_fields %} {{ hidden }} {% endfor %} {# and here go the visible ones #} {% for field in form.visible_fields %} <div class="form-field-wrapper"> {% render_field field required=False disabled=read_only %} </div> {% endfor %} {% endfor %} </form> And here comes the field that is rendered with render_field: textarea.html <div class="form-field"> <label for="field.id_for_label">{{ field.label }}</label> <textarea id="{{ field.id_for_label }}" name="{{ field.html_name }}"> {{ field.value|default:"" }}</textarea> </div> This is my … -
Configure email on Django 2
I am trying to send email from django using SMTP email backend. Here are my configurations: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'mail.mydomain.com' EMAIL_PORT = 587 EMAIL_HOST_USER = 'no-reply@rmydomain.com' EMAIL_HOST_PASSWORD = '***********' EMAIL_USE_TLS = True DEFAULT_FROM_EMAIL = 'no-reply@mydomain.com' I have two problems: Everything was working fine when i was sending email using gmail but can not send email using above configurations. Secondly, i want to use POP3 as incoming email port and SMTP 26 as outgoing email port. But how can i add this to my configurations. Django's official documentation does not contain anything on this. -
Call two different urls from a form or input submit button Django
I have a form in which I have a table.In table I have a record(title).Now along with title I have two buttons delete and edit.Now I want is that, if I click edit it calls separate url along with primary key going through it or if I click delete It calls separate url with primary key going through. here's my code: <form method="POST" action="{% url 'essay:delete_view' teacher.id %}"> <div class="page-header"> <div class="span4"> <h1>Manage Essays</h1> </div> </div> <table> <tr> <th>Title</th> <th>Edit</th> <th>Delete</th> </tr> {% csrf_token %} {% for uploadassignment in teacher.uploadassignment_set.all %} <tr> <th for="uploadassignment{{ forloop.counter }}">{{uploadassignment.id}}</th> <th><input type="submit" id="Editthis" value="{{uploadassignmentEdit.id}}" class="btn btn-primary"/></th> <th><input type="submit" id="uploadassignment{{ forloop.counter }}" value="{{uploadassignment.id}}" name="uploadassignment" class="btn btn-primary"/></th> </tr> {% endfor %} </table> </form> I want this: one url is called by below (Edit button) with teacher.id <th><input type="submit" id="Editthis" value="{{uploadassignmentEdit.id}}" class="btn btn-primary"/></th> And another url is called when hit delete button with teacher id. <th><input type="submit" id="uploadassignment{{ forloop.counter }}" value="{{uploadassignment.id}}" name="uploadassignment" class="btn btn-primary"/></th> So far due to action ="{% url 'essay:delete_view' teacher.id %}" in form I can switch to only one url.Kindly help in my code so I can switch to different urls with teacher id when clicked on delete or edit button. -
move and copy table data to another table data
We have 3 tables(models) A,B and c.Table 'A' have data, if we delete the specific table data of 'A' then that deleted data i want to save in table 'B' automatically and if we added the data in table 'C' we want that data is also added in table 'A' automatically. Please help me. Thank you -
Create circle from Leaflet circle layer to save with GeoDjango in a PostGIS database
As the title indicates, I am trying to create a circle in Leaflet and send it to a GeoDjango backend to save it. But, since circles aren't part of the GeoJSON specification, I am turning it into a polygon with circle = center.buffer(radius), which creates a multi-sided polygon which I will use as a circle. There seem to be a couple problems with this approach: Doing a buffer results in a distortion thanks to the curvature of the Earth and the projections that its doing automatically, turning my circle into an oval. How do I avoid that? What units does the GeoDjango buffer take its radius in? And how do I match the units that Leaflet sends with the units that GeoDjango uses to create its buffer? Ultimately, I just want to be able to define a point and a radius with Leaflet and turn that into a multiple sided polygon that looks almost identical and save it to the PostGIS database. Thanks a lot in advance for the help.