Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
TypeError: init() missing 1 required positional argument: 'setting_module'
I can't find where this error comes from. I already modify the wsgy.py file but it still there. I tried to set django_setting_module directly with the command line but it seems that the error is still there. Here is the traceback files: C:\mysite>python manage.py runserver Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x02BCCDB0> Traceback (most recent call last): File "C:\Python35\lib\site-packages\django\utils\autoreload.py", line 227, in wrapper fn(*args, **kwargs) File "C:\Python35\lib\site-packages\django\core\management\commands\runserver. py", line 117, in inner_run autoreload.raise_last_exception() File "C:\Python35\lib\site-packages\django\utils\autoreload.py", line 250, in raise_last_exception six.reraise(*_exception) File "C:\Python35\lib\site-packages\django\utils\six.py", line 685, in reraise raise value.with_traceback(tb) File "C:\Python35\lib\site-packages\django\utils\autoreload.py", line 227, in wrapper fn(*args, **kwargs) File "C:\Python35\lib\site-packages\django\__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Python35\lib\site-packages\django\apps\registry.py", line 108, in pop ulate app_config.import_models() File "C:\Python35\lib\site-packages\django\apps\config.py", line 202, in impor t_models self.models_module = import_module(models_module_name) File "C:\Python35\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 978, in _gcd_import File "<frozen importlib._bootstrap>", line 961, in _find_and_load File "<frozen importlib._bootstrap>", line 950, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 655, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 205, in _call_with_frames_removed File "C:\mysite\calendarium\models.py", line 14, in <module> from filer.fields.image import FilerImageField File "C:\Python35\lib\site-packages\filer\fields\image.py", line 4, in <module > from ..models import Image File "C:\Python35\lib\site-packages\filer\models\__init__.py", line … -
how to use faker with Mixer
Following the documentation of the package titled Mixer. I am trying to have a lorem ipsum like in a models.CharField() In [21]: from django.contrib.auth.models import User In [22]: mixer = Mixer(fake=True, commit=False) In [23]: product = mixer.blend(Product, description=mixer.FAKE) In [24]: product.description Out[24]: 'EyhtzVWIJYueFtPSUlxB' but following the documentation, how come that I don't have a lorem ipsum like in the description field instead of random char. -
Refreshing new messages value every second
In my Django site i have a span ,which shows how many new messages does the user have like in this image below : Now I am refreshing this value in every django view possible and it's the part of my base.html Views.py def someView(request,pk): ... mcount = UserMessage.objects.filter(receiver = request.user.pk, isRed = 0).count() ... return render(request, 'app/somehtml.html', {...'mcount':mcount...}) base.html ... <span class="messageCount"aria-hidden="true"> {{ mcount }} </span> ... What i want to do is to refresh it every few seconds without user reloading the page. How could i achieve that ? -
Django: models based on existing objects
I'm new to Django and programming overall. So far, I was able to build a website just by referring to the official docs, but now I'm stuck. I'll describe my problem using gas stations analogy. This is what I got: class Grade(models.Model): grade_name = models.CharField(max_length=30) class Station(models.Model): station_name = models.CharField(max_length=30) gas_grade = models.ManyToManyField(Grade) With that I create three grade objects: Regular, Plus, Premium. After that I create a few stations to which I "assign" any combination of grades. Easy. The problem starts when I need prices. An obvious solution would be adding Price model: class Price(models.Model): station = models.ForeignKey(Station, on_delete=models.CASCADE) price_regular = models.CharField(max_length=30) price_plus = models.CharField(max_length=30) price_premium = models.CharField(max_length=30) But adding the last three fields manually is no fun, to say the least. My "grades" and "stations" can grow daily. They also have two fields representing min/max price. So... can I dynamically create fields based on existing objects? The point is I need each new station to have a price field for each grade assigned. Please advise of any of my options. It's almost a week since I'm beating the dead horse. Maybe I'm far from figuring this out because the logic I'm following is wrong? Maybe a dedicated "add … -
Django/Postgres: Choose from DISTINCT ON sets
I have these models: class Product(Model): ... class Scanning(Model): product = ForeignKey(..) datetime = DateTimeField(...) ... I'm trying to get one scanning for each product where the scanning is a latest one from product.scanning.all() set. s1 = (product1,01.01.1000) s2 = (product2,01.01.1200) s3 = (product1,01.01.1900) s4 = (product2,01.01.1988) s5 = (product3,01.01.2015) s6 = (product3,01.01.1970) would return <s4,s3,s5> Scanning.objects.filter(product__user=u,product__active=True).distinct('product_id').order_by('datetime') Raises exception: ProgrammingError: SELECT DISTINCT ON expressions must match initial ORDER BY expressions LINE 1: SELECT DISTINCT ON ("productapp_scanning"."product_id") "pro... ^ How to make it work? -
I can't see ImageField's photos in DJango's view
something fail in my Django project, because the images that I load in the imagefields don't show in the view. https://www.dropbox.com/sh/fvx6sfmxgm08xo6/AABVR-AQGeF52pCxlzVaLuDaa?dl=0 The crab's photo it's load with "static", but the second, that it's imagefield's photo. enter image description here -
django views in different folder conflicting model
I have view files containing view functions in separate folders and they are both importing 2 different models having same name from different folders /models/telephone_expense/transistion_history.py /models/medical/transistion_history.py /views/medical/<view_files> /views/telephone/<view_files> Error RuntimeError: Conflicting 'transitionhistory' models in application 'reimbursement': <class 'reimbursement.models.medical.transition_history.TransitionHistory'> and <class 'reimbursement.models.telephone_expense.transition_history.TransitionHistory'>. -
Update FileField: what is the name of the old file
Django 1.11 When FileUpdate is called, I substitute the old file with a new one. I'd like to handle the old file. Namely move it to some other directory. Could you have a look at the picture below. New file is called "C book 1.pdf". Existing file is called "4_Oracle_Database_11g_PLSQL_Fundamentals_PLSQL.pdf". But at the breakpoint (see comment in form_valid), old_file_name = C book 1.pdf. But I can't catch why. I call super(FileUpdate, self).form_valid(form) in a couple of lines. And only there self.object = form.save(). At the breakpoint I expect self.object to be the unchanged object. Existing one. Could you help me understand how to catch the file name of the old file. class UserFile(models.Model): uuid = models.UUIDField(primary_key=False, default=uuid.uuid4, editable=False) user_file = models.FileField(verbose_name=_("file"), max_length=255, upload_to=get_file_path) class FileUpdate(UpdateView): model = UserFile form_class = FileForm def form_valid(self, form): """ Delete old file. """ parent_directory = get_parent_directory_of_file(self.object) old_file_name = self.object.user_file.name # Breakpoint self.object.user_file.delete() return super(FileUpdate, self).form_valid(form) This is the form: -
TEMPLATE_CONTEXT_PROCESSORS is not working
I have a problem with TEMPLATE_CONTEXT_PROCESSORS in my Django project. I'm using django 1.5.4 and I would like to use the session value in my base template. So, for the test I've modified the settings file and I added: TEMPLATE_CONTEXT_PROCESSORS =( "django.contrib.auth.context_processors.auth", "django.core.context_processors.debug", "django.core.context_processors.i18n", "django.core.context_processors.media", "django.core.context_processors.static", "django.core.context_processors.tz", "django.core.context_processors.request", "django.contrib.messages.context_processors.messages", ) and in my base file I added this code for check: {{ request }} But it does not work, I do not see anything. Why? Thanks, -
GAE - ImportError: No module named django.core.wsgi
First of all, let me say that I did my homework and search for this error for several hours. I get this error when I try to access my Django 1.11 'Hello world' app deployed on GAE. I'm perfectly able to run the app locally, inside a Docker with Python 2.7. My current setup is as follows: Install virtualenv env pip install -r requirements-vendor.txt -t lib/ pip install -r requirements.txt requirements-vendor.txt Django==1.11 app.yaml runtime: python27 api_version: 1 threadsafe: yes handlers: - url: /static static_dir: static/ - url: .* script: hi.wsgi.application libraries: - name: MySQLdb version: 1.2.5 skip_files: - ^(.*/)?#.*#$ - ^(.*/)?.*~$ - ^(.*/)?.*\.py[co]$ - ^(.*/)?.*/RCS/.*$ - ^(.*/)?\..*$ - ^env/.*$ appengine_config.py from google.appengine.ext import vendor #vendor.add('lib') <--- tried that too vendor.add(os.path.join(os.path.dirname(os.path.realpath(__file__)), 'lib')) The error is caused because the lib folder (which contains the Django framework and other libraries) isn't getting added to Python's PATH, but why? Why is GAE ignoring my appengine_config.py? -
Remove Favorited post from account page? Django
I have the followung code on the list page to add a favourite which will be viewed on the accounts page. I want to remove the favorited post from account page. Code: .... {% if user.is_authenticated %} <button class=" favorite btn btn-default {% if aircraft.id in favorited_aircraft_ids %}added{% endif %}" data-aircraft-id="{{ aircraft.id }}"><span class="add">Add</span><span class="remove">Remove</span> Favorite</button> {% endif %} .... <script> var favorited_aircraft_ids = {% if favorited_aircraft_ids %}{{ favorited_aircraft_ids | escapejs }}{% else %}[]{% endif %}; </script> <script src="{% static 'js/aircraft/favorite.js' %}"></script> Favourite.js $(document).ready(function() { $('.favorite').on('click', function(event) { var target = $(event.currentTarget); var url = '/accounts/favorites/aircraft/'; url += target.hasClass('added') ? 'remove/' : 'add/'; url += target.data('aircraft-id'); $.post(url, function() {}) .done(function() { target.toggleClass('added'); }); }); }); On the summary page i have the Favorited post being shown. But I only want to add a remove button. How would I reflect that with he following code? Do I need to create a separate file? -
Can't Upload Image In Django
I have a profile page where I would like to allow a user to upload a profile picture. I can edit all of the text but cannot upload an image. It works if i add the image via the Admin, but not via the user's profile page on the website. Note that when created via admin--it is uploading correctly to the directory (profile_image) that i've specified in media folder. I've created some error handling on template page, but the error generated is this: "The 'image' attribute has no file associated with it." Below is my code: models.py class UserProfile(models.Model): user = models.OneToOneField(User) first_name = models.CharField(default='',max_length=100 ) last_name = models.CharField(default='',max_length=100) email = models.CharField(max_length=100, default='') date_birth = models.DateField(default=datetime.datetime.now()) bio = models.TextField(default='') image = models.ImageField(upload_to='profile_image', blank=True) def create_profile(sender, **kwargs): if kwargs['created']: user_profile = UserProfile.objects.create(user=kwargs['instance']) post_save.connect(create_profile, sender=User) views.py @login_required def edit_profile(request): profile = get_object_or_404(models.UserProfile) if request.method == 'POST': form = forms.EditProfileForm(data=request.POST, instance=profile) if form.is_valid(): form.save() return redirect('/accounts/profile') else: form = forms.EditProfileForm(instance=profile) args = {'form':form} return render(request, 'accounts/edit_profile.html', args) forms.py from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserChangeForm from . import models class UserProfileForm(forms.ModelForm): class Meta: model = models.UserProfile fields = [ 'first_name', 'last_name', 'email', 'date_birth', 'bio', 'image', ] class EditProfileForm(UserProfileForm): … -
Django Static/Media Files in the same Server
I just deployed my django project in the cloud server digital ocean with $20/mo ,with ram and disk are more than adequate. My application atmost gets 200 users registered per month, consequently they will be having some set of tasks which produces data over 10 models. FYI,This application has a File upload task where user has to upload files 3-4 times. So my doubt is do I need to take another server for serving static files.With the above provided info, can you suggest anything. -
TypeError this constructor takes no arguments
I seem to be having a TypeError problem on my program using Django. Views.py from __future__ import unicode_literals from django.shortcuts import render from .models import Anteproyecto from .forms import formulario_anteproyecto from django.views.generic import CreateView from django.core.urlresolvers import reverse, reverse_lazy from django.contrib.messages.views import SuccessMessageMixin class CrearAnteproyecto(SuccessMessageMixin, CreateView): model = Anteproyecto form_class = formulario_anteproyecto template_name = "crear_anteproyectos.html" success_url = reverse_lazy('crear_anteproyecto') success_message = "El anteproyecto ha sido creado" def form_valid(self, form): self.object = form.save() Forms. py from django import forms from .models import Anteproyecto class formulario_anteproyecto: class Meta: model = Anteproyecto fields = ['titulo', 'resumen','estado','palabras_claves'] Models.py from __future__ import unicode_literals from django.db import models from taggit.managers import TaggableManager from Actividades.models import Actividades ESTADOS = (('Activo', 'Activo'), ('Inactivo', 'Inactivo')) class Anteproyecto(models.Model): titulo = models.CharField(max_length=100, verbose_name='Título') estado = models.CharField(max_length=8, verbose_name="Estado", choices=ESTADOS, default='Activo') resumen = models.CharField(max_length=500, verbose_name="Resumen") claves = TaggableManager(verbose_name = "Palabras claves") actividad = models.ForeignKey(Actividades, on_delete=models.CASCADE) class Meta : verbose_name = 'Anteproyecto' verbose_name_plural = 'Anteproyectos' def __str__(self): return self.titulo Importing the app "Actividades" to be used as a reference in models. Using as well Django-taggit to use a field that can work as tags, still not implemented due to TypeError. Html is a bootstrap template which prints the form as a paragraph. There are other … -
Response delay from Django REST
Possibly off topic, but having trouble researching this. I have a Django REST install, and I'd like to be able to simulate a random number of delays before responses. My views (basically verbatim from the DRF tutorial): class SnippetList(generics.ListCreateAPIView): queryset = Snippet.objects.all() serializer_class = SnippetSerializer class SnippetDetail(generics.RetrieveUpdateDestroyAPIView): queryset = Snippet.objects.all() serializer_class = SnippetSerializer And I'd like to be able to return between 3 and 5 failed responses before a successful response. Any guidance greatly appreciated. -
Easy and generic API Integration to another existing system
I want to know if there is a way to create a REST API that can be easily integrated in an existing system. Specifically what I mean, assume we have an existing system for an e-commerce website and my API is trying to automate/facilitate the process of adding items to a cart and purchasing. I know that some systems offer an API to do that but what I want is for the existing website to use my API and integrate it into their system regardless of its database architecture. Is this possible in any way? P.S. if anything is unclear please let me know to update the description with more information. -
Mailgun API unsuccessfully sending message in Django views
I'm really having a hard time creating an Exception or Error with the Mailgun API. I have weekly blogs that I create and I have a dialog form where the user can be added to the newsletter listing on the posts page: I generated a separate utils.py file and te class SendMailTo and imported the class into the views.py file. utils.py: class SendMailTo(object): def __init__(self, user, email, id, attachments=[]): self.user = user #The user we are sending mail to self.email = email self.attachments = attachments self.set_encryption = set_encryption(self.user) self.id = id def sendmail(self, subject, message=None): user_name = self.set_encryption html = unicode(open('action.html', 'r').read()).strip() html = html.format(user_name=unicode(user_name), user_id=unicode(self.id)) request_status = requests.post( "https://api.mailgun.net/v3/MY_DOMAIN/messages/", auth=("api", "MY-KEY"), files=[("inline", ("attachment", ("{attachment}.txt".format(attachment=attachment), open(attachment, 'r').read() ) ) ) for attachment in self.attachments if self.attachments ], data={"from": u"DO NOT REPLY <user@domain.com>", "to": "{0}".format(unicode(self.email)), "message": u"multipart/form-data", "html": open('action.html', 'r').read().format(user_name=unicode(user_name), user_id=unicode(self.id)), "text": u"thank you", "subject": "{0}".format(unicode(subject)), "o:require-tls": True, } ) request_status.raise_for_status() return request_status views.py: def post_detail(request): .......... send_to_user = SendMailTo(newsub.name, newsub.email, newsub.id) finish_email = send_to_user.sendmail("Subscription Notice & Thank You", "Thank you for signing up!") messages.success(request, "Thank you {name} for signing up and becoming an independent member!".format(name=newsub.name)) return HttpResponseRedirect(instance.get_absolute_url()) I'm seeing the response after the return to the main blog section indicating … -
Django - Exclude superuser from LDAP auth
I've integrated LDAP authentication to my application using this package: django-auth-ldap I also created a superuser using django command: python manage.py createsuperuser I want to be able to to exclude this particular superuser from LDAP auth. How can I do that? Thanks in advance. -
Dynamic creation of tables in mysql using python
I need to do calculations on a CSV dataset and latter store that as a SQL table in a MySQL Database. I have been thinking to use Django, but I don't think it allows dynamic creation of models. One more information I would like to provide that I don't know the number of variables in that table. So my question is, how should I proceed?. I have been thinking to create my own crude function for performing SQL queries or using Django south. Any suggestions will be appreciated. -
Django ModelForm isn`t saving data
I have a form for subscribing in footer.html that is included in base.html, so the form should work at every page on the site. I used context_processor solution for this and everything works fine, however data are not saving in DB for some reason. I spent hours with looking for proper solution on Stack but did`nt make it saving. Similar question was here, but also doesnt work for me. Should be something simple, but as Im new to django, got a little bit complicated with this. Please help. Thanks in advance Note: Be sure, 'catalogue.context_processors.SubscribeFormGlobal' is added to settings models.py from django.db import models class Subscriber(models.Model): email = models.EmailField() def __str__(self): return self.email forms.py from django import forms from .models import Subscriber class SubscriberForm(forms.ModelForm): class Meta: model = Subscriber fields = ('email',) context_processors.py from .forms import SubscriberForm def SubscribeFormGlobal(request): return {'subscribe_form': SubscriberForm()} views.py def subscribe_us(request): if request.method == "POST": subscribe_form = SubscriberForm(request.POST) if subscribe_form.is_valid(): subscribe_form.save(commit=False) subscribe_form.author = request.user subscribe_form.published_date = timezone.now() subscribe_form.save() else: subscribe_form = SubscriberForm() return render(request, '', {'subscribe_form': subscribe_form}) urls.py from catalogue import views from catalogue.models import Bancnote urlpatterns = [ url(r'^$', views.bons_list, name='bons_list'), url(r'^(?P<pk>\d+)$', DetailView.as_view(model=Bancnote, template_name='catalogue/bon_detail.html')), url(r'^feedback/$', views.feedback, name='feedback'), url(r'^$', views.subscribe_us, name='subscribe') ] footer.html {% load widget_tweaks … -
Django form fields not showing
I am new to django and trying to show a form in an html file and I don't see the fields when I get to this particular page on my browser. Here is the html file : In which I can see everything but the form showing up two_factor.html {% extends 'authentication/base.html' %} {% block title %}Two Factor{% endblock title %} {% block two_factor %} <div class="container"> <h3>Your code</h3> <form role="form" action="" method="post" enctype="multipart/form-data"> <div class="form-group"> {% csrf_token %} {{ form }} <div class="form-group"> <button type="submit" class="btn btn-success">Submit</button> </div> </div> </form> </div> {% endblock two_factor %} my forms.py class TwoFactorForm(forms.Form): code = forms.CharField(label='Code', widget=forms.TextInput(attrs={'type': 'text', 'placeholder': 'Your code'})) my views.py class TwoFactorView(View): form_class = TwoFactorForm template_name = 'authentication/two_factor.html' def get(self, request): form = self.form_class(None) return render(request, self.template_name, {'form': form}) def post(self, request): form = self.form_class(request.POST) if form.is_valid(): return redirect('authentication/secret.html') return render(request, self.template_name, {'form': form}) I added block in the base.html. I am seeing only button submit. URL is all good. -
Invalid distinct with django
I try to get a cars list on my Django project but i'm in trouble with ORM class Car(models.Model): name = models.CharField(max_length=200) owner = models.ForeignKey(User) With Car.objects.all() I have a list as: - car#1, user#1 - car#1, user#2 - car#1, user#3 - car#2, user#4 - car#3, user#4 what I would like is: - car#1 - car#2 - car#3 Then, all cars are distinct by the name, regardless of owner I've try something like Cars.objects.all().annotate(Count('owner', distinct=True)) but I still have all cars. Can someone help me with this point ? Documentation suggests annotate and aggregate but it's still hars to understand it. -
Django Error: No DjangoTemplates backend is configured
First time using (or trying to) Django. I need to dynamically generate an HTML file from a given template (lab.html): from django.template import Template, Context from django.conf import settings settings.configure() f = qc.QFile('lab.html') f.open(qc.QFile.ReadOnly | qc.QFile.Text) stream = qc.QTextStream(f) template = stream.readAll() print(template) f.close() t = Template(template) c = Context({"result": "test"}) #result is the variable in the html file that I am trying to replace However, I keep getting this odd error that I haven't found anywhere after some research. Does anyone have any thoughts on this? Thank you very much! Traceback (most recent call last): File "/Users/gustavorangel/PycharmProjects/help/HelpUI.py", line 262, in filesSearch t = Template(template) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/template/base.py", line 184, in init engine = Engine.get_default() File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/template/engine.py", line 83, in get_default "No DjangoTemplates backend is configured.") django.core.exceptions.ImproperlyConfigured: No DjangoTemplates backend is configured. -
Pass 2FA check in tests
I have this code in my views.py @otp_required def decrypt(request): pass This decorator makes sure that the user needs to be logged in with 2FA to view this page. However how can i simulate a logged in user with 2FA in my tests? I couldn't find anything in the docs regarding this 2FA module that explains how to run tests on a view with this decorator. Is there a specific test package i could use that will ignore this @otp_required or get around it somehow? -
Unpredictable file name (FileField)
Django 1.11 Ubuntu 16.04 class UserFile(CommonUrlMethodsMixin, GeneralModel): uuid = models.UUIDField(primary_key=False, default=uuid.uuid4, editable=False) user_file = models.FileField(verbose_name=_("file"), upload_to=get_file_path) def get_file_path(instance, filename): item = instance.item frame = item.frame fr = "fr" + str(frame.id) it = "it" + str(item.id) fl = "fl" + str(instance.uuid) return 'files/{frame}/{item}/{fl}/{frame}_{item}_{fl}_{filename}'.format( type=type, frame=fr, item=it, fl=fl, filename=filename) # Breakpoint. Let's go to the url leading to class FileCreate(CreateView). In the form let's choose a file called "oracle-database-11g-sql-fundamentals_Oracle_SQL.pdf". At breakpoint let's evaluate what we are going to return. The result is: 'files/fr1/it1/fl798ebdb7-5d2f-4651-aeff-8e9b6b721f4c/fr1_it1_fl798ebdb7-5d2f-4651-aeff-8e9b6b721f4c_oracle-database-11g-sql-fundamentals_Oracle_SQL.pdf' Please, don't be afraid of such a horrible name. It would suit me perfectly. The file was uploaded to /home/michael/workspace/photoarchive_project/media/files/fr1/it1/fl798ebdb7-5d2f-4651-aeff-8e9b6b721f4c. This is perfectly expectable. But the file name is fr1_it1_fl798ebdb7-5d2f-4651-aeff-8_CkZisqk.pdf Could you help me understand what is the reason for changing the result of get_file_path() to this? I know that if two files have equal names, Django appends some unique tail to the file name. But here I can't understand the behaviour. The file has a unique name because of that uuid. Maybe the file name is too long? Anyway, I can't cope with this problem. Your help would be highly appreciated.