Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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! -
Open the url with Access Token which comes in API response
I have a set of api calls which can be accessible by Access Token and I'm able to get responses from the apis but one of the responses contain URL but when I try to access it, url asks for Log in which i'm already Logged in because thats how I got Access Token. API response: { "root": "some value", "blocks": { "some value": { "display_name": "some display name", "block_id": "abc123", "view_url": "https://www.abc.come", "web_url": "https://www.abv.com", "type": "some type", "id": "some id" } } } So from this response I want to access "web_url" so when i do a Get request, it asks for Log in. So how can I access web_url without Log in ? -
Acessing dynamic url in post method
in views.py class ProcessMessage(TemplateView): template_name = 'chatbot/chat.html' def get_object(self): id=self.kwargs.get('pk') obj=None if id is not None: obj= User.objects.get(pk=id) return obj def get(self, request, pk=None,*args, **kwargs): obj=self.get_object() print(obj,pk) super(ProcessMessage, self).get(request, *args, **kwargs) return render(request, self.template_name, {'form': ChatForm()}) def post(self, request, pk=None,*args, **kwargs): obj=self.get_object() pk=pk print(pk) print('obj is',obj) form = ChatForm(data=request.POST) # log = logging.basicConfig(level=logging.DEBUG) # print('post from index') if form.is_valid(): //////something//// in urls.py app_name = 'chatbot' urlpatterns = [ path('demo', views.ProcessMessage.as_view(), name='index'), path('<uuid:pk>/demo', views.ProcessMessage.as_view(), name='index'), ] I am getting the value of obj and pk inside get method but I want those value inside post method also(getting value None currently) I need id/pk from URL in def Post method to get user information(no I don't want to use request.user) -
Save and read file in django media folder from views
I have a function in my django views which create barcode and saves it in the os temporarily. How can I save and read it in the Media Folder?? Settings.py MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') Views.py for i in items: barcode = get_barcode(value=i, width=600) a = barcode.save(formats=['PNG'], fnRoot='R123') #save this in Media folder print("a ",a) with open(a, 'rb') as image: #read from the Media folder img = image.read() grf = GRF.from_image(img, str(i)) grf.optimise_barcodes() print(grf.to_zpl()) -
creating dynamic dependent drop down from database in django
i have two drop downs from the mysql database in which both are interdependent. what i need is when i select an area from the first drop down, the second drop down as to filter accordingly matching the area from the first drop down. can anyone help me out. [The first drop down is area and the second drop down is zone ]. -
How to deploy a Django application with react serving from its static files on aws elastic beanstalk?
i have deployed a django project on aws beanstalk, gave static files path from aws elasticbeanstalk console still app is not showing up. instead i am getting this error error Failed to load resource: the server responded with a status of 404 (Not Found) -
How to use middleware for specific call in djnago web app?
I want to use middle ware in my django web app . But the problem is that i want to use middle ware only after user successfully login. I declare my custom middle ware in setting.py file but it's gives error because custom middle ware is called at unnecessary restful call. How do i call middle ware while some specific restful call. -
How to make "Shortcodes" for Django like in WordPress?
Most of my web dev stuff has been with WordPress, but I'm transitioning to Django now. So far, I'm getting the hang of it. However, one thing WordPress has that Django doesn't seem to is Shortcodes. And I desperately need them on my Django site. The way it works on my old WP site is like this: "[equipment]Grappling Hook[/equipment]". A user would type that into a TextField, somewhere within the rest of their content, and then it's displayed on the page (like in say a comment or a forum post) and it's automatically turned into a hyperlink with data that comes from a database query using "Grappling Hook" as the name to query for. Basically, [equipment]Grappling Hook[/equipment] written within a TextField automatically turns into: <a class="tooltip" href="/equipment/grappling-hook">Grappling Hook</a> when rendered on the actual page. I have scoured all of Google looking for a solution to achieve this same functionality with Django, but I just can't figure it out. I found an old app called django-shortcodes but there's very little documentation, it only seems to have a YouTube shortcode and I have no idea how to add custom ones. It doesn't have to work exactly like WordPress, either. I just need … -
Creating a User and Role Management System with multiple hierarchies
A company is divided into multiple branches. The company has 1-2 super admins who have access to everything. A branch is a separate physical location and operates as a separate business entity. A branch can have multiple departments. A department has a specific function. For example, a department will be defined as a knitting, weaving, dyeing, garmenting department. List of departments can be thought of as static as they will only be updated when developers create a new module. So I can end up having one branch that has a knitting and weaving department and another branch which has a knitting and a dyeing department. The same department should have fairly common roles throughout the different branches of a company. A person should only have access to rights of the branch that they have been given access to. When it comes to the UI/ performing actions, there is no point in showing all the screens for all the departments as screens can be department specific. So, if the screen belongs to a particular department and one has access to it, will they be able to see and modify it. Additionally, a user can be the Admin (having all the access) … -
Make change_list column editable AND change its name without changing the Model class field label
I am new to Django and am facing some issues with customizing a change_list. I am trying to make a changelist column editable, AND change the column's display name. I managed to change the display name of the column by using a callable that returns the model field value, setting its short_description property to the new column name and then adding the callable to the list_display, which works fine. I then add the callable to the list_editable, but then the editable field cannot get resolved. I get the error The value of 'list_editable[6]' refers to 'get_instruction_date', which is not an attribute of 'employee.Onboarding'. Is there a way to get this working (make column editable AND changing its display name/label) without having to change the Model itself? -
How to list the names of the objects in a PostGreSQL database tables in a Django Application running on Google Cloud App Engine
I have a Django Application running on Google Cloud App Engine. How can I list all the names of the object models / tables in the PostGreSQL database ? -
Is there is any way I can make filtering inside models in Django?
I create custom Account model and I add view columns like is_student, is_teacher. So I make another class in another app so how can I do filter something like this in models. from accounts.models import Account a = Account.objects.filter(is_student=True) class Table(models.Model): student = models.ManyToManyField(a, on_delete=models.CASCADE) -
datepicker modification for form filling
I want to make sure that the dates that are displayed in the datepicker lie between the job start and end dates. However i am not able to add the correct js code for the same. can someone please help me with this? I have written the js code modification i tried, however the change is not reflected in the application. I tried with writing minDate : 0 as well, but no change was seen. $(document).ready(function() { $("#datepicker").datepicker({ minDate : 'job.start_date' }); }); -
Inherited model with FK to base model overwrites base reference
I have a situation where I have 2 models, with the second model (B) being a subclass of the first (A), and also having a (different) FK reference to another instance of same parent model (A). The objective is to have some special cases of A linked to other instances of A's in a new table, B's. For reasons I won't get into here, these need to be 2 different models (ie I can't add a nullable 1-to-1 reference field on A). This is illustrated below. class A(models.Model): name = models.CharField() class B(A): reference = models.ForeignKey(A) However now when I try instantiate B with a reference to a different A, it doesn't work. Consider the following: >>> a1 = A(name='a1') >>> a1.save() >>> b1 = B(name='b1', reference=a1) >>> b1.save() >>> b1.id 1 >>> b1.reference.id 1 Or alternatively: >>> a1 = A(name='a1') >>> a1.save() >>> b1 = B(name='b1') >>> b1.save() >>> b1.reference = a1 >>> b1.save() >>> b1.id 2 >>> b1.reference.id 2 Whereas what I would like here is for b1.id to equal 2 and b1.reference.id to equal 1 (referencing a1). What is going on here? Why can't I have independent references to the base instance with the ptr_id and a …