Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to solve Jenkins Build trouble?
I have a Django project on BitBucket, so I was going to use Jenkins for CI, but the build keeps failing! Here is the script: cd $WORKSPACE virtualenv -q env . ./env/bin/activate cd requirements pip install -r base.txt cd .. cd manage python test_manage.py test --settings=test_site Here is the result(Jenkins console): ImportError: No module named test_site Build step 'Execute shell' marked build as failure [Cobertura] Publishing Cobertura coverage report... Finished: FAILURE How can I solve this problem ? -
How to increase RAM usage of Celery
I was using 8 GB ram machine, when i ran celery task in that system that particular task able to complete in 45mins Now i have switched to a machine of 40 GB ram, but still i am able to complete the same task in 35 mins. I hope celery is not able to make use of the 40 GB ram properly, how can i customize ram usage of Celery. Please help me with this problem. Thanks! -
How to add DateTimeField in django without microsecond
I'm writing django application in django 1.8 and mysql 5.7. Below is the model which I written class People(models.Model): name = models.CharField(max_length=20) age = models.IntegerField() create_time = models.DateTimeField() class Meta: db_table = "people" Above models create table like below. mysql> desc people; +-------------+-------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +-------------+-------------+------+-----+---------+----------------+ | id | int(11) | NO | PRI | NULL | auto_increment | | name | varchar(20) | NO | | NULL | | | age | int(11) | NO | | NULL | | | create_time | datetime(6) | NO | | NULL | | +-------------+-------------+------+-----+---------+----------------+ Here Django create datetime field with microsecond datetime(6) But I want datetime field without microsecond datetime I have other application, which also using same database and that datetime field with microsecond raising issue for me. -
django pass model fields to BetterForm
I am trying to use BetterForms to group the fields and add a legend to each group. For example i have this model: models.py class Doc(models.Model): series = models.CharField(max_length=50, help_text="2", blank=True, null=True, default=None) number = models.CharField(max_length=50, help_text="2", blank=True, null=True, default=None) name = models.CharField(max_length=150, help_text="3") citizenship = models.ManyToManyField(Citizenship, help_text="4") forms.py class DocForm(BetterForm): name = forms.CharField(max_length=150, help_text="3") class Meta: model = Doc fieldsets = [ ('main', {'fields': ['name', 'citizenship'], 'legend': 'I. PERSONAL DATA'}), ('main1', {'fields': ['series', 'number'], 'legend': 'II. PROFESSIONAL IDENTIFICATION'})] I have many more fields than i've written here. Is there a possibility to pass the model fields as in ModelForm instead of writing each field in the form again? -
Django manage.py runserver unhandled exception in thread error
In django when I am trying to run manage.py runserver its giving an unhandled exception in thread error. I am using 'ENGINE': 'django.db.backends.sqlite3' Unhandled exception in thread started by Traceback (most recent call last): File "C:\Python27\lib\site-packages\django-1.11.5-py2.7.egg\django\utils\autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "C:\Python27\lib\site-packages\django-1.11.5-py2.7.egg\django\core\management\commands\runserver.py", line 125, in inner_run self.check(display_num_errors=True) File "C:\Python27\lib\site-packages\django-1.11.5-py2.7.egg\django\core\management\base.py", line 359, in check include_deployment_checks=include_deployment_checks, File "C:\Python27\lib\site-packages\django-1.11.5-py2.7.egg\django\core\management\base.py", line 346, in _run_checks return checks.run_checks(**kwargs) File "C:\Python27\lib\site-packages\django-1.11.5-py2.7.egg\django\core\checks\registry.py", line 81, in run_checks new_errors = check(app_configs=app_configs) File "C:\Python27\lib\site-packages\django-1.11.5-py2.7.egg\django\core\checks\urls.py", line 16, in check_url_config return check_resolver(resolver) File "C:\Python27\lib\site-packages\django-1.11.5-py2.7.egg\django\core\checks\urls.py", line 26, in check_resolver return check_method() File "C:\Python27\lib\site-packages\django-1.11.5-py2.7.egg\django\urls\resolvers.py", line 254, in check for pattern in self.url_patterns: File "C:\Python27\lib\site-packages\django-1.11.5-py2.7.egg\django\utils\functional.py", line 35, in get res = instance.dict[self.name] = self.func(instance) File "C:\Python27\lib\site-packages\django-1.11.5-py2.7.egg\django\urls\resolvers.py", line 405, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "C:\Python27\lib\site-packages\django-1.11.5-py2.7.egg\django\utils\functional.py", line 35, in get res = instance.dict[self.name] = self.func(instance) File "C:\Python27\lib\site-packages\django-1.11.5-py2.7.egg\django\urls\resolvers.py", line 398, in urlconf_module return import_module(self.urlconf_name) File "C:\Python27\lib\importlib__init__.py", line 37, in import_module import(name) File "C:\Users\MY\Desktop\myproject\firstproject\firstproject\urls.py", line 18, in url(r'^admin/', admin.site.urls), NameError: name 'url' is not defined -
Django Rest Framework authtoken not migrating in MySql but migrating in SQLite
Django Rest Framework authtoken not migrating in MySql but migrating in SQLite Applying authtoken.0001_initial... OK Applying authtoken.0002_auto_20160226_1747...Traceback (most recent call last): File "C:\Users\Guest01\Envs\qcrb\lib\site-packages\mysql\connector\django\base.py", line 177, in _execute_wrapper return method(query, args) File "C:\Users\Guest01\Envs\qcrb\lib\site-packages\mysql\connector\cursor.py", line 515, in execute self._handle_result(self._connection.cmd_query(stmt)) File "C:\Users\Guest01\Envs\qcrb\lib\site-packages\mysql\connector\connection.py", line 488, in cmd_query result = self._handle_result(self._send_cmd(ServerCmd.QUERY, query)) File "C:\Users\Guest01\Envs\qcrb\lib\site-packages\mysql\connector\connection.py", line 395, in _handle_result raise errors.get_exception(packet) mysql.connector.errors.ProgrammingError: 1091 (42000): Can't DROP 'user_id'; check that column/key exists During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\Guest01\Envs\qcrb\Lib\site-packages\django\tokentutor\manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "C:\Users\Guest01\Envs\qcrb\lib\site-packages\django\core\management\__init__.py", line 367, in execute_from_command_line utility.execute() File "C:\Users\Guest01\Envs\qcrb\lib\site-packages\mysql\connector\connection.py", line 488, in cmd_query result = self._handle_result(self._send_cmd(ServerCmd.QUERY, query)) File "C:\Users\Guest01\Envs\qcrb\lib\site-packages\mysql\connector\connection.py", line 395, in _handle_result raise errors.get_exception(packet) django.db.utils.ProgrammingError: Can't DROP 'user_id'; check that column/key exists -
count views for anonymous users in django
I am creating a blog just for practice and i recently added the views counter function the problem is when an anonymous user open the post django raise an error because in the post_detail view i request the username this is the view: def post_detail(request, post_id): post = Post.objects.get(id=post_id) if UserSeenPosts.objects.filter(post=post, user=request.user).exists(): print "all ready" else: post.views += 1 post.save() UserSeenPosts.objects.create(user=request.user, post=post) return render(request, 'blog/detail.html', {'Post': Post.objects.get(id=post_id)}) the UserSeenPosts model: class UserSeenPosts(models.Model): user = models.ForeignKey(User, related_name='seen_posts') post = models.ForeignKey(Post) -
unable to install mysqlclient on mac
Hi guys i'm attempting to install mysqlclient using the command: pip install mysqlclient but i get the following error: Using cached mysqlclient-1.3.12.tar.gz Complete output from command python setup.py egg_info: /bin/sh: mysql_config: command not found Traceback (most recent call last): File "<string>", line 1, in <module> File "/private/var/folders/8d/xdwdnphs1w5b_vtxrc67__5h0000gn/T/pip-build-ifu54299/mysqlclient/setup.py", line 17, in <module> metadata, options = get_config() File "/private/var/folders/8d/xdwdnphs1w5b_vtxrc67__5h0000gn/T/pip-build-ifu54299/mysqlclient/setup_posix.py", line 44, in get_config libs = mysql_config("libs_r") File "/private/var/folders/8d/xdwdnphs1w5b_vtxrc67__5h0000gn/T/pip-build-ifu54299/mysqlclient/setup_posix.py", line 26, in mysql_config raise EnvironmentError("%s not found" % (mysql_config.path,)) OSError: mysql_config not found I uninstalled python3 using brew uninstall --force python3 and downloaded the binary from pythons website but to no avail. I also attempted to download mysql connector from oracle website and again to no avail. I have tried upgrading pip again still doesnt work. PS mysql is running in a docker container and i'm running django on my local machine. Any suggestions on why i'm getting an error attempting to install mysqlclient -
Django-admin inline default value
admin.py class CaseNoteInline(admin.TabularInline): model = CaseNote extra = 1 max_num = 5 i have a some column in CaseNote which is "User" and i want to set default value for that. -
Caching a frequently used queryset in django
I have a model which is being used a lot in my app (and the data in it almost never changes, unless a dev wants to change something). I'd like to cache this queryset to see what difference it will make for the speed of my views, but can't really get my head around it. I'm using redis and i set the cache like this: m = MyModel.objects.all() cache.set('m', m, timeout=None) And then I get it like this: c = cache.get('m') for x in range(1,200): o = c.get(pk=x) ... which of course leads to 200 DB queries. How can I store everything in the cache so that every lookup I do gets the data from the cache? Should I set each individual entry in the cache such as cache.set(primary_key, object)? Or should I convert it to a dictionary or something? -
How to create models in django with interrelationship between tables?
Most of the examples i googled were related to blogpost and i couldnt figure out how i could use django model/views(ORM) for practicing custom application. I have three tables:- user,license and common. Here is the use case i thought of mysql> describe user; +--------+-------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +--------+-------------+------+-----+---------+-------+ | userid | int(11) | NO | PRI | NULL | | | email | varchar(55) | NO | UNI | NULL | | | fname | varchar(22) | NO | | NULL | | | lname | varchar(22) | NO | | NULL | | +--------+-------------+------+-----+---------+-------+ mysql> describe license; +-----------+-------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +-----------+-------------+------+-----+---------+-------+ | licenseid | int(11) | NO | PRI | NULL | | | category | varchar(11) | NO | UNI | NULL | | +-----------+-------------+------+-----+---------+-------+ mysql> describe common; +-----------+---------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +-----------+---------+------+-----+---------+-------+ | licenseId | int(11) | NO | | NULL | | | userId | int(11) | NO | | NULL | | The common table will store the userid and licenseid which will be … -
CSRF verification failed. Request aborted. Django 1.9
i'm just starting to implement post request on my project but i have trouble with the csrf token. Even if it seem i used it correctly (I use render, have cookie enable, {% csrf_token %} is in the html code and i have the middleware in django settings) view.py : form = mouvementForm(request.POST or None) if form.is_valid(): pont = form.cleaned_data['pont'] dateheure = form.cleaned_data['dateheure'] poid = form.cleaned_data['poid'] dsd = form.cleaned_data['dsd'] typepesee = form.cleaned_data['typepesee'] #Connection to 'erp-site' DB return render(request, 'mouvementCreation.html', locals()) template : <form name="Form1" method="post" action="" enctype="text/plain" id="Form1"> {% csrf_token %} <input type="text" id="Editbox9" style="position:absolute;left:87px;top:46px;width:86px;height:16px;line-height:16px;z-index:173;" name="pont" value="" spellcheck="false"> <input type="text" id="Editbox34" style="position:absolute;left:87px;top:80px;width:86px;height:16px;line-height:16px;z-index:174;" name="dateheure" value="" spellcheck="false"> <input type="text" id="Editbox35" style="position:absolute;left:87px;top:114px;width:87px;height:16px;line-height:16px;z-index:175;" name="poid" value="" spellcheck="false"> <input type="text" id="Editbox36" style="position:absolute;left:88px;top:153px;width:84px;height:16px;line-height:16px;z-index:176;" name="dsd" value="" spellcheck="false"> <input type="text" id="Editbox37" style="position:absolute;left:87px;top:187px;width:86px;height:16px;line-height:16px;z-index:177;" name="typepesee" value="" spellcheck="false"> <input type="submit" id="Button14" name="submit" value="Submit" style="position:absolute;left:361px;top:65px;width:96px;height:25px;z-index:178;"> </form> Middleware settings : MIDDLEWARE_CLASSES = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] i have searched on multiple post and tried alot of fix but so far nothing worked and i'm still getting "Reason given for failure: CSRF token missing or incorrect." -
Django retrieve saved image as base64 string
I am trying to upload image to file system using python django as base64 string and retrieve the same as base64 string. in my model.py: Class Test(object): mission = models.TextField(blank=True) image = models.ImageField(upload_to='documents/images/',blank=True) account = models.OneToOneField(Account, related_name='account') def __str__(self): return '{}:{}'.format(self.mission, self.image) in my view.py def add_image(request, account): req = get_request_json(request) data = Test.objects.add_image(account, req) in my manager.py Class TestManager(models.Manager): def add_image(self, account, input): acc = self.get(account=account) format, imgstr = input_data.get('image').split(';base64,') ext = format.split('/')[-1] img = ContentFile(imgstr, name='temp.' + ext) acc.save() return acc; def get_doctor_profile(self, account): try: profile = self.get(account=account) except self.model.DoesNotExist: profile = [] except (MultipleObjectsReturned, ValueError, Exception) as e: profile = [] raise IndivoException(e) else: pass finally: return profile The path where the image is saved is added in the database but while returning the response I get the following error after saving and while using get TypeError: <ImageFieldFile: documents/images/temp_fRRD2oc.jpeg> is not JSON serializable. I think the error is in my models.py def __str__(self): but I am not aware of how to fix this. I need to return the saved image file as base64 string in the response. Can anyone point me in the right direction on how to fix this. -
Wagtail admin icons disappear when running collectstatic and putting everything on S3
I've been working locally and on my server and everything looks good. Then I configure django-storages to store static files and media on my S3 bucket. Everything works except for the icons/glyphicons on the admin interface. Instead of the nice pretty graphic icons, I see letters. For example once you log in, you have the search bar on the left side. Normally you would see a looking glass in the search box. I lost the looking glass and now I just see a lowercase f. My question is this. What do I search for to start debugging this? What wagtail file is collectstatic not collecting? Steps to Reproduce Set up a wagtail site Set up a bucket on s3 Install django-storages Configure django-storages to use your bucket ./manage.py collectstatic Technical details Python version: 3.5.2 Django version: 1.11.5 Wagtail version: 1.12.2 Browser version: firefox, chromium, chrome -
Input from is only 1 in html
Input from is only 1 in html.Im making Login form in index.html like <form class="my-form" action="{% url 'accounts:regist_save' %}" method="POST"> <div class="form-group"> <label for="id_username">Username</label> {{ form.username }} {{ form.username.errors }} </div> <div class="form-group"> <label for="id_email">Email</label> {{ form.email }} {{ form.email.errors }} </div> <div class="form-group"> <label class="control-label" for="id_password1">Password</label> {{ form.password1 }} {{ form.password1.errors }} </div> <div class="form-group"> <label class ="control-label" for="id_password2">Password(Conformation)</label> {{ form.password2 }} {{ form.password2.errors }} <p class="help-block">{{ form.password2.help_text }}</p> </div> <div class="form-group"> <div> <input type="submit" class="btn btn-default" value="SEND"> </div> </div> {% csrf_token %} </form> in forms.py class RegisterForm(UserCreationForm): class Meta: model = User fields = ('username', 'email',) def __init__(self, *args, **kwargs): super(RegisterForm, self).__init__(*args, **kwargs) self.fields['username'].widget.attrs['class'] = 'form-control' self.fields['email'].widget.attrs['class'] = 'form-control' self.fields['password1'].widget.attrs['class'] = 'form-control' self.fields['password2'].widget.attrs['class'] = 'form-control' in urls.py like urlpatterns = [ url(r'^login/$', login,{'template_name': 'index.html'},name='login'), ] Only Username field is shown in browser, but others are not there.By using Google validation,only Username field has input tag, but others do not have.Why does it happen?How should i fix this? -
Django: how to use a template tag as an arguments for another template tag
I need to use a template tag inside another tag that is a custom tag and it gives me this error: Could not parse the remainder: '{{message.tags}}' from '{{message.tags}}' How can I fix this? TIA for any help! html: <div class="bootstrap-iso"> {% if messages %} <div class="messages "> {% for message in messages %} <div {% if message.tags %} class="alert {{ message.tags }} alert-dismissible" role="alert" {% endif %}> <strong> {% get_message_print_tag {{message.tags}} %}: </strong> {{ message }} <a href="#" class="close" data-dismiss="alert" aria-label="close">×</a> </div> {% endfor %} </div> {% endif %} </div> -
Unknown code being added to HTML template when running local server
I was building a profile picture feature, it was working fine so I left it for a while, probably a week. I came back to it and ran the local server, but when I do there's a few lines that appear in the console. But do not exist on the source file. Source file: <script type='text/javascript'> Dropzone.options.myDropzone = { autoProcessQueue : false, paramName: 'uploaded_image', dictDefaultMessage: "Drag and drop files or click here to upload picture", init: function() { var submitButton = document.querySelector("#submitBtn") myDropzone = this; submitButton.addEventListener("click", function() { myDropzone.processQueue(); }); // Automatically overwrites file so the user can only upload one this.on("addedfile", function() { document.getElementById('submitBtn').style.visibility = "visible"; }); this.on('addedfile', function(){ if (this.files[1]!=null){ this.removeFile(this.files[0]); } }); } }; </script> <!-- Modal --> <div id="picModal" class="modal"> <!-- Modal content --> <div class="modal-content"> <span class="close"></span> <form action="{% url 'profile_test' %}" method='POST' enctype="multipart/form-data" class="dropzone" id="my-dropzone">{% csrf_token %} <!-- submit button stays hidden by default, until user selects a picture --> <button id='submitBtn' type='submit' class='pic-submit-button' style='visibility: hidden;'> Submit </button> <input id='submit-all' type='file' name='uploaded_image'/> {{form}} </form> </div> </div> Now the code I'm seeing when I run the server is only a few lines, and it's in the HTML that creates the modal: <!-- Modal --> <div … -
saving html content as json in django db
I'm using DJango to save some html designs in my db. For example here 'Body' has some html content: When I serialize the content into json, it seems like the html tags get eliminated: from django.core import serializers def list_templates(request): # retrieve all the templates from the DB all_templates = Template.objects.all() return HttpResponse(serializers.serialize('json', all_templates)) Here is what I see: Any recommendations on best practices for saving html codes and their serialization? -
Filtering on the basis of tags in Django Rest Framework
I have an array of tags as a model field, I want to filter out based on those array elements. here is the model in which tag field is an array type I guess. class Mineral(models.Model): name=models.CharField(max_length=500) tags=TaggableManager() def __unicode__(self): return self.name Now in my view, I want to filter out based on this tag field I can do that using Django way like this class MineralList(APIView): queryset = Mineral.objects.all() serializer_class = MineralSerializer permission_classes = [AllowAny] def get(self, request, format=None): mineral = Mineral.objects.all() tags = request.query_params.get('tags', None) name= request.query_params.get('name',None) if tags is not None: tags = tags.split(',') mineral = mineral.filter(tags__name__in=tags).distinct() if name: mineral = mineral.filter(name=name) serializer = MineralSerializer(mineral, many=True) return Response(serializer.data) How can I do that in REST way using filter backends and Filter class -
Default value for a field, based on another field's value
How can I define the default for a Django model field, to be based on the value of another field on the same instance? I want to define a code for the model based on the created timestamp: from django.db import models class LoremIpsum(models.Model): code = models.CharField( max_length=100, default=( lambda x: "LOREM-{0.created:%Y%m%d-%H%M%S}".format(x)), ) created = models.DateTimeField( auto_now_add=True, ) That doesn't work because the function defined for default receives no argument. How can I define a default for the code field such that it is derived from that instance's created field value? -
Django custom template tag throwing an error
I am trying to use a custom template tag and it gives me this error when I am trying to get a rendered page: Invalid block tag on line 29: 'get_message_print_tag', expected 'empty' or 'endfor'. Did you forget to register or load this tag? I am trying to get a simple title for my flash messages based on {{message.tags}} and make it bold in my template. Where am I making a mistake? apptags.py: from django import template register = template.Library() def get_message_print_tag(value): '''return a string for a message tag depending on the message tag that can be displayed bold on the flash message''' if 'danger' in value.lower(): return 'ERROR' elif 'success' in value.lower(): return 'SUCCESS' else: return 'NOTE' html: {% load apptags %} <div class="bootstrap-iso"> {% if messages %} <div class="messages "> {% for message in messages %} <div {% if message.tags %} class="alert {{ message.tags }} alert-dismissible" role="alert" {% endif %}> {% if message.level == DEFAULT_MESSAGE_LEVELS.ERROR %}Error: {% endif %} <strong> {% get_message_print_tag {{message.tags}} %} </strong> {{ message }} <a href="#" class="close" data-dismiss="alert" aria-label="close">×</a> </div> {% endfor %} </div> {% endif %} </div> -
Store numpy array in session (Alternatives)
I have a class in a view that does some calculations. The instance of this class is passed to a Django template context and the results are displayed in the html. On the other hand, I need to store these results somewhere for later use in another view, where a pdf document is generated using these results. The results are large lists of data. For example: def view_one(request): # some code class_instance = SomeClass(form.cleaned_data) html = render_to_string('results.html', {'instance': class_instance}) return JsonResponse({"result": html}) def view_two(request): # some code class_pdf = GeneratePdf(class_instance) # How can I pass the class_instance data? # some code The results are large lists of data. Should I use Django request session to store the data? Can I use Celery? There is another alternative? -
apache does not pass request to Django (404 not found)
I have a custom 404 page setup for the site, which works fine, like this: when I hit mysite.com/fdsafsadfdsa which doesn't exist, the custom 404 page shows up. However if I add a urlencoded '/' which is '%2f' at the end of url, mysite.com/fdsafsadfdsa%2f, and this gives me the apache 404 not found. it looks like apache decided to handle this 404 itself instead of passing down to Django Anybody has idea why this is happening? -
How to force 'django.contrib.sites' to be migrated first?
When using python manage.py makemigrations on a project that uses functions from the django.contrib.sites, I always received the error: django.db.utils.OperationalError: no such table: django_site. If I comment out the parts of my code that use app, and run makemigrations it works, and then I can uncomment. This (bad) approach works, but I would like to make it work correctly. I already put this app in the top of settings.INSTALLED_APPS, but it does not solve it. -
Adding charaters to a string in specified places - Django
I have a simple python action that I want to take. I have a string. something like 2364968438. I want to take that string that I have and add a - between specific places in the string to make it look like a phone number. something like this 236-496-8438 within my django/python project. I know i am going to have to splice the string into parts but I am having trouble with it. Does it matter if it is a string or integer?