Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I do to remove the circle?
Hello I have this select but I got an error with that : Here is my code : <label for="id_user">{% 'User' %} <select name="user" id="id_user" class="form-control user" data-live-search="true" data-width="100%" ng-change="user()" ng-init="user()" ng-model="user"> <option value=""></option> {% for user in users %} <option data-content="{{ user.displayname }}" value="{{ user.uniqueid }}"> {{ user.displayname }}</option> {% endfor %} </select> </label> Actually I got this : My problem I don't know why I got two circles like this... Anyone can help me please ? Thank you very much ! -
There is a question 'no [query] registered for [filtered]' when ussing elasticsearch
I use haystack and elasticsearch to finish my search function in django.but when all codes are finished, I begin to test it.but the results is empty and make an Exception elasticsearch.exceptions.RequestError: RequestError(400, 'parsing_exception', 'no [query] registered for [filtered]') I search for many solution but fail to solve this problem.So I hope someody can help me work it out. Following is the code; Blogs/models.py class Artical(models.Model): STATUS = { ("d","草稿"), ("e","发表") } title = models.CharField(max_length=254,help_text="请输入标题,不超过500个字符", unique=False) body = FroalaField(verbose_name="内容",null=True,theme="dark") pub_time = models.DateTimeField("发表时间",default=now) status = models.CharField("文章状态",choices=STATUS,default="a",max_length=1) views = models.PositiveIntegerField(verbose_name="浏览量",default=0) author = models.ForeignKey(to=BlogUser,on_delete=models.CASCADE,related_name="article") thumb_up = models.IntegerField(verbose_name="点赞数",default=0) def get_absolute_url(self): return reverse( "blog:article_detail", kwargs={ 'article_id': self.id, 'year': self.pub_time.year, 'month': self.pub_time.month, 'day': self.pub_time.day } ) def viewed(self): self.views += 1 self.save(update_fields=["views"]) def next_article(self): return Artical.objects.filter(id__gt=self.id).order_by("id").first() def pre_artocle(self): return Artical.objects.filter(id__lt=self.id).order_by("id").last() def get_comment_list(self): comment_list = self.comment_set.filter(article=self) comments_dict = {} header = [] for comment in comment_list: comments_dict[comment] = [] if comment.parent_comment is None: header.append(comment) else: comments_dict[comment.parent_comment].append(comment) return comments_dict,header class Meta: verbose_name = "文章" verbose_name_plural = verbose_name ordering = ["-views","-pub_time"] get_latest_by = "id" Blogs/search_indexes.py class ArticalIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=True, use_template=True) title = indexes.CharField(model_attr='title') def get_model(self): return Artical def index_queryset(self, using=None): """Used when the entire index for model is updated.""" return self.get_model().objects.filter(status="o") template/search/indexes/blogs/Artical_text.txt {{ object.title }} Blogs/views.py class MySearchView(SearchView): … -
django variable persist across api request
I have wriiten an api in django to send and verify an otp using phone. First api send otp and second api verify otp, but now I am getting value of dictionary variable in sendOTP to verifyOTP, how is it possible? if(request.data["task"]=="sendOTP"): url = "https://2factor.in/API/V1/"+OTP_API_KEY+"/SMS/"+request.data["PHONE_NUMBER"]+"/AUTOGEN" response_data = requests.get(url,headers = {"Content-type": "application/x-www-form-urlencoded"}) response = response_data.json() if(response["Status"]=="Success"): details = response["Details"] temp_dict[request.data["PHONE_NUMBER"]]=details return Response(custom_success_handler("OTP sent success",{"Status":"Success"}),status=status.HTTP_200_OK) else: return Response(custom_err_handler("OTP err",response.json()),status=status.HTTP_400_BAD_REQUEST) This is the api to send an OTP. elif(request.data["task"]=="verifyOTP"): print(temp_dict, file=sys.stderr) try: session = temp_dict[request.data["PHONE_NUMBER"]] print(session) #session = r.get(request.data["PHONE_NUMBER"]) except Exception as e: logger.error("radis %s",request.data["PHONE_NUMBER"]) return Response(custom_err_handler("Failed",str(e)),status=status.HTTP_500_INTERNAL_SERVER_ERROR) if session==None: return Response(custom_err_handler("Failed","No OTP is sent"),status=status.HTTP_500_INTERNAL_SERVER_ERROR) url = "https://2factor.in/API/V1/"+OTP_API_KEY+"/SMS/VERIFY/"+str(session)+"/"+request.data["OTP_INPUT"] print(url, file=sys.stderr) response_data = requests.get(url,headers = {"Content-type": "application/x-www-form-urlencoded"}) response = response_data.json() if(response["Status"]=="Success" and response["Details"]=="OTP Matched"): logger.error("OTP success") try: temp_dict[request.data["PHONE_NUMBER"]]=response["Details"] #r.set(request.data["PHONE_NUMBER"],response["Details"]) mobile_num_user = request.data["PHONE_NUMBER"] try: user = User.objects.filter(mobile_num=mobile_num_user).update(otp_verified=True) except User.DoesNotExist: user = None logger.error("Update failed") return Response(custom_err_handler("No user",None),status=status.HTTP_500_INTERNAL_SERVER_ERROR) except Exception as e: logger.error("mobile_number not worked") return Response(custom_err_handler("Failed database",str(e)),status=status.HTTP_500_INTERNAL_SERVER_ERROR) return Response(custom_success_handler("Verified",{"Status":"Success"}),status=status.HTTP_200_OK) else: try: temp_dict[request.data["PHONE_NUMBER"]]=response["Details"] #r.set(request.data["PHONE_NUMBER"],response["Details"]) except Exception as e: return Response(custom_err_handler("Failed",str(e)),status=status.HTTP_500_INTERNAL_SERVER_ERROR) return Response(custom_err_handler("Failed",response),status=status.HTTP_400_BAD_REQUEST) Here is the second api. I can access temp_dict in both api s. How is it possible? Can anyone help me? -
DJango: Can we use ALTER TABLE query in raw() function
I'm trying to alter a table and add a new column in DJango models on runtime with Manager.raw() function but it isn't adding the column to sqLite DB. Can I achieve that functionality and if yes, how? My code for above task is from test.models import Test date = datetime.today().strftime('%d_%m_%Y_%H_%M_%S') Test.objects.raw('alter table test_test add column %s integer', [date]) Thankyou. -
How to add Category and Tags on Django Project?
I tried to create a small project. But sticking to issues in the category modeling that made it impossible to post In the system administrator section Is there a trick to fix it? in my model class Category(models.Model): title = models.CharField(max_length=255, verbose_name="Title") contentcat = models.TextField(default='ใส่เนื้อหาบทความ') def __str__(self): return self.title class Post(models.Model): id = models.AutoField category = models.ForeignKey('Category',on_delete=models.CASCADE,) author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) content_images = models.ImageField(default='media/noimg-l.jpg') title = models.CharField(max_length=200,unique=True,default='ใส่ชื่อบทความ') content = models.TextField(default='ใส่เนื้อหาบทความ') created_date = models.DateTimeField(default=timezone.now) published_date = models.DateTimeField(blank=True, null=True) post_viewcount = models.PositiveIntegerField(default=0,) slug = models.SlugField(max_length=200, default='ใส่ลิงค์บทความ ตัวอย่าง /your-post-content') status = models.IntegerField(choices=STATUS , default=1) def publish(self): self.published_date = timezone.now() self.save() def __str__(self): return self.title class Option(models.Model): sitename = models.TextField(default='ใส่ชื่อเว็บไซต์') sitedescription = models.TextField(default='ใส่รายละเอียดเว็บไซต์') -
How to rendering Django default validation error with Ajax?
I want to display Django default form errors with ajax. Here it codes are supposed to display Django default form errors if forms are errors when accessed users push a submit button. But I couldn't do that. what should add a postscript to? Views.py; if form.is_valid(); ~~~~~~ if self.request.is_ajax(): return JsonResponse({ 'is_valid': True, 'redirect':reverse(/.../), }) return redirect(hogehoge) else: if self.request.is_ajax(): return JsonResponse({ 'is_valid': False, 'error':form.errors, }) Javascript; <script> $(function() { $(document).on('click', '.submit_button', function (e) { var $form = $('.form'); var form = $form[0]; e.preventDefault(); $.ajax({ processData: false, contentType: false, dataType: 'json', url: $form.attr('action'), type: $form.attr('method'), data: new FormData(form), }).done(function(data,textStatus) { if (data.is_valid) { window.location.href = data.redirect; } else { *Display Django default validation errors if there are error forms.* } }); }); }); </script> -
How to manage views,urls and models on large scale in Django?
I am new to the Django. i was going through so many Django tutorials but in all tutorials they were managing all views and model in same files as named views and model. there is any standard way so it can be properly manageable. It is possible to mange call views, urls and model using database ? How to manage this things on enterprise level. -
Django 3.0.5 ModelForm has no model class specified. Error
forms.py from django import forms from django.contrib.auth.models import User from basic_app.models import UserProfileInfo class UserForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput()) class Meta: models = User feilds = ['username','email','password'] class UserProfileInfoForm(forms.ModelForm): class Meta: models = UserProfileInfo feilds = ('portfolio_site','profile_pic') models.py from django.db import models from django.contrib.auth.models import User class UserProfileInfo(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE) portfolio_site = models.URLField(blank=True) profile_pic = models.ImageField(upload_to='profile_pics',blank=True) def __str__(self): return self.user.username Error screenshot As you can see in the above error image, my code is not functioning properly. I have added my forms.py and models.py code. Please help me resolve the issue. -
InterferanceError during unittest Django
I'm trying to write an unittest for view which uses xhtml2pdf. Unfortunately all the time I'm getting error [...] cursor = self.connection.cursor() psycopg2.InterfaceError: connection already closed What's weird, all tests works fine, but when I add just this lines in tests def test_html_to_pdf(self): response = self.client.get(reverse("generate_pdf", args=["pierwszy-post"])) Above error pop up. My view: class HtmlToPdfView(View): def get(self, request, *args, **kwargs): self.one_post = get_object_or_404(Post, slug=self.kwargs["slug"]) context = {"post": self.one_post} pdf = render_to_pdf("pdf.html", context) response = HttpResponse(pdf, content_type="application/pdf") response[ "Content-Disposition" ] = f'inline; filename="{settings.BLOG_TITLE} - {self.one_post.title}.pdf"' return response And URL path( "generate/pdf/<slug:slug>", HtmlToPdfView.as_view(), name="generate_pdf", ), -
Django Make delete migrations to delete records from database
How do I make a script in Django to delete all rows (with some criteria) from a certain (sql) database. I understand the .filter().delete() etc but I don't know where to do this to make it as a script. -
Upload file to Django using requests.post()
I'm quite new to django and I just can't figure out a way to upload a simple html file to django using requests.post(). I tried the steps given in this https://blog.vivekshukla.xyz/uploading-file-using-api-django-rest-framework/ but I keep getting a status 400 when I give import requests file_ob = open("/root/Desktop/sampletext.html", "rb") print(file_ob) payload = { 'remark1': 'hey', 'remark2': 'hello', 'File': file_ob } r = requests.post("http://127.0.0.1:8000/upload/files/", data=payload) print(r.status_code) models.py class Files(models.Model): remark1 = models.CharField(max_length=20) remark2 = models.CharField(max_length=20) File = models.FileField(blank=False, null=False) views.py class FileView(APIView): parser_classes = (MultiPartParser, FormParser) def post(self, request, *args, **kwargs): file_serializer = FileSerializer(data=request.data) if file_serializer.is_valid(): file_serializer.save() return Response(file_serializer.data, status=status.HTTP_201_CREATED) else: return Response(file_serializer.errors, status=status.HTTP_400_BAD_REQUEST) def get(self, request): files = Files.objects.all() file_serializer = FileSerializer(files, many=True) return Response(file_serializer.data, status=status.HTTP_200_OK) serializers.py class FileSerializer(serializers.ModelSerializer): class Meta: model = Files fields = '__all__' What am I doing wrong? Is there a better way to do this? I cant find any example online where requests.post() was used. It's Postman everywhere. -
Django: Audio Record from Button Click
I am trying to create a webapp with Django and Google Cloud Speech-to-Text. Essentially, I want to call this Python function: https://github.com/GoogleCloudPlatform/python-docs-samples/blob/master/speech/microphone/transcribe_streaming_mic.py when a button is clicked on my web page. I've tried, but I am getting an error. Can someone tell me what I'm doing wrong? In views.py: def button(request): return render(request, 'home.html') def speech_to_text(request): ... return render(request, 'home.html', {'speech_text': transcribed_text}) In urls.py: ... urlpatterns = [ url(r'^$', views.button), url(r'^speech_to_text', views.speech_to_text, name='script'), ] In home.html: <div class="row"> <div class="col-md-12" style="text-align:center;"> <button onclick="location.href='{% url 'script' %}'"><i class="fa fa-microphone btn btn-danger" aria-hidden="true"></i></button> <hr> {% if speech_text %} {{speech_text}} {% endif %} </div> </div> Any help please? Thank you! -
Suggestion for django model for annual payment plans
I am using the default django user auth models for authentication in my django 3 app. I want to offer users 3 plans either of which they can purchase. Plan A, Plan B, Plan C. All 3 plans have different views accessibility but have same duration of 1 year. What would be the best way to extend the User model to keep tab on which plan the user has paid for? Also how do I 'expire' the plan after 1 year from date of purchase? from django.db import models from django.contrib.auth.models import User class UserSubscription(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) none = 0 planA = 1 planB = 2 planC = 3 Plans = ( (planA, _('Plan A')), (planB, _('Plan B')), (planC, _('Plan C')), ) plan = models.PositiveSmallIntegerField( choices=Plans, default=none, ) start_date = models.DateField(null=True, blank=True) is_subscribed = models.BooleanField(_('no'), default=False) Thanks in advance -
How can I ask quetions randomly to different user in django?
I want to create a list of quetions and from it i want to ask random 5 quetions to each logged in user.How can i do it. where can i create a list of quetions and options.How can i render quetions and answer to html page ? I tried to create a db table and used it to get values in html template But couldn't work. class Quetions(models.Model): quetion =models.CharField(max_length=100,default='') option1=models.CharField(max_length=20,default='') option2=models.CharField(max_length=20,default='') option3=models.CharField(max_length=20,default='') option4 =models.CharField(max_length=20, default='') -
My discord bot have a error "Traceback (most recent call last):"
I have error with my discord bot My discord bot error look like this: I run in iTerm2 and error looks like this And picture is my code [The above exception was the direct cause of the following exception: Traceback (most recent call last): File "bot.py", line 14, in <module> client.run('NzA4OTk1ODkwODMxOTQ5ODc1.XrpMrA.czBvFQb3Dvnt2HfPUnKMdjC3igs') File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/discord/client.py", line 640, in run return future.result() File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/discord/client.py", line 621, in runner await self.start(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/discord/client.py", line 584, in start await self.login(*args, bot=bot) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/discord/client.py", line 442, in login await self.http.static_login(token.strip(), bot=bot) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/discord/http.py", line 261, in static_login data = await self.request(Route('GET', '/users/@me')) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/discord/http.py", line 165, in request async with self.__session.request(method, url, **kwargs) as r: File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/aiohttp/client.py", line 1012, in __aenter__ self._resp = await self._coro File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/aiohttp/client.py", line 480, in _request conn = await self._connector.connect( File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/aiohttp/connector.py", line 523, in connect proto = await self._create_connection(req, traces, timeout) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/aiohttp/connector.py", line 858, in _create_connection _, proto = await self._create_direct_connection( File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/aiohttp/connector.py", line 1004, in _create_direct_connection raise last_exc File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/aiohttp/connector.py", line 980, in _create_direct_connection transp, proto = await self._wrap_create_connection( File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/aiohttp/connector.py", line 938, in _wrap_create_connection raise ClientConnectorCertificateError( aiohttp.client_exceptions.ClientConnectorCertificateError: Cannot connect to host discordapp.com:443 ssl:True \[SSLCertVerificationError: (1, '\[SSL: CERTIFICATE_VERIFY_FAILED\] certificate verify failed: unable to get local issuer certificate … -
Django not rendering Crispy Form Fields from model
Hi I am a beginner to using django. In my project I am trying to construct a new project form to fill in information to store online. I'm using bootstrap4 as the default template pack in django_crispy_forms. I have been trying to render a form with the crispy tags/filter. I have another form I have used and had success in rendering the fields from a form. However this time I need to render the form from a model. The button and title render on the template but no matter what I try from other examples of modelforms I cant seem to make my fields render to the template like it should. Any help would be greatly appreciated. my related code is as follows: models.py from django.db import models from colorful.fields import RGBColorField class Tag(models.Model): name = models.CharField(max_length=200, null=True) def __str__(self): return self.name class colourtag(models.Model): color = RGBColorField(colors=['#FF0000', '#00FF00', '#0000FF']) # Create your models here. class Project(models.Model): PROJECT_STATUS = ( ('Project Pending', 'Project Pending'), ('Project Active', 'Project Active'), ('Project Completed', 'Project Completed'), ('Project Suspended', 'Project Suspended'), ('Project Cancelled', 'Project Cancelled'), ) PROJECT_CLASSIFICATION = ( ('As-Built Plans', 'As-Built Plans'), ('New Structure', 'New Structure'), ('Renovation', 'Renovation'), ('Extension', 'Extension'), ('New Building', 'New Building'), ) … -
Unable to get custom urls of ModelAdmin working
I am trying to add a custom view to django ModelAdmin on top of the default change, add, history.... views. I basically tried to replicate the code of ModelAdmin.get_urls so that taking the concept of: http://localhost:8000/admin/app_name/model_name/1/change/ represent change action for object id 1 I want to do: http://localhost:8000/admin/app_name/model_name/1/myaction/ represent myaction for object id 1 The following is my code: from django.contrib import admin from django.contrib.contenttypes.models import ContentType from django.http import HttpResponseRedirect from functools import partial, reduce, update_wrapper from django.conf.urls import url from django.utils.html import format_html from django.urls import reverse from django.urls import path class MakerChackerAdmin(admin.ModelAdmin): def get_urls(self): urls = super().get_urls() def wrap(view): def wrapper(*args, **kwargs): return self.admin_site.admin_view(view)(*args, **kwargs) wrapper.model_admin = self return update_wrapper(wrapper, view) info = self.model._meta.app_label, self.model._meta.model_name custom_urls = [ path(r'<path:object_id>/myaction/', wrap(self.myaction), name='%s_%s_deposit' % info) ] return urls + custom_urls However when I go to: http://localhost:8000/admin/app_name/model_name/1/myaction/ I get the following error message: model_name with ID “1/myaction” doesn’t exist. Perhaps it was deleted? -
Allowing Django Register to Take more than 3 Tags
I am trying to use both an image cropping tool and Django sortable tool on the same model. However, it says I can only add up to 3 positional arguments. What does this mean exactly, is there a particular solution for this or a work around? from django.contrib import admin from .models import Rower, Race, Leadership, Event from image_cropping import ImageCroppingMixin from adminsortable2.admin import SortableAdminMixin class MyModelAdmin(ImageCroppingMixin, admin.ModelAdmin): pass class MyModelAdminSorting(SortableAdminMixin): pass admin.site.register(Rower, MyModelAdmin) admin.site.register(Race) admin.site.register(Leadership, MyModelAdminSorting, MyModelAdmin) admin.site.register(Event) Error: admin.site.register(Leadership, MyModelAdminSorting, MyModelAdmin) TypeError: register() takes from 2 to 3 positional arguments but 4 were given -
Django, send form data to m2m_changed signal
I'm using a m2m_signal to do a process to verify is a specific Person is in another Room in a Reservation on the same date period, but I have a problem, I added a clean method on a Reservation ModelForm that executes the m2m_changed signal to check if that Reservation beign created complies with these requirements, but I need to send the date_start and date_end of that reservation to the m2m_changed, right know on the m2m_changed receiver I have the instance, but I cannot query for this object since it still doesn't exist, so I'm passing the date_start and date_end to clean method on the ModelForm, but I'm getting a error message saying prevent_same_room_person() missing 2 required positional arguments: 'date_start' and 'date_end' Here is the code I'm using. In signals.py @receiver(m2m_changed, sender=Reservation.person.through) def prevent_same_room_person(sender, instance, date_start, date_end, action, reverse, model, pk_set, **kwargs): if action != 'pre_add': return if reverse: # Adding Rents to a Person. pass else: # Adding Persons to a Reservation. persons = Person.objects.filter(pk__in=pk_set) persons_duplicate = {} persons_duplicate_html = [] date_period = DateRange(date_start, date_end, bounds='[]') overlap_reservations = Reservation.objects.filter( date_period__overlap=date_period ).exclude(pk=instance.id) for person in persons: if person.id in overlap_reservations.values_list('person__id', flat=True): rents = [] rents_html = [] for rent in … -
Django ORM to get average of data in 15 minutes time block
I have been scraping a data for every 30 seconds and storing it in this model. class Frequency(models.Model): """Store the frequency scraped""" timestamp = models.DateTimeField() frequency = models.DecimalField(max_digits=5, decimal_places=2) Now i have been given a task that for every 15 minutes of a day i have to average out the results and group into something like 08:15-08:30, 08:30-08:45 .... 23:45-24:00. What i thought is to use two loops. The outer one will loop in the hours in a day and the inner one will loop in (00, 15, 30, 45) and then alter todays datetime.now() and filter it. Is there any better way or this is fine?? -
Django relational Model implementation
I am starting learning Django rest framework and creating some apis using rest framework.I have created some api using simple model and that work successfully. Now i am coming into for relational table, but i don know how this relational works..Here is my code: class Countries(models.Model): country = models.CharField(max_length=255) class Meta: managed = False db_table = 'countries' class Users(models.Model): name = models.CharField(max_length=255) email = models.CharField(max_length=255) country = models.ForeignKey(Countries, models.DO_NOTHING) date = models.DateTimeField() class Meta: managed = False db_table = 'users' In views.py def get(self,request): print(UsersSerializer) users = Users.objects.all() serializer = UsersSerializer(users,many = True) return Response(serializer.data) Serializer: class UsersSerializer(serializers.ModelSerializer): class Meta: model = Users fields = '__all__' When i run api i am getting [ { "id": 3, "name": "dsadasd", "email": "dasd@gmail.com", "date": "2020-05-12T12:15:24Z", "country": 1 } ] On the country field i am getting country id and i was expecting country name here... country table having id,country -
Uploading multiple Images to a model in Django admin using multiple upload feature. Not able to display the images on html page
Below is my models, forms, admin and views.py files. I am trying to add multiple images to an event model on the admin panel and trying to display them in the event-detail.html page. Below is the block of code on my event-detail.html page. <div class="row mt-4"> {% for image in companyevent.eventphotos_set.all %} <div class="col-md-4"> <a href=""><img src="{{image.image.url}}" class="img-border" alt=""></a> </div> {% endfor %} Models.py class CompanyEvent(models.Model): title = models.CharField(max_length=100) slug = models.SlugField(max_length=100, blank=True, null=True,unique_for_date='published_date', help_text="SEO friendly post title (automatically filled)") event_cover= models.ImageField(upload_to='EventImages', blank=True, help_text="Add Cover Image to the Event", null=True) categories = models.ManyToManyField(Categories, blank=False, default='General', help_text="Category of the Event") description= RichTextUploadingField(help_text="content of the post goes here", blank=True, null=True) created_date = models.DateTimeField(auto_now_add=True, help_text="Date on which the event has been Created") tags = models.ManyToManyField(Tags) status = models.CharField(choices=STATUS, default='DRAFT', max_length=10, help_text="to segregate events based on status") published_date = models.DateTimeField(auto_now_add=True, help_text="Do you want to publish the event") updated_date = models.DateTimeField(auto_now=True, help_text="Any changes to the Event!") objects = EventQuerySet.as_manager() def __str__(self): return self.title def __unicode__(self): return self.title def save(self, *args, **kwargs): self.slug = slugify(self.title) super(CompanyEvent, self).save(*args, **kwargs) class Meta: ordering= ['-published_date'] def get_all_content(self): return ''.join(map(lambda x: '%s' % str(x), (self.title, self.description))) def get_absolute_url(self): # return '/' + self.slug + '/' return reverse('company_events:event_detail', kwargs={ 'slug': self.slug … -
Spreadsheet like UI and function in django
So I am trying to build an app in Django with a table in it and I want a part of it to behave like a spreadsheet. The features that I would want to be able to do is Copy Pasting values from google sheet/excel to the UI and vice versa. Automatically add Rows based on the data copied google sheet/excel. For eg: If the table shows 10 rows and the data copied is 15 rows from the Google sheet. Then while pasting in the UI it will automatically add the rows. My question is what would be the best way to achieve the above? I haven't yet started building the app yet because I want to figure out first how this would work and which tools would do it suitably well and most importantly how can I connect it with Django. Being a noob to the Django and python (and coding in general) I have been researching this for the past few days and did read articles about this. But haven't found anything concrete. Maybe I am not searching in the right direction. Any help is appreciated. -
Linux Server Django Database population Scheduler
I am running a django project on a linux server via digitalocean. Everything is successful and is working fine. I would like to run a certain script called main(x,y,z) -which populates the postgresql database, to run each night at 00:00. How would I go about achieving this? I just need to be pointed into the right direction :) Take note: The script is working perfectly, I only need to automate running the script.. currently the script is located in the myproject/myapp/views.py file -
How to Reload page only if in first page of the Django pagination
I have this Django code which helps me to do some pagination, Now, it's fetching the all new records whenever any entry done.(DB Mysql) So i want it to auto refresh data in every 3 seconds which is working but its refreshing all pagination pages and getting same data on all page only after it get refresh. {% comment %} Pagination Code {% endcomment %} {% if data.has_other_pages %} <ul class="pagination"> {% if data.has_previous %} <li><a class="btn btn-outline-secondary" href="?page={{ data.previous_page_number }}">&laquo;</a></li> &nbsp; {% else %} <li class=" btn btn-outline-secondary disabled"><span>&laquo;</span></li> &nbsp; {% endif %} {% for i in data.paginator.page_range %} {% if data.number == i %} <li class="btn btn-secondary active"><span>{{ i }} <span class="sr-only">(current)</span></span></li> &nbsp; {% else %} <li><a class="btn btn-outline-secondary" href="?page={{ i }}">{{ i }}</a></li> &nbsp; {% endif %} {% endfor %} {% if data.has_next %} <li><a class="btn btn-outline-secondary" href="?page={{ data.next_page_number }}">&raquo;</a></li> &nbsp; {% else %} <li class="btn btn-outline-secondary disabled"><span>&raquo;</span></li> &nbsp; {% endif %} </ul> {% endif %} {% comment %} Pagination End Here {% endcomment %} Using ajax to refresh Table data Every 3 seconds. setInterval(function refresh() { $.ajax({ url: "{% url 'transaction' %}", success: function(data) { var dtr = $("#container2", data); //#container2 is table id $('#container2').html(dtr); } …