Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how do i solve this problem ? elasticsearch problem
"/home/ram/Asiaville/asiaville-project/lib/python3.5/site-packages/django/template/base.py", line 990, in render bit = node.render_annotated(context) File "/home/ram/Asiaville/asiaville-project/lib/python3.5/site-packages/django/template/base.py", line 957, in render_annotated return self.render(context) File "/home/ram/Asiaville/asiaville-project/lib/python3.5/site-packages/django/template/defaulttags.py", line 322, in render return nodelist.render(context) File "/home/ram/Asiaville/asiaville-project/lib/python3.5/site-packages/django/template/base.py", line 990, in render bit = node.render_annotated(context) File "/home/ram/Asiaville/asiaville-project/lib/python3.5/site-packages/django/template/base.py", line 957, in render_annotated return self.render(context) File "/home/ram/Asiaville/asiaville-project/lib/python3.5/site-packages/django/template/base.py", line 1046, in render return render_value_in_context(output, context) File "/home/ram/Asiaville/asiaville-project/lib/python3.5/site-packages/django/template/base.py", line 1024, in render_value_in_context value = force_text(value) File "/home/ram/Asiaville/asiaville-project/lib/python3.5/site-packages/django/utils/encoding.py", line 76, in force_text s = six.text_type(s) File "/home/ram/Asiaville/asiaville-project/lib/python3.5/site-packages/elasticsearch/exceptions.py", line 58, in str cause = ', %r' % self.info['error']['root_cause'][0]['reason'] List item -
Django: How to transfer a html table from a template to a database table?
I have a html template (review.html) which get populated dynamically with a html table. The table data can be changed by the user. After the user has made his changes, he than can save the whole table data to a django database table by clicking a submit button. Here is the part where I need help: How can I insert the html table data into the database table? The database table exists and all migrations are done. The html table has the same columns and column names as the database table, the datatypes are also the same. I just don't know how to write the function for the POST-request for the button click event. -
How exactly do we implement swagger docs for django APIView
So I have a django GenericAPIView Endpoint, for which I want to add swagger documentation. I have searched all over the documentation on how to do the django-rest-swagger, but I can't seem to understand them very much. Below are my files. views.py class SignUpAPIView(GenericAPIView): """ get: Not Available post: This endpoint presents Sign Up facility for the user. Try it urself by sending a request in the below form """ permission_classes = [AllowAny] serializer_class = SignupSerializer def get(self, request, format=None): return Response("Only POST Method is allowed") def post(self,request,format=None): serializer = SignupSerializer(data=request.data) data = request.data if serializer.is_valid(): valid_data=serializer.data print(valid_data) return Response("Success", status=status.HTTP_200_OK) serializer.py class SignupSerializer(serializers.Serializer): name = serializers.CharField(required=True, max_length=150) username = serializers.CharField(required=True, max_length=150) mobileNumber = serializers.CharField(required=True, max_length=10) email = serializers.CharField(required=True, max_length=150) password = serializers.CharField(required=True, max_length=150) This is the current Swagger Doc UI, that is being rendered. How do I make the example value in the Description to something of the below form? { "user":{ "name":"string", "username":"string", "mobileNumber":"string", "email":"string", "password":"string" } } Also, If someone could explain how exactly we can create good documentation using swagger, it would be of great help. A brief explanation of how exactly swagger works would be helpful. Thanks in advance. -
How to use DataTable for Dynamic table create in javascript
Hello everyone I am new in django and i wnt to refresh the datatable without page refresh if some data added in database i am add a refresh button in my page and i call the ajax function and i am add the all data in my data table everything is runing but by defult row is select 10 and if my data row is 30 then it give me 30 row in short my datatable is not work if i am create a dynamic table in ajax this is my html page sse this is live http://hp30405.pythonanywhere.com/savedata/ html : <form id="myForm" method="POST"> <input type="submit" value="Refresh"> </form> <table id="example" class="display nowrap" style="width:100%"> <thead> <tr> <th style="text-align:center;">id</th> <th style="text-align:center;">Username</th> <th style="text-align:center;">Password</th> <th style="text-align:center;">Email</th> </tr> </thead> <tbody> <tr> </tr> </tbody> </tbody> </table> <script> $(document).on('submit','#myForm',function(e){ e.preventDefault(); $.ajax({ type:'POST', url: '/refresh/', data:{ csrfmiddlewaretoken : "{{ csrf_token }}" }, success: function(d){ $("#example tbody tr").remove(); for (var i = 0; i < d['data'].length; i++){ var tableRef = document.getElementById('example').getElementsByTagName('tbody')[0]; // Insert a row in the table at row index 0 var newRow = tableRef.insertRow(tableRef.rows.length); // Insert a cell in the row at index 0 var newCell1 = newRow.insertCell(0); var newCell2 = newRow.insertCell(1); var newCell3 = newRow.insertCell(2); var … -
Django test failing with posts.models.Post.DoesNotExist: Post matching query does not exist
I have these files: models.py from django.db import models from django.contrib.auth.models import User class Post(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=50) body = models.TextField() created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.title test.py from django.test import TestCase from django.contrib.auth.models import User from .models import Post class BlogTests(TestCase): def setUpTestDate(cls): # create a user testuser1 = User.objects.create_user( username='testuser1', password='abc123') testuser1.save() # create a blog post test_post = Post.objects.create( author=testuser1, title='Blog title', body='Body content...') test_post.save() def test_blog_content(self): post = Post.objects.get(id=1) expected_author = f'{post.author}' expected_title = f'{post.title}' expected_body = f'{post.body}' self.assertEqual(expected_author, 'testuser1') self.assertEqual(expected_title, 'Blog title') self.assertEqual(expected_body, 'Body content...') When I run python manage.py test I get this error: $ python manage.py test Creating test database for alias 'default'... System check identified no issues (0 silenced). E ====================================================================== ERROR: test_blog_content (posts.tests.BlogTests) ---------------------------------------------------------------------- Traceback (most recent call last): File "/Users/paulcarron/PycharmProjects/blogapi/posts/tests.py", line 20, in test_blog_content post = Post.objects.get(id=1) File "/Users/paulcarron/.pyenv/versions/3.7.2/lib/python3.7/site-packages/django/db/models/manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/Users/paulcarron/.pyenv/versions/3.7.2/lib/python3.7/site-packages/django/db/models/query.py", line 399, in get self.model._meta.object_name posts.models.Post.DoesNotExist: Post matching query does not exist. ---------------------------------------------------------------------- Ran 1 test in 0.002s FAILED (errors=1) Destroying test database for alias 'default'... I've double checked and can't see any mistakes in my code. Is there something I've got wrong? -
How can I use Django's translation strings with Wagtailtrans (Add-on for supporting multi language Wagtail sites)
So I have a website which is using the Wagtailtrans extension for Wagtail. I basically enables multi language by duplicating the page tree. So the url gets fixed with the language-code at the start. I can translate all my content which I define through my models perfectly fine. Here's an example of how that works: class ServicesPage(MetadataPageMixin, TranslatablePage): description = models.CharField(max_length=255, blank=True,) content_panels = Page.content_panels + [ FieldPanel('description', classname="full") ] Instead of Page you define it as TranslatablePage in your model. All is working fine, however I still need some additional strings which I don't define in my models to be translated. I just use Django's translation feature with {% load i18n %} and then the strings wrapped inside {% trans "String" %}. So far so good, I defined my two languages in Wagtail admin (Wagtail trans creates an option for that) which in this case is English and Dutch. I set English as the main language so the strings are in english. I use ./manage.py makemessages and it creates a .po file for me, with all the tagged strings in there. At last I use ./manage.py compilemessages. But translated strings are not showing up when I switch to Dutch … -
How can I communicate with external python script from Django server
I have a Django server running in my pc and a client browser running into a Raspberry Pi. The Raspberry Pi has a RFID-RC522 reader which may read nfc tags. My idea is to write a python script on the client side (RPi) that detect when a RFID card is read and send the read rfid id to the Django Server in order to login a user. Mi question is, How can I communicate with the server using this external python script? Im using this SimpleMFRC522 Library to read from rfid reader. The desired workflow is: A user access to the WebApp using a local IP ("192.168.0.105:8000"). Django server respond serving the login page. The user wants to login with the RFID card, and bring the card to the reader. The reader, running in a external python, send the id of the card to Django Server. Django server autenticate the user. -
Django - Media Files are not loading in production, but Static files are working just fine
I am using pythonanywhere.com services and I am not able to load media files while in production, when DEBUG=False. All of the files are working without any problems when DEBUG=False My file structure: -- AO-project -- AO -- __init__py -- settings.py -- urls.py -- ..... -- car-images -- .....all media images -- cars -- __init__py -- admin.py -- models.py -- views.py -- ..... -- static -- css -- jss -- static-webiste-images This is my settings.py file and setup of STATIC and media files: STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR) This is my urls.py urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) This is my models.py and model that is set to store media files: # Image Storing image = models.ImageField('PragrindineNuotrauka', upload_to='car_images/', blank=True, default='/car_images/default.png') I have also set STATIC files directory in pythonanywhere.com as show bellow: URL '/static/' Directory '/home/AutoMotyvas/AO-project/static' URL '/media/' Directory '/home/AutoMotyvas/AO-project/car_images' I understand that I do not specify 'media' in MEDIA_ROOT but all of the files are working just file while in development Any thoughts or help would be greatly appreciated!!!! -
Not able to find Solution for :django.core.exceptions.ImproperlyConfigured: The included URLconf does not appear to have any patterns in it
Need help in understanding what I am doing wrong: Relates to Django framework, I am trying to map base url to view: here is url.py of app: https://www.screencast.com/t/DODOUYBhYK here is url.py of the main project: https://www.screencast.com/t/NjjFQ9HQ When I used: python manage.py makemigrations learninglogs (learninglog is the app) , I got this error (venv) C:\Users\Dell\PycharmProjects\Learning_Log>python manage.py makemigrations learninglogs Traceback (most recent call last): File "C:\Users\Dell\PycharmProjects\Learning_Log\venv\lib\site-packages\django\urls\resolvers.py", line 535, in url_patterns iter(patterns) TypeError: 'module' object is not iterable During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "C:\Users\Dell\PycharmProjects\Learning_Log\venv\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() File "C:\Users\Dell\PycharmProjects\Learning_Log\venv\lib\site-packages\django\core\management\__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\Dell\PycharmProjects\Learning_Log\venv\lib\site-packages\django\core\management\base.py", line 316, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\Dell\PycharmProjects\Learning_Log\venv\lib\site-packages\django\core\management\base.py", line 350, in execute self.check() File "C:\Users\Dell\PycharmProjects\Learning_Log\venv\lib\site-packages\django\core\management\base.py", line 379, in check include_deployment_checks=include_deployment_checks, File "C:\Users\Dell\PycharmProjects\Learning_Log\venv\lib\site-packages\django\core\management\base.py", line 366, in _run_checks return checks.run_checks(**kwargs) File "C:\Users\Dell\PycharmProjects\Learning_Log\venv\lib\site-packages\django\core\checks\registry.py", line 71, in run_checks new_errors = check(app_configs=app_configs) File "C:\Users\Dell\PycharmProjects\Learning_Log\venv\lib\site-packages\django\core\checks\urls.py", line 40, in check_url_namespaces_unique all_namespaces = _load_all_namespaces(resolver) File "C:\Users\Dell\PycharmProjects\Learning_Log\venv\lib\site-packages\django\core\checks\urls.py", line 67, in _load_all_namespaces namespaces.extend(_load_all_namespaces(pattern, current)) File "C:\Users\Dell\PycharmProjects\Learning_Log\venv\lib\site-packages\django\core\checks\urls.py", line 57, in _load_all_namespaces url_patterns = getattr(resolver, 'url_patterns', []) File "C:\Users\Dell\PycharmProjects\Learning_Log\venv\lib\site-packages\django\utils\functional.py", line 37, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\Dell\PycharmProjects\Learning_Log\venv\lib\site-packages\django\urls\resolvers.py", line 542, in url_patterns raise ImproperlyConfigured(msg.format(name=self.urlconf_name)) django.core.exceptions.ImproperlyConfigured: The included URLconf … -
how to pass username in html email template in django using msg.send()
I am new to Django coding. I am currently working on DRF Django Rest Framework along with API. I have been trying to send a HTML email template with attachment as soon as the user register . I have achieved sending the same but i want to pass the dynamic contents like email of the user registered to the HTML email template from views.py , But unable to do it. I am using msg.send(). IN VIEWS.PY: def attachment(request): queryset = User.objects.all() em=[] h=[] for star in queryset.iterator(): em.append(star.email) print(em) h=em[-1] template = get_template('C:/Users/hp/Anaconda3/Lib/site- packages/allauth/templates/account/email/email_confirmation_message.html') content = template.render(Context({'h': 'h'})) print('content',content) msg.content_subtype = "html" msg.attach_file('C:/Users/hp/Downloads/APIV1-master/APIV1- master/polls/img.jpg') msg = EmailMessage(subject='attachment', body= msg_html, from_email='test@gmail.com',bcc=[h]) msg.attach_alternative(context,"text/html") msg.send() return HttpResponse('<h1>Created</h1>') IN HTML TEMPLATE: <p>Thanks for signing up! We're excited to have you as an early user.</p> <p> Your registered email is : </p> <p> <strong> {{ h }} </strong></p> -
unresolved import 'Blog' in django
I am getting a unresolved import "Blog" in visual studio code. It happened all of a sudden, I am using a venv through conda, I haven't changed anything with the venv, everything is still working, but it's really annoying to have it. As I said, I haven't changed anything in the project that could potentially create this problem intentionally. from django.contrib import admin from django.urls import path, include from Blog import views urlpatterns = [ path('admin/', admin.site.urls), path("blog/", include("Blog.urls")), path("index/", views.index.as_view(), name="index"), path("", include("django.contrib.auth.urls")), path("signup/", views.SignUp.as_view(), name="SignUp"), path("accounts/", include("django.contrib.auth.urls")), ] -
how to query an object if it has a field with only a specific value in views psql django
my models.py is : class Order(models.Model): truck_number = models.CharField(max_length=30,default=None) date= models.DateField() product=models.CharField(max_length=30) depot = models.CharField(max_length=10) volume = models.CharField(max_length=30, blank=True) volume_delivered = models.CharField(max_length=30, blank=True) driver_name=models.CharField(max_length=30,default=None) driver_id_number=models.IntegerField(default=None) driver_phone_number=models.IntegerField(default=None) order_status = models.CharField(max_length=50, blank=True) so i need a view which needs to render the whole objects of Table Order if only the value of field order_status is Loaded. How do i write this logic in django views. -
Format JsonResponse data into a table [duplicate]
This question already has an answer here: Output JSON to html table 2 answers I am trying to format Django JsonResponse data into a table in my template. Here is my code so far. script <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script> (function($){ function processForm( e ){ var inputText = $('#input-Text').val(); var inputTemplate = $('#input-Template').val(); $.ajax({ url: '/parse/', //replace this with url that you want to hit without reloading the page dataType: 'text', type: 'post', contentType: 'application/x-www-form-urlencoded', data: $(this).serialize(), success: function( data, textStatus, jQxhr ){ var result = JSON.parse(data); alert(data); $.each(result, function (i, val) { console.log(val); }); }, error: function( jqXhr, textStatus, errorThrown ){ // This is executed when some error occures alert(errorThrown); } }); e.preventDefault(); } $('#my-form').submit( processForm ); })(jQuery);</script> views.py return JsonResponse({'result': result}) It alerts me, on success, {'result' : [['Keys'], ['148']]} I am trying to generate a table with first item in the result as table header and others are like table rows. I have little understanding with Jquery/ajax/js. Can anyone help me with this please? -
"Were sorry but something went wrong" while trying to access Django application on A2
I have been working on deploying a somewhat existing django application on an A2 shared server. I have been following the following guides: https://medium.com/@isaactchikutukutu/deploying-django2-python3-on-a2-hosting-9e786a3e38ad https://www.a2hosting.co.uk/kb/developer-corner/python/installing-and-configuring-django-on-unmanaged-servers Any time I try to visit my website all I get is a page that says "We're sorry, but something went wrong" It gives me an error ID and says Web application could not be started by the Phusion Passenger application server. Please read the Passenger log file (search for the Error ID) to find the details of the error. I'm not sure where to find the Passenger log files and thus I have no idea how to figure out what isn't working properly. When I run manage.py it seems to run fine. I can call run server and it works fine. It would be awesome if someone could help me move forward with this. Thanks! -
Converted whole pyshipping project from python 2 to 3 by using the in-built python tool 2to3 but it does not work in python 3
Pyhton newbie here, very good chance I am doing a silly mistake here.. After losing a good amount of hair and searching for many hours, I am still not able to convert a whole project to python 3. I have a project made in django framework and it uses python 3.7, and I wanted to incorporate this library into my app. But, because pyshipping uses python 2.7, I thought it may cause compatibility issues. Following this answer,I converted the whole project and tried running this file binpack_simple.py. But it gives me an error I am not able to understand at all. When I run this file using my pycharm terminal when the project iterpreter is set to python 2.7 it runs perfectly, but when I set iterpreter to 3.7, it gives me the following error return _pyprofile._Utils(Profile).run(statement, filename, sort) File "C:\Users\idadarklord\AppData\Local\Programs\Python\Python37\lib\profile.py", line 53, in run prof.run(statement) File "C:\Users\idadarklord\AppData\Local\Programs\Python\Python37\lib\cProfile.py", line 95, in run return self.runctx(cmd, dict, dict) File "C:\Users\idadarklord\AppData\Local\Programs\Python\Python37\lib\cProfile.py", line 100, in runctx exec(cmd, globals, locals) File "<string>", line 1, in <module> File "C:/Users/idadarklord/PycharmProjects/untitled/pyshipping/binpack_simple.py", line 230, in test bins, rest = binpack(packages) File "C:/Users/idadarklord/PycharmProjects/untitled/pyshipping/binpack_simple.py", line 218, in binpack return allpermutations(packages, bin, iterlimit) File "C:/Users/idadarklord/PycharmProjects/untitled/pyshipping/binpack_simple.py", line 203, in allpermutations trypack(bin, todo, bestpack) … -
Code should print post of particular user but it is printing post of all users
**MODELS.PY** class User(auth.models.User,auth.models.PermissionsMixin): def __str__(self): return "@{}".format(self.username) def get_absolute_url(self): return reverse("accounts:login") class Group(models.Model): name = models.CharField(max_length = 255,unique = True) slug = models.SlugField(allow_unicode = True,unique = True) description = models.TextField(default = '') members = models.ManyToManyField(User,related_name = "group") def save(self,*args,**kwargs): self.slug = slugify(self.name) super(Group,self).save(*args,**kwargs) def get_absolute_url(self): return reverse('groups:single',kwargs = {'slug':self.slug}) def __str__(self): return self.name class Post(models.Model): message = models.TextField() created_at = models.DateField(auto_now = True) user = models.ForeignKey(User,related_name='posts',on_delete=models.CASCADE) group = models.ForeignKey(Group,related_name='posts',on_delete=models.CASCADE) def __str__(self): return self.message def get_absolute_url(self): return reverse('posts:single',kwargs = {'username':self.user.username,'pk':self.pk}) class Meta(): ordering = ['-created_at'] **Views.py** class UserPosts(generic.ListView): model = models.Post template_name = 'posts/user_post_list.html' def get_query_set(self): if self.request.user.is_authenticated: self.username = get_object_or_404(User,username__iexact=self.request.user.username) return models.Post.objects.filter(user=self.username) else: raise Http404 **Html Code** <div class="col-md-4"> {% for post in post_list %} <p> {{ post.user.username }} </p> {% endfor %} </div> This code should print post of particular user but it is printing post of all users, something is wrong with this code but i am not getting it.I have tried some other combinations but that also not working.Can anyone help? Thanks in advance -
How to display in progress bar the progress of ajax request in Python and Jquery
When users send the form in my page they have to wait approximately 13 seconds to get data ,because of 6 different queries behind the tool which are being executed. Now I am showing simple loader icon but would like to replace it by the progress bar and show the current status. For example, I have 6 queries so I'd like to inform the browser that a given query is done. Is there a possibility to do that in python/django ? Was trying to find something in google, but nothing was similar to my problem Thanks in advance -
django access related model status in custom managers
I use model_utils library in Django. I've got two models as shown below class Book(TimeStampedModel): STATUS_CHOICES = Choices( (0, 'public', _('public')), (1, 'private', _('private')), ) status = models.IntegerField( verbose_name=_('status'), choices=STATUS_CHOICES, default=STATUS_CHOICES.public, db_index=True, ) class Page(MPTTModel, AbstractPage): STATUS_CHOICES = Choices( (0, 'draft', _('draft')), (1, 'public', _('public')), (2, 'private', _('private')), ) status = models.IntegerField( verbose_name=_('status'), choices=STATUS_CHOICES, default=STATUS_CHOICES.public, db_index=True, ) book = models.ForeignKey( 'book.Book', verbose_name=_('book'), related_name='pages', db_index=True, on_delete=models.CASCADE, ) Both Book and Page models have status field. I've got two custom query set classes in managers.py. class BookQuerySet(models.QuerySet): def public(self): return self.filter(status=self.model.STATUS_CHOICES.public) class PageQuerySet(models.QuerySet): def public(self): return self.filter(book__status=0, status=self.model.STATUS_CHOICES.public) As shown above, book__status=0 this code surely works, but I am a bit frustrated because I'd like to use the code like self.book.model.STATUS_CHOICES.public. Please, tell me how to access the related model object property. If I import from .models import Book, it will cause "circular imports". Thank you. -
Can I render an id of a tag instead of full page
Hey guys I am building a website in which the sections of that website are in same html pages and they are given an id ,Now in this special case I want to make a url in django which can go to the specific id not the whole html page Is this possible? -
Want to print all groups to which user belongs
**Models.py** class User(auth.models.User,auth.models.PermissionsMixin): def __str__(self): return "@{}".format(self.username) def get_absolute_url(self): return reverse("accounts:login") class Group(models.Model): name = models.CharField(max_length = 255,unique = True) slug = models.SlugField(allow_unicode = True,unique = True) description = models.TextField(default = '') members = models.ManyToManyField(User,related_name = "group") def save(self,*args,**kwargs): self.slug = slugify(self.name) super(Group,self).save(*args,**kwargs) def get_absolute_url(self): return reverse('groups:single',kwargs = {'slug':self.slug}) def __str__(self): return self.name **Views.py** class ListGroups(ListView): model = Group **Html code** <div class="col-md-8"> <div class="list-group"> {% if user.is_authenticated %} <h2>Your Groups!</h2> {% if user.group.count == 0 %} <p>You have not joined any groups yet! <p> {% else %} {% for group in user.group.all %} <a class="list-group-item" href="{% url 'groups:single' slug=group.slug %}"> <h3 class="list-group-item-heading">{{group.name}}</h3> <div class="list-group-item-text container-fluid"> {{group.description|safe}} <div class="row"> <div class="col-md-4"> <span class='badge'>{{group.members.count}}</span> member{{group.members.count|pluralize}} </div> <div class="col-md-4"> <span class='badge'>{{group.posts.count}}</span> post{{group.posts.count|pluralize}} </div> </div> </div> </a> {% endfor %} {% endif %} {% endif %} </div> According to me it should print all the groups and it's details to which current logined user belongs but it is not printing anything.I have no idea what is wrong in this code.I have tried some other approaches but nothing works.Can anyone help? Thanks in advance. -
ABC Chlid Class Issue
In my Django App I have a module dropdown dropdown __init_.py select.py inline.py In select.py have a class from inline import doauto class AbstractOption(ABC): def method1: def method2: class Select(AbstractOption): def load_request: def method_helper: .... doauto() .... In inline.py i have a class class Inlineselect(AbstractOption): def load_request: def method_helper: def doauto: inl= Inlineselect() inl.load_request() I am getting following error: ImportError: cannot import name AbstractOption from select (/../../select.py) I am not getting why this issue is coming. in inline.py i imported AbstractOption class from select.py and when I am using a child class from inline in select module class it gives class import error. -
How to correctly parse JSON object returned from django response to template into data attribute
I wasn't able to find similar topic in google. I return simple object into the django template through views views: return render(request, 'mainPage.html', { 'obj': getObj() }) def getObj(): path = '/home/myPage' + 'obj.json' fd = open( path, 'r') obj = fd.read() fd.close() return json.dumps(obj) template: <input type="hidden" id="obj" data-obj="{{ obj }}"> and JS: var obj = JSON.parse( $('#obj').data('obj') ); console.log( obj ); I see in the console the right result: { "2018": { "First": { "obj1": "4", "obj2": "231", } } } but when I try to refer to this obj by console.log(obj ['2018']); it returns undefined Will be thankful for your help Thanks in advance -
return value from middle ware says:'str' object has no attribute 'get'
I have this middleware: def process_request(self, request): x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR') if x_forwarded_for: x = x_forwarded_for.split(',')[-1].strip() else: x = request.META.get('REMOTE_ADDR') return x I want to use of x in another file in my app but when I run the prject it return error: Traceback (most recent call last): File "\env\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "\env\lib\site-packages\django\utils\deprecation.py", line 93, in __call__ response = self.process_response(request, response) File "\env\lib\site-packages\django\middleware\clickjacking.py", line 26, in process_response if response.get('X-Frame-Options') is not None: AttributeError: 'str' object has no attribute 'get' [ERROR ] [2019-02-24 17:26:22,117] [django.request] [Internal Server Error: /api/v1/permission_groups] Traceback (most recent call last): File "\env\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "\env\lib\site-packages\django\utils\deprecation.py", line 93, in __call__ response = self.process_response(request, response) File "\env\lib\site-packages\django\middleware\clickjacking.py", line 26, in process_response if response.get('X-Frame-Options') is not None: AttributeError: 'str' object has no attribute 'get' [ERROR ] [2019-02-24 17:26:22,119] [django.server] ["GET /api/v1/permission_groups HTTP/1.1" 500 68328] -
Saving many to one without inline formsets - Django 2.1
What is the best procedure in Django for saving a form related to another model without the use of inline formsets? Problem setup: Model Address is related by a foreign key to Model User Each User can have multiple Addresses. I want to add a new address to an User. views.py In the AddAddress class (extending CreateView) the form.errors has the error {'user': ['This field is required.']} The user pk is in the url 'user/address/add/' -
use Django views and DRF views together
I am new to Django REST Framework. i describe my question with a example. for example, i have a api view function that can handle GET method and return a list of Users in json. the url of this api is www.exp.com/api/users now i want a view that get list of Users, send them to a template and render the template. the url of this view is www.exp.com/users logics of above views are same. how can i do like above example? should i write two seprate view (api and django view)?