Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Multiple django model values depend on choice field value
My Django model has a pricing_plan choice field. There are 12 fields whose value depends on the pricing_plan value. class Organisation(models.Model): PRICING_CHOICES = ( ('basic', 'Basic'), ('team', 'Team'), ('super', 'Super') ) # some fields... pricing_plan = models.CharField(max_length=50, default='basic') max_host_accounts = models.IntegerField(default=1) max_admin_accounts = models.IntegerField(default=1) max_guests = models.IntegerField(default=10) # more fields whose value depends on pricing_plan value For every different pricing_plan these fields get specific values. In code that could be described like: if pricing_plan == 'basic': max_host_accounts = 1 max_admin_accounts = 1 max_guests = 10 ... elif pricing_plan == 'team': max_host_accounts = 10 max_admin_accounts = 3 max_guests = 25 ... However, there might be more pricing plans in the future and more options and I am afraid that an if/elif/else statement will be huge and not-easily readable. What would be the best/idiomatic way to implement that in a Django model? Use more CHOICE tuples with constant values for every pricing plan? Use Enum classes with constant values for every pricing plan? Use Organisation as parent class and create subclasses like: . class BasicOrganisation(Organisation): max_host_accounts = models.IntegerField(default=1) max_admin_accounts = models.IntegerField(default=1) max_guests = models.IntegerField(default=10) class TeamOrganisation(Organisation): max_host_accounts = models.IntegerField(default=10) max_admin_accounts = models.IntegerField(default=3) max_guests = models.IntegerField(default=25) Anything else? -
How I select any elements with same id in javascript in django
I have a table in Django where all the answers of a test are stored, but when I select them to compare with the response provided by the user, all the answers are the same as the first question. I know this has to do with getElementsById, which only selects the first element. But how do I select all elements of the same id in HTML? {% for resposta in questao.resposta_set.all %} <input type="hidden" id="resposta" name="resposta" value="{{resposta.resposta}}"> <script type="text/javascript"> function mostrarSel(){ if (getRadioValor('opcao_escolhida') == document.getElementById("resposta").value){ alert('Resposta Correta'); } else{ alert('Resposta Incorreta'); } } function getRadioValor(name){ var rads = document.getElementsByName(name); for(var i = 0; i < rads.length; i++){ if(rads[i].checked){ return rads[i].value; } } return null; } </script> {% endfor %} -
How to improve time of python code with database queries
I have some database queries in Django 1.11 which takes about 40 seconds and I want to improve the speed, but my ideas are going out. I want to create a Chart with 6 graphs with the data without having to wait 40 seconds. This is The Model: from django.db import models class MinutenReserveLastYear(models.Model): datum = models.DateField() produkt = models.CharField(max_length=100) grenz_lp = models.FloatField() mittl_lp = models.FloatField() class Meta: indexes = [ models.Index(fields=['datum', 'produkt']), ] I make an Ajax request to get the Data: var neg_last_year = $.ajax({ method: "POST", url: "/prognose/minutenreserve/data/", data: { "produkt": "NEG", "zeitraum": "last_year" }, dataType: "json", context: this }); The view function to get the Data from database: def minutenreserve_data(request): if request.method == "POST": produkt_group = request.POST.get("produkt") zeitraum = request.POST.get("zeitraum") datum_list = {} grenz_lp = {} mittl_lp = {} if zeitraum == "last_year": if produkt_group == "NEG": produkt_list = ["NEG_00_04", "NEG_04_08", "NEG_08_12", "NEG_12_16", "NEG_16_20", "NEG_20_24"] dataset = MinutenReserveLastYear.objects last_year = datetime.date.fromtimestamp(datetime.datetime.timestamp( datetime.datetime.now() - datetime.timedelta(weeks=52))).year days = (datetime.date(last_year, 12, 31) - datetime.date(last_year, 1, 1)).days for j in range(6): grenz_lp[j] = [] mittl_lp[j] = [] datum_list[j] = [] produkt = produkt_list[j] for i in range(days+1): datum = datetime.date(last_year, 1, 1) + datetime.timedelta(days=i) datum_list[j] += [datum.strftime('%d.%m.%Y')] grenz_lp[j] += [dataset.filter(datum=datum, … -
How can I ensure changes to my Celery countdown wont break anything?
I have a number of celery tasks in my Django application that are currently being tested synchronously using CELERY_ALWAYS_EAGER. However this option means that I can't test that changes to the countdown value in apply_async won't break anything. How can I test that nothing else in my application was depending on the longer countdown now that I suspect I no longer need it? I'm using Django 1.10 and Celery 3.1 with Python 3.5. -
Convert flask application to django Blueprint() function
I'm converting this flask application, we use the blueprint function in 3 '.py' files. In the demosite.py file we register using - app.register_blueprint(app_name) and then in 2 '.py' files we use the blueprint function as: some_name = Blueprint('some_name', name)(the double underscore is not shown on either sides of name as it "name" becomes in Bold letters! -_-). Moving over, Now in flask we use the Blueprint() function. I have to covert this flask application to django application. How can I implement the same function? This image shows 1st one is the demosite where the registration is done and the rest two are login.py and uma.py where Blueprint() is used. -
Elastic beanstalk Django admin css not loading
Using Django 1.11.6, python 3.6.2 Short summary: static files are collected correctly on server but only one app's sub directory is served, the admin's static files return as 404. Running the local development server everything works as expected. After deploying to my EB instance none of the static files for the admin app load. If i run eb ssh and look around on the server I can see the collected static folder, along with all the different app's subfolders. The files are all there where I'd expect. The links produced on the django front-end map in a sensible way to these paths, it's just that anything in static/admin returns a 404, while the files in static/entities work fine. Testing paths on the front end: /static/admin/css/base.css (404) /static/entities/style.css (works) On server, all collected files in static look fine: /opt/python/current/app/static/admin/css /opt/python/current/app/static/entities No idea why one sub directory is server fine but the others return 404s. From my django.config option_settings: "aws:elasticbeanstalk:application:environment": DJANGO_SETTINGS_MODULE: "spf.settings" "PYTHONPATH": "/opt/python/current/app:$PYTHONPATH" "ALLOWED_HOSTS": ".elasticbeanstalk.com" "aws:elasticbeanstalk:container:python": WSGIPath: spf/wsgi.py NumProcesses: 3 NumThreads: 20 "aws:elasticbeanstalk:container:python:staticfiles": "/static/": "static/" ... 03_collectstatic: command: "source /opt/python/run/venv/bin/activate && python manage.py collectstatic --noinput" Running the collectstatic command locally produces the correct static folder with the same subdirectories for each … -
Django queryset, order by dynamic criteria based on external value
I need to scramble order of a queryset, based on an external value. The order must be replicable. For example (with sorted, but if it's possible inside the queryset is better): value = 1 sorted(MyModel.objects.all(), lambda n, value: < what to put here?>) For example, If MyModel has 5 objects, I think something like: value | order 1 | 1, 4, 2, 5, 3 2 | 4, 1, 5, 3, 2 3 | 5, 1, 3, 2, 4 -
Django prefetch_related and select_related
I am wondering about the behaviour of prefetch_related() and select_related(). If I do something like Model.objects.filter(...).prefetch_related(), I notice that there are much less database queries occurring. So my initial guess is that, if one does not specify the needed look-ups in prefetch_related(), it will automatically go through all of the model fields and do the needed job. However, I cannot find any reference to it on the web, which seems pretty strange to me. Is my guess correct or am I missing something? -
DRF: Creating a list in a field
I am new to DRF and I want to create a field that can take multiple value. I tried using StringListField as: in my serializers.py,: class StringListField(serializers.ListField): child = serializers.CharField() class XYZSerializer(serializers.ModelSerializer): branch = StringListField(max_length=20) class Meta: model = Api fields = ('id', 'notice_name', 'notice_desc', 'notice_author', 'notice_valid_till', 'notice_publish_date','year', 'branch') views.py class AddNotice(APIView): permission_class = (IsAuthenticated,) serializer_class = AddNoticeSerializer def post(self, request, format=None): data = request.data serializer = AddNoticeSerializer(data=data) if serializer.is_valid(raise_exception=True): serializer.save() new_data = serializer.data return Response(new_data) return Response(serializer.errors, status=HTTP_400_BAD_REQUEST) But as soon as I post it gives something like this error: File "/home/yathartha/.local/lib/python3.5/site-packages/django/core/handlers/exception.py", line 41, in inner response = get_response(request) File "/home/yathartha/.local/lib/python3.5/site-packages/django/core/handlers/base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/yathartha/.local/lib/python3.5/site-packages/django/core/handlers/base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/yathartha/.local/lib/python3.5/site-packages/django/views/decorators/csrf.py", line 58, in wrapped_view return view_func(*args, **kwargs) File "/home/yathartha/.local/lib/python3.5/site-packages/django/views/generic/base.py", line 68, in view return self.dispatch(request, *args, **kwargs) File "/home/yathartha/.local/lib/python3.5/site-packages/rest_framework/views.py", line 489, in dispatch response = self.handle_exception(exc) File "/home/yathartha/.local/lib/python3.5/site-packages/rest_framework/views.py", line 449, in handle_exception self.raise_uncaught_exception(exc) File "/home/yathartha/.local/lib/python3.5/site-packages/rest_framework/views.py", line 486, in dispatch response = handler(request, *args, **kwargs) File "/home/yathartha/Desktop/Desktop/notices-api/api/views.py", line 28, in post serializer.save() File "/home/yathartha/.local/lib/python3.5/site-packages/rest_framework/serializers.py", line 215, in save self.instance = self.create(validated_data) File "/home/yathartha/Desktop/Desktop/notices-api/api/Serializers.py", line 19, in create return Api.objects.create(**validated_data) File "/home/yathartha/.local/lib/python3.5/site-packages/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, … -
How to get extension of file
I am trying to get mimetype from decoded string. I sent base64 string of a xls file, This is my code: def save_file(request_data, id=None): """ """ data = base64.b64decode(request_data.get('file')) mime = magic.Magic(mime=True) content_type = mime.from_buffer(data) print(content_type) print(guess_extension(content_type.decode("utf-8"))) Output: b'application/octet-stream' Unable to get file extensions. Does anyone know how to get file extension from base64 string. -
Generating single hash of CSV file
I have a service that received CSV files with size ranging from MBs to GBs and I need to generate a single hash against all contents of a file. Is there an optimized solution for this that doesn't require me to read the file line by line and concatenate each line in a string and then generate a hash of that string? That method would take too much time for a file that can contain millions of rows. Any help will be appreciated. By the way, I will be using SHA256 from hashlib for hashing. -
Datatables uncaught reference error with django
Hi i'm using datatable in a django/python app, i have an index page that load a list from a DB and put it in a datatable. Since this morning i have an error that start with : TypeError : C is undefined (that seem to point on the line where i define the datatable) and then of course this error pop everytime the setInterval is called on this tab : ReferenceError : oTable is undefined My view : def index(request): listOPT = [] Data = [] fluxManagerState = settings.FLUX_MANAGER_STATE cursor = connections['site'].cursor() try: cursor.execute("{CALL SP_webGET_RESUME_MVT_INIT_ACTIF}") mouvements = dictfetchall(cursor) finally: cursor.close() return render(request, 'index.html', locals()) Function that works with ajax to refresh the datatable : def listMVTinit(request): cursor = connections['site'].cursor() try: cursor.execute("{CALL SP_webGET_RESUME_MVT_INIT_ACTIF}") data = dictfetchall(cursor) finally: cursor.close() return HttpResponse(json.dumps(data), content_type = "application/json") My template : {% load static %} <!doctype html> <html> <head> <meta charset="utf-8"> <title>Liste Mouvement initiaux</title> <meta name="generator" content="WYSIWYG Web Builder 12 - http://www.wysiwygwebbuilder.com"> <link href="{% static 'css/Gestion_Mouvements.css' %}" rel="stylesheet"> <link href="{% static 'css/index.css' %}" rel="stylesheet"> <link href="{% static 'css/base/jquery-ui.min.css' %}" media="all" rel="stylesheet"> <link href="{% static 'css/jquery.dataTables.min.css' %}" media="all" rel="stylesheet"> <link href="{% static 'css/bootstrap.min.css' %}" rel="stylesheet" media="all"> <link href="{% static 'css//bootstrap-datetimepicker.min.css' %}" media="all" rel="stylesheet"> <script src="{% static 'js/jquery-1.12.4.min.js' … -
NoReverseMatch django template url
Sory for my english. I can understand why my code doesnt work. Before it work, but now, i run server, test, and this code not work. I have url when user is registration, i send him activation email, like this: def send_activation_email(serializer, request, user): current_site = get_current_site(request) message = render_to_string('acc_active_email.html', { 'user': user, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': account_activation_token.make_token(user), }) mail_subject = 'Activate your blog account.' to_email = serializer.data['email'] email = EmailMessage(mail_subject, message, to=[to_email]) email.send() acc_active_email.html {% autoescape off %} Hi {{ user.username }}, Please click on the link to confirm your registration, http://{{ domain }}{% url 'activate' uidb64=uid token=token %} {% endautoescape %} and my url file . . url(r'^activate/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$', views.activate_account, name='activate'), . . but i have error: Exception Type: NoReverseMatch Exception Value: Reverse for 'activate' with keyword arguments '{'uidb64': b'NDM', 'token': '4qz-8f770502bd8b02786da9'}' not found. 1 pattern(s) tried: ['activate/(?P<uidb64>[0-9A-Za-z_\\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$'] highlights this line http://{{ domain }}{% url 'activate' uidb64=uid token=token %} -
One view for multiple sub-domains using django-hosts
I need to have multiple sub domains for my project. Each sub domain represents some company. For example: company1.myproject.io, company2.myproject.io. I used django-hosts library to set up sub domains. hosts file: 127.0.0.1 localhost 127.0.0.1 myproject.io 127.0.0.1 www.myproject.io 127.0.0.1 company1.myproject.io 127.0.0.1 company2.myproject.io settings.py: ROOT_URLCONF = 'core.urls' ROOT_HOSTCONF = 'core.hosts' DEFAULT_HOST = 'www' DEFAULT_REDIRECT_URL = "http://www.myproject.io:8000" core/hosts.py: from hostsconf import urls as redirect_urls host_patterns = [ host(r'www', settings.ROOT_URLCONF, name='www'), host(r'(?!www).*', redirect_urls, name='wildcard'), ] hostsconf/urls.py: from .views import wildcard_redirect urlpatterns = [ url(r'^(?P<path>.*)', wildcard_redirect) ] hostsconf/views.py: DEFAULT_REDIRECT_URL = getattr(settings, "DEFAULT_REDIRECT_URL", "http://www.myproject.io:8000") def wildcard_redirect(request, path=None): new_url = DEFAULT_REDIRECT_URL if path is not None: new_url = DEFAULT_REDIRECT_URL + "/" + path return HttpResponseRedirect(new_url) I have a few problems now: When I go to myproject.io it succesfully redirects me to the www.myproject.io. But when I go to company1.myproject.io I got an Invalid HTTP_HOST header: 'company1.myproject.io:8000'. You may need to add u'company1.myproject.io' to ALLOWED_HOSTS Do I really need each time add new host to ALLOWED_HOSTS when I got new sub domain or I am doing something wrong? How to implement a single view for all sub-domains where will by dynamic context for each company. Basically I need to make queries into the db by sub domain name. … -
After upgrade to Django 1.11 site doesn't work in Chrome
I face strange problem. When running django development server I cant display pages in Chrome but I can in FireFox and MsEdge. The server returns 200 response, so page should be displayed. I did not touch any options related to security. Chrome stucks on spinning wheel, and no other information is available, no timeout, no errors. Django 1.11.7 here. Do not hasitate to comment as it could lead us to an answer. -
Is there 'imagecreatefromjpeg' function in python like in PHP ?
I'm trying to add a cover profile into my web application that could be repositionned .. I found a useful tutorial in this link The problem is that the server side code is in PHP and I'm working with PYTHON and Django . I can't find some functions used in PHP like imagecreatefromjpeg , imageSY , imagedestroy ...etc.. Any help ? -
check existing template in mandrill django
in my database, I stored template info. now I need to check my template is existing in mandrill or not. I read documentaion of mandrill. but I could not check it. could anyone suggest any way to check my template is existing in mandrill or not? -
response['Content-Disposition'] = 'attachment;' in django not downloading the file
filename = "/filepath/in/server" with open(filename, 'rb') as f: response = HttpResponse(f.read(), content_type='application/octet-stream') response['Content-Type'] = 'application/octet-stream' response['Content-Disposition'] = 'attachment; filename=filename' print response return response`enter code here` //Clicking on button in my web application should download and save the file from server to my desktop. My html code contains only the button and onclick function(which submits the form and invokes POST). The Post script is written in views.py. The above code is also written in views.py but clicking on the button doesn't download the file as attachment. I can see response content printed in server side. -
Why is my CSS in pythonanywhere taking a day to load?
I change a CSS file, run collectstatic but nothing happens - the app keeps the previous styling, even though that CSS no longer exists anywhere in my files. I got frustrated and gave up yesterday, and found that this morning it had updated, but the initial problem persists. Has anyone else experienced this? Is it just an issue with pythonanywhere or might there be a problem in my code? -
Auto Fill User In Django Form
In my project as soon as user signup it is redirected to update view where he has to fill this information.Since the user has also logged in automatically after signup I want that user field to be filled automatically and can't be edited. models.py class Userpro(models.Model): user = models.OneToOneField(User) dob = models.DateField(default=datetime.date.today) country = models.CharField(max_length=50, default='') qualification = models.CharField(max_length=10, choices=CHO, default='No') university = models.CharField(max_length=100, default='') location = models.CharField(max_length=100, default='') def __str__(self): return str(self.user) forms.py class UserProForm(forms.ModelForm): class Meta: model = Userpro fields = '__all__' views.py def update(request): if request.method == 'POST': form = UserProForm(request.POST or None) if form.is_valid(): form.save() return redirect('/') else: redirect('/') else: form = UserProForm() return render(request, 'app/update.html', {'form': form}) All the required libraries are imported. -
I am unable to deploy my django app on the heroku .How to solve?
So I am trying to deploy my django app over heroku since 3 hrs . Went through many tutorials but still I am unable to make it work . The app is working fine locally Even the foreman app is running the app fine . But I am unable to make it work on heroku .It is deployed successfully but fails to works. Kindly help. Directory and files are in following manner The directories and files are made like that. The codes are on github : https://github.com/Atif8Ted/test_blog This is first try on heroku . Kindly be gentle. -
Django website on VPS with WHM CPanel
What's the difference between mod_wsgi and mod_python. In order to publish django websites on VPS, which one should I install on VPS? -
crispy forms + Bootstrap3: bad position of error field with input-group-addon
When using a input-group-addon, when there's an error, the span element of the error is wrapped by the input-group-addon: the html: <div class="controls col-md-6 input-group"> <input name="name" value="English" class="lang_name dropdown-toggle dropdowntogglewidget form-control form-control-danger" maxlength="40" required="" id="id_name" type="text"> <span role="button" class=" input-group-addon dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> <span class="caret"></span></span> <span id="error_1_id_name" class="help-block"><strong>Languages with this Name already exists.</strong></span> </div> my forms.py: class LanguagesForm(forms.ModelForm): ... def __init__(self, *args, **kwargs): super(LanguagesForm, self).__init__(*args,**kwargs) self.helper = FormHelper() self.helper.form_class = 'form-horizontal text_detail' self.helper.label_class = 'col-md-3' self.helper.field_class = 'col-md-6 input-group' ... I guess it's the same problem than Bootstrap 3 form using input-group-addon wrapping error labels with Jquery Validate but here, we have less option... -
How do I prepopulate an inline formset that is purely ImageFields?
I have two models: Profile and CredentialImage. I have implemented inlineformsets to allow the Profile to upload up to 5 maximum images(CredentialImage). Currently, the images save to the database but they will not pre-populate when I revisit the update form, thus allowing the user to upload an unlimited amount of photos 5 at a time. Ideally, the same images saved to the database would pre-populate on the form as to limit the Profile to own and edit only 5 photos at a time. From my understanding, I need to pass in the object to the page to pre-populate information, and I believe I'm doing just that by defining get_object. Here are the two models: class Profile(models.Model): ... def get_absolute_url(self): return reverse("profile:profile_detail", kwargs={"username": self.user}) class CredentialImage(models.Model): profile = models.ForeignKey(Profile, default=None, related_name='credentialimage') image = models.ImageField(upload_to=credential_photo_upload_loc) The modelforms + initialization of the inlineformset_factory: from django.forms.models import inlineformset_factory class ProfileUpdateForm(ModelForm): class Meta: model = Profile fields = [ "introduction", "biography", ] class CredentialImageForm(ModelForm): image = ImageField() class Meta: model = CredentialImage fields = ['image', ] CredentialImageFormSet = inlineformset_factory(Profile, CredentialImage, fields=('image', ), extra=4, max_num=4) A class-based UpdateView for updating a Profile: class ProfileUpdateView(LoginRequiredMixin, UpdateView): form_class = ProfileUpdateForm template_name = 'profile/profile_edit.html' def get_context_data(self, **kwargs): context = … -
Can I execute makemigrations and migrate command in my PyCharm?
I changed my project interpreter to python 3.5, and I still has used to in the terminal to execute the : python manage.py makemigrations python manage.py migrate Because I have changed the project interpreter to python 3.5, I must use python3 manage.py migrate to realize that, sometimes I will write python rather than python3. So is there a method in PyCharm to realize that?