Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Dynamic Django models for CMS like functionality [on hold]
In my company we would like to build a Content app for Django that will allow publishing the static pages. The editors would like to have an ability to create templates for the contents (mardown) through the admin panel. The tricky part is, that editors would also like to add custom fields to each content template, like one template could have, for example ,obligatory field called approval number that should be displayed at the bottom of the template. I thought about using separate model for those extra fields with name, type, order, is_required, content_id fields for starter. Is this approach correct? Could anyone suggest some package that could help in this case? I looked ad Django-cms and Wagtail but it looks those systems don't support such functionalities. -
Impossible to catch an integrityError during object delete in Django CBV
I override a deleteView to make it ajaxable and adapted to my needs. It works fine. When deleting an object is not possible for db integrity sake, I'm not able to catch the exception. I've tried to catch any exception and the code runs as if there was no try block. The delete method fails and it raises a 500 errors. class AjaxableDeleteView(BaseAjaxable, DeleteView): """ Delete mixin for ajax CRUD opérations. """ _action_url = 'dashboard_staff:settings_delete_' @property def action_url(self): return reverse(f'{self._action_url}{self.object_name}', args=(self.object.pk, )) def get(self, request, *args, **kwargs): self.object = self.get_object() self.extra_context.update({'action': self.action_url, 'form': self.form_class()}) return super().get(request, *args, **kwargs) def delete(self, request, *args, **kwargs): object = self.get_object() try: object.delete() except: return JsonResponse({'data': _( "You can't delete this object as it is used somewhere else." )}, status=400) return self.success_json() In Python console, running the deletion inside a try block works fine. I can't understand wWhy inside this class base view the exception is not catched? -
Django How to post data to database and show data from database on same page
I am currently able to post data to the Django database on one page (/form) and get data from the database and show it on another page(/form1). How would I be able to create a single page that would allow the user to add data to the database while showing up every time the page renders the current data in the database? views.py: def give_sensor_name(request): if request.method == "POST": form1 = SensorForm(request.POST, prefix='form1') form2 = SensorViewForm(request.POST, prefix='form2') form3 = MountedSensorViewForm(request.POST, prefix='form3') form4 = MountedSensorForm(request.POST, prefix='form4') form5 = VehicleForm(request.POST, prefix='form5') form6 = SensorPackageForm(request.POST, prefix='form6') #if form1.is_valid() and form1.is_valid() and form2.is_valid() if form1.is_valid() and \ form2.is_valid() and \ form3.is_valid() and \ form4.is_valid() and \ form5.is_valid() and \ form6.is_valid(): form1.save() form2.save() form3.save() form4.save() form5.save() form6.save() else: form1 = SensorForm(prefix='form1') form2 = SensorViewForm(prefix='form2') form3 = MountedSensorViewForm(prefix='form3') form4 = MountedSensorForm(prefix='form4') form5 = VehicleForm(prefix='form5') form6 = SensorPackageForm(prefix='form6') context = {'form1': form1, 'form2': form2, 'form3': form3, 'form4': form4, 'form5': form5, 'form6': form6} return render(request, 'app/sensor_name_tmpl.html', context) def get_sensor_name(request): form = SensorForm() obj = Sensor.objects.all() context = {'form': form, 'obj': obj} return render(request, 'app/sensor_name_tmpl.html', context) urls.py: urlpatterns = [ path('', views.index, name='index'), url(r'^form/$', views.give_sensor_name, name='GiveSensorName'), url(r'^form1/$', views.get_sensor_name, name='GiveSensorName1'), I would like the give_sensor_name and get_sensor name methods to … -
In Django Display combo box items as list in update view
I have a model that maintains a list of batches for courses to be conducted like the following, class CourseBatch(models.Model): start_date = models.DateTimeField(null = True, blank = True) end_date = models.DateTimeField(null = True, blank = True) batch_name = models.CharField(max_length=50, default="Enter Batch Name") course = models.ForeignKey(Course, on_delete=models.CASCADE, related_name="batches") trainer = models.ForeignKey(Trainer, on_delete=models.CASCADE, related_name="trainer") college = models.ForeignKey(College, on_delete=models.CASCADE, related_name="college") additional_notes = models.TextField(max_length=500, default="No_Points",blank=True) user = models.ForeignKey(User, verbose_name='user', on_delete=models.CASCADE, default=1) objects = models.Manager() def __str__(self): return self.batch_name Every batch has an associate check point list, to maintain the list of topics that have been covered in that particular batch like the following, class ChkListForBatch(models.Model): batch = models.ForeignKey(CourseBatch, on_delete=models.CASCADE, related_name="checklistitems") chkpoint = models.ForeignKey(CheckPoint, on_delete=models.CASCADE, related_name="chkpoint") chkpoint_done = models.BooleanField(default=False) updated_on = models.DateTimeField(null = True, blank = True) objects = models.Manager() def __str__(self): return self.chkpoint.description I am able to display a list view of batches to which I have added a hyperlink column, which takes the user to the checklist for the particular batch. Now the issue is I want to display all the chkpoint and chkpoint_done fields in a table form where every row has 1 check point and a check box for the chkpoint_done field. Currently i am using the generic updateview which shows … -
Using httpie to test api and get timed out error after testing on browser with Django REST
I am practicing restful api by following the Django REST Tutorials. After done whole code of the tutorial, I tried to use httpie for testing. It's work perfectly. http http://127.0.0.1:8000/snippets.json HTTP/1.1 200 OK ... [ { "code": "foo = \"bar\"\n", ... And then I test the same url on a browser, It's also work perfectly. http://127.0.0.1:8000/snippets.json [{"id":1,"title":"","code":"foo = \"bar\ ... But after testing on browser, the time out errors occurred when go back to use httpie to test. http: error: Request timed out (30s). the error can be fixed by restarting django. How can I solve this problem? -
How to start server in debug mode - Pycharm
I want to debug my code and put breakpoints. However I am not able to start my server in debug mode. I have a setup.sh file. It has multiple export statements and last statement is python manage.py runserver. In manage.py I added DEBUG = True as shown below : if __name__ == "__main__": DEBUG = True The application did not stop on debug points i had put. -
Setting up SendGrid in Django
I'm not able to send emails through Django using SendGrid. I have configured my SendGrid account and created an API key and configured my Django settings files. Various online tutorials show different methods. None have worked for me. Here are my specific questions: specific question is whether or not I need to pip install sendgrid. specific question is should I be able to successfully test sending emails by going into the python editor and entering... from django.core.mail import send_mail send_mail('Subject here', 'Here is the message.', 'from@example.com', ['to@example.com'], fail_silently=False) The above results in a "1" in the python editor but no email delivered. Should the SendGrid dashboard show a new "Request" when the message is sent successfully? Mine shows 1 and has not changed. Here is my Django settings.py EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' SENDGRID_API_KEY = get_env_variable('SEND_GRID_API_KEY') EMAIL_HOST = 'smtp.sendgrid.net' EMAIL_HOST_USER = 'apikey' EMAIL_HOST_PASSWORD = SENDGRID_API_KEY EMAIL_PORT = 587 EMAIL_USE_TLS = True -
How to fix unpickling stack underflow error when a pickled object is sent as a paramter to a GET request?
I am pickling my model objects and sending them as parameters to a get request, so that the objects can be used in another view. After receiving the pickled object as string I encode it and then unpickle which gives me: Exception Type: UnpicklingError Exception Value: unpickling stack underflow I want to filter the models , pickle them , send them as url parameters encode them and unpickle. (is it because GET request encodes URLs?) Views.py class SearchView(View): def get(self,request): qs = report.objects.all() #FILTER STUFF item = pickle.dumps(qs) return render(self.request,self.template_name,{'qs':qs,'item':item}) def report_download(request,item): succ1 = item.encode() succ = pickle.loads(succ1) #DO STUFF return response urls.py url_patterns =[ url(r'^download/( ?P<item>.*)/$',views.report_download,name='dload'),] template.html <form action="."> <button type="submit" class="btn btn-primary"><a href="{%url 'auto_project:dload' item %}">Download</a></button> </form> -
how save image into models after create new image with pillow wi
in first, I create a image with pillow library and save into media file, now , I want save in to Temporary's model but does not save file. ''' class TemporaryImage(models.Model): image = models.ImageField(upload_to='temporary_images', verbose_name=_('image')) class Meta: verbose_name = _('Temporary image') verbose_name_plural = _('Temporary images') ''' -
How to check which user triggered a signal?
I have a simple signal in my project, that checks which fields have been updated in the form. I also need to check the user who changed data in those fields. Request.user doesn't seem to work here. @receiver(sender=BackOperator, signal=pre_save) def change_log(**kwargs): instance = kwargs['instance'] try: original_object = BackOperator.objects.using('operator').get(pk=instance.pk) except: return if original_object: field_names = [field.name for field in original_object._meta.fields] for field in field_names: try: ori_field = getattr(original_object, field) new_field = getattr(instance, field) message = (field + ": " + str(ori_field) + " changed to: " + str(new_field)) if ori_field != new_field: BackNote.objects.using('operator').\ create(operator=instance.pk, note=message) except: return I'd like to add a user's username as a string to message, that is saved in the BackNote table. -
Django module not found error, but it's been deleted and all references removed
I'm running Django 2.2, python 3.6.7 and I'm working in a virtual environment on Ubuntu 18.04. Having done a tutorial where the project "mysite" was built, I'm now doing another exercise to build an API. I'm using the same virtualenv. However when I migrate in my new project, call it tutorial, I get ModuleNotFoundError: No module named 'mysite'. So I deleted mysite. And I get the same error. And then I deleted the parent directory, recreated it (obviously not including mysite) and get the same error. I've searched recursively the codebase and the virtualenv and "mysite" does not turn up. What's going on here? -
'str' object has no attribute 'META' error while returning a JsonResponse
I want to return a JsonResponse/HttpResponse from my Django views function. However I am getting 'str' object has no attribute 'META' error. The code for the function is given below. def search(request): queryset_list = Influencer.objects.orderby('username') if 'username' in request.GET: username = request.GET['username'] if username: queryset_list = queryset_list.filter(username__iexact=username) #Full Name if 'fullname' in request.GET: fullname = request.GET['fullname'] if fullname: queryset_list = queryset_list.filter(full_name__iexact=fullname) context = { 'listings':queryset_list, 'values':request.GET } filtered_data = serializers.serialize("json",context) return JsonResponse(filtered_data) -
How to override how many-to-many saves on 'through' field in Django?
Summary I want to auto-increment an order field on Item defined with m2m fields within a Set (bad name I know) so I can easily change their order. The many-to-many field is defined with a through model called SetMeta, which contains just item, set, and the new field order. I've tried over riding save() but this is never called. How can I programatically set order to something other than a default each time an item is added to set? Detail Every time a new item is added to set, I want to set it's order to len(set.items.all()). To do this, I've redefined save() on SetMeta, but it's never called. What do I have to override to ensure this works the way I'd like? models.py class Item(models.Model, AdminVideoMixin): title = models.TextField(max_length=5000) .... class Set(Item): items = models.ManyToManyField(Item, related_name='in_sets', through='SetMeta', max_length=5000,) def get_absolute_url(self): return reverse('curate:set_detail',kwargs={'slug':self.slug}) def get_queryset(self): return self.items.all().order_by('-itemOrder__order') def __str__(self): return self.title def auto_increment_order(self): print('IS THIS WORKING') <----never prints. length_of_set = len(self.set.items.all()) return length_of_set class SetMeta(models.Model): item = models.ForeignKey(Item, on_delete=models.CASCADE, related_name='itemOrder', max_length=5000) set = models.ForeignKey(Set, on_delete=models.CASCADE, related_name='SetOrder', max_length=5000) order = models.IntegerField(default=0, null=True,) def up(self): self.order += 1 self.save() print(self.order) def down(self): self.order -= 1 self.save() print(self.order) def save(self, *args, **kwargs): if … -
How to correct the format given by JsonResponse
I am printing the output from my views function in Django using JsonResponse and want to correct the output and only include certain fields.How should I proceed? The function is : influencers = Influencer.objects.all() influencer_data = serializers.serialize("json",influencers) context = { 'influencer_data':influencer_data, } return JsonResponse(context) The output/returned value is: {"influencer_data": "[{\"model\": \"influencer_listings.influencer\", \"pk\": 7250, \"fields\": {\"full_name\": \"Be Yourself\", \"username\": \"tapasya_agnihotri\", \"photo\": \"\", \"email_id\": \"\", \"external_url\": \"\", \"location_city\": \"Kolkata\" The output is like the one given above.However I want the output to be without the slashes.Also why is JsonResponse printing the slashes. -
How to store data from a function's output (in views.py) to Database
I want to store a function's output(in views.py) to database I want to check 2 different data from different location (ie, 2 differnet functions in views.py). So i have to store these two outputs in database. I stored one function's output to database (from userUI). In another fn i want output from a command (like nmcli). I want store this fn's op to db. -
Unable to save form data to database and display data from database using django and angular js
Hi my project works on Django framework with some use of AngularJS. What I need to achieve is when I click on submit on my page(html), it should save all the values I entered into the database and should display the data from database in html file when i click submit button. I am very new to AngularJS. The following is my codes. Thanks in advance. design_data.html <script src="{% static 'js/angular.min.js' %}"></script> <script src="{% static 'js/design_data.js' %}"></script> <script> var app = design_data_app; //Need this as area-service and land-converter use app as ng-app design_data_app.factory('Settings', function() { return { registrationid: {{ registration.id }} } }); design_data_app.factory('Answers', function() { {% autoescape off %} ANSWERS_BYLAWS = {{ bylaws_answered_questions }}; {% endautoescape %} var _answers_bylaws = {}; for(idx in ANSWERS_BYLAWS) { _ans_and_remark = {}; _ans_and_remark.answer = ANSWERS_BYLAWS[idx]['fields']['answer']; _ans_and_remark.remarks = ANSWERS_BYLAWS[idx]['fields']['remarks']; _answers_bylaws[ANSWERS_BYLAWS[idx]['fields']['question']] = _ans_and_remark; } return { {#all: answers,#} bylaws: _answers_bylaws, getBylawsAnswerByQuestion: function(question_id) { return _answers_bylaws[question_id]; }, } }); </script> <div id="ByLaw" class="tab-pane fade" ng-controller="bylaws"> <div class="table-responsive"> <table class="table table-bordered table-hover table-condensed table-striped designtable-bylaw"> <thead> <tr> <th></th> <th width="800">Building Elements</th> <th>As per submitted Design</th> <th></th> <th>Remarks</th> </tr> </thead> <tbody> {% for question_group in bylaws_questions_groups %} <tr class="table-category"> <td colspan="5">{{ question_group.group_name }}</td> </tr> {% for question in … -
Is there a 'DetailView' in Django Admin?
I know there is a change/update view in Django admin but is there any detail view that just lists out the record's attributes? Kind of like the DetailView in the Django app? Or does anyone know any 3rd party packages I can install to provide the same functionality? -
netcdf4-python can't run in celery/django
It works well as normal function, But when I run the netcdf in celery task/django,It can't work,and show me this error: File "...", line 53, in ... with Dataset(path, format='NETCDF4') as dataset: File "netCDF4/_netCDF4.pyx", line 2291, in netCDF4._netCDF4.Dataset.__init__ File "netCDF4/_netCDF4.pyx", line 1855, in netCDF4._netCDF4._ensure_nc_success OSError: [Errno -101] NetCDF: HDF error: b'/my/nc/path' What happened when I use celery/django? -
Django - django-select2 doesn t work with inlineformset
i`ve made a inlineformset wich contains a django-select2 field. The problem appears when i try to add another inline .The select2 data don t work on cloned field. this is my template {{ form_m.management_form }} {% for m in form_m.forms %} <div class="{% cycle 'row1' 'row2' %} formset_row"> <div class="row"> <div class="col-sm-12"> {{ m.id }} {{ m.medicament }} </div> </div> <div class="row"> <div class="col-md-2"> {{ m.cantitate }} </div> <div class="col-md-2"> {{ m.nr_zile }} </div> <div class="col-md-2"> {{ m.mod_administrare }} </div> <div class="col-md-2"> {{ m.schema }} </div> </div> </div> {% endfor %} this is my script for clone fields {% load static %} <script src="{% static 'style/jquery.formset.js' %}"></script> <script type="text/javascript"> $('.formset_row').formset({ addText: '<button id="add_more" class="btn btn-sm btn-success float-right mr-1">Adauga medicamentatie</button>', deleteText: '<button class="btn btn-sm btn-danger float-right mr-5">Elimina</button>', prefix: 'form_m_set', }); </script> -
Why isn't favicon shown up in production?
Favicon isn't shown up in the tab though Django's response code is 200. Static files are located in 'myproject/build' (and 'settings.py' in 'myproject/server', and app in 'myproject/blog'). Though HTML page with css and js files is served well. And 'favicon.ico' is located in the same directory as 'index.html' page I tried to open a page by "localhost:8000' address in different browsers and I got the same thing: favicon isn't shown up in the tab. I also looked at "Sources" in developers options: there aren't any 'favicon.ico' file settings.py : STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'build/static') ] STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' urls.py (in 'server/'): urlpatterns = [ path('admin/', admin.site.urls), path('api/', include('blog.api.urls')), re_path('.*', TemplateView.as_view(template_name='index.html')) ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) index.html (in 'build/') : <link rel="shortcut icon" href="/favicon.ico" /> Console: [10/Jun/2019 09:57:29] "GET /favicon.ico HTTP/1.1" 200 2242 -
Django ORM equivalent of the following sql query
What is the django orm equivalent of the following sql query. SELECT MAX(quantity) FROM table_name GROUP BY product; -
Generate a sequential alpha-numeric string in Django
Using Django, I have to create user ids, which are alpha-numeric, such that it auto generates as the user increases For example - A0000 A0001 A0002 . . . A0010 And so on I have to make this using class and functions -
UNIQUE constraint failed: cms_cmsplugin.path
Trying to move Django-CMS info from one computer to another using fixtures. Iḿ trying to use this for a project on my work, but I can't get it to other PCs, because of dependencies and constraints when trying to load fixtures. Error found: Traceback (most recent call last): File "manage.py", line 18, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python3.7/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.7/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python3.7/site-packages/django/core/management/base.py", line 316, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python3.7/site-packages/django/core/management/base.py", line 353, in execute output = self.handle(*args, **options) File "/usr/local/lib/python3.7/site-packages/django/core/management/commands/loaddata.py", line 72, in handle self.loaddata(fixture_labels) File "/usr/local/lib/python3.7/site-packages/django/core/management/commands/loaddata.py", line 113, in loaddata self.load_label(fixture_label) File "/usr/local/lib/python3.7/site-packages/django/core/management/commands/loaddata.py", line 177, in load_label obj.save(using=self.using) File "/usr/local/lib/python3.7/site-packages/django/core/serializers/base.py", line 219, in save models.Model.save_base(self.object, using=using, raw=True, **kwargs) File "/usr/local/lib/python3.7/site-packages/django/db/models/base.py", line 747, in save_base updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields) File "/usr/local/lib/python3.7/site-packages/django/db/models/base.py", line 830, in _save_table result = self._do_insert(cls._base_manager, using, fields, update_pk, raw) File "/usr/local/lib/python3.7/site-packages/django/db/models/base.py", line 868, in _do_insert using=using, raw=raw) File "/usr/local/lib/python3.7/site-packages/django/db/models/manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/usr/local/lib/python3.7/site-packages/django/db/models/query.py", line 1133, in _insert return query.get_compiler(using=using).execute_sql(return_id) File "/usr/local/lib/python3.7/site-packages/django/db/models/sql/compiler.py", line 1285, in execute_sql cursor.execute(sql, params) File "/usr/local/lib/python3.7/site-packages/django/db/backends/utils.py", line 100, in execute return super().execute(sql, params) File "/usr/local/lib/python3.7/site-packages/django/db/backends/utils.py", line 68, in execute return self._execute_with_wrappers(sql, params, many=False, executor=self._execute) File … -
In which file should I define my ModelForm that I'm creating for a Model?
I have created a Model in my /models.py for which the code is shown below. I'm trying to define a ModelForm for my Question Model class. In which file should I define my ModelForm class for it? class Question(models.Model): """ Defines logical structure of question object. """ question_text = models.CharField(max_length=200) pub_date = models.DateTimeField() def __str__(self): return self.question_text -
I want to make a django application which can create lists inside lists
Basically, I am making a django application which is something like a Todo List.Each item in the Todo list has a list of their own.For eg. if I have items A,B,C,D in the todo list then each item has their own lists inside of them. Moreover I want to make A,B,C,D such that I can go from each item in the todo list to a menu/listings page and then select items for them from the menu/listings page. I am stuck on the second part and confused on how to proceed.