Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django model.save() alternative without changing id
I noted that invoking 'save()' on an existing django object , the original id of the object will be changed when I just want to update some value of its attribute. So is there any method, e.g. update(?), on the object that allows me to do that, i.e. changing attribute values while remaining the same id? -
How do I make an IntegerField get autoincrement and not editable?
I have a field called "number", and would like it to be autoincrement and not editable. I have a system that has multiple users. Each user can register a document that follows an ordinal sequence. Each user can only create as many documents as he wants, but each document has its number generated in order, and should never be repeated. I tried using: number = models.IntegerField (unique = True) However, it occurs that if another user has already created a document with that number, another user can not create it. class Document(models.Model): date = models.DateTimeField(default=timezone.now) responsible = models.ForeignKey(Responsible, on_delete=models.PROTECT) from = models.CharField(max_length=80) work_from = models.CharField(max_length=80) subject = models.CharField(max_length=80) text = models.TextField() number = models.IntegerField() -
Who get correct value for join ManyToMany in Django?
I try to have the same result that this SQL query... SELECT * FROM my_BDD.Fernand, my_BDD.Fernand_has_Clothaire, my_BDD.Clothaire where Fernand.idFernand=Fernand_has_Clothaire.Fernand_idFernand AND Fernand_has_Clothaire.Clothaire_idClothaire=Clothaire.idClothaire; ...but with django. But, in django, it is a bit more complex to me to have the same result. After an inspectdb i have theses model from my_BDD models.py class Clothaire(models.Model): idclothaire = models.AutoField(db_column='idClothaire', primary_key=True) #otherfieds....... class Meta: managed = False db_table = 'Clothaire' class Fernand(models.Model): idfernand = models.AutoField(db_column='idFernand', primary_key=True) #others fields has_Clothaire = models.ManyToManyField(Clothaire, related_name='clothaires', through="FernandHasClothaire", through_fields=('fernand_idfernand', 'clothaire_idclothaire')) class Meta: managed = False db_table = 'Fernand' unique_together = (('idfernand'),) class FernandHasSt(models.Model): fernand_idfernand = models.ForeignKey(Fernand, models.DO_NOTHING, db_column='Fernand_idFernand') clothaire_idclothaire = models.ForeignKey('Clothaire', models.DO_NOTHING, db_column='Clothaire_idClothaire') #otherfields class Meta: managed = False db_table = 'Fernand_has_Clothaire' unique_together = (('fernand_idfernand', 'clothaire_idclothaire'),) So, i try this... view.py #just for the example def main(): clothaires = Clothaire.objects.all() fernands = Fernand.objects.all() createDataTableGeneral(clothaires,fernands) def createDataTableGeneral(clothaires,fernands): for f in fernands: for c in clothaires.filter(idclothaire__in=fernands.values('has_Clothaire')): print(c.anotherfield) And here, i have all the n-n combination... Thanks in advance for your answer. -
Django DRF ModelSerializer isvalid() always false when deserialize JSON
I'm apologize in advance for my poor english. Despite of all I found here , I don't find any solutions to my problem. I'm using django rest framework to work on REST API in Pycharm on Python 3.x http://www.django-rest-framework.org/api-guide/serializers/ When I use the ModelSerializer on my code, i can create a json from my model self.woodrow_attributes = {'name': 'RankA', 'gps_position_x': Decimal('40.15'), 'gps_position_y': Decimal('45.50'), 'gps_position_z': Decimal('30.50')} self.woodrow = WoodRow.objects.create(**self.woodrow_attributes) self.woodrow_serializer = WoodRowSerializer(instance=self.woodrow) data_json = JSONRenderer().render(self.woodrow_serializer.data,) my json is good and contains all information in bytes type : b'{"row_id":1,"name":"RankA","gps_position_x":"40.1500000","gps_position_y":"45.5000000","gps_position_z":"30.5000000"}' And when I want to deserialize it and test if the contents is valid, the answer is always false. I use ModelSerializer and when I run this code : deserialize_data = BytesIO(data_json) deserialize_data = JSONParser().parse(deserialize_data) print(deserialize_data) print(type(deserialize_data)) serializer = WoodRowSerializer(data=deserialize_data) print(serializer.is_valid()) print(serializer.error_messages) I got this : {'row_id': 1, 'name': 'RankA', 'gps_position_x': '40.1500000', 'gps_position_y': '45.5000000', 'gps_position_z': '30.5000000'} <class 'dict'> False {'required': 'This field is required.', 'null': 'This field may not be null.', 'invalid': 'Invalid data. Expected a dictionary, but got {datatype}.'} The error said that my data is invalid and datatype but I just print before that it is a dict. When I try my code in python console, it works and the serializer … -
Unable to implement jspdf using javascript?
I am trying to use jspdf to download a pdf and save it using javascript. Now, the problem is that when I try to execute jspdf function, I get this annoying error. I am using django with python. My goal is to be able to download the page using jspdf and then automatically trigger the print preview event for the user. What could I be doing wrong ?? jspdf.min.js:70 Uncaught TypeError: Cannot read property 'name' of undefined at k (jspdf.min.js:70) at r (jspdf.min.js:70) at r (jspdf.min.js:70) at r (jspdf.min.js:70) at r (jspdf.min.js:70) at jspdf.min.js:70 at i (jspdf.min.js:70) at v (jspdf.min.js:70) at x (jspdf.min.js:70) at Object.e.fromHTML (jspdf.min.js:70) This is what I tried so far. What could I be doing wrong? <div id="content"> <div class="mdl-grid"> <div> {% if messages %} <div > <ul class="messages"> {% for message in messages %} <li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li> {% endfor %} </ul> </div> {% endif %} </div> </div> <div class="mdl-grid"> <!-- profile card --> <!-- Square card --> <style> .demo-card-square.mdl-card { {#width: 320px;#} min-height: 200px; max-height: 600px; } .demo-card-square > .mdl-card__title { color: #fff; min-height: 250px; max-height: 250px; background: url('/media/profile.png') bottom right 15% no-repeat #3C5D73; } {#.mdl-card__supporting-text {#} {# … -
HTML manifest caches the entire index page
I load all my files with ?v=x at the end but since I started using a manifest appcache for my website to load all the card images (about 80-90 images that need to be cached) I realized that when I make changes to the project, the browser does not update them at all. For example, you can see the version number in the page (http://royplus.herokuapp.com/) but when I deploy changes with a different version number, the browser doesn't render it at all, just cached index page. So how can I cache all my images and keep the index out of cache? -
How to display the value of the decorated @property on the html page?
I was asked to correct someone else's code. The man who wrote it, has long resigned. It seems to me that this should be done through the decorator @property. I'm trying to use the decorator @property in django version 1.10: Model: class TblReestr(models.Model): id = models.IntegerField(primary_key=True) # AutoField? ean13 = models.CharField(max_length=50, blank=True, null=True) reg_price = models.DecimalField(max_digits=15, decimal_places=2, blank=True, null=True) trade_name = models.CharField(max_length=1000, blank=True, null=True) fabr_name = models.CharField(max_length=500, blank=True, null=True) reg_data = models.DateField(blank=True, null=True) mnn_name = models.CharField(max_length=250, blank=True, null=True) valuta_name = models.CharField(max_length=20, blank=True, null=True) num_prikaz = models.CharField(max_length=30, blank=True, null=True) @property def current_price(self): surcharge = 0 if (self.reg_price is None) or (self.reg_price == 0): return surcharge if self.reg_price < 50: surcharge = self.reg_price * 0.1173 + self.reg_price * 0.246 elif 50 <= self.reg_price <= 500: surcharge = self.reg_price * 0.12 + self.reg_price * 0.249 elif self.reg_price > 500: surcharge = self.reg_price * 0.1175 + self.reg_price * 0.243 return self.reg_price + surcharge class Meta: managed = False db_table = 'tbl_reestr' But the data is not output to the html page: {% elif target == 'reestr' %} <table class="table table-bordered table-condensed table" onselectstart="return false"> <thead> <tr class="info"> <th class="text-center">Наименование</th> <th class="text-center">Производитель</th> <th class="text-center">Цена</th> </tr> </thead> <tbody> {% for item in item_list %} <tr class="active"> … -
python Django command argument parsing returning an array
I have this simple Django command I'm writing as such: def add_arguments(self, parser): parser.add_argument('--type', nargs='+', type=str) parser.add_argument('--overwrite', nargs='?', type=bool, default=False) parser.add_argument('--unsubscribe', nargs='?', type=bool, default=False) def handle(self, *args, **options): print(options['type']) If I run myCommand --type=all I see my type printed as ['all']. Why is this coming back as an array? I just want the string value all. -
Why are session records not being saved in my Django app?
I have a Django (1.11.8) application running on a staging server on Heroku. I imported the database with existing records, users, etc and it all seems to be working fine. When I sign in, I am sometimes returned to the sign in page. Other times I am signed in and I'm redirected to the user profile page. However, if I do anything after that I end up getting signed out. I tried making sure the name of the cookies don't clash with the production application (which works fine). I also inspected Session records via the shell. When I manage to sign in, it doesn't look like it's creating any new session records. To be sure I cleared all the session records and no new ones get created when I sign in. The database connection seems fine, as I'm able to create a user record by signing up. I've also been able to manually create a session record via the shell. I just don't see any being created as a result of the sign in page. Any ideas appreciated? -
I need that my button close whenever i click javascript
I have a button for notification the problem is that it can be closed whenever I click... I need to press again on the button. I try to change the javascript like mouseout or something like this but nothing work. Django template : <div class="notification"> <span class="glyphicon glyphicon-bell"></span> {% if unread_notifications_count %} <div class="counter">{{unread_notifications_count}}</div> {% endif %} <ul class="notifications hidden"> {% for n in notifications %} <li class="{% if not n.read %} new {% endif %}"> <div class="icon"><img src="/static/img/icon-popup.svg"></div> <a href="{{n|notification_url}}"> {{n.text}} <div class="date" data-date="{{n.date.ctime}}">{{n.get_date}}</div> </a> <div class="clearfix"></div> </li> {% endfor %} <a href="{% url 'notification_list' %}"><div class="see-all">See all</div></a> </ul> </div> Javascript: initNotification(){ $('.notification').on('click', function(event){ $(this).find('.notifications').toggleClass('hidden'); }) CSS: .notification{ position: relative; float: left; // notification icon span.glyphicon{ font-size: 25px; padding-top: 6px; } .counter{ position: absolute; top: 0; z-index: 9999; right: -5px; color: red; border-radius: 50%; background: $red; color: $white; width: 17px; height: 17px; font-size: 12px; text-align: center; } &:hover{ cursor: pointer; } } -
Failed to process message due to a permanent exception with message Cannot submit message Django Outlook/hotmail
If someone had this issue, I will be sincerely thankful for your help. I'm having this error sending local email with hotmail: Traceback (most recent call last): File "/usr/local/lib/python3.6/site-packages/huey/consumer.py", line 169, in process_task task_value = self.huey.execute(task) File "/usr/local/lib/python3.6/site-packages/huey/api.py", line 357, in execute result = task.execute() File "/usr/local/lib/python3.6/site-packages/huey/api.py", line 842, in execute return func(*args, **kwargs) File "/usr/local/lib/python3.6/site-packages/huey/contrib/djhuey/__init__.py", line 108, in inner return fn(*args, **kwargs) File "/code/app/tasks.py", line 89, in send_email email_message.send() File "/usr/local/lib/python3.6/site-packages/django/core/mail/message.py", line 348, in send return self.get_connection(fail_silently).send_messages([self]) File "/usr/local/lib/python3.6/site-packages/django/core/mail/backends/smtp.py", line 111, in send_messages sent = self._send(message) File "/usr/local/lib/python3.6/site-packages/django/core/mail/backends/smtp.py", line 127, in _send self.connection.sendmail(from_email, recipients, message.as_bytes(linesep='\r\n')) File "/usr/local/lib/python3.6/smtplib.py", line 888, in sendmail raise SMTPDataError(code, resp) smtplib.SMTPDataError: (432, b'4.3.2 STOREDRV.ClientSubmit; sender thread limit exceeded [Hostname=DM5PR19MB1050.namprd19.prod.outlook.com]') ERROR process_task Unhandled exception in worker thread Traceback (most recent call last): File "/usr/local/lib/python3.6/site-packages/huey/consumer.py", line 169, in process_task task_value = self.huey.execute(task) File "/usr/local/lib/python3.6/site-packages/huey/api.py", line 357, in execute result = task.execute() File "/usr/local/lib/python3.6/site-packages/huey/api.py", line 842, in execute return func(*args, **kwargs) File "/usr/local/lib/python3.6/site-packages/huey/contrib/djhuey/__init__.py", line 108, in inner return fn(*args, **kwargs) File "/code/app/tasks.py", line 89, in send_email email_message.send() File "/usr/local/lib/python3.6/site-packages/django/core/mail/message.py", line 348, in send return self.get_connection(fail_silently).send_messages([self]) File "/usr/local/lib/python3.6/site-packages/django/core/mail/backends/smtp.py", line 111, in send_messages sent = self._send(message) File "/usr/local/lib/python3.6/site-packages/django/core/mail/backends/smtp.py", line 127, in _send self.connection.sendmail(from_email, recipients, message.as_bytes(linesep='\r\n')) File "/usr/local/lib/python3.6/smtplib.py", line 888, in … -
AttributeError in Django 2 but not Django 1.11
The following code worked fine in Django 1.11, but in DJango 2 and up it fails: 'imageToLoad' : imageQ[0].imagePath The error is AttributeError: 'ImageFieldFile' object has no attribute 'replace' I was reading through the DJango 2 documentation but couldn't figure out what the issue is. Here is the entire code block: def getContextFromObject(request,imageQ): if (imageQ != None): imageJson = serializers.serialize("json", imageQ) print("image id is " + str(imageQ[0].id)) request.session['image_id'] = imageQ[0].id print("attempt to load: " + str(imageQ[0].imagePath)) # Below is the block that fails on DJango 2. Specifically, it is the first part, 'imageToLoad' : imageQ[0].imagePath context = {'imageToLoad' : imageQ[0].imagePath, 'imageWidthPixels': imageQ[0].widthPixels, 'imageHeightPixels': imageQ[0].heightPixels, 'imageMeasuredCenter': (imageQ[0].swMeasuredCenter).quantize(Decimal('.01'), rounding=ROUND_DOWN), 'micronsPerPixel': imageQ[0].micronsPerPixel, 'imageChannelSelect': imageQ[0].channelSelect, 'imageId' : str(imageQ[0].id), 'images' : imageJson } else: context = { } return context; -
Django Deploying 500 status when debug=False
I'm using django to build my own blog now and I think it's good.But now I've noticed a problem.When I change the debug var to False,System checks are OK but It'll return a 500 error status.When I change it to True,The bug won't happen again.So what's the problem?Can anybody help me? -
Django: How to pass a list of PKIDs to next view through AJAX, then redirect
Premise: The user is presented a table with a list of objects with checkboxes next to them. The user is able to check as many checkboxes as they want. The user then clicks a button that will redirect them to another page, that does stuff with only those objects that were selected. So I need to pass an array of object IDs I capture through jQuery to my next view (from here on GraphView) through a POST request embedded in a button, to show a list of only those objects on the next redirected page. How do I handle that in my URLs and in my view? My jQuery: // This is the event listener for the button click that would redirect you to the next page $("#graphRuns").click(function() { var array = []; // IDs come from checkboxes. You select which objects you want // in your next page, then click a button. Here I determine // which IDs to add to the array through a data-attribute // on my HTML object templates choiceContainer.find("input:checked").each(function() { var run_id = $(this).data("run_id"); array.push(run_id); }); // I checked and the list of IDs is correct. console.log(array) // So I do a post request to … -
"you don't have permission to edit anything" on custom AdminSite if user is not superuser
I wan't to have multiple AdminSite on my Django project and I don't want to give every user the superuser role just to see and edit the models of the application. Here is the layout of my project: > djangoApp > djangoApp - settings.py - etc... > AAA - admin.py - urls.py - etc.. > BBB - admin.py - urls.py - etc.. > CCC - admin.py - urls.py - etc.. > ressources - models.py - etc.. > core - admin.py - auth.py - models.py - views.py Here is the admin.py of BBB (I use a different database for each AdminSite): from django.contrib import admin from django.contrib.admin import AdminSite, site from core.admin import UserAuthenticationForm from ressources.models import Adresse class BBBAdminSite(AdminSite): site_header = 'BBB admin' login_form = UserAuthenticationForm login_template = "core/login.html" def has_permission(self,request): user = request.user return user.is_active and user.is_staff and (user.account_id == 100 or user.account_id == 0) class AdminModel(admin.ModelAdmin): using = 'DATABASE_NAME' def has_add_permission(self, request): user = request.user return user.is_active and user.is_staff and (user.account_id == 100 or user.account_id == 0) def has_change_permission(self, request, obj=None): user = request.user return user.is_active and user.is_staff and (user.account_id == 100 or user.account_id == 0) def has_delete_permission(self, request, obj=None): user = request.user return user.is_active and user.is_staff and … -
Django drag-n-drop form validation
So basically I was tasked to make a drag and drop form, in which I would have a table of available users, and create a team from that table, by dragging and dropping the users. My problem is, that I have no idea where to start tackling this problem, mostly because I'm not sure how to validate the data that is dropped after I hit submit. So my goals are: Validate drag-n-drop data Add a user status so it won't be reassigned to another team. Assign credits to users upon competition of the given task (this is used for making reports and to add an "achievements" functionalities) Anything leading to drag-n-drop validation in django will be helpful too My models.py for users class Employee(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) department = models.CharField( max_length=100, default='' ) title = models.CharField( max_length=60, default='' ) date_joined = models.DateField( default=datetime.date.today ) avatar = models.ImageField( upload_to="avatars" ) My models.py for creating the teams, (I still need to write a Foreign Key or something to store the users that will be on the team): class Task(models.Model): Task_name = models.CharField( max_length=15, default="" ) Task_date = models.DateField() Task_deadline = models.DateField() Task_credits = models.DecimalField( max_digits=2, decimal_places=0 ) Task_reference = models.CharField( max_length=100, … -
where the django is most suitable? Where I should prefer it the most?
Im a new to web application Development! and I want to start it with Django so I wanted to know that which kind of Web app will be best to practice Django ? -
Upload image from URL in Wagtail admin panel
For some reason there seems to be no discussion on this anywhere that I can find. Presumably, then, there's no easy solution for this, but could anyone suggest a solid approach for this use case? My ideal setup would be to have images copied into the richtexteditor automatically be uploaded to the server, although with Wagtail2.0 and the new draftail wysiwyg editor this no longer seems possible. For now I'd be happy with simply modifying the Wagtail UI to allow the "Upload Image" form to alternatively take an image URL, instead of only providing the option to browse for a local file. Is the best way to go about this actually modifying Wagtail itself? Or should I instead write a script completely separate from Wagtail? If the latter, is there a nice way to be able to interact with that script from within the Wagtail admin panel? Thanks for any thoughts on this topic. Sorry to be asking such a broad question on here, but like I say it seems there isn't much discussion on this topic anywhere. -
django-ckeditor how to remove restrictions off decorator while uploading files?
I am new in Django and trying to upload images with user group = non staff user using ckeditor_uploader but while uploading images i am getting error 502 Bad Gateway as it is require staff_member_required decorator, but i want to remove this restriction, so i have gone through reference link and see this point https://github.com/django-ckeditor/django-ckeditor#restricting-file-upload Point number 2)By default the upload and browse URLs use staff_member_required decorator - ckeditor_uploader/urls.py - if you want other decorators just insert two urls found in that urls.py and don't include it. I am not understanding statement "if you want other decorators just insert two urls found in that urls.py and don't include it." Please help -
Django-rest-auth HTML email
Is it possible to send password reset email in HTML in django-rest-auth? Here is my url.py from rest_auth.views import PasswordResetView, url(r'^api/auth/reset/$', PasswordResetView.as_view(), name='rest_password_reset'), And I've copied password_reset_email.html to templates\registration. Now I can edit email content, but it's displays as text. I've found def password_reset(request, template_name='registration/password_reset_form.html', email_template_name=None, subject_template_name='registration/password_reset_subject.txt', password_reset_form=PasswordResetForm, token_generator=default_token_generator, post_reset_redirect=None, from_email=None, extra_context=None, html_email_template_name='registration/password_reset_email.html', extra_email_context=None): and class PasswordResetView(PasswordContextMixin, FormView): email_template_name = None extra_email_context = None form_class = PasswordResetForm from_email = None html_email_template_name = 'registration/password_reset_email.html' subject_template_name = 'registration/password_reset_subject.txt' success_url = reverse_lazy('password_reset_done') template_name = 'registration/password_reset_form.html' title = _('Password reset') token_generator = default_token_generator But I can't use them from Django-rest-auth. -
Two variables in Django URL
I want a URL something like this: /(category)/(post-slug) On the link this is what I have: {% url category.blog category.slug %} and for the url.py: url(r'^(I DON"T KNOW WHAT TO PUT ON THIS PART TO GET THE CATEGORY)/(?P<slug>[0-9A-Za-z._%+-]+)', views.post, name='post'), thanks -
click a button on a second html page automatically when directed one html page
How can I make a button (a form button) to be auto clicked when we click a button on one webpage "abc/x" where x is an id and hence is a variable. So "abc/123","abc/234" etc are webpages having a "button1". So when we click button1- we should be directed to url "abc/pqr" and a "button2" should be auto-clicked. This button should only be clicked when directed from abc/x and not when from any other url. Any pointers how to proceed? -
make a number of survey forms in Django like Google Forms
Consider an educational project like Coursera. Such projects usually have a number of survey forms. The forms sometimes ask them to answer a few questions, sometimes asking feedback about a course, sometimes they may also ask users about the features that they want the site to have etc. These forms are usual forms but there lifetime is limited. You will want to analyse the input by your user and then make decisions accordingly. My projects too needs to have multiple survey forms from time to time.The problem is that making such large number of forms, handling validations, storing in database can be a hard task. I can use Google Forms but I don't want external links in my app. I also want to validate that actual users of my site use fill up the survey. Is there a third party app which makes it easy to make such forms? -
Is there a way to use permission_required for entire app in django?
I already read about this article, but don't know how to reuse this code. I want to use permission_required decorator for each app, not class-view or just view. Is there a way to use permission_required for entire app (or url) in django? -
Django Ceilometer get resource list and resource type
I am using Openstack Mitaka. In Django I am trying to get all the resources for tenants. (This is ok) After that I need to understand the resource type. For example if it is an instance or floating ip, etc. def sync_resources(): logger.info("Executing sync_resources") sync_tenants() tenants = Tenant.objects.all() managers = Manager.objects.filter(is_active=True) for manager in managers: services = manager.services.all() regions = manager.region_set.all() for region in regions: ceilometer_driver = CeilometerDriver(region_name=region.name, **manager.ceilometer_params) if ceilometer_driver.is_authenticated: for tenant in tenants: queries = [ceilometer_driver.make_query("project_id", ceilometer_driver.EQUAL, tenant.tenant_id)] resource_list = ceilometer_driver.get_resource_list(query=queries) In this code I get all the resources for a tenant. However I do not need all of them. And I will filter them based on list of types. Such as "Instance, floating_ip, volume, snapshot, etc" Here is a sample resource detail: sample resource floating_ip from the metadata I can see that it is a floating_ip. However I cannot see somewhere in the details that its type floating ip. The metadata changes for different type of resources. I alsoe checked from terminal with $ ceilometer resource-list $ ceilometer resource-show id-of-resource Again the details are not helpful. So I need a way to easily understand the resource type and match them with "Instance, floating ip, volume, snapshot, etc."