Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Creating a web app: Should I use an API or the JSON dataset file?
so I'm new to web development, and I want to create UofT web application where the client is able to Select a campus --> Select a department --> Search the course --> etc. Kinda like these http://fillme.org/ or http://findacourse.ca/index.php. (Obviously the premise behind my web app will be different, but will have the same functionality in terms of searching for courses.) With that said, I found an API ( https://cobalt.qas.im/ ) that is able to return the information I need in JSON format. In addition, the API has a github with the all of the courses from all three campuses stored in a JSON file so I guess I don't really need to use the API. My question is: In terms of practicality, should I use that API to access that information every time a client uses the webapp or download the JSON file that contains all of the information I need and somewhat figure out how to access it in the web app? My thoughts I've seen tutorial videos of how API's work, however, I'm more concerned about the number of requests I can make. Also, if this web app becomes public and deployed to my website, I'm guessing … -
Django testing - how to create files
Upon python manage.py test, Django creates a temporary database schema which is deleted after the tests are finished. However, some of the requests I am testing via the Client class should create files. However, in the testing mode, Django just seems to refuse to create those. How to force it to do so? And ideally, they shall be deleted automatically afterwards along with the database schema. -
How do i loop through a drop down model form field to display only some values in django
So i have 4 choices target = (('Week', 'Weekly target'), ('Day', 'Daily target'), ('Verify', 'Verify'), ('Done', 'Done')) and this is my model to implement the choices class GoalStatus(models.Model): target = models.CharField(max_length=100, choices=target, default="Week") name = models.ForeignKey(ScrummyUser, on_delete=models.CASCADE) goal_status = models.ForeignKey(ScrummyGoals, on_delete=models.CASCADE) This is my Model form class ChangeTaskForm(forms.ModelForm): class Meta: model = GoalStatus fields = '__all__' and this is my html file {% if user.is_authenticated %} {% if request.user|has_group:"ADMIN" %} <form action="{% url 'myapp:move_goal' %}" method="post"> {% csrf_token %} {% for field in form.data.target %} {% for foo in field %} {% if foo == Day %} {{ foo }} {% endif %} {% endfor %} {% endfor %} </form> How do i iterate through the drop down list in my form to display only a desired choice say 'Day'for a user that has permission to choose only 'Day'. i am very new to django and on a deadline to complete a task -
Freezegun always causes RuntimeWarning of receiving naive datetime
I'm working with a testcase where an organization can be suspended. Currently I'm using freezegun to freeze a firm time, which is a datetime.datetime object with tzinfo=pytz.UTC. In the test below you'll see a print of self.fake_datetime which returns a tzaware datetime: 2000-01-01 00:00:00+00:00. When the test runs, I keep getting the famous RuntimeWarning: /usr/local/lib/python2.7/dist-packages/django/db/models/fields/init.py:1447: RuntimeWarning: DateTimeField Organization.suspended received a naive datetime (2000-01-01 00:00:00) while time zone support is active. RuntimeWarning) import datetime import pytz from freezegun import freeze_time # crop class OrganizationSuspendTestCase(TestCase): def setUp(self): self.organization = OrganizationFactory() self.fake_datetime = datetime.datetime(2000, 1, 1, 0, 0, 0, tzinfo=pytz.UTC) print self.fake_datetime def test_suspend_organization(self): """ Case: An organization is being suspended with the suspend service. Expected: The organization is updated with the suspending datetime and the reason. """ with freeze_time(self.fake_datetime): mc_organization.services.organization.suspend(organization=self.organization, reason="Did not pay the bill") self.assertEqual(self.organization.suspended, datetime.datetime(2000, 1, 1, 0, 0, 0)) I've been playing around with the freezegun timezone examples without any success to remove the runtime warning. Any suggestions on how this should be resolved properly? I'd like to keep using Freezegun for this without a RuntimeWarning. Suppressing is an option, but I'd prefer not to. -
Unexpected behaviour with django debug false
I am using pygithub for sending the code to GitHub repo using my web app. First of all, I take the path of the repository. After that, I run the commit on the code and finally push the code. Here are the code samples of committing and pushing. from git import Repo repo = Repo('some_git_repo_path') try: repo.git.commit('-am', 'some commit message') except Exception: pass repo.git.push('origin', 'master') The code works when I am calling it from python shell or using runserver but when I am using this in the production environment the code is not getting pushed or committed. I have given the permission to my current user for the directory using the following command. sudo chown -R me:me directory Please help me with this. Thanks in advance. -
Django queryset based on input type
on Django 1.9, I have a form that allows the user to filter models based on their input: def get_queryset(self): cvs = Clean.objects.all() query = self.request.GET.get('q') if query: cvs = cvs.filter(Q(cvscore__gte=query)).distinct() cvs = cvs.order_by('cvscore') return cvs I want them to be able to search for a string also and have tried: cvs = cvs.filter(Q(cvscore__gte=query) | Q(cv__icontains=query)).distinct() The problem with this is if the input is a str, an error will be thrown: invalid literal for int() with base 10: Is there a way around this? Something like: def get_queryset(self): cvs = Clean.objects.all() query = self.request.GET.get('q') if query **is an integer**: cvs = cvs.filter(Q(cvscore__gte=query)).distinct() cvs = cvs.order_by('cvscore') else: cvs = cvs.filter(Q(cv__icontains=query)).distinct() return cvs -
Django AWS MySQL Database Issues
I am new to learning Django, and for a project, I need to connect a MySQL Database (using AWS RDS Database) to my app. I've been following the tutorial, but I've been having an issue with 'RDS_HOSTNAME' not being in os.environ (my RDS_HOSTNAME is specific to my database on AWS). I don't think this if statement is true: if 'RDS_HOSTNAME' in os.environ: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': os.environ['RDS_DB_NAME'], 'USER': os.environ['RDS_USERNAME'], 'PASSWORD': os.environ['RDS_PASSWORD'], 'HOST': os.environ['RDS_HOSTNAME'], 'PORT': os.environ['RDS_PORT'], } } But I don't know why (could it be my requirements.txt, which is Django==1.9.12 MySQL-python==1.2.3 (my engine is MySQL 5.6.39) Or could it be something else like one of my .configs? Thank you! -
Submitting two forms at once in Django
I'm working on a ListView which includes two forms, a search form and a filter form. Both of the forms ultimately change the view's queryset through its get_queryset method. I would like to make it such that when you search for something, the filters are persisted, and vice versa. It is more-or-less working, but there is still one bug: whenever I search for something, a 'CLEAR FILTERS' button appears which should not be there: In the template, the search form is included like so: {% block search_form %} {% with action='dashboard:families' placeholder='Search Families' %} {% include '_search.html' %} {% endwith %} {% endblock %} where _search.html is {% load get %} <form action="{% url action %}" method="get" class="left search col s6 hide-on-small-and-down" novalidate> <div class="input-field"> <input id="search" placeholder="{{ placeholder }}" autocomplete="off" type="search" name="q" value="{{ search_form.q.value.strip|default:'' }}" data-query="{{ search_form.q.value.strip|default:'' }}"> <label for="search" class="active"><i class="material-icons search-icon">search</i></label> <i data-behavior="search-clear" class="material-icons search-icon" {% if not search_form.q.value %}style="display: none;"{% endif %}>close</i> </div> {% if filter_form %} {% for field in filter_form %} <input type="hidden" name="{{ field.name }}" value="{{ request.GET|get:field.name }}"/> {% endfor %} {% endif %} </form> and the custom filter get simply implements the dict.get method: from django import template register = template.Library() @register.filter … -
Failed load PDF from file DJANGO using embed tag
Im trying to load a PDF My .html <div class="container"> <div class="row"> <div class="col-lg-12"> <embed src="../uploads/{{ documento.adjunto }}" type="application/pdf" width="100%" height="600px" /> </div>> </div> </div> Where documento.adjunto its the url where the document its saved (in my case "curriculums/CV_2017.pdf") It throws me Failed to load resourse: 404 not found http://127.0.0.1:8000/INTRANET/uploads/curriculums/CV_2017.pdf But there is where the PDF is saved -
Celery task not run at the specified time
I created celery task and it should start each hour in 0 minutes. But it not run, I make according to documentation. What doing wrong? celery from __future__ import absolute_import, unicode_literals import os import pytz from celery import Celery from datetime import datetime from celery.schedules import crontab os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'app.settings') app = Celery('app', broker='amqp://rabbit:5672') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() @app.on_after_configure.connect def setup_periodic_tasks(sender, **kwargs): sender.add_periodic_task(crontab(minute=0, hour='0,1,2,3,4,5,6,7,8,9,10,11,12, \ 13,14,15,16,17,18,19,20,21,22,23,24'), task.s()) @app.task def task(): #any code In terminal i see this info, but task not run [2018-05-09 19:05:16,275: INFO/Beat] beat: Starting... -
Display a docx file on the screen
I created a ms-word document using MailMerge in django. It´s worked ok. Right now, i´d like to show this file on screen. I write the code bellow, but it didn´t work. views.py with open(file_path) as doc: response = HttpResponse(doc.read(), content_type='application/ms-word') response = HttpResponse(template_output) response['Content-Disposition'] = 'attachment;filename=var_nomdocumento_output' error: [Errno 13] Permission denied: 'C:\\GROWTHTECH\\Projetos\\blockchain\\media_root/procuracao' -
Django model validate a ManyToMany field before adding
I have a model that looks somewhat like this: class Passenger(models.Model): name = models.CharField(max_length=50) surname = models.CharField(max_length=50) class Flight(models.Model): capacity = models.IntegerField() passengers = models.ManyToManyField(Passenger) Before adding a new passenger to the flight I would like to validate whether the number of passengers is not going to exceed the capacity. I was wondering what would be the best way to go about this. Obviously I could manually check the number of passengers before adding a new one, but maybe there is some support in django? I tried writing a validator, but wasn't sure how to do it. -
Error to create formset factory using django
I'm trying to use two formset_factory in the same view, but I'm getting this error [DOM] Found 2 elements with non-unique id #id_form-TOTAL_FORMS: When I try to put a prefix on the second form it just generates one id then if add more than one item it will save the last item. I would like to know how to fix this problem and why it happened ? thanks in advance. my forms.py class ResearchLineForm(forms.ModelForm): class Meta: model = ResearchLines fields = ('title', ) widgets = { 'title':forms.TextInput(attrs={ 'class':'form-control', 'placeholder':'Linhas de Pesquisa' }) } LinesFormSet = formset_factory(ResearchLineForm) class TokenForm(forms.Form): name = forms.CharField( max_length=255, widget=forms.TextInput( attrs={ 'class':'form-control', 'placeholder':'Linhas de Pesquisa' }) ) email = forms.CharField(max_length=255, widget=forms.TextInput( attrs={ 'class':'form-control', 'placeholder':'Linhas de Pesquisa' }) ) TokenFormSet = formset_factory(TokenForm) my view.py def ubc_register(request): if request.method == "POST": ubc = Ubc() form = UbcForm(request.POST) tokenformset = TokenFormSet(request.POST, request.FILES) formset = LinesFormSet(request.POST, request.FILES) if form.is_valid(): ubc.name = form.cleaned_data['name'] ubc.laboratory_departament = form.cleaned_data['laboratory_departament'] ubc.partner_category = form.cleaned_data['partner_category'] ubc.parent_institution_name = form.cleaned_data['parent_institution_name'] ubc.coordinator = form.cleaned_data['coordinator'] if "phone" in form.cleaned_data: ubc.phone = form.cleaned_data['phone'] if "email" in form.cleaned_data: ubc.email = form.cleaned_data['email'] if "cnpj" in form.cleaned_data: ubc.cnpj = form.cleaned_data['cnpj'] if "rad_operating_time" in form.cleaned_data: ubc.rad_operating_time = form.cleaned_data['rad_operating_time'] if "rh_count" in form.cleaned_data: ubc.rh_count = form.cleaned_data['rh_count'] if "website" … -
Cassandra Celery python timeout happens on raw query execution using django db connection execute
My celery is configured for the Cassandra session like this: def cassandra_init(*args, **kwargs): """ Initialize a clean Cassandra connection. """ if cql_cluster is not None: cql_cluster.shutdown() if cql_session is not None: cql_session.shutdown() connection.setup([settings.DATABASES["default"]["HOST"],], settings.DATABASES["default"]["NAME"]) # Initialize worker context (only standard tasks) worker_process_init.connect(cassandra_init) When I am executing a raw cassandra query, timeout happens, from django.db import connection cursor = connection.cursor() total_ap = cursor.execute( "SELECT cpu_info FROM ap_live_stats;") It works well all over in my django project but not inside the celery tasks. Error: [2018-05-09 18:50:21,576: ERROR/ForkPoolWorker-5] Task apps.statistic.tasks.ap_hourly_data_migrator[77a596d4-61a2-43f4-8580-6abc6e9b5866] raised unexpected: OperationTimedOut("errors={'192.168.98.65': 'Client request timeout. See Session.execute[_async](timeout)'}, last_host=192.168.98.65",) Traceback (most recent call last): File "/home/vkchlt0079/virtuals/wlc-env/lib/python3.5/site-packages/celery/app/trace.py", line 374, in trace_task R = retval = fun(*args, **kwargs) File "/home/vkchlt0079/virtuals/wlc-env/lib/python3.5/site-packages/celery/app/trace.py", line 629, in __protected_call__ return self.run(*args, **kwargs) File "/home/vkchlt0079/projects/hfci_wlcd/src/web_gui/backend/django/hfci_wlcd/apps/statistic/tasks.py", line 59, in ap_hourly_data_migrator "SELECT cpu_info FROM ap_live_stats;") File "/home/vkchlt0079/virtuals/wlc-env/lib/python3.5/site-packages/django_cassandra_engine/utils.py", line 47, in execute return self.cursor.execute(sql) File "/home/vkchlt0079/virtuals/wlc-env/lib/python3.5/site-packages/django_cassandra_engine/connection.py", line 12, in execute return self.connection.execute(*args, **kwargs) File "/home/vkchlt0079/virtuals/wlc-env/lib/python3.5/site-packages/django_cassandra_engine/connection.py", line 86, in execute self.session.set_keyspace(self.keyspace) File "cassandra/cluster.py", line 2448, in cassandra.cluster.Session.set_keyspace (cassandra/cluster.c:48048) File "cassandra/cluster.py", line 2030, in cassandra.cluster.Session.execute (cassandra/cluster.c:38536) File "cassandra/cluster.py", line 3844, in cassandra.cluster.ResponseFuture.result (cassandra/cluster.c:80834) cassandra.OperationTimedOut: errors={'192.168.98.65': 'Client request timeout. See Session.execute[_async](timeout)'}, last_host=192.168.98.65 Tried to increase the timeout, but not working and not sure, where it is to … -
How can I filter a ManyToManyField against the current User in the Browsable API in DRF?
I have 2 models, Todo and a Tag. Todo has a ManyToMany relationship with Tag. When adding new Todos from the Browsable API, I want to be able to see only the Tags added by the current user as the available options in the multiselect. Currently, it shows all the added Tags, irrespective of who added them. I want to limit the options to only show the Tags added by the current user. (Authentication is setup already) The models: class Todo(models.Model): title = models.CharField(max_length=100) description = models.TextField(blank=True) created_at = models.DateTimeField(auto_now_add=True) due_at = models.DateTimeField(blank=True) updated_at = models.DateTimeField(auto_now=True) tags = models.ManyToManyField(Tag, related_name='todos') creator = models.ForeignKey(User, on_delete=models.CASCADE, related_name='todos') class Tag(models.Model): name = models.CharField(max_length=20) creator = models.ForeignKey(User, on_delete=models.CASCADE, related_name='created_tags') def __str__(self): return self.name The Serializers: class TodoGetSerializer(serializers.ModelSerializer): created_at = serializers.ReadOnlyField() updated_at = serializers.ReadOnlyField() creator = UserSerializer(read_only=True) tags = TagSerializer(many=True) class Meta: model = models.Todo fields = ('title', 'description', 'due_at', 'created_at', 'updated_at', 'creator', 'tags') class TodoCreateSerializer(serializers.ModelSerializer): #This is the one being used for a POST class Meta: model = models.Todo fields = ('title', 'description', 'due_at', 'tags') Is there some serializer field or some other way to specify which queryset to use in the Serializer? Is there another better approach? -
Django view that redirects to another domain
How to redirect to another domain with python django and pass additional informations? For example i want to redirect to https://ssl.dotpay.pl/test_payment/ and give additional informations so url will look like this https://ssl.dotpay.pl/test_payment/?id=123456&amount=123.00&description=Test but I don't want to generate url in my view, just pass the data in json or something like that. What is the way to do this? -
add query string parameter to media file in django admin form
I would like to append a version number to a javascript file defined in the Media class of a django admin form. class Media: js = ['scripts/my_file.js?v=abc1234, ] But... the url gets encoded so that the '?' becomes '%3F'. Is there any way to have django NOT encode the URL? As a side note, the reason I do this is to get the last git commit of my static files when the site loads by putting the following in my settings file: STATIC_COMMIT = check_output(['git', 'log','-n', '1','--pretty=format:%h','--', os.path.join(BASE_DIR, 'my_app/static')]).decode("utf-8").strip() Then use the following in the Media class: js = [f'scripts/my_file.js?{settings.STATIC_COMMIT}', ] If I can do this, then I will never have to manually version media files or ask users to refresh browser cache, or worst of all have the wrong javascript (or css) file run from cache. -
Django form errors (__init__() takes 1 positional argument but 2 were given)
I use Django 1.11 and python 3.6.5 . I made a model and a form for user registration. every thing seems fine except i have this error that I could not solve. init() takes 1 positional argument but 2 were given here is the model: from django.db import models class User_account(models.Model): first_name = models.CharField(max_length=64) last_name = models.CharField(max_length=64) user_name = models.CharField(max_length=128) email = models.EmailField(max_length=254, blank=False, unique=True) password = models.CharField(max_length=64) address = models.ForeignKey(Address, on_delete=models.CASCADE) here is the form: from django import forms from .models import User_account class User_accountForm(forms.ModelForm): class Meta: model = User_account fields = ['first_name', 'last_name', 'user_name', 'email', 'password', 'address'] Here is a portion of the view: from django.shortcuts import render, redirect from .models import * from django.views import View from .forms import * from django.contrib.auth import authenticate, login class User_accountFormView(View): form_class = User_accountForm template_name = 'towns/salehslist/registeration_form.html' # display a blank form def get(self, request, *args, **kwargs): form = self.form_class(None) return render(request, self.template_name, {'form':form}) the URL setting: from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^register/$', views.User_accountFormView, name='register'), -
How to handle generic ListView pagination with filtered queryset?
Code: class MyObjects(LoginRequiredMixin, ListView): model = AllObjects template_name = "my_objects.html" paginate_by = 10 def get_queryset(self, *args, **kwargs): queryset = super(MyObjects, self).get_queryset() return queryset.filter(added_by=self.request.user).order_by('-last_modified') I have a view that lists user's addings to a table. The problem is pagination is not working properly. I think it is because each time django renders the page, it filters the queryset again, causing only first 10 items to be listed. What can be done to handle this problem? Or should i not use generic view for doing such thing? -
Search query on more than one model in Django
I have two models: class City(models.Model): name = models.CharField(max_length=50, verbose_name='Qyteti') slug = models.SlugField(unique=True) class Business(models.Model): name = models.CharField(max_length=120, verbose_name='emri') slug = models.SlugField(unique=True) city = models.OneToOneField(City, verbose_name='qyteti') created = models.DateTimeField(auto_now_add=True, verbose_name='krijuar') categories = models.ForeignKey(Category, related_name='businesses', verbose_name='kategoria') user = models.ForeignKey(User, related_name='user_businesses', verbose_name='autori') geom = gis_models.PointField(u"longitude/latitude", geography=True, blank=True, null=True) I want to create a serach like yelp.com I want people to search in three different ways. One type of business in all cities. All type of businesses in one city. One type of business in one city. I've tried chain from itertools, but no results so far. I'd like to do just a simple search for now, not with external search engines. Anyone's help is appreciated. -
Dango Rest Framework: set foreign_key if condition is met
Hy, I am writing Django Rest Framework API and I will try to explain my problem on the example with 2 tables: table1 id / user_id / album table2 id / user_id / table1_id / song user_id column in both tables is for storing id of the user who created content id and user_id have unique_together condition in model definition table2 has many songs and each song can be from one album (table1) Now, when creating new song in table2 I would like to set foreign_key which will point to already named album in table1 BUT ONLY IF that album is created by the same user who is trying to create new song (if user_id from table1 and user_id from current user are the same). Else there should be no foreign_key set for that song. I am trying to set foreign_key under this condition to maintain tenant data isolation so the song from table2 could not mistakenly be connected to album from table1 if the same user didn't create both the album and then the song. I have no problems with setting foreign_key for user_id column from active user but I am stuck on this one. Thank you in advance … -
How to implement dynamic form in django with editable fields from admin?
I need to create a list of question that user will answer in the form (dropdown choices)... those questions have to be added and edited from admin side. So I guess I can create three models: Question, Answer(foreign key to question) and another one, let's say SignUp model with ManyToMany field. Maybe there Is more convenient way? -
Setting a Log file max size in Django project
I have this configuration in my project: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'file': { 'level': 'WARNING', 'class': 'logging.FileHandler', 'filename': os.path.join(BASE_DIR, 'debug.log'), }, }, 'loggers': { 'django': { 'handlers': ['file'], 'level': 'WARNING', 'propagate': True, }, }, } Now its size grows uncontrollably. Is there a way to control a size of debug.log file? What is the best way to operate with log files in Django projects? I have found similar question but I am not calling python logger directly. -
Send data via callback to a Django app
I would like to send climate data via callback to a Django app and to store it in a database. How is this best achieved? Thanks! Following an extract of my model.py from django.db import models from django.contrib.auth.models import User ... class Data(models.Model): logger = models.ForeignKey('Logger', on_delete=models.CASCADE) date = models.CharField(max_length=20) relative_humidity = models.FloatField(max_length=5) temperature = models.FloatField(max_length=5) author = models.ForeignKey(User, on_delete=models.PROTECT) class Meta: verbose_name_plural = 'data' def __str__(self): return self.logger.name -
Django - How to access prefetch_related fields?
students = Student.objects.prefetch_related('user__applications').all() students.user__applications # Error So a student has a foreign key to a User object which is associated with a list of applications. But how do I access the list of applications from the Student object?