Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
is it good idea to use micro services in django application?
we are developed django application in monolithic architecture so we have move to microservices architecture.Is it good idea? Please provide me any reference link -
Differentiate request from admin portal and from basic API - Django/REST
I was wondering if it was possible to differentiate a request from the Django administration portal from a request from the API ? For example, using permissions, a user would not be able to delete an instance with a basic API call. But the same user through the admin portal would be able to delete the instance. I tried to look at the parameters of the request object but didn't find anything that can be used. -
Authenticate function return none value so user cant login
from django.shortcuts import render, redirect, reverse from reg.models import Reg_page from django.contrib.auth.models import User,auth from django.contrib import messages from django.contrib import auth from django.contrib.auth import authenticate,login from django.http import HttpResponseRedirect from django.db.models import Q from django.core.exceptions import ObjectDoesNotExist from django.template import RequestContext def user_login(request): if request.method == 'POST': username = request.POST['username'] password = request.POST['password'] print("username", username) print("password", password) user=auth.authenticate(username=username, password=password) #user=User.objects.filter(username=username, password=password).exists() print("value",user) if user: auth.login(request, user) return redirect("/welcome") else: return render(request, "login.html", {'error': 'username and password incorrect'}) else: return render(request, "login.html") user can not login because autheticate function return none value it is not give any error so let me know how i can do this -
Exporting queryset data using Django without have to re-query data
I have set up a Django app that queries from a PostgreSQL database. Exporting all the data within a model seems relatively straight forward but what if I wanted to export only the data from a returned queryset. Currently I'm managing this by having a button on my page and changing the url when the user wishes to export data. The code within the view that I'm rendering is as follows. def export_data(request,pk): resource_class = MDPResource() queryset = MDP.objects.filter(mdp_id=pk) dataset = person_resource.export(queryset) response = HttpResponse(dataset.csv, content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="mdpbasic.csv"' return response However, this means that I'm going to be making one query when the user initially opens the page and then a second query (in effect 2 extra) when the user wishes to export the data which I have already queried for in the previous view. Moreover, in a section of my page I'm also using Q models for complex filtering. The above method is not sufficient for exporting data in that case (I don't want to have to reconstruct the query). I also do not want to have to write the data to a file (if I can help it) because then that raises the issue of having … -
error when creating a new virtual environment in django
enter image description hereI get the error "OSError: [Errno 9] Bad file descriptor" whenever I try create a new virtual environment or when when I try torun server of my django project.I am using python 3.7.3 on windows 10. I have tried repairing,uninstalling and reinstalling python but it seems not to work still. -
Deleting mutiple selected objects at once in django [duplicate]
This question already has an answer here: How to delete a record in Django models? 4 answers I want to create something like in the django admin, where one can select objects you want to delete. I have the my model bellow . class People(models.Models): names=models.Charfield view.py def display(request): people=People.objects.all() context={'people':people} def delete_objs(request,id): # i am stock on how to implement a code that will delete selected objects In my django template {% for obj in people %} {{obj.name}} {% endfor %} In my django template and view , how to make it possible for user to select and delete selected objects.Thanks in advance -
When I put my django project on AWS ubuntu server mysqclient error
When i push my django project on AWS ubuntu server and run i got mysql client error below: django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module. Did you install mysqlclient? Then i run below command but same error: 1)sudo apt update 2)sudo apt install mysql-server 3)sudo systemctl status mysql but same erro -
AssertionError at /api/todo/ 'ToDOView' should either include a `serializer_class` attribute, or override the `get_serializer_class()` method
I'm developing a todo api with django. I am getting error as ToDoView(view class name) should include serializer_class but i already have it. Here is the code Router and url router = routers.DefaultRouter() # add this router.register(r'todo', views.ToDOView ,'todo') # add this urlpatterns = [ path('admin/', admin.site.urls), path('api/', include(router.urls)) # add this ] View: class ToDOView(viewsets.ModelViewSet): serializer_class: ToDOserializer queryset = ToDo.objects.all() serializers: class ToDOserializer(serializers.ModelSerializer): class Meta: model : ToDo fields : ('id','title','description','completed') id,title,description and completed are field of my model -
Can I run code every time an abstract class is inherited?
I need to connect a django signal to all classes which inherit from an abstract class. Is there a magic python method like __on_inherit__ which would allow me to run the signal connection code every time my abstract class is inherited? -
'HttpResponse' object has no attribute 'seek'
i want to export from data in excel and i try below code def exel_all_attendance(request,course_id): all_submit_attendance = SubmitedAttendance.objects.filter(course_id=course_id) response = HttpResponse(content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') response['Content-Disposition'] = 'attachment; filename=course.xlsx' attendance_workbook = Workbook() attendance_worksheet = attendance_workbook.active attendance_worksheet.title = 'list_hozor_qiab' columns = [att.submit_time for att in all_submit_attendance.all()] row_num = 1 for col_num, column_title in enumerate(columns, 1): cell = attendance_worksheet.cell(row=row_num, column=col_num) cell.value = column_title attendance_workbook.save(response) return response but i give this error AttributeError: 'HttpResponse' object has no attribute 'seek' and i check where is from error attendance_workbook.save(response) any solution? -
How to write csv file in html?
I have read file of csv but I have a problem that how to read CSV file and save it in table.html? import csv html_about = '' names = [] with open('filo.csv') as data_file: csv_data = csv.reader(data_file) for line in csv_data: names.append(f'{line[0]}') html_output = '\n<ul>' for name in names: html_output += f'\n\t<li>{name}</li>' html_output += '\n</ul>' from prettytable import PrettyTable x = PrettyTable(line[0]) html_code = x.get_html_string() html_file = open('table.html','w') html_file = html_file.write(html_code) -
django "type object 'UserProfile' has no attribute 'DoesNotExist' "
I'm using django restapi framework and trying to do crud , I completed with insert ,update ,select operations but cant delete record. I'm little stuck with this ponit if anyone can tell which direction I should go to fix this I'ill be really glad ty. urls.py I try both url and path version path('user/profile/add', views.AddProfile.as_view(), name='user_profile_add'), # path('user/profile/delete/', views.DeleteProfile.as_view(), name='user_profile_delete'), url(r'^user/profile/(?P\d+)/delete/$', views.DeleteProfile.as_view(), name='user_profile_add'), views.py class DeleteProfile(APIView): permission_classes = (IsAuthenticated,) def get_object(self, pk): try: return UserPorfile.objects.get(pk=pk) except UserProfile.DoesNotExist: raise Http404 def delete(self, request, pk): userprofile = self.get_object_or_404(id=pk) userprofile.delete() return Response(status=status.HTTP_204_NO_CONTENT) serializers.py class UserProfileSerializer(serializers.ModelSerializer): class Meta: model = UserProfile fields = ('id', 'userid', 'accounttype') models.py from django.shortcuts import render, redirect, get_object_or_404, render_to_response from .models import UserProfile from rest_framework.permissions import IsAuthenticated from rest_framework.response import Response from rest_framework.views import APIView from rest_framework import serializers from rest_framework import status class UserProfile(models.Model): id = models.AutoField(primary_key=True, verbose_name='PID') userid = models.BigIntegerField(verbose_name='UID') accounttype = models.CharField(max_length=20, verbose_name='AccType') list_display = ('id', 'accounttype', 'userid') -
How to access to a Many to Many object to get another model property?
I'm coding a tooltip for a Django dashboard, so one of the scenarios says that when the user has not connected their Github account the repository link will be disabled. I already solved the problem but I didn't realized that it only works for the owner of the repo, so if I add somebody else as a collaborator, the link is going to work for them, because ofc, they are not the owners. I have this in my main model: owner = models.ForeignKey( TeamMember, related_name="github_repos", blank=True, null=True, on_delete=models.SET_NULL, ) members = models.ManyToManyField( TeamMember, related_name="new_projects", blank=True, through=ProjectMember, ) So basically how I solved the problem was this way: def html_message(self): pattern = re.compile("Github Repository", re.IGNORECASE) if self.project.owner.has_connected_github: git_connection = self.project.owner.django_user.socialaccount_set.filter( provider="github" ).first() if git_connection: html_message = pattern.sub( f"<a href='{self.project.html_url}'>Github Repository</a>", self.message ) else: html_message = pattern.sub( f"<a href='#' data-toggle='tooltip' title='Connect your Github account to access repository.'>Github Repository</a>", self.message ) That works but as I said before, only for the owner of the app, I need to know how to access to members, instead of owner, because as you can see is a Many to Many Field. And also here is how TeamMember model looks like: class TeamMember(models.Model): class Meta: unique_together = … -
MySql Old Version djang-mysql field incompatible
I was trying to add django-mysql app in my project https://django-mysql.readthedocs.io/en/latest/model_fields/json_field.html#jsonfields-in-forms It worked perfectly on my local system. But When I ran it into production, it created an error (django_mysql.E016) MySQL 5.7+ is required to use JSONField HINT: At least one of your DB connections should be to MySQL 5.7+ What can I do now? -
My css properties changes when I use bootstrap4 with django
I have two pages both in the same app sharing a common style.css - search.html and add.html. I have used bootstrap4 for forms in add.html and not with search.html. When I do this the image size in the add.html changes automatically and the css properties like font, div height changes. Can someone tell me how to fix it? search.html {% load staticfiles %} <!DOCTYPE html> <html lang="en"> <link rel="stylesheet" type="text/css" href="{% static 'css/style.css' %}"> <head> <meta charset="UTF-8"> <title>Transport Portal - Search Page</title> </head> <body> <div class="headerbar"> <img src="{% static 'images/hpcl_logo.png' %}"> <h1>Transportation Portal</h1> </div> <div class="topnav"> <ul> <li><a href="">Home</a></li> <li><a class="active" href="">Search</a></li> <li><a href="">Add</a></li> </ul> </div> </body> </html> add.html {% load staticfiles %} <!DOCTYPE html> <html lang="en"> <link rel="stylesheet" type="text/css" href="{% static 'css/style.css' %}"> <head> <meta charset="UTF-8"> <title>Transport Portal - Search Page</title> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous"> </head> <body> <div class="headerbar"> <img src="{% static 'images/hpcl_logo.png' %}"> <h1>Transportation Portal</h1> </div> <div class="topnav"> <ul> <li><a href="">Home</a></li> <li><a href="">Search</a></li> <li><a class="active" href="">Add</a></li> </ul> </div> </body> </html> style.css * { margin: 0px; padding: 0px; outline: none; border: 0px; } .headerbar { height: 70px; width: 100%; position: relative; margin-left: 0px; margin-right: 0px; padding-left: 0px; padding-right: 0px; border: none; background: #4b6cb7; … -
Django admin two step import from Excel with formset-validation on the second step
I have to import some SKU to Order from excel, but I have to show validation form with error-fields and make some changes for fields before save import results. All in Django admin. Here is 2-nd step mockup (in Russian only, sorry) I can not understand how to generate custom formset page in django admin, with working validation and using initial data. I am understanding how to create custom form pages in django-admin: context = { 'title': 'Import', 'app_label': self.model._meta.app_label, 'opts': self.model._meta, 'has_change_permission': self.has_change_permission(request), 'form': form, 'adminform': admin.helpers.AdminForm(form, list([(None, {'fields': form.base_fields})]), self.get_prepopulated_fields(request)) } return render(request, 'admin/orderscomposing/import.html', context) But it does not work for formsets -
django drag and drop ordering for with many to many relationship of table
ManyToMany admin.TabularInline to display related objects in the admin app, and it works great except I can't figure out what to set the "ordering" property to so it can sort by one of the cross-referenced field names. I used this module django-admin-ordering==0.9.0. -
DjangoCMS on Plugin update CSS are not loading
I am running a DjangoCMS application(3.5.2). When a CRUD operation happens to any of the plugins, the whole page turn into plane white loosing all the CSS. As per my research, I could learn that this is happening since the CMS default page reload is not happening. When dig more into CMS package, noticed that minified js has been used for the same which restrict me to customise the JS. Would be great if anyone can advice me what exactly needs to be done to fix this. -
How to save the selected options of a multi select drop down into a java script list?
How to save all the selected options of a multi select drop down, created using bootstrap, into a java script variable as a list? And further,how to make use of that variable in a python script else where? -
Ubuntu 18.04, Nginx, Gunicorn, Django - how to keep the .env file secure
I'm using django-environ for using separate .env files that store sensitive data. In the case of the server being hacked, the file would be accessible to the intruder. Also, from what I read on this post, any intruder that manages to hack into the app owner account or root has access to the process memory. What is the most secure option for keeping the .env file secure in this enviroment? -
What should be the correct approach to pass in primary key into URL?
Right now I am using Class-based delete view, and my URL contains two arguments which are the primary keys of my 2 models: Post and Lesson. However, I am encountering an "Attribute Error": Generic detail view LessonDeleteView must be called with either an object pk or a slug in the URLconf. These are my two models Lesson and Post: class Post(models.Model): title = models.CharField(max_length=100) image = models.ImageField(default = 'default0.jpg', upload_to='course_image/') description = models.TextField() price = models.DecimalField(decimal_places=2, max_digits=6) date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) rating = models.IntegerField(default = 0) def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail', kwargs={'pk' : self.pk}) class Lesson(models.Model): title = models.CharField(max_length=100) file = models.FileField(upload_to="lesson/pdf") date_posted = models.DateTimeField(default=timezone.now) post = models.ForeignKey(Post, on_delete=models.CASCADE, null=False, blank=False) def __str__(self): return self.title def get_absolute_url(self): return reverse('lesson_upload', kwargs={'pk': self.pk}) This is my URLs.py: path('post/<int:post_id>/lesson_uploaded/<int:lesson_id>', LessonDeleteView.as_view(), name='lesson_delete'), Right now this is how I am trying to insert the parameters in my html template: {% block content %} <div id="main"> <table class="table mb-0"> <thead> <tr> <th>Title</th> <th>Author</th> <th>Download</th> <th>Delete</th> </tr> </thead> <tbody> {% for l in Lesson %} <tr> <td> {% if l.file %} {{ l.title }} {% else %} <h6>Not available</h6> {% endif %} </td> <td>{{ l.post.author }}</td> <td>{% if l.file %} <a … -
How to improve search results in Django Haystack + ElasticSeach
I have used Django Haystack + ElasticSearch for my search page. I followed this tutorial : https://techstricks.com/django-haystack-and-elasticsearch-tutorial/ Now the search process is working fine. But there are lots of unwanted results in search page. For eg: Searched word : Anon Result Obtained :Anonymous, adit ,Billa (and all names) Required Result : Anonymous Searched word : TestName1 Result Obtained :TestName1, TestName2 ,TestName3 Required Result:TestName1 I need exact matches if it were present. When I searched , I came to know about SearchQuerySet. But I have no clue about how to add it , where to add it , how to change my urls.py to the above code. I also think the wrong results were also because of the EDGENGRAM field. So How do I change MINnGRAM AND MAXnGARAM? search_indexes.py from haystack import indexes class UploadFileIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.EdgeNgramField(document=True, use_template=True, indexed=True) FileName = indexes.CharField(model_attr="FileName") User = indexes.CharField(model_attr="User") def get_model(self): return UploadFileModel def index_queryset(self, using=None): """Used when the entire index for model is updated.""" return self.get_model().Objects.all() urls.py url(r'^search/', include('haystack.urls'), name="haystack_search"), settings.py HAYSTACK_CONNECTIONS = { 'default': { 'ENGINE': 'haystack_elasticsearch.elasticsearch5.Elasticsearch5SearchEngine', 'URL': 'http://127.0.0.1:9200/', 'INDEX_NAME': 'haystack', }, } HAYSTACK_SIGNAL_PROCESSOR = 'haystack.signals.RealtimeSignalProcessor' I currently dont have anything in my views and forms related to search. How do … -
HTML head tag appears inside body tag after adding django to the project
Following html code worked as needed before adding django to it. I didn't change anything, but now when i execute it, it has indent on the top of the page and head tag appears inside body tag in chrome. I tried to change position of some of the django syntax, but it didn't change anything. Here is the output of the code {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name = "viewport" content="width=device-width"> <meta name="description" content="Help Pets. We care about animals."> <meta name="keywords" content="charity, foundation, help pets, adoption"> <meta name="author" content="Irina Gorbacheva"> <title>Help Pets | Home page</title> <link rel="stylesheet" href="{% static 'style.css' %}"> </head> <body> <header class="header"> <div class="container"> <img src="{% static 'imgs/footprint.png' %}"> <div id="logo"> <h1><span>Help</span> Pets</h1> </div> <div> <button id ="popupclick">Donate</button> </div> <nav id="navbar" class="topnav"> <a href="{% url 'home' %}" id="cur">Home</a> <a href="{% url 'help' %}">Help</a> <a href="{% url 'adoption' %}">Rehoming</a> <a href="{% url 'reports' %}">Reports</a> <a href="{% url 'about' %}">About us</a> <a href="javascript:void(0);" class="icon" onclick="responsive()"> <svg width="30" height="30"> <path d="M0,5 30,5" stroke="#fff" stroke-width="5"/> <path d="M0,14 30,14" stroke="#fff" stroke-width="5"/> <path d="M0,23 30,23" stroke="#fff" stroke-width="5"/> </svg> </a> </nav> </div> </header> {% block content %} {% endblock content %} </body> </html> -
i can read the excel file and am showing that data in view page but i want to store that data in database and how to create rest api for this
here it is my code plz help me to do this am a beginner of this Django this is views.py from Django.shortcuts import render import openpyxl from .models import FileFieldForm def index(request): if "GET" == request.method: return render(request, 'well/index.html', {}) else: FileFieldForm = request.FILES["excel_file"] # you may put validations here to check extension or file size wb = openpyxl.load_workbook(FileFieldForm) # getting all sheets worksheet = wb.sheetnames print(worksheet) excel_data = list() # iterating over the rows and # getting value from each cell in row for sheet_name in wb.sheetnames: worksheet = wb[sheet_name] for row in worksheet.iter_rows(): row_data = list() for cell in row: row_data.append(str(cell.value)) excel_data.append(row_data) return render(request, 'well/index.html', {"excel_data": excel_data}) -
User Feedback through Django Email
I have an app, in which the main User adds a sub user and sends him an email. I want the sub user to have a button in the email template that would lead him/her to a Feedback form. That feedback form's url must have the user's name in it as it gives a personal touch. But I am not understanding how do I save the feedback data. I will create a scenario to make you guys understand better. There is a main user Chris, Chris adds a sub user Leon in his email list. (P.S both are R.E bad asses). Chris sends an email to Leon, Leon will receive the email and if he want he can give a feedback by clicking the feedback button in email. If Leon clicks the button he will be redirected to a page where the url could be something like this (www.feedback/Leon.com), there will be form where Leon will add his review and submit. The problem is how do I save Leon's information in the sub user model and his review in the feedback model. models.py class FeedBack(models.Model): feedback = models.TextField('Feedback') user_feedback = models.ForeignKey(PersonData) class Meta: verbose_name = ("Client FeedBack") verbose_name_plural = ("Client …