Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is there any way to include PassengerPoolIdleTime in htaccess file?
I can't find and edit httpd.conf (apache server config file) cuz I'm on a shared hosting and not the root user. The error I get after every 5 minutes is Checking whether to disconnect long-running connections for process 725169, application /home/quarcprs/public_html/terminalbound.com/mysite (production) and my guess is it's because of PassengerPoolIdleTime whose default value is 300s. -
How Can Solve Django Required Fields Problem?
my models.py my views.py Eventhough this settings, when I leave one of the 5 fields I set non required it gives this field is required error. What am I doing wrong ? -
Django: are dynamically created models the only way here?
I am not very advanced with Django and databases, but I have been able to create simple apps. Now I am plotting another app, but I am not sure how to approach it from the conceptual side. Basically, I want to build a web Database Editor for myself, and among other things I want to have the option to create new tables from using GUI (think adding new languages to a web dictionary, but with different sets of properties). Once created, a table will generally be there to stay rather than being added and removed. I am aware of Django Dynamic Models, but I am wondering if there are alternatives to this approach, i.e. if using the SQL language directly wouldn't be a better option in my case, or if there are solutions already close to what I described. -
How to use asyncio with django rest api framework just the way jquery promises work so that responses don't need to wait
I am on python 3.7 with django 2.2.3 running. I want a solution with asyncio so that the api can just call the async function & return the response without waiting just the way we do things with the jquery promises. the definition my_coro is just for example. I will be running moviepy functions that usually require 40-50 seconds to complete. I don't want the api to wait that long for sending out the response. I am also confused on how to handle the thread pool. how to use thread pool here? because I intend to make the moviepy iterations fast as well. So how to create a pool for handling my_coro calls? async def my_coro(n): print(f"The answer is {n}.") async def main(): await asyncio.gather(my_coro(1),my_coro(2),my_coro(3),my_coro(4)) class SaveSnaps(APIView): def post(self, request, format = None): if request.user.is_anonymous: return Response({"response":"FORBIDDEN"}, status = 403) else: try: asyncio.run(main()) return Response({"response": "success"}, status = 200) except Exception as e: return Response({'response':str(e)}, status = 400) -
I'm in trouble to do this api i'm tottaly biggenner let me know how to do this. plz tell a hoew to do this with step by step. tnx in advance
''' Implement Simple Twitter API - Read the following models - UserProfile holds all Twitter users - Tweet holds all tweets for all users - FriendRelation holds following/follower relation between users - Examples: - from_user_profile -> to_user_profile - 1 -> 2 (user profile with id 1 is following user profile id with 2) - 1 -> 3 - 1 -> 4 - user profile with id 1 is following user profiles with ids 1, 2 and 3 ''' `''this is model.py class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) email = models.EmailField(max_length=120) profile_url = models.URLField(max_length=200, null=True, blank=True) joined_on = models.DateTimeField(null=True, blank=True) class Tweet(models.Model): user_profile = models.ForeignKey(UserProfile, related_name='user_tweets') content = models.TextField() posted_on = models.DateTimeField(auto_now_add=True) likes_count = models.IntegerField(default=0) comments_count = models.IntegerField(default=0) retweets_count = models.IntegerField(default=0) class FriendRelation(models.Model): from_user_profile = models.ForeignKey(UserProfile, related_name='user_followings') to_user_profile = models.ForeignKey(UserProfile, related_name='user_followers') created_at = models.DateTimeField(auto_now_add=True) 'this is views.py' # Task Part I # - News Feed API, fetch user's own and all user's following users' tweets def merge_tweets(news_feed, tweets): """ The function takes in 'tweets' and merge with 'news_feed'. """ pass class NewsFeedAPIView(APIView): authentication_classes = (BasicAuthentication,) def get(self, request, format=None): """ You need to do following: - Filter out user's friends - Filter each friend's top 100 tweet ordered by post date … -
django operational error when model contains created_at and updated_at datetime fields
models.py class Profile(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE) # on_deleting user, profile will also be deleted image = models.ImageField(default="profilepic.jpg",upload_to="profile_pictures") dob = models.DateField(null=True) bio = models.TextField(null=True) anonymous = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return f'{self.user.username} Profile' my model has been working just fine untill now. I recently added created_at and updated_at fields to the form. I deleted all the files in migration folder. did makemigrations and migrate to start fresh. despite all this, i keep getting the error : no such column: users_profile.created_at -
Export HTML django Table Data to Excel using JavaScript
I have a download button in my HTML page and on clicking the button, I want to download all it into excel. any idea or source on it. the following webiste export the data but it is with raw html data. In my case html table data are all passed from the django context. https://www.codexworld.com/export-html-table-data-to-excel-using-javascript/comment-page-1/?unapproved=102240&moderation-hash=57c49b5312566fc98830c9d5d0b00d28#comment-102240 -
How should reply model look like i Django?
I am working on blog project in Django. I have made a Comment system that is working fine. I want to add a reply model can anyone tell me how Reply Class will look like in models.py file? **Here is my Comment Class ** class Comment(models.Model): user=models.ForeignKey(User, on_delete=models.CASCADE) blog_id=models.IntegerField(default=0) text=models.TextField() def __str__(self): return self.text[0:17]+' .... by '+ self.user.username ** I am trying with following code but it is giving errors when I makemigrations** class Reply(models.Model): comment=models.ForeignKey(Comment,on_delete=models.CASCADE) text=models.TextField() def __str__(self): return self.text[0:15] -
How do I return multiple lines in python to html?
def output4(request): # Apply the vectorizer tfidf_matrix = vectorizer.fit_transform(raw_files) print(tfidf_matrix.shape) #print out this line terms = vectorizer.get_feature_names() from sklearn.cluster import KMeans, MeanShift, estimate_bandwidth, SpectralClustering, AffinityPropagation num_clusters = 5 km = KMeans(n_clusters=num_clusters) km.fit(tfidf_matrix) clusters = km.labels_.tolist() novels = { 'title': filenames, 'text': raw_files, 'cluster': clusters } df = pd.DataFrame(novels, index = [clusters] , columns = ['title', 'text', 'cluster']) #sort cluster centers by proximity to centroid order_centroids = km.cluster_centers_.argsort()[:, ::-1] for i in range(num_clusters): if i != 0: print ("Cluster %d words: " % i, end='') #print out this line #print (b + "\n") for j, ind in enumerate(order_centroids[i, :10]): if (j == 0): b = '%s' % vocab_df.loc[terms[ind].split(' ')].values.tolist()[0][0] print (b) #print out this line else: c= '%s' % vocab_df.loc[terms[ind].split(' ')].values.tolist()[0][0] print (c) # print out this line #print(c) #print() print("Cluster %d titles: " % i, end='') for j, title in enumerate(df.loc[i]['title'].values.tolist()): if (j == 0): d= '%s' % title else: e= ', %s' % title print (e) #print out this line ms = MeanShift() ms.fit(tfidf_matrix.toarray()) n_clusters_ = len(np.unique(ms.labels_)) print("Number of estimated clusters: {}".format(n_clusters_)) sc = SpectralClustering(n_clusters=num_clusters) sc.fit(tfidf_matrix) clusters = sc.labels_.tolist() sc_df = pd.DataFrame(sc.affinity_matrix_, index=filenames, columns=filenames) print(sns.heatmap(sc_df.corr())) sc_df return render(request, 'clust.html', {'b':b},{'c':c},{'d':d}, {'e':e}) I want to print out the lines that … -
How to set django database setting on app level
I have a django project that has multiple applications. The different applications are using multiple databases which are defined in the common settings.py file. The goal is now to manage the databases not on a project level but on an app level. Therefore the first idea was to have seperated settings.py files, which does not seem to be possible. Then the idea was to use the AppConfig in both apps. If I set the database connection in the ready function there with: setattr(settings, 'DATABASES', { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'db1', 'USER': 'root', 'PASSWORD': 'pw', 'HOST': 'host', 'PORT': 'port' }, 'db1': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'db1', 'USER': 'root', 'PASSWORD': 'pw', 'HOST': 'host', 'PORT': 'port' } }) I get an django.db.utils.ConnectionDoesNotExist: The connection parts doesn't exist. What would be the right way to achieve this or how would I be able to handle the error and set the databases in the ready or init function? -
Which is the best programming language among React-js, Dajango, and Laravel to be a good web developer..?
I already learnt WordPress beside of HTML, CSS, basic JAVASCRIPT, JQUERY, and PHP.But, I want to learn different thing. But, I do not have the idea, Which thing will be good for me & my future. Please describe about it. -
Registering custom path converters in django3 not working
I created a 'custom path converter' which looks like from urllib.parse import quote, unquote class Query: regex = '.*[a-zA-z0-9%]' def to_python(self, value): return unquote(value) def to_url(self, value): return quote(value) and used it to create a path with this code register_converter(Query, 'Query') urlpatterns = [ path('query/<Query:query>/', search), ] but everytime I try to access this URL I'm getting 404 not found error. The URL looks like this 'http://127.0.0.1:8000/query/q%3A' and in debug mode it show Request URL: http://127.0.0.1:8000/query/q: & The current path, query/q:, didn't match any of these but in the list of searched views i can see the view I created and since it's looking for 'q:' and not 'q%3A' I suppose the converter is working, partially perhaps. I followed the example from django docs here. So I was wondering why it isn't working. If anyone knows what I'm doing wrong please point me in the right direction. I'm new to django so I really don't know a lot about it. Thanks. -
clear session data after multi-page form submit in Django
I've a 4-page form, where in 3rd form i'm selecting an image for upload. I'm storing the contents of first 3 forms in session. after 4th form is submitted, i'm collecting the required data from session variables and saving them in database. How do i destroy the session variables in django after 4th form is submitted because when i'm filling a new 4-page form, i get the previously uploaded image in 3rd form. Is there any better way to execute multi-page forms in django? -
Could not build wheels for cryptography which use PEP 517 and cannot be installed directly
C:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools\VC\Tools\MSVC\14.24.28314\bin\HostX86\x64\cl.exe /c /nologo /Ox /W3 /GL /DNDEBUG /MD "-IE:\Python Project\PropertyTax\venv\i nclude" -IC:\Users\pc1\AppData\Local\Programs\Python\Python38\include -IC:\Users\pc1\AppData\Local\Programs\Python\Python38\include "-IC:\Program Files (x86)\Microsoft Visual Studio\2019\Bu ildTools\VC\Tools\MSVC\14.24.28314\include" "-IC:\Program Files (x86)\Windows Kits\NETFXSDK\4.8\include\um" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.18362.0\ucrt" "-IC:\Progra m Files (x86)\Windows Kits\10\include\10.0.18362.0\shared" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.18362.0\um" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.18362.0\ winrt" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.18362.0\cppwinrt" /Tcbuild\temp.win-amd64-3.8\Release_openssl.c /Fobuild\temp.win-amd64-3.8\Release\build\temp.win-amd64-3.8\R elease_openssl.obj _openssl.c build\temp.win-amd64-3.8\Release_openssl.c(498): fatal error C1083: Cannot open include file: 'openssl/opensslv.h': No such file or directory error: command 'C:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools\VC\Tools\MSVC\14.24.28314\bin\HostX86\x64\cl.exe' failed with exit status 2 Failed building wheel for cryptography Running setup.py clean for cryptographyenter code here Failed to build cryptography Could not build wheels for cryptography which use PEP 517 and cannot be installed directly -
django filter and distinct
this is my data in admin site looks like I use distinct() to eliminates duplicate rows from the query results but I wonder why the result is like this even though my html code is {% for n in total %} <tr> <td>{{n.Teacher}}</td> <td>{{n.Subjects}}</td> <td>{{total.Students_Enrollment_Records.Students_Enrollment_Records.Student_Users}}</td> <td>{{total}}</td> </tr> {% endfor %} I have this distinct() code in my views.py mystudent = grade.objects.filter(Teacher = m.id).values_list('Students_Enrollment_Records', flat=False).distinct() and this is my model.py class grade(models.Model): Teacher = models.ForeignKey(EmployeeUser, related_name='+', on_delete=models.CASCADE, null=True, blank=True) Grading_Categories = models.ForeignKey(gradingCategories, related_name='+', on_delete=models.CASCADE, null=True, blank=True) Subjects = models.ForeignKey(Subject, related_name='+', on_delete=models.CASCADE, null=True) Students_Enrollment_Records = models.ForeignKey(StudentsEnrolledSubject, related_name='+', on_delete=models.CASCADE, null=True) Average = models.FloatField(null=True, blank=True) can you guys please explain why the result is like this? -
How to implement paginator in search results
I have able to get all my items from all categories displayed on search results, now I have to add paginator on my search result for all items in categories that have been searched for. How can I implement paginator on search results to display all items in categories paginated? With my code below, the search results do not paginate all items categories properly. I do not know if itertool will be a better idea. def search_result(request): query = request.GET.get('q') if query is None: return redirect("shop:homepage") else: item = Item.objects.all().order_by("timestamp") if item: item = item.filter( Q(title__icontains=query) ).distinct() if item.count() == 0: messages.error(request, "No search results found") paginator = Paginator(item, 1) page = request.GET.get('page') try: queryset = paginator.get_page(page) except PageNotAnInteger: queryset = paginator.get_page(1) except EmptyPage: queryset = paginator.get_page(paginator.num_pages) context = { 'search': item, 'pagination': queryset, 'query': query, } return render(request, 'search_result.html', context) <nav class="my-4 flex-center" style="font-weight:400"> {% if pagination.has_other_pages %} <ul class="pagination pagination-circle pg-blue mb-0"> {% if pagination.has_previous %} <li class="page-item"> <a class="page-link" href="?page={{ pagination.previous_page_number }}" aria-label="Previous"> <span aria-hidden="true">Previous</span> <span class="sr-only">Previous</span> </a> </li> {% endif %} {% for i in pagination.paginator.page_range %} {% if pagination.number == i %} <li class="page-item active"><span class="page-link">{{ i }} <span class="sr-only">(current)</span></span></li> {% else %} <li class="page-item"><a … -
While I am installing cryptography in django project using pycharm, I got the error. Failed building wheel for cryptography
While I am installing cryptography got the following error. Failed building wheel for cryptography Running setup.py clean for cryptography Failed to build cryptography Could not build wheels for cryptography which use PEP 517 and cannot be installed directly Please help me, anybody... -
unable to change the BooleanField value in Django
models.py class Profile(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE) # on_deleting user, profile will also be deleted image = models.ImageField(default="profilepic.jpg",upload_to="profile_pictures") dob = models.DateField(null=True) bio = models.TextField(null=True) anonymous = models.BooleanField(default=False) def __str__(self): return f'{self.user.username} Profile' views.py @login_required def profile_edit(request): if request.method == 'POST': u_form = UserUpdateForm(request.POST, instance=request.user) p_form = ProfileForm(request.POST, request.FILES, instance=request.user.profile) if u_form.is_valid() and p_form.is_valid(): u_form.save() p_form.save() messages.success(request, f'your account has been updated') return redirect('users:profile') else: u_form = UserUpdateForm(instance=request.user) p_form = ProfileForm() context = { 'u_form' : u_form, 'p_form' : p_form } return render(request, 'users/profile_edit.html',context) in users/profile_edit.html <div class="form-group"> <label class="radio-inline"><input type="radio" name="anonymous" value='True'>Anonymous</label> <label class="ml-5 radio-inline"><input type="radio" name="anonymous" value='False' checked>Non-Anonymous</label> </div> the rest of the form works fine (updates the contents of profile as expected) but the BooleanField for anonymous does not work when the radio buttons are clicked before submitting the form -
ImportError: cannot import name 'GuideTeacher' from 'teacher.models'
I have a Teacher model and a Academic model. When i import something in academic model from teacher model Then I found a Import Error like File "/media/sajib/Work/Project/schoolmanagement/teacher/models.py", line 3, in from academic.models import Department, ClassInfo, Section, Session, Shift File "/media/sajib/Work/Project/schoolmanagement/academic/models.py", line 2, in from teacher.models import GuideTeacher ImportError: cannot import name 'GuideTeacher' from 'teacher.models' (/media/sajib/Work/Project/schoolmanagement/teacher/models.py) Now how can i solve this? academic/models.py from teacher.models import GuideTeacher class ClassRegistration(models.Model): department_select = ( ('general', 'General'), ('science', 'Science'), ('business', 'Business'), ('humanities', 'Humanities') ) department = models.CharField(choices=department_select, max_length=15, null=True) class_name = models.ForeignKey(ClassInfo, on_delete=models.CASCADE, null=True) section = models.ForeignKey(Section, on_delete=models.CASCADE, null=True) session = models.ForeignKey(Session, on_delete=models.CASCADE, null=True) shift = models.ForeignKey(Shift, on_delete=models.CASCADE, null=True) guide_teacher = models.OneToOneField(GuideTeacher, on_delete=models.CASCADE, null=True) date = models.DateField(auto_now_add=True) class Meta: unique_together = ['class_name', 'section', 'shift', 'guide_teacher'] def __str__(self): return str(self.class_name) teacher/models.py from academic.models import Department, ClassInfo, Section, Session, Shift class GuideTeacher(models.Model): name = models.OneToOneField(PersonalInfo, on_delete=models.CASCADE, null=True) date = models.DateField(auto_now_add=True) def __str__(self): return str(self.name) -
Django Model Terms of Service With Timestamp, Username, and Prompt User To Agree To Updated Terms of Service
I would like to create a model that contains a timestamp and the allauth currently logged in user who agreed to the Terms of Service. Then, on every page (if the user is logged in), annotate if the user has agreed to the latest Terms of Service (by comparing the timestamp of their last agreement to the timestamp of the latest updated Terms of Service), and if the user has not agreed to the most recent Terms of Service version they are redirected to a page that requires them to agree to the updated version. Then it redirects the user back to whence they came after they agree. How does one go about creating something like this? What I have so far is below. Models.py: from django.contrib.auth.models import User class TermsOfService(models.Model): agreement = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True,blank=True, null=True) user = models.ForeignKey(User, blank=True, null=True, on_delete=models.CASCADE) def __str__(self): return self.agreement Forms.py: from .models import TermsOfService class TermsOfServiceForm(forms.ModelForm): class Meta: model = TermsOfService fields = ('agreement',) def __init__(self, *args, **kwargs): super(TermsOfServiceForm, self).__init__(*args, **kwargs) self.fields['agreement'].widget.attrs={ 'id': 'agreement_field', 'class': 'form-control', 'required': 'true', 'autocomplete':'off'} App Urls.py: from django.urls import path from .views import ( terms_of_service_view ) app_name = 'app' urlpatterns = [ path('terms_of_service_view/', terms_of_service_view, name='terms_of_service_view'), ] … -
Custom system for permissions with django
I'm looking for a way to make my own system of groups and permissions in Django. I know that Django by default brings a system of groups and permits, but in my project due to teacher requirements I had to create my own models. You can create new groups and add permissions to those groups, but since they are not the default models of django I cannot use the template-level functions such as 'perms.car.add_car' for example. What I mean by this? That at the template level, I don't know how to validate if the user has the permission. I hope I have explained myself well, I await your answers and thank you in advance! -
Django : DISTINCT ON fields is not supported by this database backend
How to fix DISTINCT ON fields is not supported by this database backend in django? total = grade.objects.values('Grading_Categories').annotate(Average= Avg('Average')).filter(Teacher = m.id).distinct('Grading_Categories') this is my model.py class finalrating(models.Model): Teacher = models.ForeignKey(EmployeeUser, related_name='+', on_delete=models.CASCADE, null=True, blank=True) Subjects = models.ForeignKey(Subject, related_name='+', on_delete=models.CASCADE, null=True) Students_Enrollment_Records = models.ForeignKey(StudentsEnrolledSubject, related_name='+', on_delete=models.CASCADE, null=True) Average = models.FloatField(null=True, blank=True) Status = models.CharField(max_length=500, null=True, choices=Pending_Request, blank=True) my problem is from this line total = grade.objects.values('Grading_Categories').annotate(Average= Avg('Average')).filter(Teacher = m.id).distinct('Grading_Categories') -
Tabulator ajaxURL adding a question mark to end
I am using wagtail/django for a project and am trying to do ajax calls to tabulator. I currently have this var table = new Tabulator("#example-table", { ajaxURL:"http://localhost:8000/api/v2/people/?fields=*", //ajax URL ajaxConfig:{ method:"get", //set request type to Position headers: { "Content-type": 'application/json; charset=utf-8', //set specific content type }, }, height:"311px", layout:"fitColumns", placeholder:"No Data Set", columns:[ {title:"Name", field:"name", sorter:"string", width:200}, {title:"Date", field:"date", sorter:"string"}, ], }); table.setData(); But my debug console in the browser has Request URL:http://localhost:8000/api/v2/people/?fields=*? "message": "fields error: unexpected char '?' at position 1" Why is a question mark being added to the end? I can replicate the same error if I add a question mark to the end in the Django Rest Page. -
How to limit a model to one record per month (Django)?
I want to build a simple way to track my credit score monthly. I want to be able to track the score from the three major credit agencies for each month of the year. I should only be allowed to make these entries for one month of one year. So far I have the following in my model. class Score(models.Model): equifax_score = models.IntegerField() experian_score = models.IntegerField() transunion_score = models.IntegerField() The end goal is to have an HTML table in my view that shows me my credit score month to month. I want to be able to track this in a line graph once I have enough data. Is this the best way to store this? -
Convert html page to excel
This is my home page and when I click on the download button, Firstly I want the HTML table to converted into an excel sheet and then get downloaded. Any ideas will be highly appreciated.