Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to use action object and target in django notifications
i"m working on a project with django something blogging like webapp. I'm using django notifications for my websites notification. i'm recieving notifications if someone comment on my post or like the post. However i can't go to the specific post from the notifications by clicking the notification. my views.py : @login_required def like_post(request): # posts = get_object_or_404(Post, id=request.POST.get('post_id')) posts = get_object_or_404(post, id=request.POST.get('id')) # posts.likes.add for the particular posts and the post_id for the post itself its belongs to the post without any pk is_liked = False if posts.likes.filter(id=request.user.id).exists(): posts.likes.remove(request.user) is_liked = False else: posts.likes.add(request.user) is_liked = True notify.send(request.user, recipient=posts.author, actor=request.user, verb='liked your post.', nf_type='liked_by_one_user') context = {'posts':posts, 'is_liked': is_liked, 'total_likes': posts.total_likes(),} if request.is_ajax(): html = render_to_string('blog/like_section.html', context, request=request) return JsonResponse({'form': html}) -
django.core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL refers to model 'wwwdj.CustomUser' that has not been installed
settings.py AUTH_USER_MODEL = 'wwwdj.CustomUser' # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'wwwdj', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.humanize', 'django.contrib.messages', 'django.contrib.sessions', 'django.contrib.staticfiles', 'django_mysql', ] model: class CustomUser(AbstractUser): company = models.ForeignKey(Company, models.SET_NULL, blank=True, null=True) When I run python3 manage.py makemigrations I get this traceback: Traceback (most recent call last): File "/mnt/c/Users/Evgeny/Desktop/Projects/dj-bagntag/env/lib/python3.6/site-packages/django/apps/config.py", line 178, in get_model return self.models[model_name.lower()] KeyError: 'customuser' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/mnt/c/Users/Evgeny/Desktop/Projects/dj-bagntag/env/lib/python3.6/site-packages/django/contrib/auth/init.py", line 165, in get_user_model return django_apps.get_model(settings.AUTH_USER_MODEL, require_ready=False) File "/mnt/c/Users/Evgeny/Desktop/Projects/dj-bagntag/env/lib/python3.6/site-packages/django/apps/registry.py", line 210, in get_model return app_config.get_model(model_name, require_ready=require_ready) File "/mnt/c/Users/Evgeny/Desktop/Projects/dj-bagntag/env/lib/python3.6/site-packages/django/apps/config.py", line 181, in get_model "App '%s' doesn't have a '%s' model." % (self.label, model_name)) LookupError: App 'wwwdj' doesn't have a 'CustomUser' model. During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line 21, in main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/mnt/c/Users/Evgeny/Desktop/Projects/dj-bagntag/env/lib/python3.6/site-packages/django/core/management/init.py", line 381, in execute_from_command_line utility.execute() File "/mnt/c/Users/Evgeny/Desktop/Projects/dj-bagntag/env/lib/python3.6/site-packages/django/core/management/init.py", line 357, in execute django.setup() File "/mnt/c/Users/Evgeny/Desktop/Projects/dj-bagntag/env/lib/python3.6/site-packages/django/init.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/mnt/c/Users/Evgeny/Desktop/Projects/dj-bagntag/env/lib/python3.6/site-packages/django/apps/registry.py", line 114, in populate app_config.import_models() File "/mnt/c/Users/Evgeny/Desktop/Projects/dj-bagntag/env/lib/python3.6/site-packages/django/apps/config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "/usr/lib/python3.6/importlib/init.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "", line 994, in _gcd_import File "", line 971, in _find_and_load File "", line 955, … -
Why is my Django forms not showing any validation errors?
I have a form field in Django named weight which takes integer as input. However, I want to validate the data before allowing the user to post it. Contrast to that, I am failing to raise validation error if the user inputs wrong data (value outside 0 or 10). Obviously I got something wrong. However, I cannot figure it out, it would be a great help if someone would take their valuable time to review my code. Plus, I believe I can get better insights about writing more cleaner code. This is my models.py class Issue(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) updated_by_user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='issue_updated_by', blank=True) updatd_time = models.DateTimeField(auto_now=True) created_by_user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='issue_created_by') created_on = models.DateTimeField(auto_now_add=True) title = models.CharField(max_length=256) description = models.TextField(blank=True, null = True) open = models.BooleanField(default=True) start_date = models.DateField(null=True, blank=True) due_date = models.DateField(null=True, blank= True) restrict_access = models.BooleanField(default=False) project = models.ForeignKey(Project,on_delete=models.CASCADE, related_name='project_issue') weight = models.IntegerField(blank=True, default= None, null= True, validators=[MinValueValidator(0), MaxValueValidator(10)]) This is my forms.py IssueForm(forms.ModelForm): title = forms.CharField(label='Title', required=True) description = forms.CharField(label='Description',required = False, widget=forms.Textarea) due_date = forms.DateTimeField(initial=datetime.date.today, input_formats=['%d/%m/%Y'], widget=forms.DateTimeInput( attrs={ 'class': 'form-control datetimepicker-input', 'data-target': '#datetimepicker2' }),required=False, ) restrict_access = forms.BooleanField(label='Restrict access',required=False) weight = forms.IntegerField(required=False, validators=[MaxValueValidator(10),MinValueValidator(0)]) class Meta: model = Issue fields = ['title','description','start_date','due_date','restrict_access','weight'] def … -
Python: Storing class type on a class variable durig class initialization
I'm trying to initialize an objects field with a class that needs to know the type that is using it: class Device(Model): objects = AbstractManager(Device) # the rest of the class here This is how AbstractManager is defined: class AbstractManager: def __init__(self, cls: type): self.cls = cls def all(self): result = [] for cls in self._get_subclasses(): result.extend(list(cls.objects.all())) return result def _get_subclasses(self): return self.cls.__subclasses__() So I can later call this and returns all() from all subclasses: Device.objects.all() The issue here is that I cannot use Device while initializing Device.objects, since Device is still not initialized. As a work-around I'm initializing this outside of the class, but there's gotta be a better way: class Device(Model): objects = None # the rest of the class here Device.objects = AbstractManager(Device) PD: I have a C#/C++ background, so maybe I'm thinking too much about this in a static-typing mindset, can't tell -
Reverse for 'new_entry' with arguments '('',)' not found. 1 pattern(s) tried: ['new_entry/(?P<topic_id>[0-9]+)/$']
I'm new learning Django and I want a study tracker web app with Django. So far I've been able to solve errors a long the way but I do not know how to go about fixing this issue. I've checked all my inheritance urls and templates for errors but I can't figure out what seems to the problem. The error came up when I creating the function and template for new entries - this will allow a user write a detailed note about a topic they are currently learning about but whenever I run the template I get an error message reading >Reverse for 'new_entry' with arguments '('',)' not found. 1 pattern(s) tried: ['new_entry/(?P[0-9]+)/$']. I've tried looking at the latest new_entry() function I wrote and tweak the topic variable name but the did not solve the issue. I also cross checked my url paths for any misspelling or whitespaces but there isn't. Here are my project files. views.py file: from django.shortcuts import render, redirect from .models import Topic from .forms import TopicForm, EntryForm # Create your views here. def index(request): """The home page for django app.""" return render(request, 'django_apps/index.html') def topics(request): """Show all topic""" topics_list = Topic.objects.order_by('id') context = {'topics_list': … -
How you would create endpoint with one time use per user without changing the URL? ( Its the closest title I can think of, I'm open to anything)
I'm using Django rest framework for work and there is a new feature request to make a new endpoint which will be used for anyone without login to submit a form. My first thought was to generate a unique token and add it to the URL, so this token would be used for authentication and form submission will be a one time only as this token will expire after first use, but the problem is, this form invitation link would be sent to a group of users at once because there are so many phone numbers and they wouldn't be generating an invitation link one by one for each user so they are doing a bulk send ( copy the link. paste it into a template and Bam ), as you can see in this way invitation link should be somehow used for multiple but only once for a user. So how to achieve this goal by keeping one time use ( for data credibility ) and security in mind. I thought for some other solutions, like doing this endpoint completely with Django and handle everything from there (but it's not good if someone wants to integrate in the future) … -
Django Application AWS deploymenyt error is happening
This is the error log details. Error is occuring while deploying the django application on AWS. I cant understand why this is happening Please read the log properly and help me. module.js:472 throw err; ^ Error: Cannot find module './.webpack.config/prod.js' at Function.Module._resolveFilename (module.js:470:15) at Function.Module._load (module.js:418:25) at Module.require (module.js:498:17) at require (internal/module.js:20:19) at buildConfig (/opt/python/bundle/3/app/webpack.config.js:4:12) at requireConfig (/opt/python/bundle/3/app/node_modules/webpack/bin/convert-argv.js:102:15) at /opt/python/bundle/3/app/node_modules/webpack/bin/convert-argv.js:109:17 at Array.forEach (native) at module.exports (/opt/python/bundle/3/app/node_modules/webpack/bin/convert-argv.js:107:15) at Object.<anonymous> (/opt/python/bundle/3/app/node_modules/webpack/bin/webpack.js:153:40) (ElasticBeanstalk::ExternalInvocationError) ------------------------------------- /var/log/eb-commandprocessor.log ------------------------------------- throw err; ^ Error: Cannot find module './.webpack.config/prod.js' at Function.Module._resolveFilename (module.js:470:15) at Function.Module._load (module.js:418:25) at Module.require (module.js:498:17) at require (internal/module.js:20:19) at buildConfig (/opt/python/bundle/3/app/webpack.config.js:4:12) at requireConfig (/opt/python/bundle/3/app/node_modules/webpack/bin/convert-argv.js:102:15) at /opt/python/bundle/3/app/node_modules/webpack/bin/convert-argv.js:109:17 at Array.forEach (native) at module.exports (/opt/python/bundle/3/app/node_modules/webpack/bin/convert-argv.js:107:15) at Object.<anonymous> (/opt/python/bundle/3/app/node_modules/webpack/bin/webpack.js:153:40) (ElasticBeanstalk::ExternalInvocationError) Please Let me know how to fix it. -
Sql Query variable output
im struggling with the query... How do i put he value of "KN" that is getting selected into a variable ?? @login_required() def Info_anlegen(request, id=None): item = get_object_or_404(Kunden, id=id) itemKN = Kunden.objects.raw('Select KN from blog_Kunden where id = %s', [id]) item1 = get_object_or_404(WindowsHome, KN=) kontaktform_form = InfoForm(request.POST or None, instance=item) winform_form = InfoWinForm(request.POST or None, instance=item1) if kontaktform_form.is_valid(): return redirect('/Verwaltung/KontaktAnlegen') else: form = acroniform(instance=item) return render(request, 'blog/infokontakt.html', {'kontaktform_form': kontaktform_form, 'winform_form': winform_form}) -
how to create custom authentication for my django app my model in django
** I have a model(name:coders) in my Django app** model name coders username password email profile_pic so on I want to authenticate the user using login with (username or email) how I can do this in Django 2 in default Django authentication only allows any one field (but I want both) -
Unable to filter a queryset by using year and month
I am trying to filter a queryset by year and month on a model property. If I filter by year: procedures = Procedure.objects.filter(clinic = clinicobj, timestr__year=2020) for proc in procedures: print(f'{proc.pk} {proc.timestr}') I get: 66 2020-01-08 12:38:37.237585+00:00 67 2020-01-11 15:40:00.344492+00:00 68 2020-01-12 04:50:56.190794+00:00 69 2020-01-26 05:58:36.962205+00:00 70 2020-01-29 09:51:59.038017+00:00 71 2020-02-01 14:24:18.921779+00:00 72 2020-02-09 06:20:30.993496+00:00 73 2020-02-15 10:23:09.068201+00:00 74 2020-02-15 14:04:29.368066+00:00 75 2020-02-16 06:25:09.702327+00:00 76 2020-02-19 14:05:19.369457+00:00 77 2020-02-20 11:13:35.934392+00:00 However when I try to narrow it down by adding the month, I am getting no results. What's wrong here? Procedure.objects.filter(clinic = clinicobj, timestr__year=2020, timestr__month=2) <QuerySet []> Procedure.objects.filter(clinic = clinicobj, timestr__year=2020).filter(clinic = clinicobj, timestr__month=2) <QuerySet []> -
Unicode error happens only for update from admin.py
I bumped into this error, when I am updating the column (datatype text) on django admin.py. unicode error happens only for update '\\xF0\\x9F\\x98\\xA1' for column 'object_repr' at row 1 This is because of UTF-8 problem,When I use 4byte character it happens. The text data(it uses 4byte characters) is already stored in mysql database and definition of table is like this below. show create table tweet_corpus; +--------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ | Table | Create Table | +--------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ | tweet_corpus | CREATE TABLE `tweet_corpus` ( `id` int(11) NOT NULL AUTO_INCREMENT, `text` text, `manual_judge` int(11) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=2471024 DEFAULT CHARSET=utf8mb4 | +--------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ 1 row in set (0.00 sec) And connection from django to mysql is utf8mb4 DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'corpustest', 'USER': 'root', 'PASSWORD': 'mysql', 'HOST': '127.0.0.1', 'PORT': '3306', 'OPTIONS': { 'charset': 'utf8mb4', } } } my admin.py is like this , class CorpusAdmin(admin.ModelAdmin): list_display = ['text','manual_judge'] search_fields = ['text','manual_judge'] list_editable = ['manual_judge'] def _issues(self,row): return row.id Is there any place I need to check??? -
DRF: API Design
I'm using the ContentType framework and GenericForeignKeys with Django. When embedding the content_object into an object field for serialization– is it better to embed it as a field named content_object? Or as a named field that's injected? So for example, let's say I have notifications with a loosely associated object: Should I: Inject a type field for the client to consume, with types like FRIEND, ALERT and so on. Inject a relevant object, like friend, alert OR Infer the type from the content_type field. However this will be unreadable, so the client will simply need to know this enum. Injet the relevant content_object field but keep it named content_object, switching off of the content_type field. -
How do you pass a python variable to my templates HTML file?
I am using django and I would like to learn how to pass a variable which had been generated in my python script to my templates html file. The thing is my script is a loop and i am expecting it to update this value after some time however I cannot do this by rendering from views.py as when i tried rendering and passing it to the html, it kind of just clubbed all of the script's outputs and then rendered the html file placing all of them in that one python variable reference i placed in my html file. Any help is much appreciated. Thanks! -
Add a folder and all files in that folder to urls in Django
I'm trying to add one of my project's folder (with name of 'uploads') with all of the files in this folder to urls.py. location of this folder is in the project folder (not in the app folder), I upload my ImageField images to this folder, but I can access to files of this folder. please help me, thanks. example of url: localhost:8000/uploads/example.png (If it possible, when someone go to localhost:8000/uploads can't see list of all files.) -
After Add any model.How to Django Table Migrate without losing data
class UserSubStatus(models.Model): msisdn = models.CharField(max_length=200) category = models.CharField(max_length=200, null=True, blank=True) validity = models.IntegerField(default=1,null=True,blank=True) sub_status = models.IntegerField(default=0) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: ordering = ['-created_at'] db_table = "user_sub_status" I add this table on my model.py file. How add this "user_sub_status" table on my database without losing any data. -
Sq3Lite Query handling with python forms and DB
Hello iam trying to get this to work but have no clue whats wrong in my code.... the variable "item" gets the current db-row with its ingridients. the variable "itemKN" should obtain the specific row id" which is not working somehow and last but not least the variable "item1) should display the db-row with the same value in "KN" displaying "item" works but the other 2 parts "itemKN", "item1" not. views.py @login_required() def Info_anlegen(request, id=None): item = get_object_or_404(Kunden, id=id) itemKN = Kunden.objects.raw('SELECT KN FROM blog_Kunden WHERE id = 'id'') item1 = get_object_or_404(WindowsPro, id=itemKN) kontaktform_form = InfoForm(request.POST or None, instance=item) winform_form = InfoWinForm(request.POST or None, instance=item1) if kontaktform_form.is_valid(): return redirect('/Verwaltung/KontaktAnlegen') else: form = acroniform(instance=item) return render(request, 'blog/infokontakt.html', {'kontaktform_form': kontaktform_form, 'winform_form': winform_form}) infokontakt.html {% extends 'blog/base.html' %} {% load bootstrap4 %} {% block supertitle %} InfoPage {% endblock %} {% block Content %} {% load static %} <html> <div class="p-2 mb-1 bg-white text-black"> <head> <div class="d-flex justify-content-center align-items-center container "> <img src="{% static 'blog/Gubler.jpeg' %}" alt="Gubler" height="300" width="700"> </div> </head> <br> <body> <form class="form-row" action="" method="post"> <div style="margin-left: 2.5em;"> <font color="black"> <div class="col-sm-10 col-form-label"> {% csrf_token %} {% bootstrap_form kontaktform_form %} </div> </font> </div> </form> <form class="form-row" action="" method="post"> <div style="margin-left: 2.5em;"> … -
Add manytomanyfield as text
This is my view.I want to add a manytomanyfield through text rather than checkbox so that I can create new and get old ones. I want user to just split each language with space class CreateBooksView(LoginRequiredMixin,CreateView): login_url = "/books/login" form_class = CreateBooksForm template_name = "books/create.html" success_url = reverse_lazy('home') def form_valid(self,form): tag_list=[] books = form.save(commit=False) books.author = self.request.user ''' Here many to many query so that I can get or create with text rather than choosing .. ''' books.save() return super(CreateBooksView,self).form_valid(form) def form_invalid(self,form): print (form.errors) return super(CreateBooksView,self).form_invalid(form) from django import forms from books.models import Book class CreateBooksForm(forms.ModelForm): class Meta: model = Book fields = "name","about","language","image" widgets = { 'language': forms.Textarea(attrs={'cols': 80, 'rows': 2}), This is my models.So the ManytoManyField that I want to get filtered is language. class Language(models.Model): name= models.CharField(max_length=100) def __str__(self): return self.name class Book(models.Model): name=models.CharField(max_length=200) about =models.TextField() image = models.ImageField(upload_to=upload_image) language = models.ManyToManyField(Language,related_name='book') author = models.ForeignKey(User,on_delete=models.PROTECT,related_name='bauthor') def __str__(self): return self.name class Meta: ordering = ('-pk',) -
Django Rest Framework: POST to Viewset with URL parameter
Typically, in a DRF Viewset you might do something like this: class FooViewSet(viewsets.ViewSet): """ Foo-related viewsets. """ permission_classes = [IsAuthenticated,] def list(self, request): """ A list of foo objects. """ context = {'request': self.request} queryset = Foo.objects.all() serializer = FooSerializer(queryset, many=True, context=context) return Response(serializer.data) def retrieve(self, request, pk=None): """ Get one publicly available Foo item. """ context = {'request': self.request} queryset = Foo.objects.all() store_object = get_object_or_404(queryset, pk=pk) serializer = FooSerializer(store_object, context=context) return Response(serializer.data) This works fine, and respectively correlates to: GET /foo and GET /foo/<pk>. However, the last endpoint I need is POST /foo/<pk>. The problem here is that providing a create method to the views typically will be routed to POST /foo. Is there anything neat and elegant I can do from the ViewSet itself? Or is the only option basically to route POST /foo/<pk> to a specific one-off view? -
Django how to create table inside views
I want to create a table with a row of per student and in the columns the grades at a specific date , please help me to fix my table.. def periods(request): students = studentsEnrolledSubjectsGrade.objects.filter(Teacher=teacher).filter(grading_Period=period).filter( Subjects=subject).filter(Grading_Categories=category).filter(GradeLevel=grade).order_by( 'Students_Enrollment_Records', 'Date').values('Students_Enrollment_Records', 'Date', 'Grade') dates = list(students.values_list('Date', flat=True).distinct().order_by('Date')) # table basics table = [] student_name = None table_row = None columns = len(dates) + 1 # table header table_header = ['Student Name'] table_header.extend(dates) table.append(table_header) for student in students: if not student['Students_Enrollment_Records'] == student_name: if not table_row is None: table.append(table_row) table_row = [None for d in range(columns)] student_name = student['Students_Enrollment_Records'] table_row[0] = student_name table_row[dates.index(student['Date']) + 1] = student['Grade'] table.append(table_row) return render(request, 'Homepage/period.html', {'table': table}) my html {% for v in table.0 %} <td>{{ v }}</td> {% endfor %} </tr> <tbody> {% for row in table %} <tr> <td>{{ row.0 }}</td> {% for c in row %} <td>{{ c }}</td> {% endfor %} </tr> {% endfor %} this is the admin view of my studentsEnrolledSubjectsGrade models studentsEnrolledSubjectsGrade i get this result current result this is the result i want to display desire result -
Receiving 2 password reset emails in Django everytime i try to reset a password
I am a beginner in Django and i have been following an online tutorial to build a web application. I had been trying to add the password reset functionality to the application for the past few days. I set up a google app password and finally got the password reset to work. But now, every time i try to reset a password, i receive 2 password reset emails on my email account. I have reset the password successfully a few times but i continue to receive two emails every time i try to reset a password. I tried to look for answers online but couldn't find anything. I have also cross-checked my code with the tutorial. Here are some code snippets that might be relevant: Project settings.py: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = os.environ.get('EMAIL_USER') EMAIL_HOST_PASSWORD = os.environ.get('EMAIL_PASS') Project urls.py: urlpatterns = [ path('admin/', admin.site.urls), path('register/', user_views.register, name='register'), path('login/', auth_views.LoginView.as_view(template_name='users/login.html'), name='login'), path('logout/', auth_views.LogoutView.as_view(template_name='users/logout.html'), name='logout'), path('password-reset/', auth_views.PasswordResetView.as_view(template_name='users/password_reset.html'), name='password_reset'), path('password-reset/done/', auth_views.PasswordResetDoneView.as_view( template_name='users/password_reset_done.html'), name='password_reset_done'), path('password-reset-confirm/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view( template_name='users/password_reset_confirm.html'), name='password_reset_confirm'), path('password-reset-complete/', auth_views.PasswordResetCompleteView.as_view( template_name='users/password_reset_complete.html'), name='password_reset_complete'), path('profile/', user_views.profile, name='profile'), path('', include('blog.urls')), ] Any help will be highly appreciated. Thanks! PS: This is my first question on StackOverflow. Please let me … -
ValueError: set_wakeup_fd only works in main thread on Apache2.4.41 + Python 3.8.1 + Django 3.0.2 + MySQL 8.0.19
When I run my Django Web application with Apache2.4.41 + Python 3.8.1 + Django 3.0.2 + MySQL 8.0.19 on Windows 10 Professional version it throws Value Error at /. set_wakeup_fd only works in main thread. This issue was a result of regression in Python 3.8 and was fixed in November in later builds of Python. For more details - https://bugs.python.org/issue38563. Stacktrace of the error is as follows - Environment: Request Method: GET Request URL: http://127.0.0.1/ Django Version: 3.0.2 Python Version: 3.8.1 Installed Applications: ['Analysis.apps.AnalysisConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.humanize'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "c:\python38\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "c:\python38\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "c:\python38\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "F:\IndianMarketAnalysis\ISMA\Analysis\views.py", line 8, in home date_list = dict(d.date_list()) File "F:\IndianMarketAnalysis\ISMA\Analysis\models.py", line 7, in date_list with connection.cursor() as cursor: File "c:\python38\lib\site-packages\django\utils\asyncio.py", line 19, in inner event_loop = asyncio.get_event_loop() File "c:\python38\lib\asyncio\events.py", line 636, in get_event_loop self.set_event_loop(self.new_event_loop()) File "c:\python38\lib\asyncio\events.py", line 656, in new_event_loop return self._loop_factory() File "c:\python38\lib\asyncio\windows_events.py", line 310, in __init__ super().__init__(proactor) File "c:\python38\lib\asyncio\proactor_events.py", line 632, in __init__ signal.set_wakeup_fd(self._csock.fileno()) Exception Type: ValueError at / Exception Value: set_wakeup_fd … -
django table in view
I want to create a table with a row of per student and in the columns the grades at a specific date def periods(request): students = studentsEnrolledSubjectsGrade.objects.filter(Teacher = teacher).filter(grading_Period = period).filter(Subjects = subject).filter(Grading_Categories = category).filter(GradeLevel = grade).order_by('Students_Enrollment_Records', 'Date').values('Students_Enrollment_Records', 'Date', 'Grade') dates = list(students.values_list('Date', flat=True).distinct().order_by('Date')) # table basics table = [] student_name = None table_row = None columns = len(Date) + 1 # table header table_header = ['Student Name'] table_header.extend(dates) table.append(table_header) for student in students: if not student['Students_Enrollment_Records'] == student_name: if not table_row is None: table.append(table_row) table_row = [None for d in range(columns)] student_name = student['Students_Enrollment_Records'] table_row[0] = student_name table_row[dates.index(student['Date']) + 1] = student['Grade'] table.append(table_row) return render(request, 'Homepage/period.html', {'table': table}) my html <table id="blacklistgrid" border="2px"> <tr> {% for v in table.0 %} <td>{{ v }}</td> {% endfor %} </tr> <tbody> {% for row in table|slice:"1:" %} <tr> <td>{{ row.0 }}</td> {% for c in row|slice"1:" %} <td>{{ c }}</td> {% endfor %} </tr> {% endfor %} </tbody> this is my models.py of studentsEnrolledSubjectsGrade class studentsEnrolledSubjectsGrade(models.Model): Teacher = models.ForeignKey(EmployeeUser, related_name='+', on_delete=models.CASCADE, null=True,blank=True) GradeLevel = models.ForeignKey(EducationLevel, 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) Grading_Categories = models.ForeignKey(gradingCategories, related_name='+', on_delete=models.CASCADE, null=True,blank=True) grading_Period = models.ForeignKey(gradingPeriod, related_name='+', on_delete=models.CASCADE, null=True,blank=True) … -
500 Internal Server Error - Django wsgi error showing on apache2 log
I am getting an Internal Server Error and not sure if i need to change something in wsgi. The app was working fine while tested on virtual environment on port 8000. I followed all the steps using the tutorial https://www.youtube.com/watch?v=Sa_kQheCnds the apache error log shows the following : [Sun Feb 23 02:13:47.329729 2020] [wsgi:error] [pid 2544:tid 140477402474240] [remote 24.189.204.68:59870] mod_wsgi (pid=2544): Target WSGI script '/home/recprydjango/rec$ [Sun Feb 23 02:13:47.329817 2020] [wsgi:error] [pid 2544:tid 140477402474240] [remote 24.189.204.68:59870] mod_wsgi (pid=2544): Exception occurred processing WSGI script $ [Sun Feb 23 02:13:47.330088 2020] [wsgi:error] [pid 2544:tid 140477402474240] [remote 24.189.204.68:59870] Traceback (most recent call last): [Sun Feb 23 02:13:47.330125 2020] [wsgi:error] [pid 2544:tid 140477402474240] [remote 24.189.204.68:59870] File "/home/recprydjango/recipe/app/wsgi.py", line 12, in <mo$ [Sun Feb 23 02:13:47.330130 2020] [wsgi:error] [pid 2544:tid 140477402474240] [remote 24.189.204.68:59870] from django.core.wsgi import get_wsgi_application [Sun Feb 23 02:13:47.330148 2020] [wsgi:error] [pid 2544:tid 140477402474240] [remote 24.189.204.68:59870] ModuleNotFoundError: No module named 'django' I have the following structure wsgi.py """ WSGI config for app project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/2.2/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'app.settings') application = get_wsgi_application() apache config <VirtualHost *:80> # The ServerName directive sets … -
django - post_save - Order matching query does not exist error
To create an instance of WishList model and and instance of Order model when a Profile model is created, and to create an instance of Profile model when a User is registered, so it goes like this: user register —> User —> Profile —> WishList and Order the series of creation, I thought ‘post_save’ signal would be the best, and the code goes: # to create a profile whenever a user is created @receiver(post_save, sender=User, dispatch_uid="create_user_profile") def create_profile(sender, instance, created, **kwargs): user_profile, created = Profile.objects.get_or_create(user=instance) if created: user_profile.save() @receiver(post_save, sender=Profile, dispatch_uid="create_user_wish_list") def create_wish_list(sender, instance, created, **kwargs): user_wish_list, created = WishList.objects.get_or_create(profile=instance) user_wish_list.save() # to create a shopping_bag/order whenever a profile is created @receiver(post_save, sender=Profile, dispatch_uid="create_profile_order") def create_profile_order(sender, instance, created, **kwargs): if not Order.objects.get(profile=instance, is_ordered=False): profile_order, created = Order.objects.get_or_create( profile=instance, ref_number="{}'s shopping bag".format(instance.user.username), ) profile_order.save() They were originally in three different directories according to their own apps (users app: Profile model; wishlist app: WishList model; shopping app: Order model), and they worked fine when a registered user logged in, such as a superuser I created at the beginning of the entire profile. However, when a new user is registered, after submitting the RegistrationForm, this error occurs: Order matching query does not exist. … -
Decrease memory consumption with objects inside python lists
I'm currently using Docker-compose and numpy to populate a PostGIS database in Django. The current issue is that I'm not sure what's consuming so much memory here: tile_density = int(map_height * map_width / settings.NUM_OF_USERS) root2 = sqrt(2) map_radius = map_width / (2 * root2) lat_range = 90 / map_width # 180 / map_width / 2 lon_range = 90 / map_height # 180 / map_height / 2 print("Beginning migration creation") # Begin migration based on shade for i, y in enumerate(data): # y starts from top then goes to bottom # We have to imagine the current numpy array is like the coordinate system # Then translate it when creating user locations temp_users = [] for x in y: # x is now a tile. x starts from left and moves to right # Points go up to 14 decimal places if x in (-200.0, 0.0): # No data or no people continue # Calculate the 4 Points as boundaries for these users' coordinates. theta = np.arcsin(i / map_radius / root2) temp = np.arcsin((2 * theta + np.sin(2 * theta)) / pi) lat_range = ( temp - lat_range, temp + lat_range ) temp = pi * x / 2 / map_radius …