Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Use of a boolean flag inside django 1.9 (template)
I have the following database models (truncated): class Enzymes(models.Model): class Meta: verbose_name_plural = 'Enzymes' barcode = models.CharField(max_length=200) class Activitydiagram(models.Model): enzymes = models.ForeignKey(Enzymes, on_delete=models.CASCADE) description = models.CharField(max_length=200) class Spectraimage(models.Model): enzymes = models.ForeignKey(Enzymes, on_delete=models.CASCADE) activity = models.ForeignKey(Activitydiagram, on_delete=models.CASCADE) description = models.CharField(max_length=200) I am trying to make it so that on my webpage, it shows the data in blocks. Specifically that it shows the spectraimage(s) under the corresponding activity diagram, followed by any 'unassigned' spectraimages as follows: Activitydiagram x1 Spectraimage y1 Spectraimage y2 Activitydigram x2 Spectraimage y3 Spectraimage y4 (that belongs to the enzyme but doesn't have a matching activity diagram) I got most of the desired behaviour working except, getting they4 spectraimage to show apart from the rest. I was looking into using a boolean flag where in my html file I would do something like this (Notice the bits between **): views.py class DetailView(LoginRequiredMixin, generic.DetailView): template_name = 'gts/detail.html' model = Enzymes def get_context_data(self, **kwargs): context = super(DetailView, self).get_context_data(**kwargs) enzyme = context['object'] activities = Activitydiagram.objects.filter(enzymes=enzyme) spectras = Spectraimage.objects.filter(enzymes=enzyme) context['activities'] = activities context['spectras'] = spectras return context details.html {% if activities %} <hr/> <h3> Activity Diagram </h3> <br/> {% for activity in activities %} <img class="img-responsive" src="/{{activity.activity_image}}" onerror="imgError(this);"/> <br/> {% if spectras %} … -
How Users can upload an responsive image within markdown on a Django Blog?
I have done the following: pip install django-markdown-deux added to INSTALLED_APPS in settings.py markdown_deux and then in app_detail.html loaded the markdown tags & added the markdown filter to instance.content {{ instance.content|markdown}} Now when uploading image via markdown how to make that image responsive using built-in django/python or any third party but without using JScript or JQuery?? Please guide. -
Why select_for_update works in concurrent inserts?
I have a code, that should work under concurrent request and heavy load. I wrote an example to give a better understanding of that I'm trying to do: def add_tag(): with transaction.atomic(): image = Image.objects.get(pk=2) tag = Tag.objects.get(pk=6) image.tags.add(tag) # concurrent insert return 'done' class Command(BaseCommand): def handle(self, *args, **options): with ProcessPoolExecutor(max_workers=3) as executor: futures = [] for _ in range(3): futures.append(executor.submit(add_tag)) for future in as_completed(futures): print(future.result()) And here is my models: class Image(models.Model): title = models.CharField(max_length=255) tags = models.ManyToManyField('ov_tags.Tag') class Tag(models.Model): title = models.CharField(max_length=255) I'm trying to insert in ManyToMany-relation table in parallel. Obviously, this causes an error, because of READ COMMITED isolation level: django.db.utils.IntegrityError: duplicate key value violates unique constraint Absolutely fine, but how to remove this error completely? To protect my image, I tried to use select_for_update on Image select. image = Image.objects.select_for_update().get(pk=2) And... It works! I run it several times. There are no errors anymore and item inserted correctly. But I don't know why? Is select_for_update locking relational table anyhow? Or is it happening on an application side? Is there a right way to achieve such behavior? Can I use empty select to lock for insert? SELECT "image_tags"."tag_id" FROM "image_tags" WHERE ("image_tags"."tag_id" IN (6) AND "image_tags"."image_id" … -
pip install django-twilio Error installation
im trying to install django-twilo using pip Getting error doc Could not find a version that satisfies the requirement django-twillio (from versions: ) No matching distribution found for django-twillio -
No gray timepicker to use on Django template
I am placing the Jquery code for no gray time picker. <input id="my_timepicker_input" name="my_timepicker_input" type="text"> <script type="text/javascript" src="ng_all.js"></script> <script type="text/javascript" src="ng_ui.js"></script> <script type="text/javascript" src="components/timepicker.js"></script> <script type="text/javascript"> ng.ready( function() { var my_timepicker = new ng.TimePicker({ input:'my_timepicker_input' }); }); </script> This code is work in HTML input. When i have integrated it with django template the same shows nothing. image showing timepicker in html page when i have used with django it shows only a text box. Not showing the visual clock in the above picture. Please help me... i dont know anything about jquery. I just want to set time in the web page for alarm. -
How to send img src from templates to modules
There is a img in templates: <div class="header content clearfix"> <img class="logo" src="timg.png"> </div> Now I need to send this image's "src" attribute to modules.py, How could I code? -
Switch "like button" using js in django
I have implemented like button in my Django project, everything is working fine except like and dislike button aren't switching after clicking on them, to change I have to refresh the whole page! how to make dislike button display immediately after liking it and vice versa? Here's the code HTML <p> <strong id="like_count">{{ post.likes }}</strong> people like this category {% if user.is_authenticated %} <button id="likes" data-post_id="{{post.id}}" class="btn btn-primary" type="button"> <span class="glyphicon glyphicon-thumbs-up"></span> </button> {% endif %} </p> JS $('#likes').click(function(){ var postid; postid= $(this).attr("data-post_id"); $.get('/blog/like_post/', {post_id: postid}, function(data){ $('#like_count').html(data); $('#likes').hide(); }); }); $('#likes').click(function() { $('#display_advance').toggle('1000'); $("i", this).toggleClass("glyphicon glyphicon-thumbs-down glyphicon glyphicon-thumbs-up"); }); Thank you -
Apache server, user can't access local network file link
I created Django application and use Apache2 WSGI to host the server. Everything is fine, however when I add the link in the html file which link to local network another server, when I try to click to access this link, Apache raise the 404 page not found error. When I paste the link directly in web browser, I can access the link. Do I miss to configure something in Apache2? below is detail: Apache server is 10.10.10.14 Windows File server is 10.10.20.163 (share folder named "share") They all in LAN and I would like to link File server file link(\10.10.20.163\share\test.txt) on the Apache, so the user can access file in Django application. Code: test file -
Django: want to display ValidationError message without showing "Please correct the error below."
I have a form raising a ValidationError in admin panel, like this class HistoryForm(forms.ModelForm): class Meta: model = History fields = '__all__' def clean(self): raise ValidationError("A history error") When the ValidationError is raised, the admin page always showing "Please correct the error below." with the error message "A history error". Now I want to show the error message "A history error" only without "Please correct the error below.", how can I achieve it? -
Excluding More than one columns at once?
Suppose my models.py is like so: class Table(models.Models): col1 = models.BooleanField() col2 = models.BooleanField() col3 = modals.BooleanField() col4 = modals.BooleanField() Now I want to filter the result such that I get only those rows where the value of the first column i.e., col1 is true and rest of the columns have a false value. There may be more than four columns. -
Displaying the child elements of a particular node in a boot of a bootstrap tree using DJango
i am developing a webpage in DJANGO which contains a bootstrap tree view. Now if i click o a particular node i need to display the children in a bootstrap list. Here is my view def get_context_data(self, **kwargs): context = dict() organization = Organization.objects.all() orglocations = Orglocations.objects.all() locationprocessarea = Locationprocessarea.objects.all() processareaasset = Processareaasset.objects.all() processtaglink = Processareaassettaglink.objects.all() context["TreeStructure"] = [ { 'text': organizations.name, 'nodes': [ { 'text': orglocationss.name, 'nodes': [ { 'text': processarea.name, 'nodes': [ { 'text': processasset.name, 'nodes':[{ 'text':processareafilter.name, 'nodes':[{ 'text':taglink.name }for taglink in processtaglink.filter(areaassetid=processareafilter.id)] }for processareafilter in processareaasset.filter(parentassetid=processasset.id)] } for processasset in processareaasset.filter(processareaid=processarea.id).filter(parentassetid__isnull=True)] } for processarea in locationprocessarea.filter(locationid=orglocationss.id)] } for orglocationss in orglocations.filter(organizationid_id=organizations.id)] } for organizations in organization.filter(id=1)] return { "tree_view": context } thanks in advanceenter code here -
Admin and Meta don't see the fields of parent abstract classes
I use Django 1.10. I have the following model structure: class GenericPage(models.Model): """Abstract page, other pages inherit from it.""" book = models.ForeignKey('Book', on_delete=models.CASCADE) class Meta: abstract = True class GenericColorPage(models.Model): """Abstract page that is sketchable and colorable, other pages inherit from it.""" sketched = models.BooleanField(default=False) colored = models.BooleanField(default=False) class Meta: abstract = True class GenericBookPage(GenericColorPage): """A normal book page, with a number. Needs to be storyboarded and edited.""" ### #various additional fields ### class Meta: # unique_together = (('page_number', 'book'),) # impedes movement of pages ordering = ('-book', '-page_number',) abstract = True objects = BookPageManager() # the manager for book pages class BookPage(GenericBookPage): """Just a regular book page with text (that needs to be proofread)""" proofread = models.BooleanField(default=False) Additionally, an excerpt from Admin: class BookPageAdmin(admin.ModelAdmin): # fields NOT to show in Edit Page. list_display = ('__str__', 'page_name', 'sketched', 'colored', 'edited', 'proofread',) list_filter = ('book',) readonly_fields = ('page_number',) # valid page number is assigned via overridden save() in model actions = ['delete_selected',] I tried to do ./manage.py makemigrations but if throws the following errors: <class 'progress.admin.BookPageAdmin'>: (admin.E116) The value of 'list_filter[0]' refers to 'book', which does not refer to a Field. progress.BookPage: (models.E015) 'ordering' refers to the non-existent field 'book'. In … -
Django/TinyMCE: How to adjust individual HtmlField's editor height?
Currently, I have a model Section with two HTMLField and will be edited through admin panel, like this class Section(models.Model): question = tinymce_models.HTMLField() answer= tinymce_models.HTMLField() Now, I want to set height of editor for question and answer, may be 100px for question and 50 px for answer. I know that adjusting TINYMCE_DEFAULT_CONFIG in setting.py can change height of HTMLField's widget, however, it is just a global setting for all HTMLField, not individual. TINYMCE_DEFAULT_CONFIG = { 'plugins': "table,spellchecker,paste,searchreplace", 'theme': "advanced", 'cleanup_on_startup': True, 'custom_undo_redo_levels': 10, 'width':'100%', 'height':300, } How can I set individual widget height? -
Domain name masking for django webapp
I have a website with the domain address: www.example.com. We are providing a SaaS solution. The issue is we are facing a demand from some clients & that is domain name masking, i.e. the client wants to access my website from www.client1website.com & www.client2website.com & so on.... Is there any option that would be possible in Django? I dont want to change the Allowed Host thing as that would make the service non-scalable. FYI: I am using Apache as of now & can also move to nginx of needed. -
django template 2 conditions in ifnotequal
I want to know if there is a way to include 2 conditions in a ifnotequal django template tag, such that the the 2 conditions are checked simultaneously. For eg: {% ifnotequal cond1 and cond2 %} #do something here {% endifnotequal %} #This code doesn't seem to work though Or is there any other way in which 2 conditions, each containing equality comparison between 2 fields of django model instances. My exact code in the template is: {% ifnotequal user.profile.rollno applied_job.student_id %} {% ifnotequal job.company applied_job.student_applied_job %} I want the above 2 conditions to be simultaneously evaluated. Is there any other better way to do it? -
In django, why does this call to save() clears data from parent table?
I am starting out with django and have gone through only beginners' documentation. I was trying out the following. models.py from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver from org.models import Organization # Create your models here. class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) organization = models.ForeignKey(Organization, null=True) @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() When I create a user, the code works fine. Row gets added to auth_user table and to 'profile' table. At the time of user creation I do not associate Organization to user. organization_id in the 'profile' table remains NULL. mysql> select * from user_profile; +----+---------------+---------+ | id | organization_id | user_id | +----+---------------+---------+ | 2 | NULL | 3 | +----+---------------+---------+ Later I associate user to organization. I have the following code. views.py ... def user_association_done(request): organization_id = request.POST['organization_id'] user_id = request.POST['user_id'] organization = Organization(id=organization_id) user = User(id=user_id) user.profile.organization = organization user.save() return HttpResponse('Done') ... The code above associates the organization to user (entry in the profile table gets updated to populate the organization_id.), mysql> select * from user_profile; +----+---------------+---------+ | id | organization_id | user_id | +----+---------------+---------+ … -
how to make dislike button display immediately after liking it and vice versa? In Django
I have successfully created a like button which works, and if i like a post the counter is incremented and it doesn't show the unlike button immediately, i have refresh the page for it display and even after refreshing it says like instead of unlike but if i click on it it reduces the count i.e unlikes it, So how to make dislike button display immediately after liking it and vice versa? Thank you Here's the code models.py class Post(models.Model): author = models.ForeignKey('auth.User') title = models.CharField(max_length=200) text = models.TextField() created_date = models.DateTimeField(default=timezone.now) published_date = models.DateTimeField(blank=True,null=True) likes = models.IntegerField(default=0) def publish(self): self.published_date = timezone.now() self.save() def __str__(self): return self.title Views.py def like_post(request): liked = False if request.method == 'GET': post_id = request.GET['post_id'] post = Post.objects.get(id=int(post_id)) if request.session.get('has_liked_'+post_id, liked): print("unlike") if post.likes > 0: likes = post.likes - 1 try: del request.session['has_liked_'+post_id] except KeyError: print("keyerror") else: print("like") request.session['has_liked_'+post_id] = True likes = post.likes + 1 post.likes = likes post.save() return HttpResponse(likes, liked) def post_detail(request, pk): post = get_object_or_404(Post, pk=pk) Post.objects.get(pk=pk) post_id = post.pk liked = False if request.session.get('has_liked_' + str(post_id), liked): liked = True print("liked {}_{}".format(liked, post_id)) context = {'post': post, 'liked': liked} return render(request, 'blog/post_detail.html', {'post': post}) urls.py url(r'like_post/$', views.like_post, name='like_post'), … -
allow users to design forms with choices
let's say I have an app that's suppose to allow (fashion designers) to post a "Design with Customizations" the wanted result in the template is like this : Dress: Please select material : 1- wool, 2-cotton, 3-cashmere (only one can be selected) what colours would you like : black $10, blue, red, yellow (multiple selections) I'd like to allow designers to add options with choices and decide if (customers) can select one choice (Radio Group) or Multiple choices (check boxes) with extra charge and decide default ones... ** Models.py ** class Choice(models.Model): # e.g red name = models.CharField(max_length=500) extra_charge = models.DecimalField(default=0, max_digits=10, decimal_places=2) class Option(models.Model): # what colours? name = models.CharField(max_length=500) choice = models.ForeignKey(Choice) class Dress(models.Model): options = models.ManyToManyField(Choice, related_name='Dress') name = models.CharField(max_length=500) price = models.DecimalField(max_digits=10, decimal_places=2) I have been working on Django for a while now but I have no idea how to go about this.... -
Unable to run django migrations because of missing contenttypes
I'm trying to run my Django 1.10 based app migrations on a blank database with: python manage.py migrate --run-syncdb but this fails with: Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/usr/local/myproject/.env/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line utility.execute() File "/usr/local/myproject/.env/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 359, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/myproject/.env/local/lib/python2.7/site-packages/django/core/management/base.py", line 294, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/myproject/.env/local/lib/python2.7/site-packages/django/core/management/base.py", line 345, in execute output = self.handle(*args, **options) File "/usr/local/myproject/.env/local/lib/python2.7/site-packages/django/core/management/commands/migrate.py", line 224, in handle self.verbosity, self.interactive, connection.alias, apps=post_migrate_apps, plan=plan, File "/usr/local/myproject/.env/local/lib/python2.7/site-packages/django/core/management/sql.py", line 53, in emit_post_migrate_signal **kwargs File "/usr/local/myproject/.env/local/lib/python2.7/site-packages/django/dispatch/dispatcher.py", line 191, in send response = receiver(signal=self, sender=sender, **named) File "/usr/local/myproject/.env/local/lib/python2.7/site-packages/django/contrib/contenttypes/management.py", line 122, in update_contenttypes for ct in ContentType.objects.using(using).filter(app_label=app_label) File "/usr/local/myproject/.env/local/lib/python2.7/site-packages/django/db/models/query.py", line 256, in __iter__ self._fetch_all() File "/usr/local/myproject/.env/local/lib/python2.7/site-packages/django/db/models/query.py", line 1087, in _fetch_all self._result_cache = list(self.iterator()) File "/usr/local/myproject/.env/local/lib/python2.7/site-packages/django/db/models/query.py", line 54, in __iter__ results = compiler.execute_sql() File "/usr/local/myproject/.env/local/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 835, in execute_sql cursor.execute(sql, params) File "/usr/local/myproject/.env/local/lib/python2.7/site-packages/django/db/backends/utils.py", line 79, in execute return super(CursorDebugWrapper, self).execute(sql, params) File "/usr/local/myproject/.env/local/lib/python2.7/site-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) File "/usr/local/myproject/.env/local/lib/python2.7/site-packages/django/db/utils.py", line 94, in __exit__ six.reraise(dj_exc_type, dj_exc_value, traceback) File "/usr/local/myproject/.env/local/lib/python2.7/site-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) django.db.utils.ProgrammingError: relation "django_content_type" does not exist LINE 1: ..."."app_label", "django_content_type"."model" FROM "django_co... I get this same error even if I try to run: python … -
Django Login not creating session id
I'm using this project: https://github.com/Seedstars/django-react-redux-base When I login as the superuser via the frontend (/login), no session id gets created, so when I visit /admin/ it asks me to login again. The project is using django-rest-knox and has a custom user model. Is something missing in the authentication or permissions? -
How to past the id of the html button to python file by using django?
I have the following code in html file that is to created the dynamic button. {% for i in loop_times %} <button type="submit" class="'btn btn-lg" name="{{ i }}" id="{{ i }}" onclick="alert(this.id)" formmethod="post"><a href="{% url 'button' %}">{{i|safe}}</a></button><br><br> {% endfor %} this button have url link which link to urls.py: url(r'^button',views.data, name='button'), The id of this buttons will dynamically created based on hw many product I have and now I want get the id of the particular buttons to pass to the python file in order for me to used the id to do analysis, so I have the following code in my view.py file labelid = request.GET[("id", False)] Anyone have idea on how to pass id of the dynamically buttons to my view.py, because above code not able to run, I'm very new to python and don't have any basic for my programing background hope that I can get some idea here, thanks -
Comparing offset-naive and -aware datetimes in Django
Let's say I have a list of dates in an array, I'd like to keep only the ones that has expired in order to erase them later. But I'm trying to pass an IF condition on each dates in the array and print only the ones that has expired. The problem is that I don't understand how I can do it with Python. Here is what I thought doing : # model.objects.all() contains the dates of each objects for data in model.objects.all(): if data.created_date < datetime.datetime.now() - datetime.timedelta(seconds=20): print(data.created_date) The code above gives me this error : TypeError: can't compare offset-naive and offset-aware datetimes What am I doing wrong, what's the solution ? -
How to populate CreateView hidden field with Data from URL?
I have a generic CreateView to create a ModelInstance that has a ForeignKey to another Model. The user gets there by clicking a link on the other Models DetailView. Instead of the user choosing the ForeignKey Object I'd like to hide this field and prepopulate it from an ID passed in the URL similar to this: url(r'^t/(?P<pk>\d+)/add_r/$', ReceiptCreateForTask.as_view(), name="receipt_create_for_task"), Which function do I have to override to access the 'pk' in the url and pass it into the form data before validation so it counts as input to the hidden field? Thank you for your help! -
Is there some kind of reverse Foreign Key relationship in Django?
I have two models like: class Task(models.Model): ... class MilageReceipt(models.Model): ... Every Receipt is supposed to list a lot of tasks. This could be done quickly with a ForeignKeyField("MilageReceipt") on the Task model. But the Receipt is generated much later and because I want to select the Tasks while creating it I'd prefer to have the Receipt link to the Tasks it lists and not the other way round. I could use a ManyToMany relationship here, but then I'd need to verify all the time that no Task has been billed twice. In a single word I need a ManyToOneRelation. I'm sure this is a common problem. What is the most straightforward way to solve this? I especially want to avoid having to massively modify the admin. Sorry, I'm sure there are other questions like this, but I didn't find a good solution. -
Django: I need to open a file in one view that I created in another view
I created a csv file in one view (its not saved in a model) and now I need to open and and send this file to an api via another view. I'm having a hard time finding the proper way to achieve this. Any suggestions? I found where you could send the filename via messages but that turns it into a message object and becomes worthless to me. I need to be able to access the file and send it in my run_all_modal view. I'm sending the data to HATScript() to process and send off. These are my views if you need to see them: def run_test_suite_in_hatit(request): testrail_suite_id = int(request.GET['suite']) print(testrail_suite_id) testrail_instance = TestRailInstance.objects.first() project = request.user.humanresource.project testrail_project_id = project.testrail.project_id testrail_project = get_testrail_project(testrail_instance, testrail_project_id) testrail_suites = testrail_project.get_suites() testrail_suite = [s for s in testrail_suites if s.id == testrail_suite_id][0] testrail_cases = testrail_suite.get_cases() hatit_csv_filename = bulk_hatit_file_generator(testrail_cases) messages.add_message(request, messages.INFO, hatit_csv_filename) return HttpResponseRedirect('/run_all_modal/') def run_all_modal(request): if request.method == 'POST': form = TestRunnerForm(request.POST) if form.is_valid(): data = form.cleaned_data scripts = get_messages(request) csvfile = "" for script in scripts: csvfile = script hs = HATScript() hs.apn = data.get('apn') hs.holly_server = data.get('browser') hs.basic_connection_test() response = hs.hatit_execute() else: print(form.errors) return JsonResponse({'success': True})