Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Deploying a minizinc & django app to the web
I am looking to deploy a small minizinc optimisation model using a web app. I am completely new to web deployment and was wondering the following: Is this something pythonanywhere would support? I looked through https://www.pythonanywhere.com/ and couldn't find any mention of optimisation software attachments. I assume this is something that amazon web services could do. Am I right in thinking that this could be done via elastic beanstalk? Would using an open source solver other than minizinc be preferred? Many thanks for your help. -
Making a group by query in Django
Here is my model: from django.db import models # Create your models here. class Skill(models.Model): name = models.CharField(max_length=100) def __str__(self): return '%s' % self.name class AppForm(models.Model): creation_date = models.DateField(db_index=True) first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) phone_number = models.CharField(max_length=100) ... preferred_skill = models.ManyToManyField(Skill,db_index=True) preferred_skill_other = models.CharField(max_length=250,default='') ... I would like to make the following query: sqlite> SELECT "app_form_appform_preferred_skill"."skill_id", COUNT("app_form_appform"."id") FROM "app_form_appform" INNER JOIN "app_form_appform_preferred_skill" ON ("app_form_appform"."id" = "app_form_appform_preferred_skill"."appform_id") GROUP BY "app_form_appform_preferred_skill"."skill_id"; NOTE: app_form_appform_preferred_skill is a table created by django due to the many-to-many relationship specified in the model. Can this query be made using just the django ORM? I tried to use aggregate, but I could not get it to do what this query does, the difficulty for me is in getting the GROUP BY clause using the ORM. -
error import django rest_framework
I follow the tutorial http://www.django-rest-framework.org/tutorial/quickstart/ but appears the next message error: File "/Applications/djangostack-1.8.17-0/python/lib/python2.7/importlib/init.py", line 38, in import_module import(name) ImportError: No module named rest_framework I don't understand why doesn't work, i have settings.py file ok. -
How to override save method to change data in Django?
Model: ATTN_TYPE_CHOICES = ( ('N', 'Entry'), ('X', 'Exit'), ('L', 'Leave'), ) class Attn(Timestamp): emp_id = models.CharField( max_length=10 ) date = models.DateField() time = models.TimeField( default=time(00, 00) ) type = models.CharField( max_length=1, choices=ATTN_TYPE_CHOICES, default='N' ) @property def late(self): return type == 'N' and self.time > LATE_LIMIT def save(self, *args, **kwargs): try: Attn.objects.get(emp_id=self.emp_id, date=self.date, type='N') except Attn.DoesNotExist: pass else: try: exit = Attn.objects.get(emp_id=self.emp_id, date=self.date, type='X') except Attn.DoesNotExist: self.type = 'X' else: exit.delete() super(Attn, self).save(*args, **kwargs) class Meta: unique_together = ('emp_id', 'date', 'type') I will create objects thrice. The first time is simple. The type will be N. The second time I want the save method to check if type N already exists, if it does, then change the type to 'X' and save second object. Third time, I want it to check for N and then for X. But this time it will find X and will delete the existing entry for X before saving the new entry with type X. For some reason, the code seems to get stuck at the unique_together and doesn't let me save data from the admin panel. Should I try and catch the Integrityerror for this problem? -
PermissionError: [Errno 13] Permission denied | WeasyPrint
I use WeasyPrint app to generate pdf file in my django project. I have next code which raise error. It seems to me that main problem in this line output = open(output.name, 'r'). I think user doen't have access rights. How to fix this problem? views.py: def generate_pdf(request, project_code): project = get_object_or_404(Project, pk=project_code, status='open') html_string = render_to_string('project/pdf.html', {'project': project}) html = HTML(string=html_string) result = html.write_pdf() response = HttpResponse(content_type='application/pdf;') response['Content-Disposition'] = 'inline; filename=technical_specification.pdf' response['Content-Transfer-Encoding'] = 'binary' with tempfile.NamedTemporaryFile(delete=True) as output: output.write(result) output.flush() output = open(output.name, 'r') <-- ERROR response.write(output.read()) return response ERROR: Traceback (most recent call last): File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35\lib\site-packages\django\core\handlers\exception.py", line 39, in inner response = get_response(request) File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35\lib\site-packages\django\core\handlers\base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35\lib\site-packages\django\core\handlers\base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Nurzhan\PycharmProjects\RMS\project\views.py", line 1808, in generate_pdf output = open(output.name, 'r') PermissionError: [Errno 13] Permission denied: 'C:\\Users\\Nurzhan\\AppData\\Local\\Temp\\tmp_vx7wo99' Also I have such WARNING: WARNING: @font-face is currently not supported on Windows -
how to add django base.html to angular js pages?
So I have created a project which has its frontend in angularjs and backend in Django rest framework. now I have created a django login page which should authorize all other angular pages. so how can we extend the base.html in angularjs pages with static files. my tree structure is as follows: project | | application templates manage.py project | settings.py urls.py public | static html files Hope to get answer to this. thanks -
Importing Django App functions in celery.py
I am developing an application where i have to periodically call a function which is in myapp/task.py from the celery.py file which is located in my project directory.But when I do an import statement from the celery.py file like from myapp.tasks import test I get the following error which I am not able to resolve: django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. -
Django - How Updating Author Model in the mid-way?
I have Author model which looks like this: class Author(models.Model): name = models.CharField(max_length=100) email = models.EmailField(unique=True) created = models.DateTimeField(auto_now_add=True) last_login = models.DateTimeField(auto_now=True) Now I want to connect Author Model to User model and in the process add some additional fields in the Author model. Here is the updated version of Author model. class Author(models.Model): user = models.OneToOneField(User) ## additional fields phone = models.IntegerField(blank=True) address = models.CharField(max_length=200) bio = models.TextField() Author model is also connected to the Story model via ForeignKey. My question is how do I update my Author model without deleting my any Story related to it. -
No module named 'imp'
I have to extend the code that an ancient student done. After installing all the library needed I finally tried the code and got this error : $ ./main Traceback (most recent call last): File "/usr/lib/python3.4/tkinter/__init__.py", line 39, in <module> import _tkinter File "/usr/lib/python3.4/importlib/_bootstrap.py", line 2237, in _find_and_load return _find_and_load_unlocked(name, import_) File "/usr/lib/python3.4/importlib/_bootstrap.py", line 2226, in _find_and_load_unlocked module = _SpecMethods(spec)._load_unlocked() File "/usr/lib/python3.4/importlib/_bootstrap.py", line 1191, in _load_unlocked return self._load_backward_compatible() File "/usr/lib/python3.4/importlib/_bootstrap.py", line 1161, in _load_backward_compatible spec.loader.load_module(spec.name) File "ExtensionLoader__tkinter.py", line 22, in <module> File "ExtensionLoader__tkinter.py", line 3, in __bootstrap__ File "/usr/lib/python3.4/importlib/_bootstrap.py", line 2237, in _find_and_load return _find_and_load_unlocked(name, import_) File "/usr/lib/python3.4/importlib/_bootstrap.py", line 2224, in _find_and_load_unlocked raise ImportError(_ERR_MSG.format(name), name=name) ImportError: No module named 'imp' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/local/lib/python3.4/dist-packages/cx_Freeze-4.3.4-py3.4-linux-x86_64.egg/cx_Freeze/initscripts/Console.py", line 27, in <module> File "main.py", line 13, in <module> File "/usr/lib/python3.4/importlib/_bootstrap.py", line 2237, in _find_and_load return _find_and_load_unlocked(name, import_) File "/usr/lib/python3.4/importlib/_bootstrap.py", line 2226, in _find_and_load_unlocked module = _SpecMethods(spec)._load_unlocked() File "/usr/lib/python3.4/importlib/_bootstrap.py", line 1191, in _load_unlocked return self._load_backward_compatible() File "/usr/lib/python3.4/importlib/_bootstrap.py", line 1161, in _load_backward_compatible spec.loader.load_module(spec.name) File "/home/aitech/Scrivania/folder_test/GUI_videoServer/mainFrame.py", line 4, in <module> File "/usr/lib/python3.4/importlib/_bootstrap.py", line 2237, in _find_and_load return _find_and_load_unlocked(name, import_) File "/usr/lib/python3.4/importlib/_bootstrap.py", line 2226, in _find_and_load_unlocked module = _SpecMethods(spec)._load_unlocked() File "/usr/lib/python3.4/importlib/_bootstrap.py", line 1191, in _load_unlocked return … -
How to confgure django-python3-ldap authentication for Active Directoy?
I am currently trying to setup django 1.10 to authenticate with the django-python3-ldap 0.9.14 module. I found this module here on https://github.com/etianen/django-python3-ldap I first tested communication with the Active Directory Studio (http://directory.apache.org/studio/) using my credentials. I noticed that I have to authenticate with the following settings. Network Parameters Hostname: serversipaddress Port: 389 Encryption method: StartTLS extension Provider: Apache Directory LDAP Client API Authentication Bind user: ECDC\testuser password: xxxxx Then I can connect. I tried to apply the same to configuration, but I realize that the default configuration in settings.py need to be adapted to Active Directory. But after setting the configuration up, I can't login to the admin page. http://127.0.0.1:8000/admin/login/?next=/admin/ Can someone help me figure out what's wrong with my configuration? The error that shows up in the log System check identified no issues (0 silenced). May 25, 2017 - 08:36:38 Django version 1.11.1, using settings 'project1.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. LDAP connect failed: LDAPInvalidCredentialsResult - 49 - invalidCredentials - None - 80090308: LdapErr: DSID-0C0903A8, comment: AcceptSecurityContext error, data 52e, v1db1 settings.py """ Django settings for goldfish project. Generated by 'django-admin startproject' using Django 1.11. For more information on this file, see https://docs.djangoproject.com/en/1.11/topics/settings/ For … -
Load articles from wordpress multiple sites DBs by django
I new in Django Python and need help. I must load articles from wordpress multiple sites DBs, how to connect always to new database in Django model class. from django.db import models from django.db import connections # Create your models here. class WordpressSite(models, connections): site_name = None url = None articles = [] database = None def __init__(self, **kwargs): self.name = kwargs['name'] self.url = kwargs['url'] self.database = ... -
Are Django DB connections isolated between process?
If I close db connection in one process, will it affect other processes? Example: I'm running the same application with: gunicorn celery Management command: python /../../manage.py somecommand If I do something like this in somecommand: from django.db import connection connection.close_all() In that case will the connection to the database be closed in gunicorn and celery instances? PS. CONN_MAX_AGE is set to 3600. -
Is there a way to make Django report unit test errors as and when they occur?
Is there a tool/package to make Django report errors, perhaps to a socket or a file that can be tailed, as it goes through the tests. I hate to have to wait a good 15+ minutes for the whole test suite to be complete before seeing the failed tests. Particularly annoying when having upgraded Django, you find that a number of tests have errors. -
Moving a django project to production
I made a very simple form in Django on my laptop, and as i finished it, i bought a production server. I have limited understanding how the migration should be done. For my production server i only have SFPT connection, so i cant really do anything with the manage.py file. I originally created the project with sqlight however the production server has postgresql. I has able to create a test "helloworld" page on my prod server, and after that what i did was i simply uploaded all the files i wrote to the prod server. If i visit the site, i see an SQL error, that the tables are not found. This is understandable, because i havent created them. I thought Django will restore it from the models.py. My question is: How can i migrate the database to the prod server without access to the manage.py? From the test server i created a 'JSON' with python3 manage.py dumpdata > ..., however as i dont have access to and ssh for the prod server i cant load it with the manage.py there. Also is it correct to simply upload the created files to the prod server? Thanks -
Django ImportError out of the blue
I am getting ImportError everywhere in my app all of a sudden. I made no changes since yesterday, I did not pull any changes from origin, and these errors are happening in every branch. I can't even run the server. I have absolutely no idea how it just broke without even touching anything. The only thing I can think of is that yesterday I was watching a Python Udemy course and probably closed my current project in PyCharm. The Udemy course uses Python 3 but my app uses Python 2.7, but I am pretty sure I didn't even open the Udemy project (and if I had I don't see how that would have an effect in an entirely different project), all I did was just close the project of my app. -
django i18n - get current path for different language
I am using Django and developing an i18n site serving many languages. I want to make a modal that stays in base.html, so that users can switch the language wherever they are. I managed to do something like this. <div class="modal-body"> {% get_available_languages as languages %} {% for lang_code, lang_name in languages %} {% language lang_code %} <a href="{% url 'home' %}" class="btn lang-btn {% ifequal request.LANGUAGE_CODE lang_code %}selected{% endifequal %}">{{lang_code|lang_name}}</a> {% endlanguage %} {% endfor %} </div> Which turns out urls like:/ja/, /en/, /fr/, etc.. but this kind of approach links to the main page only. When using {{request.path}} or {{request.get_full_path}} for the url like: <a href="{{ request.path }}" class="btn lang-btn {% ifequal request.LANGUAGE_CODE lang_code %}selected{% endifequal %}">{{lang_code|lang_name}}</a> It doesn't include the i18n url patterns.. Is there any way for directing current url with request.path?? TARGET When in /foo/ : /ja/foo/ /en/foo/ /fr/foo/ When in /bar/ : /ja/bar/ /en/bar/ /fr/bar/ Thanks in advance! -
Django: Set kwargs value for excluded field in generic view
Hi I am trying since yesterday. models.py class Event(models.Model): def get_absolute_url(self): return reverse('events:event-detail', kwargs={'pk': self.pk}) urls.py url(r'^kategorie/(?P<pk>[0-9]+)/create/$', views.KategorieCreate.as_view(), name='kategorie-create'), html <a href="{% url 'events:kategorie-create' event.id %}">Neue Kategorie</a> views.py class KategorieCreate(generic.CreateView): model = Kategorie fields = '...' # 'event' is excluded template_name_suffix = '_create_form' def get_context_data(self, **kwargs): context = super(KategorieCreate, self).get_context_data(**kwargs) context['event'] = kwargs.get(self.pk) return context I received: NOT NULL constraint failed: events_kategorie.event_id -
How do i custom django admin site using jwt?
I tried to search google but didn't get anything relate to custom django admin site . I don't want to use session , i want admin site use jwt token. How to custom ? -
refer to the user_email in reply to a comment
we are using django-contrib-comments in are project for communication between stuff and clients. Staff communication work's internally and I've made a custom email notification system which will notify you every time some other stuff member left a comment on your page. Now the problem that I'm facing is that the user who want's to reply to a comment will only notify it's self and not the staff member who left a comment. Email notification setup is made of two parts, first part is for the staff member who is leaving a comment and second is for the user who is replying to the comment. Problem is how to refer to the user who all ready left a comment, I need his email, so I could add him to the recipient list so he will be notify when someone else replies to the comment. comment.user and comment.user_email are things on which you refer on the comment model, but I can not find how to refer to user_email who's all ready left a comment when you want to reply to it, this part of the documentation explain model fields, I can understand that user_email - The email of the user who posted … -
Django template takes long to load
I have a django template that receives from the server a long list (in size of almost 1 million!) and I want to show all the list in a table. the problem is that it takes really long (few minutes for sure)... what can I do? -
get unicode string in python/django
When I tried to print kwargs['instance'].__unicode__ in django post_save signal method it gives me an output like this<bound method BillRecord.__unicode__ of <BillRecord: [2L, 4L, 10L, 16L]>> How can I get values [2L, 4L, 10L, 16L] from the above output. -
How to use Django with Angular-cli@webpack
I have a working Django project. I want to use Angular 2 with it. I am new to Angular and taking a few tutorials. I have been following this link to use Django with Angular2. But due to some package incompatibilities I wanted to start a new angular project with angular-cli and pull in my code. But the angular-cli seems to have systemjs.config.js removed which was the file I had to edit to connect to the initial index.html code of Django in Angular2. So, now is there an alternative for systemjs.config.js ? Any pointers to tutorials, videos or documentations regarding Django integration with Angular-cli@webpack would be appreciated. -
how to add a select field in the forms.py
I have a forms.py I want to be able to see the select tag in HTML I'm getting an error forms.py class ArticleForm(ModelForm): class Meta: STATUS_CHOICES = ( ('d', 'Draft'), ('p', 'Published'), ) model = Article fields = ( 'title', 'description', 'article_header_image', 'status', ) widgets = { 'status': Select(STATUS_CHOICES), } models.py class Article(TimeStampedModel): """ Article model. """ STATUS_CHOICES = ( ('d', 'Draft'), ('p', 'Published'), ) title = models.CharField('title', max_length=150) description = models.TextField('content') status = models.CharField('article status', max_length=1, choices=STATUS_CHOICES, blank=True, null=True, default='p') article_header_image = models.ImageField( upload_to="artice__header_image/%Y/%m/%d" ) create.html <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <input class="btn" type="submit" value="Create" /> </form> I do not see the select tag on HTML html source <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Django Class Based Views Rock</title> <link rel="stylesheet" href="https://cdn.jsdelivr.net/materialize/0.98.2/css/materialize.min.css"> <style> .title { text-align: center; font-weight: 200; } </style> </head> <body> <div class="container"> <h3 class="title">Create New Article</h3> <form method="post" enctype="multipart/form-data"> <input type='hidden' name='csrfmiddlewaretoken' value='V6IJWF7lceEbe8pT4yN7GaCqgHnbZsbgpFWTcH9dwxzpNZzX2GFKILzpMyvs5Fls' /> <p><label for="id_title">Title:</label> <input id="id_title" maxlength="150" name="title" type="text" required /></p> <p><label for="id_description">Content:</label> <textarea cols="40" id="id_description" name="description" rows="10" required> </textarea></p> <p><label for="id_article_header_image">Article header image:</label> <input id="id_article_header_image" name="article_header_image" type="file" required /></p> <p><label for="id_status">Article status:</label> <select id="id_status" name="status"> <option value="">---------</option> <option value="d">Draft</option> <option value="p" selected="selected">Published</option> </select></p> <input class="btn" type="submit" value="Create" /> </form> … -
Remote control Web App
I am looking to build a small web app to control from a browser things I connect to the GPIO of a raspberry pi and I'm not sure the way to go so I'd like some advise if possible. Just to get a concept going, I'm looking to have only a few buttons on the app, 'on', 'off', right or left. I can program in PHP and HTML, do some javascript, jquery and python. I'm looking at write the server end in python as python has some nice libraries to control GPIOs and it is not too difficult. What I am a bit lost is on the front end. What comes to mind first is to use django and will allow to also use python. Also, not sure if this is even possible, but I think I could do some something like using javascript and AJAX. Basically, using event listeners so when I press a button, and if I keep it pressed, it will write to and xml or some file the gpoi up value, that a python script in the server will constantly be reading from, and when this gpoi up value gets picked up by the python script, … -
Is it "okay" for my view decorator to add an item to kwargs that are passed to the view function?
I wrote a decorator to wrap a lot of my views with. It essentially checks to see that the request.user is the 'owner' of an object. # urls.py ... urlpatterns = [ url(r'^(?P<pk>\d+)/$', views.my_view, name='my_view'), ] # decorators.py ... def user_can_access_object(function): def wrap(request, *args, **kwargs): my_object = get_object_or_404(MyModel, pk=kwargs['pk']) if request.user == my_object.owner: # I actually do more to ensure the user can access, but this is for my SO question to keep it simple. kwargs['my_object'] = my_object # <-- Am I doing something terrible here? return function(request, *args, **kwargs) else: raise PermissionDenied wrap.__doc__ = function.__doc__ wrap.__name__ = function.__name__ return wrap # views.py ... @login_required @user_can_access_object def my_view(request, pk, my_object): # Now that 'my_object' is set, my_view must be setup to accept it. Also, 'pk' is the pk for my_object. """" A view that does something to 'my_object'. """ ... some_function(my_object) ... return render(request, "my_template.html", some_context) Here is my original solution. # decorators.py ... def user_can_access_object(function): def wrap(request, *args, **kwargs): my_object = get_object_or_404(MyModel, pk=kwargs['pk']) if request.user == my_object.owner: return function(request, *args, **kwargs) else: raise PermissionDenied wrap.__doc__ = function.__doc__ wrap.__name__ = function.__name__ return wrap # views.py ... @login_required @user_can_access_object def my_view(request, pk): # This seems to be better, or at least …