Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django rest_framework. desirialize bytes represented as string from json response
Actually, I'm not sure how rest_framework serialize my bytes Data, it's assumption. I was trying to find how it works, but nothing happened. I think for my deserialization process it isn't important because it's already represented somehow bytes and i need to find a way how to deserialize it. I use: python 3.8.0 Django 3.0.3 djangorestframework 3.11.0 My code: root urls file from django.contrib import admin from django.urls import path, include from django.conf.urls import url from rest_framework import routers import rest_framework from AccontsCenter.views import AccountViewSet from rest_framework.serializers import HyperlinkedModelSerializer from django.contrib.auth.models import User, Group class UserSerializer(HyperlinkedModelSerializer): class Meta: model = User fields = ["url", "username", "email"] from rest_framework.viewsets import ViewSet, ModelViewSet class UserViewSet(ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer router = routers.DefaultRouter() router.register(r"users", UserViewSet) router.register(r"accounts", AccountViewSet) urlpatterns = [ url(r'^', include(router.urls)), url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')), path('admin/', admin.site.urls), # path('accounts/', include('AccontsCenter.urls')), # path('proxies/', include('Proxies.urls')), # url(r'^', include(router.urls)), # url(r'^api-auth/', include("rest_framework.urls", namespace="rest_framework")) ] Account model is: import typing import inspect import os, sys import json from django.db import models from Accounts import FloodAccount from modules_simpified import loadFromModules # modules_obj_list = loadFromModules() class Account(models.Model): # on_add_acc_events: typing.List[typing.Callable] = [(name, obj) for name, obj in vars(modules_obj_list).items() if inspect.isfunction(obj)] on_add_acc_events = [] username = models.CharField(max_length=200) email … -
Virtual Code Studio debug . Django debugging not stopping on breakpoint
It's clear in the image, " print " can work when a breakpoint is existing my question -
Using my django remotely with a ubuntu server
I want to have access to my Django project from anywhere. For this reason, I have a Raspberry Pi with Ubuntu. If I run the command python manage.py runserver, it runs the project in http://127.0.0.1:8000/ as default. But this is the localhost of my raspberry/ubuntu and what I want is run the project on my laptop. for this reason I change the 127.0.0.1 for the adress of my server http://xxx.xx.xx.x:8000/ and I run it on my browser. THIS FAILS. Ok, reading some information I see that I have to open a port to access remotely, for this goal I use the ufw library. I open the 80 port using ufw, Now if I write http://xxx.xx.xx.x:80 on my browser, don't fail, appear this, Thus I understand that now is opened. The problem is that if now I run again my django project as python manage.py runserver 80 and I write again http://xxx.xx.xx.x:80/user_app/login/ in my browser, appears the following, What I'm doing wrong? I'm newbie and I don't know what I have to do. The objective is to be able to access the project remotely. Can somebody help me? Thank you very much. -
Django 3 TemplateDoes not exist
Even though I am providing correct path it still giving me an error. in this project have made custom user model so I am not able to understand where i am going wrong kindly guide as i am a beginner. thank you And also added the required paths in settings.I tried the same code even by using include method in urls,py but still failed kindly guide as of where exactly i am making mistake model.py: from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager # Create your models here. class MyAccountManager(BaseUserManager): def create_user(self, aadhar, name, phonenumber, password=None): if not aadhar: raise ValueError("Must have aadhar number") if not name: raise ValueError("Must have name") if not phonenumber: raise ValueError("Must have phone number") user = self.model( aadhar = aadhar, name = name, phonenumber = phonenumber ) user.set_password(password) #user.save(user=self._db) user.save(using=self._db) return user def create_superuser(self, aadhar, name,phonenumber, password): user = self.create_user( aadhar=aadhar, name=name, password =password, phonenumber=phonenumber ) user.is_admin = True user.is_staff = True user.is_superuser = True user.save(using= self._db) return user class Account(AbstractBaseUser): aadhar = models.CharField(verbose_name='aadhar',max_length=18,unique=True) name = models.CharField(max_length=50, unique=False) phonenumber = models.CharField(max_length=30) date_joined = models.DateTimeField(verbose_name='date joined', auto_now_add=True) last_login = models.DateTimeField(verbose_name='last login', auto_now=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) USERNAME_FIELD … -
Update objects with values of a different model joined by multiple columns with additional filtering on their FKs using Django ORM
Here is what my models look like: EntryGroup(models.Model): ... EntrySource(models.Model): entry_group = FK(EntryGroup) ... Entry(models.Model): entry_group = FK(EntryGroup) ... EntryItem(models.Model): entry = FK(Entry) attribute_1 = ... attribute_2 = ... ... EntryItemCandidate(models.Model): entry_source = FK(EntrySource) attribute_1 = ... attribute_2 = ... existing_entry_item = FK(EntryItem, null=True) ... I am trying to achieve the following functionality: Get all the objects from model EntryItemCandidate with specified field entry_source_id (FK EntrySource), and update their exitsting_entry_item field with id of object EntryItem that meets following criteria: EntryItem has the same values of fields attribute_1 and attribute_2 as EntryItemCandidate EntryItem's Entry has the same value of field entry_group (FK EntryGroup) as EntryItemCandidate's EntrySource field entry_group (FK EntryGroup) If there is no EntryItem meeting these criteria, exitsting_entry_item should be set to Null. I used to perform this operation iterating for each Entry, but it was way to slow (it would execute order of 10000s queries for each task). I then managed to perform this operation using SQL: update entry_item_caindidate set entry_item_candidate.existing_entry_item = entry_item.id from entry_item_candidate inner join entry_item on entry_item_candidate.attribute_1 = entry_item.attribute_1 and entry_item_candidate.attribute_2 = entry_item.attribute_2 inner join entry on entry.id = entry_item.entry_id inner join entry_source on entry_source.id = entry_candidate.entry_source_id where entry_source.entry_group_id = entry.entry_group_id and entry_item_candidate.entry_source_id = {param} … -
boost django aggregation on a list of objects
I have a model and getting data out of it with django queries. class carts: product_id = models.foreginkey('Product') count = models.IntegerField() price = models.IntegerField() I need total_price for list of products: list_of_prices = [] for product in products: list_of_prices.append(carts.objects.filter(product_id=product.id)\ .aggregate(total_price=Sum(F(count) * F(price)))) is there any way to get list_of_prices without for loop? gettign it with just one or two queries? -
Error in Sending form data to Django views through AJAX
I have a HTML form, which takes in input from the user. On clicking the submit button, form data needs to be sent to the views.py in a JSON format, through AJAX. I tried out something, but I am getting an error the JSON object must be str, not 'NoneType' . The JSON data is being loaded in the views.py through: form = json.loads(request.POST.get('form')) The data is returned in form of a dictionary called 'searchdata'. The form has an id of inputForm . the AJAX call I have written: $.ajax({ url : window.location.href, type : 'POST', cache : false, data:{form:JSON.stringify(formdata)}, success:function(res){ if(typeof res.searchdata != 'undefined'){ self.$dispatch('searchdataevent',res.searchdata); } if(typeof res.message != 'undefined'){ self.message = res.message; } self.loading = false; }, error : function(err){ self.message = 'Error communicating with server'; self.loading = false; } }); Where am I going wrong? Any help is appreciated. -
How to change the default value of STATIC_URL = '/STATIC/' in django?
I'm trying to serve my static files through AWS s3, but I can't change the value of STATIC_URL which remain equal to '/STATIC/', no matter what I type in the settings.py file. -
how could pass dynamic variable with static text in template custom tag in django
How could I use the dynamic parameter with static text in template to custom tag ? in view.py you can use this way to pass many parameters message = 'hello {} this is {}'.format(from_user, to_user) how could I translate above code to template.html code ? I want following condition with multi args for example like this : {% if users|is_user_authorised_to_view_page:'users/<page_id>/<username>/'.format(page.id, user.username) %} {# do this ... #} {% endif %} how could I do that? I searched but didn't find any solution , thanks in advance .. -
celery worker print all log even i have defined only error
I have setup celery in my project and i run worker using celery -A scraper_api worker -l error to print any error if there. But it is printing all logs. Please check below image. -
django registerring apps in INSTALLED_APPS
What is the difference between registering apps in the INSTALLED_APPS like 'nameOfApp' and 'nameOfApp.apps.NameOfAppConfig' Registering the app in the settings.py file -
How can I change the django-leaflet openlayers canvas?
I have a django-leaflet widget, but the widget shows some imagery instead of openlayers map, how can i change this on modelform? from django import forms from django.contrib.gis.forms import OSMWidget, PointField, ModelForm from leaflet.forms.widgets import LeafletWidget class YourMapWidget(LeafletWidget): geometry_field_class = 'geom' class ApartmentForm(forms.ModelForm): class Meta: model = Apartment fields = '__all__' widgets = {'geom': YourMapWidget()} -
Django admin TypeError during templating: missing 1 required positional argument: 'context'
I can't figure out where I'm going wrong here. The error happens during templating when trying to view the admin list and the admin change views. Django==3.0.4 from django.contrib import admin from . import models @admin.register(models.Order) class OrderAdmin(admin.ModelAdmin): list_display = ('id', 'customer_email', 'date', 'status') search_fields = ('id', 'customer_email') date_hierarchy = 'date' list_filter = ('status',) Here's the full traceback: Traceback (most recent call last): File "/home/my_project/venv/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/my_project/venv/lib/python3.6/site-packages/django/core/handlers/base.py", line 145, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/my_project/venv/lib/python3.6/site-packages/django/core/handlers/base.py", line 143, in _get_response response = response.render() File "/home/my_project/venv/lib/python3.6/site-packages/django/template/response.py", line 105, in render self.content = self.rendered_content File "/home/my_project/venv/lib/python3.6/site-packages/django/template/response.py", line 83, in rendered_content return template.render(context, self._request) File "/home/my_project/venv/lib/python3.6/site-packages/django/template/backends/django.py", line 61, in render return self.template.render(context) File "/home/my_project/venv/lib/python3.6/site-packages/django/template/base.py", line 171, in render return self._render(context) File "/home/my_project/venv/lib/python3.6/site-packages/django/test/utils.py", line 95, in instrumented_test_render return self.nodelist.render(context) File "/home/my_project/venv/lib/python3.6/site-packages/django/template/base.py", line 936, in render bit = node.render_annotated(context) File "/home/my_project/venv/lib/python3.6/site-packages/django/template/base.py", line 903, in render_annotated return self.render(context) File "/home/my_project/venv/lib/python3.6/site-packages/django/template/loader_tags.py", line 150, in render return compiled_parent._render(context) File "/home/my_project/venv/lib/python3.6/site-packages/django/test/utils.py", line 95, in instrumented_test_render return self.nodelist.render(context) File "/home/my_project/venv/lib/python3.6/site-packages/django/template/base.py", line 936, in render bit = node.render_annotated(context) File "/home/my_project/venv/lib/python3.6/site-packages/django/template/base.py", line 903, in render_annotated return self.render(context) File "/home/my_project/venv/lib/python3.6/site-packages/django/template/loader_tags.py", line 150, in render return compiled_parent._render(context) File "/home/my_project/venv/lib/python3.6/site-packages/django/test/utils.py", line 95, in instrumented_test_render return self.nodelist.render(context) File … -
want to make infinite scroll i have data of 7000 lines
''' $(window).scroll(function () { // End of the document reached? if ($(document).height() - $(this).height() == $(this).scrollTop()) { $.ajax({ type: "POST", url: "http://192.168.1.8:8099/quran_app/surah/display/", contentType: "application/json; charset=utf-8", data: '', dataType: "json", success: function (items) { $.each( items, function (intIndex, objValue) { console.log(intIndex, objValue) // $("#data").appendTo( "div") ; $("#data").appendTo("div"); } ); }, error: function (req, status, error) { alert("Error try again"); } }); } }); here is the HTML {% block container %} {% for ayah in all_ayah %} {{ ayah.text_simple }} {% for word in ayah.word_set.all %} {% for trans in word.wordtransliteration_set.all %} {{ trans.text }} {% endfor %} {% endfor %} {% endfor %} -
Django Framework
I am new and learning DRF, I'm struggling to get the titles of the specific tag that I want to query in the postman, can anyone shed a light on this where I did wrong below? Thank you models.py class BookTags(TimeStampedModel): class Meta: verbose_name = _('Tag') verbose_name_plural = _('Tags') ordering = ['-created'] book_tags = models.CharField( _(u'Tag Name'), max_length=255, null=False, blank=False, ) def __unicode__(self): return self.book_tags class Title(TimeStampedModel): tags = models.ManyToManyField( "BookTags", verbose_name=_('tags'), blank=True, ) serializers.py class TagSerializer(serializers.ModelSerializer): title_set = LibraryTitleSerializer(read_only=True, many=True) ## when True I get an empty list [{}, {}] when False gives me an error AttributeError: Got AttributeError when attempting to get a value for field `title_set` on serializer `TagSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `Title` instance. class Meta: model = BookTags fields = ['title_set'] views.py class TagApiView(generics.ListCreateAPIView): serializer_class = serializers.TagSerializer search_fields = ['tags__book_tags'] filter_backends = (filters.SearchFilter,) queryset = Title.objects.all() I want to output titles when I search tags localhost:8000/api/tags/?search=Comedy when I hit that endpoint it should list all titles that has tag of Comedy [ {'book_tags': 'Comedy', 'title': "Title 1", }, {'book_tags': 'Comedy', 'title': "Title 2", } ] -
How to connect choose table number from Table model to Bill model with displaying table number from the combobox in django?
I am currently working in Resturant management system in django. I tried to make selected number from the combox. I have two models like Table and Bill. I am confusion on working in selected number. -
present request's data is getting updated in the database but the http response returns previous request's data, why?
tickets_object = Tickets.objects(id=body['_id']).get() Tickets is my mongo model class tickets_object.update( workflowId=workflowId, EntityData=entity_json_object['entities_dict'], StateData=changed_state_dict ) update() is mongoengine atomic update ticket_object_dict={} ticket_object_dict['workflowId']=tickets_object.workflowId ticket_object_dict['EntityData']=tickets_object.EntityData ticket_object_dict['StateData']=tickets_object.StateData returnHttpResponse(json.dumps({'success':True, 'ticket_object_dict':ticket_object_dict})) -
The best way to implement Followers and Following feature with Django ORM
I am struggling with getting this feature done. What I want to achieve is to have same functionality as for example Instagram has. If user A follows user B, that means user A is following user B, and user B is followed by user A. So: A.following = [B], B.following= [], A.followers = [], B.followers = [A]. How do I put this in Django relationship code? I've tried many ways, now I have something like this: class Profile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) follows = models.ManyToManyField('self', related_name='followers', symmetrical=False) But now I don't know, do I have to another relationship to reflect 'Followed by'? Or somehow I have this now, but don't know to write this in code? Help me understand, please. -
DRF (beginner question ) : How to change globally date format in setting.py
Please don't consider it a duplicate because I have tried all the solutions and it did not work for me. Maybe I just miss something. So to change the date Format I add the following command in the setting.py but none of them worked. I first tried : REST_FRAMEWORK = { # "DATE_INPUT_FORMATS": "%d-%m-%Y", doesn't works 'DATE_INPUT_FORMATS': ["%d.%m.%Y"], } then just : 'DATE_INPUT_FORMATS': ["%d.%m.%Y"] or DATE_INPUT_FORMATS : ( "%d.%m.%Y") or DATE_INPUT_FORMATS : "%d.%m.%Y" I have been looking in the documentation . I don't know what I am missing ? I got this error : django.core.exceptions.ValidationError: ['“11.11.1111” value has an invalid date format. It must be in YYYY-MM-DD format.'] thank you in advance for your help :) -
How to read Pdf file from dajngo inMemoryUploadedFile?
I uploaded a pdf file that file type is . How to read pdf from InMemoryUploadedFile type. views.py class TextUploadAPI(APIView): parser_classes = (MultiPartParser,) permission_classes = [IsAuthenticated & IsProjectAdmin] def post(self, request, *args, **kwargs): if 'file' not in request.data: raise ParseError('Empty content') self.save_file( user=request.user, file=request.data['file'], file_format=request.data['format'], project_id=kwargs['project_id'], ) return Response(status=status.HTTP_201_CREATED) @classmethod def save_file(cls, user, file, file_format, project_id): project = get_object_or_404(Project, pk=project_id) parser = cls.select_parser(file_format) if file_format == 'pdf': file = file.read() file = io.BytesIO(file) with pdfpluber.load(file) as pdf: pages = pdf.pages print(pages) data = parser.parse(file) storage = project.get_storage(data) storage.save(user) First i converted InMemoryLoadedFile type to bytes because i got error when i tried open file with open function expected only str,bytes or None type not InMemoryLoadedFile type . After i tried https://github.com/jsvine/pdfplumber/issues/173 this solution but not working . Please help me any one. -
Database information lost after deploy to localhost
I have developed a Django (Cookiecutter-django) app using PostgreSQL and Docker. During development, I have added important data to the database that I don't want to lose. Now, I am trying to deploy it (using this tutorial https://realpython.com/development-and-deployment-of-cookiecutter-django-via-docker/), so first I create a docker-machine locally. I do docker build and up and the project works but my database information is not displaying and my superuser does not seem to exist either. If I run the app outside the docker-machine locally the data does show. I am quite new with Django... Any idea what can I do so that the data is displayed? I have also tried makemigrationsand migrate Please, if you need me to post any fragment from my code tell my and I will update de question. -
Django Deployment on CWP 7
I have a Python Django Project in local . I want to deploy that in CWP 7. I have installed Apache and the version of python is 2.7.I have set Debug=False in settings.py. Via putty i have installed all the packages required for my project. What are the deployment configuration files needed? Kindly guide me as this is my first project. -
Optimize xlsxwriter with more than 300 000 rows
My code is in django / python. I'm using xlsxwriter, maybe it's the wrong choice. I'm open to other plugins. My problem is i have to write more than 300 000 rows in an excel, that taking to much time (some hours). I would like to accelerate it. Here my code : def export_all_agent(request): output = io.BytesIO() epoch = datetime.now().strftime('_%d-%m-%Y_%H-%M-%S') filename = "export_all_agent" + str(epoch) + ".xlsx" workbook = xlsxwriter.Workbook(output, {'in_memory': True}) worksheet = workbook.add_worksheet() row = 0 col = 0 titles = ['matricule', 'name', 'first name', 'gender', 'birth day', 'status', 'Percentage Worktime', 'job category', 'grade_name', 'etab name', 'etab siret', 'territoire', 'region'] agents = Agent.objects.all() for i, item in enumerate(titles): worksheet.write(row, col + i, item) row += 1 for agent in agents: worksheet.write(row, 0, agent.matricule) worksheet.write(row, 1, agent.name) worksheet.write(row, 2, agent.first_name) worksheet.write(row, 3, agent.gender) worksheet.write(row, 4, agent.birth_date) worksheet.write(row, 5, agent.status) worksheet.write(row, 6, agent.percentage_woktime) worksheet.write(row, 7, agent.job_category) worksheet.write(row, 8, agent.grade_name) worksheet.write(row, 9, agent.etablissement.name) worksheet.write(row, 10, agent.etablissement.siret) worksheet.write(row, 11, agent.etablissement.territoire.name) worksheet.write(row, 12, agent.etablissement.territoire.region.name) row += 1 workbook.close() output.seek(0) response = HttpResponse(output.read(), content_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet") response['Content-Disposition'] = "attachment; filename=" + filename return response Do you see some way to optimize it ? or should i change my plugin maybe ? Thank for you help ! -
Django, How to prevent submit form? using ajax
And dont know why the e.preventDefault(); doesn't work, any ideas? or my ajax is wrong? I have this form <form id="myform" class="form" action="{% url 'Updatestudentbehavior' %}" method="POST" style="width: 100%" >{% csrf_token %} <input type="submit" value="Update"> </form> and this is my script <script type="text/javascript"> $(document).on('submit', '.myform', function(e) { e.preventDefault(); console.log(this); }); </script> this is my views.py def Updatestudentbehavior(request): global marks,corevalues id = request.POST.get('student') marks=[] for mark in request.POST.getlist('Marking'): marks.append(mark) #print(marks) corevalues = [] for corevaluesid in request.POST.getlist('coredescription'): corevalues.append(corevaluesid) for i, student in enumerate(request.POST.getlist('id')): marked =marks[i] psa = StudentBehaviorMarking(id=marked) update = StudentsBehaviorGrades.objects.get(id=student) update.Marking = psa update.save() sweetify.success(request, 'You did it', text='Good job! You successfully showed a SweetAlert message', persistent='Hell yeah') return redirect(request.path_info) this is the result, i get -
How to make a periodic task in tasks.py using django and celery
I have a file tasks.py to sending email : def send_email(): top_article = Article.objects.all()[0] article1 = Article.objects.all()[1:3] article2 = Article.objects.all()[3:5] last_article = Article.objects.all()[5:8] context = { 'top_article': top_article, 'article1': article1, 'article2': article2, 'last_article': last_article, } users_mail = UserMail.objects.all() for each_user in users_mail: if each_user.auto_send_mail == True: msg_plain = render_to_string('timeset/email_templates.txt') msg_html = render_to_string('timeset/index3.html', context) subject = "NEWS" recepient = each_user.user_mail send_mail(subject, msg_plain, EMAIL_HOST_USER, [recepient], html_message=msg_html, fail_silently=False) else: print("Not Sending") and in the settings.py in django I setup a schedule : CELERY_BEAT_SCHEDULE = { 'send_email_to_user': { 'task': 'crawldata.tasks.send_email', 'schedule': 10.0, } now i want to make a schedule to sending email into tasks.py not in settings.py anymore , how can i do that ??? , i using celery in django , thanks you!