Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is there any way convert Django model queryset to json or json string in template?
I want to combine react (or vue) with django template, but I don't want to change the backend to restful api. So I wonder is there any way convert Django model queryset to json or json string in template, so that I can fetch the data from dom used in jsx or vue. -
Django build a DRF frontend page
I've made an API, and it works fine as API: view.py class TestView(viewsets.ModelViewSet): """ test rest""" queryset = models.Pippo.objects.all() serializer_class = PippoSerializer renderer_classes = (JSONRenderer,) template_name = 'pippo_app/test.html' url.py app_name = 'pippo_app' router = routers.DefaultRouter() router.register(r'ertest', views.PippoView) now I need an HMTL frontend to this API: class Manage(TemplateView): """test HTML frontend """ template_name = 'label_app/label_MAN_form.html' def get_context_data(self, **kwargs): context = super(Manage, self).get_context_data(**kwargs) context['prova'] = serializers.PippoSerializer() return context with this template.html {{prova}} I can see data form serializer. This is the correct approach? Are there better way without setup a frontend framework as angular, to manage the web frontend inside django? -
how to fetch youtube search videos from python Django using API's?
urls.py urlpatterns = [ url(r'^search/$',views.search, name='search'), url(r'^get_videos/$',views.get_videos, name='get_videos'), ] views.py def search(request): return render(request,'search.html') def get_videos(): if request.method == 'POST': Api_key = "my key here" #i have key search_list_url = "https://www.googleapis.com/youtube/v3/search" #what is the code to be added? return render(request,'display.html') Template <form action="/get_videos/" method="post">{% csrf_token %} <h1>Search for Top Youtube Videos Here</h1> <input type="text" id="search" placeholder="search here" required="required" /> <button type="submit">Search</button> </form> Basically i want to fetch youtube results for queried keyword through my template seach button only through Api (not through beautiful Soup), i know how to do it through scarpy, but need help regarding API , TIA. -
Selecting foreign keys in Django REST Framework's Browsable API
I have a simple ForeignKey relationship between two models: class Ticket(models.Model): description = models.CharField(max_length=1000) created_by = models.ForeignKey(User, related_name="created_ticket") class User(models.Model): username = models.CharField(max_length=64, unique=True, primary_key=True) email = models.CharField(max_length=255) I have a serialiser for each, with the user serialized within the ticket as a nested serialiser. What I would ideally like is in an update view of Tickets on the Browsable API, being able to choose from a dropdown list of extant users, and when entering a username and an e-mail, the application should check if users exist with those parameters, and if so, assign them to the ticket, and if not, raise a validation error (the validation part I got working, the rest... not so much). So far, I've tried to follow overriding the update/create methods, but when I enter a code, the application always tries to create a new object, then complains that an object with the same username (the pkey) already exists. I have tried getting some sense out of the documentation on the subject, but with not much luck. -
How to make a condition with string on Django 1.9 with tags?
I wanted to know how to make a condition work with a string from the Django 1.9 template. What happens is that when I do a condition with integers, it works perfectly, but when I do a condition with a string, it does not work anymore. I do not know if I have any errors in the syntax. {% if caso.status == "Anulado" %} <a class="btn btn-primary btmargeniz" href="/historico-casos/{{caso.acciones}}" title="Detalle del caso"><i class="fa fa-file-text fa-lg"></i></a> {% else %} <a class="btn btn-primary btmargeniz" href="/historico-casos/{{caso.acciones}}" title="Detalle del caso"><i class="fa fa-file-text fa-lg"></i></a> <a class="btn btn-success btmargeniz" data-caso="{{caso.acciones}}" onclick="carga_datos(this)" data-toggle="modal" data-target="#agregar_dealer_caso" title="Agregar Dealers al Caso"><i class="fa fa-thumb-tack fa-lg"></i></a> <a class="btn btn-warning btmargeniz" onclick="carga_datos(this)" title="Anular Caso" data-toggle="modal" data-target="#ModalAnularCaso" data-caso="{{caso.acciones}}"><i class="glyphicon glyphicon-flash fa-lg"></i></a> {% endif %} -
Celery tasks should be queued on worker getting lost
I am using django-celery 3.2 and celery 3.1.25. I have added below settings - CELERY_TASK_ACKS_LATE = True task_reject_on_worker_lost = True The application results in below error and fails to load if I use celery 4.x with django-celery 3.2 ImportError: No module named vine.five Steps to reproduce Trigger some tasks, and get their pids from logs. I kill a worker(pid) at random using kill command. Expected behavior The task should come back to the queue and picked up by same or other worker. Actual behavior The task is getting lost. -
Django:Getting List of values from query set
I have the following query country=employees.objects.filter(manager_id__emp_id=111).values('emp_loc').distinct() I get Output as <QuerySet [{'emp_loc': 'IND'}, {'emp_loc': 'MLA'}]> But I need list ['IND','MLA'] How Can I do it? -
Django stacktrace not informative
When I have a bug in Django, the stacktrace usually showed only Django's internal files, not my application files (usually view.py,..) that caused the bug. How can I make Django show me the full stacktrace? -
Slug in Django URL
I need your help. I working on my own project. And I need show single news from news list.I do next steps: in model: class Notice(models.Model): notice_header = models.CharField(max_length=150, verbose_name="Notice header", blank=False) notice_content = RichTextField(verbose_name="Notice content") notice_publish_date = models.DateField(verbose_name="Publish date", default=date.today) notice_slug = models.CharField(max_length=50, verbose_name="Notice URL", blank=False, default="#", unique=True) #SEO Data seo_page_title = models.CharField(max_length=150, verbose_name="SEO Page Title", blank=True) seo_page_description = models.TextField(verbose_name="SEO Page Description", blank=True) seo_page_keywords = models.TextField(verbose_name="SEO Keywords", blank=True) class Meta: verbose_name = "Notice" verbose_name_plural = "Notice list" def __str__(self): return self.notice_header def __unicode__(self): return self.notice_header In view: from django.shortcuts import render_to_response as rtp from models import * def notice_list(request): notice_articles = Notice.objects.order_by("-id") context = {"NOTICE_LIST": notice_articles} return rtp("notice.html", context) def single_notice(request, alias): current_news = Notice.objects.get(notice_slug=alias) context = {"NOTICE_SINGLE": current_news} return rtp("notice_single.html", context) in urls: url(r'notice/', notice_list), url(r'notice/(?P<alias>[^/]+)', single_notice), I see notice list on the page. But, when I try to select single notice for reading, page reloads and single_notice function doesn't work. notice_slug in database contains chars and numbers. What I doing wrong? best regards, Alex -
How to work with Django-Scheduler and Django Rest Framework?
I am making a booking system. I have a model known as products, so products are created. Now I have create the events and rules for the product as to when and how these product are available for bookings. Like a product might be available from Monday to Friday at 1pm and 4 pm. And I need all these working with Django Rest Framework. This is the Django Scheduler. https://github.com/llazzaro/django-scheduler I am looking for a view something like this. More info about product. Its a marketplace for Activity Providers and the Agents. So I need the functionality of creating a Activity and Supplier(Activity Providers) should be able to mark on which days he is not operation and on which days the price is different, the price will be different also on the basis of the Age of the Traveller. I have integrated the django-scheduler in Django, however it is installed as a separate -
django channels change time format of datetime field
I'm new to django channels and i'm stuck at how to change the format of the datetime field in this particular binding class. class InfoBinding(WebsocketBinding): model =Info stream = "stream" fields = ["time_stamp"] @classmethod def group_names(cls, *args, **kwargs): return ["binding.values"] def has_permission(self, user, action, pk): # print(self.time_stamp) return True -
Display all model fields in template
I am trying to display all the fields of a model called company as a list in my template. But can't seem to make it work. Code <ul> {% for field in company.fields.all %} <li>{{ fields.name }}</li> {% endfor %} </ul> -
Django: How to load javascript from static files with template usage
I have a problem: in addWorkout.html: {% extends "workout/base.html" %} {% block footer %} <script type="text/javascript" src="{% static js/addWorkout.js %}"></script> {% endblock %} in base.html: {% load static %} <!DOCTYPE html> <html lang="en"> <body> {% block content %}{% endblock %} {% block footer %}{% endblock %} </body> </html> This will generate an error: Invalid block tag on line 49: 'static', expected 'endblock'. Did you forget to register or load this tag? This error stems from the src attribute of the script tag in addWorkout.html. Apparently, django doesn't allow for the static tag to be inside of a block tag. But how can I then import javascript from static by using the script-tag at the bottom of the body element? -
Python - Get all the variable in template passed from views.py render() function
Code in my views.py from django.shortcuts import render def webapppage(request): parameter = { 'key1':'hello', 'key2':['hiiii','whats up','buddy'] } return render(request, 'template2.html', parameter) How can I get both {{key1}} and {{key2}} in one single variable like (parameter) in my template file? Code inside template2.html {% for c in parameter %} `{{c}} {% endfor %} I want output like hello ['hiiii','whats up','buddy'] -
How to add/use javascript code in Django textfield in the condition that safe filter is used?
How to add/use javascript code in Django textfield in the condition that safe filter is used? I want to add some interactive charts by javascript, namely using<script>...</script>in my blog article, but all the content of the article is in the textfield of Django models. The chart can not be shown in the article, but it can be shown outside the article in the web page. What's reason for that? Please help me. -
Get current db migration status from db, not models in django
What i need is to get a migration describing the current structure in db and not what i defined in my models file because my models are not aligned to the structure of db, so i would like to get the current status and then apply my modifies defined in my models and make them aligned. Is it possible? And how? -
easy-thumbnails.. Is it a good option to use to reposition a cover profile photo?
I'm trying to add a function of repositioning a cover profile photo and I found a useful tutorial to add a cover profile into my web application that could be repositionned The backend code is in PHP and I'm working with PYTHON and Django . I have translated the server side code to python .. but things are not working as expected (maybe error when translating) I have used an Alternative for PHP GD library in python to translate some functions like imagecreatefromjpeg , imageSY , imagedestroy..etc what I noticed is that the PHP server side code is based on making a thumbnail of the original repositionned image and save it .. I wonder if easy-thumbnails package does the same thing . Do somebody worked with this plugin ? Is it a good option for my case ? Or I focus more on my code to correct the errors ? -
Running existing Django project
I've installed existing Django project very 1st time and I've the problem with starting servers python manage.py runserver Here it's what I've done 1.Clone the repo, 2.Make a virtual environment 3.Pip install requirements.txt 4.Generate access token and secret key and put in secrets.sh. I've the same SECRET_KEY in settings.py and secrets.sh and I've added secrets.sh to .gitignore 5.Change settings.py as follows: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), 'USER': 'name', 'PASSWORD': '', 'HOST': 'localhost', 'PORT': '', } } And I cannot run python manage.py migrate results below: (tag_gen) local_user@local_user:~/Repo/tag_gen/generator$ python manage.py runserver Performing system checks... Unhandled exception in thread started by <function wrapper at 0x7febe4712488> Traceback (most recent call last): File "/home/local_user/Repo/tag_gen/tag_gen/local/lib/python2.7/site-packages/django/utils/autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "/home/local_user/Repo/tag_gen/tag_gen/local/lib/python2.7/site-packages/django/core/management/commands/runserver.py", line 125, in inner_run self.check(display_num_errors=True) File "/home/local_user/Repo/tag_gen/tag_gen/local/lib/python2.7/site-packages/django/core/management/base.py", line 359, in check include_deployment_checks=include_deployment_checks, File "/home/local_user/Repo/tag_gen/tag_gen/local/lib/python2.7/site-packages/django/core/management/base.py", line 346, in _run_checks return checks.run_checks(**kwargs) File "/home/local_user/Repo/tag_gen/tag_gen/local/lib/python2.7/site-packages/django/core/checks/registry.py", line 81, in run_checks new_errors = check(app_configs=app_configs) File "/home/local_user/Repo/tag_gen/tag_gen/local/lib/python2.7/site-packages/django/core/checks/urls.py", line 16, in check_url_config return check_resolver(resolver) File "/home/local_user/Repo/tag_gen/tag_gen/local/lib/python2.7/site-packages/django/core/checks/urls.py", line 26, in check_resolver return check_method() File "/home/local_user/Repo/tag_gen/tag_gen/local/lib/python2.7/site-packages/django/urls/resolvers.py", line 254, in check for pattern in self.url_patterns: File "/home/local_user/Repo/tag_gen/tag_gen/local/lib/python2.7/site-packages/django/utils/functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/home/local_user/Repo/tag_gen/tag_gen/local/lib/python2.7/site-packages/django/urls/resolvers.py", line 405, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) … -
Djoser - User Registration - How to store non required user fields
I am using Djoser and Django Rest Framework for user registration with a custom user model. When I try to add NON REQUIRED fields to my custom user models and pass them (as **kwargs) , these additional fields do not get saved. Is this by design or is there a trick to saving these? class UserManager(BaseUserManager): def create_user(self, email, phone, password, **kwargs): user = self.model( email=email, phone=phone, **kwargs ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, phone, password, **kwargs): user = self.model( email=email, phone=phone, is_staff=True, is_active=True, **kwargs ) user.set_password(password) user.save(using=self._db) return user class User(AbstractBaseUser): userId = models.AutoField(primary_key=True) email = models.CharField(unique=True, max_length=45, null=False) phone = models.CharField(max_length=15, unique=True, null=False) password = models.CharField(max_length=255, blank=True, null=True) is_active = models.IntegerField(blank=True, null=True) class Meta: managed = False db_table = 'User' objects = UserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['phone'] def get_full_name(self): return self.email def get_short_name(self): return self.email def natural_key(self): return self.email def __str__(self): return self.email -
At which point in UpdateView is the data saved?
I was wondering when the data given to the UpdateView was saved. I have the following situation: I update a model object via a form. I would expect the changes to the model only to be saved after the Update View's form_valid is through. But when I print the object attributes right at the start of form_valid, they have already changed to the new ones inserted into the form. So when exactly is the change to the model saved and how would I go about if I wanted to do something with the previous values? I am relatively new to Django and I hope that this question is not too far off track. -
Django-helpdesk "Reverse for 'auth_password_change' not found"
I am trying to enable users to change their passwords in django-helpdesk. In the docs, this is done by adding this to settings.py: HELPDESK_SHOW_CHANGE_PASSWORD = True Doing so results in the following error: NoReverseMatch at /helpdesk/tickets/ Reverse for 'auth_password_change' not found. 'auth_password_change' is not a valid view function or pattern name. And points to line 75 in python2.7/site-packages/helpdesk/templates/helpdesk/navigation.html which reads: <li><a href="{% url 'auth_password_change' %}"><i class="fa fa-user-secret fa-fw"></i> {% trans "Change password" %}</a></li> Is this a Django-helpdesk bug or am I missing something? -
Django DRF TemplateHMLRenderer
Trying to display the django rest framework data in an html template: view.py class TestView(viewsets.ModelViewSet): """ test rest""" queryset = models.Pippo.objects.all() serializer_class = PippoSerializer renderer_classes = (JSONRenderer, TemplateHTMLRenderer) template_name = 'pippo_app/test.html' url.py app_name = 'pippo_app' router = routers.DefaultRouter() router.register(r'ertest', views.PippoView) template.html {% load rest_framework %} <html><body> <h1>Profile - {{ dim_spessore }}</h1> {{form}} {% load rest_framework %} <form action="{% url 'pippo_app:pippo-list' %}" method="post"> {% csrf_token %} {% render_form serializer%} <input type="submit" value="Save" /> </form> </body></html> result in : builtins.AttributeError AttributeError: 'str' object has no attribute 'data' the Json call works: Response 200 Status: Ok -
How to update database courses in openedx
I am trying to update my database entries. after restoring sql file, it is showing in database. but not updated in openedx site (lms /cms). also in home page it shows old entries. How can i update gui entries?? -
django on_delete
I have two models in django Photos and Posts (foreign key between them). post = Posts.objects.get(pk=1) post.delete() # all photos is deleted. cascade delete. it's fine but when I want delete from pgadmin DETAIL: Key (id)=(1) is still referenced from table "photos". why I can not delete from pgadmin ? -
How to get multiple places names in Google Places API?
In my Django project, I let users to mark in which city they were recently. I use for this Google Places API - autocomplete with map. I have multiple use cases which I can't figure out to work with Google Places API T&C and this is one of them: There is a filter of users. Each user have chosen their last visited place (so I can store place_id). When user filtered 100 users, they are showed one by one by their cards in results. The card should contain the user's last visited place. So I have to show 100 cards with 100 places (cities). How to do that if I have only place_id's? Should I send 100 detail requests to Google Places API to get name of each city? def user_filter(request): filtered_users = .... for user in filtered_users: api_result = request.get('https://maps.googleapis.com/maps/api/place/details/json?placeid=ChIJN1t_tDeuEmsRUsoyG83frY4&key=MY_API_KEY') recent_city_name = parse_from_result(api_result) .... return render(request,....) Although this should teoretically work, it is a big overkill - time consuming and API requests consuming. Is there a better way to do that? I didn't find any bulk request option.