Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Best way to organize a python project to easily access all of the modules
I know this question has been asked in a lot of places, but none of them really seem to answer my question. I am creating a standalone application in python, my current project structure is like so: Project/ utils/ log.py api/ get_data_from_api.py main.py I would like to have a set up similar to django, in which I can refer to any file by using a Project.<package> syntax. For example, if I wanted to access my log module from my get_data_from_api module, I could do something like this: get_data_from_api.py import Project.utils.log # Rest of code goes here... However, I can't seem to get that to work, even when I added an __init__.py file in the root directory. I read somewhere that I should modify my PYTHONPATH, but I would like to prevent that, if possible. Additionally, django seemed to pull it off, as I couldn't find any PYTHONPATH modification code in there. I really appreciate the help! Post Note: Where would tests fit in this file structure? I would like them to be separate, but also have access to the entire project really easily. -
In django, how to use another model data from function based views
So I have a form that updates a key_instance object with a borrower. Currently my app needs the user to enter the name of the borrower, but I want it to display a dropdown list of data from another model the user model to select from, is there anyway to do this in a class based view? Here are my views.py and my template views.py def submit_key_request(request, pk): """ View function for renewing a specific keyInstance by admin """ key_inst=get_object_or_404(KeyInstance, pk=pk) # If this is a POST request then process the Form data if request.method == 'POST': # Create a form instance and populate it with data from the request (binding): form = UpdateKeyForm(request.POST) # Check if the form is valid: if form.is_valid(): # process the data in form.cleaned_data as required (here we just write it to the model due_back field) key_inst.is_requested = True key_inst.status = 'r' key_inst.date_requested = datetime.date.today() key_inst.borrower = form.cleaned_data['borrower'] key_inst.save() # redirect to a new URL: return HttpResponseRedirect(reverse('all-available-keys') ) # If this is a GET (or any other method) create the default form. else: form = UpdateKeyForm(initial={'borrower': 'N/A'}) return render(request, 'catalog/keyinstance_request_update.html', {'form': form, 'keyinst':key_inst}) template {% extends "base_generic.html" %} {% block content %} <div class="wrapper"> <div … -
Pycharm helpers path
I am using Pycharm pro edition and I have set up a vagrant interpreter which works perfectly. I am trying to see from Pycharm all the libraries, and frameworks that I have installed in my vagrant, but not in my windows. For example, Django. I am not able to find admin templates from django in Pycharm. These templates (as the rest of the libraries) are at library folder at: /usr/local/lib/python3.6/dist-packages For example: /usr/local/lib/python3.6/dist-packages/django The interpreter automatically set up as helpers path the path: /home/vagrant/.pycharm_helpers To solve that, I trie to create a symlink as ln -s /usr/local/lib/python3.6/dist-packages /home/vagrant/.pycharm_helpers/vagrant-packages Despite that, I am not able to see from Pycharm django framework folder, or any other library folder installed in my vagrant. How can I solve that? -
"Hot" algorithm always returns 0
I'm trying to replicate reddit's hot algortithm for sorting my posts. Here's my function: def hot(self): s = self.upvotes baseScore = log(max(s, 1)) now = datetime.now() timeDiff = (now - self.post.date).days if (timeDiff > 1): x = timeDiff - 1 baseScore = baseScore * exp(-8 * x * x) print('Final:', baseScore) #always prints 0 return baseScore basically, exp(-8 * x * x) always makes the number 0. So i'm curious how I'm supposed to make this algorithm work. Any idea? -
make one field as mandatory in two fields in django forms
I have the form field like this so how to make only one field as optional either hi or bye i need at least one field mandatory and another is optional while submitting the form django class MeForm(forms.Form): hi = forms.CharField(max_length=100) by = forms.CharField(max_length=100) -
Get objects one by one in django
I have filled 10 questions in one table of database. Whenever i print one question , all 10 questions are printed at one time. But I want , one question to be printed then that question to be answered by the user, then the next question should appear. so the next question should appear once the previous question is answered. models.py class Questions(models.Model): id = models.PositiveIntegerField(primary_key=True) question = models.CharField(max_length=500) def __str__(self): return self.question view.py def qpage(request): questions = Questions.objects.all() return render(request, 'data/quit.html', {'questions': questions}) quit.html <form class="form" method="post" action=""> {% csrf_token %} {% for q in questions %} <h3> {{ q.id }}.{{ q.question }}</h3> <input type ="text" name ="ans" id = "q1a"> {% endfor %} <button value ="Next">Next</button> </form> -
Testing Form Widget Type
I'm writing tests form a Django model form: class TemplateFieldTextForm(forms.ModelForm): class Meta: model = TemplateFieldText fields = [] def __init__(self, *args, **kwargs): super(TemplateFieldTextForm, self).__init__(*args, **kwargs) field = self.instance.template_field label = field.label or var_to_proper(field.identifier) if field.input_type == 'text_area': self.fields['text'] = forms.CharField(label=label, required=field.required, widget=forms.Textarea) else: self.fields['text'] = forms.CharField(label=label, required=field.required) I am trying to test that the correct widget for the text field gets set, like so: def test_submit_with_char_field(self): template_field = mommy.make(TemplateField, label='char_field') template_field_text = mommy.make(TemplateFieldText, template_field=template_field, award_process=self.award_process) form_data = { 'text': 'some text' } form = TemplateFieldTextForm(form_data, instance=template_field_text) self.assertEqual(form.fields['text'].widget.__class__.__name__, 'TextInput') However, the widget seems to always be the Textarea widget, rather than the default TextInput. When I check the form in the actual rendered template, the form does indeed change as expected. Any ideas as to where I am going wrong? -
How to send pdf file as an attachment in Django
I have a form where the user can ask for an document. They need to enter the name and the email address and the document will be sent to that email address. How to do that? My code is as follows: if download_form.is_valid(): ln_go = get_lang_code(request, request.GET.get('lang')) file_to_be_sent = "/assets/documents/case_study" + ln_go + ".pdf" name = request.POST.get('name') email = request.POST.get('email') msg = EmailMultiAlternatives('Het aangevraagde document', 'Geachte {0}, <br/><br />In bijlage sturen wij u het aangevraagde document door. <br /><br />Met vriendelijke groeten, <br /><br /> Het Autralis team'.format(name), 'no-reply@autralis.com', [email, ], # TO ['some-email-address@gmail.com', ]) # cc msg.content_subtype = "html" # Main content is now text/html msg.attach("case_study.pdf", file_to_be_sent, "application/pdf") msg.send() And the project tree where those documents are is as follows: I have two problems: First problem: email = request.POST.get('email') is myemail@hotmail.com, but the email has not been send to that email, the cc email address some-email-address@gmail.com get the mail but the attachment is not correct Second problem is the attachment. My attachment is 1.2MB but I do not get what it should be. I get something as follows: Any idea how to solve it? -
Uploading files and compressing them in lossless compression in django rest framework
How do I upload a file and then compress it in lossless compression ? -
Breaking For Loop Without Affecting The Data
I'm working on a website on which someone can ask a question & also answer it. This is how i'm going, class Question(models.Model): . . . . class Answer(models.Model): question = models.ForeignKey(Question) . . . Inside the template there's a question at top & below it lies all the answers. Here's how, # Question {{ question.question_text }} # It's Answers {% for answer in question.answer_set.all %} # Answer 1 # Answer 2 # Answer 3 # Answer 4 {% endfor %} What I wanna do is to insert some text after answer 1 & before answer 2 (without breaking or affecting other answers). Something like, {% for answer in question.answer_set.all %} # Answer 1 # Some Text # Answer 2 # Answer 3 # Answer 4 {% endfor %} I can't use slice because that will block other answers after answer 1. How can I do that? Thank You . . . -
Django prefetch related and exists
I am using prefetch_related when querying a model that have several m2m relationships: qs = context.mymodel_set.prefetch_related('things1', 'things2', 'things3') So that when I do this there is no need to perform an additional query to get things1, they should have been fetched already: r = list(qs) r[0].things1.all() But what if I do r[0].things1.exists()? Will this generate a new query? Or will it use the prefetched information? If it generates a new query, does that mean that going for r[0].things1.all() for the purposes of existence checking is more efficient? PS: cached information being in desync with the database does not worry me for this particular question. -
Django - assertRedirect raises error (because of language URL prefix)
Trying to create a simple test to check redirect if user is not logged in. class IndexTest(TestCase): def setUp(self): self.user = User.objects.create(username='testuser') def test_login_required(self): response = self.client.get(reverse("profiles:user_filter")) self.assertRedirects(response,urljoin(reverse("account_login"),"?next={}".format(reverse("profiles:user_filter")))) The problem is probably with internationalization. AssertionError: Couldn't retrieve redirection page '/accounts/login/': response code was 302 (expected 200) I think that it returns 302, because when user opens '/accounts/login/' they are being redirected to the same url with /en/ prefix. So the url is in fact '/en/accounts/login/'. The best would be probably to not use such prefixes in tests at all. Do you know what to do? -
Should I redirect a user, if they do not have access to a page?
I am building a "locallibrary". I have created 2 member groups: library member, and librarian . If a library member somehow comes across a staff page URL (ex: a page to view all loaned library books) and does not have the permissions that a librarian has, is it enough to just check for permissions using {% if %} and deny him access? Should I be doing anything else? This is my first time working with authentication, so I am not sure what the common practices are. My current template: {% extends "base_generic.html" %} {% block content %} {% if perms.catalog.can_view_all_borrowed %} <h1>All Borrowed books</h1> {% if bookinstance_list %} <ul> {% for bookinst in bookinstance_list %} <li class="{% if bookinst.is_overdue %}text-danger{% endif %}"> <a href="{% url 'book-detail' bookinst.book.pk %}">{{bookinst.book.title}}</a> ({{ bookinst.due_back }}) </li> {% endfor %} </ul> {% else %} <p>there are no books borrowed.</p> {% endif %} {% else %} <p>You don't have permission to access this page </p> {% endif %} {% endblock %} -
Does not work cycle "for"
I have a models.py: class Part(models.Model): Party_number = models.CharField(max_length=10) Film = models.CharField(max_length=5) viesws.py: from django.shortcuts import render from django.views.generic import ListView from description.models import Part class PartyNumView(ListView): template_name = 'part_list.html' model = Part def partList(self, request): my_var = Part.objects.all() return render(request, 'part_list.html', {"my_var": my_var}) And HTML template part_list.html: {% extends 'base.html' %} {% load staticfiles %} {% load static %} {% block activeButton %} <li class="active"><a href="/parties">Описание партий</a></li> <li><a href="/measures">Ic и QE</a></li> {% endblock %} {% block tableName %} Список партий {% endblock %} {% block content %} {% for object in my_var %} object.Party_number {% endfor %} {% endblock content%} My question is why part of code which consist cycle "for" does not working? i.e. objects of Party_number does not displayed on html page -
Are chained celery tasks guaranteed to run on the same node worker?
Are chained celery tasks guaranteed to run on the same node worker? I know that I can build a queue for dedicated tasks, however my chain of tasks involves creating png files which need to be sent to S3. The Creation of png files is a different task in the chain so if they run in different workers the next tasks might not find the png file. I don't want to build a seperate queue for it because otherwise I would need to run all the tasks in that particular queue and nowhere else. result = (process_diode.s() | plot_results.s() | send_to_s3.s()).apply_async() In the above code if the plot_results task and send_to_s3 task run in different workers than there is no guarantee that the png file will be there. Having the guarantee that all tasks inside a chain run in the same worker node is good enough for me. Is that the case? -
How to add a git clone command in Dockerfile
I would like to clone a GitHub repo through my requirements.txt in Docker. Actually the requirements file contains : -e git://github.com/USERNAME/REPO.git Django==1.11.8 .... what is the specific command that I should add in Dockerfile to execute correctly the git clone command. I tried RUN git clone git@github.com:USERNAME/REPO.git without any success. Any suggestions ? -
Django Channels: Could I know who is the sender of a message?
I'm using Django channels 2.1.1 So, this is my logic, one Websocket instance is getting messages of the same type "alarm.data" from 2 differents groups. One group "alarms" and another groupr "alarms_specific_for_user_IDUSER" Could I know where they come from whitout adding a "tag" in the text message? -
Talk about the timezone in the Django when store in the database
I created those data by the API of my Django/Django-Rest-Framework project. but there is a issue, in the database, the timezone is UTC, and my timezone is +8(Beijing Time) timezone. but when I query out the data, it still is the UTC time. How to standardizing this timezone? I surmise there are two way to do that, when store the data, timezone set to the +8. when query out the data, the time convert to +8 timezone. But both I don't know how to realize, who can tell me what's your best solution? my configurations in settings.py are bellow: LANGUAGE_CODE = 'zh-cn' TIME_ZONE = 'Asia/Shanghai' USE_I18N = True USE_L10N = True USE_TZ = True -
AWS OSError /opt/python/current/app/webpack-stats.json
I have problem with AWS+Django+React. I do this tutorial https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create-deploy-python-django.html . When i write "eb open" i have some trouble. Error 1 image Error 2 image My code: settings.py ALLOWED_HOSTS = ['django-decor-env.ffp8hmcfus.us-west-2.elasticbeanstalk.com', '*'] BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ['core/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', ], }, }, ] STATIC_URL = '/static/' STATIC_ROOT = "" STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'core/static'), ] MEDIA_URL = '/media/' MEDIA_ROOT = BASE_DIR # Webpack config WEBPACK_LOADER = { 'DEFAULT': { 'CACHE': not DEBUG, 'BUNDLE_DIR_NAME': '/', # must end with slash 'STATS_FILE': os.path.join(BASE_DIR, 'webpack-stats.json'), 'POLL_INTERVAL': 0.1, 'TIMEOUT': None, } } .exbetensions/python.config option_settings: aws:elasticbeanstalk:container:python: WSGIPath: decor/core/wsgi.py Project structure Structure I've spent so much time solving this issue... Any helpful advices would be great for me. -
Rabbitmq listener using pika in django
I have a django application and I want to consume messages from a rabbit mq. I want the listener to start consuming when I start the django server.I am using pika library to connect to rabbitmq.Proving some code example will really help. -
Unable to deploy django application on amazon linux
I am trying to deploy Django 1.11.13 based project on Amazon Linux using virtualenv. Here is my configuration for WSGI: Alias /static /var/www/cryptoapp/static <Directory /var/www/cryptoapp/static> Require all granted </Directory> WSGIDaemonProcess cryptoapp python-home=/var/www/djangoenv/lib python3.5/site-packages python-path=/var/www/cryptoapp WSGIProcessGroup cryptoapp WSGIScriptAlias /cryptoapp /var/www/cryptoapp/cryptoapp/wsgi.py process-group=cryptoapp WSGIPassAuthorization On <Directory /var/www/cryptoapp/cryptoapp> <Files wsgi.py> Require all granted </Files> Order allow,deny Allow from all </Directory> If i run my project in virtualenv, it runs successfully but when i want to access from browser. It's not working and getting error like this: Fatal Python error: Py_Initialize: Unable to get the locale encode ImportError: No module named 'encoding' Current thread 0x00007f23d9878840 Note: I have tested all the possible ways like reconfigure virtualenv and python 3 configuration. -
Allow user to create formulas dynamically
I have a Django web app that deals with a bunch of KPIs, each KPI has its own formula, formulas now are statically implemented in python code as defined functions. As these formulas might change in the future, I want to allow the user to have a way to enter the fomula to begin with and then change it when needed. Example : KPI1 = sum(table1.column1) + sum(table1.column2) * avg(table1.column3) I want the user to be able to graphically (through the web interface) create a formula for each KPI, and change it afterwards, then the system would parse it each time it wants to calculate the KPI, but I have no idea on how I can do so. Any help would be much appreciated -
Dynamic html table with django
I want to realize HTML page with table which consist from date from database. And if I add element to database I want to HTML table updated too. How to realize it with django? -
How to configure multiple flask / Django websites on one server
I there, I have been using PHP to create web apps for several years and my typical configuration is: NGINX web server PHP-FPM MYSQL In my configuration I set up a maximum number of clients ex. 100 in PHP-FPM and this value is shared among all the domains configured in NGINX (every domain serves a different application). This way I can set a global number related to the virtual machine capabilities. I was trying to configure web applications realised in python, specifically with Flask, but the question is valid with Django as well. For what I understand as true beginner in this language, a typical configuration might be: NGINX uWSGI or GUNICORN (or other servers) FLASK app MYSQL In all the examples I found, both with uWSGI and GUNICORN, it seems to me that you need to specify a number of workers (processes or threads, depending on the specific server you choose), for every application you want to serve, even when you work with a supervisor mode. This way each app has a number of workers on in general of "resources", but if I assign a value of 10 to one app and 10 the another app I could end … -
Set if error condition for value attribute
In the following template code, I set value="{{ form.title.value }}" and it displays as I intended, <div class="form-group"> <label for="title" class="col-sm-1 control-label">Title</label> <div class="col-sm-11"> <input type="text" class="form-control" id="title" name="title" placeholder="Write Title Later" value="{{ form.title.value }}"> </div> However, in other template, if I set value="{{ form.username.value }}", it display None <div class="form-group"> <label for="username" class="col-sm-1 control-label">Username</label> <div class="col-sm-11"> <input type="text" class="form-control" id="username" value="{{ form.username.value }}" name="username" placeholder="Email"> </div> </div> I have to set value="{% if form.username.value %}{{ form.username.value }}{%else%}{%endif%}" <div class="form-group"> <label for="username" class="col-sm-1 control-label">Username</label> <div class="col-sm-11"> <input type="text" class="form-control" id="username" value="{% if form.username.value %}{{ form.username.value }}{%else%}{%endif%}" name="username" placeholder="Email"> </div> </div> I cannot figure out what's the difference between the two form template.