Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Model: Getting result from a table using unique foreign key
I have two models that look like this: class Author(models.Model): name = models.CharField(max_length=200) class Book(models.Model): author = models.ForeignKey('Author', on_delete=models.CASCADE) isbn_id = models.CharField(max_length=50, null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) How can I make a query such that: I get each author with the total number of books created, number of books with an isbn. Each time a book is created for an author, I can get the last_created, last_modified. This is an example of the result I am trying to achieve; s/n| author| no_books_with_isbn| all_books| last_created| last_modified 1. Faye 2 2 ... .... 2. Soya 2 5 3. Jake 6 6 4. Gurj 4 4 5. Zoom 2 10 -
how to get only one column from a entire table using foreign key in Django
I'm working on a Django project. where I need to map the fields using foreign key. Here's my model.py for table developer: class Developers(models.Model): Developer_Name = models.CharField(max_length=100, unique=True) Role = models.CharField(max_length=500) Level = models.CharField(max_length=30) Expertise = models.CharField(max_length=200) Availability_Hours = models.CharField(max_length=500) and here's my main table where I perform foreign key relation class Jira_Stories(models.Model): Jira_Story = models.CharField(max_length=100) Short_Description = models.CharField(max_length=500) Story_Points = models.CharField(max_length=30) Sprint = models.CharField(max_length=200) DX4C_Object = models.CharField(max_length=500) Developer_Assigned = models.ForeignKey(Developers, on_delete=models.CASCADE,to_field="Developer_Name") and here's my view: def dependency_management(request): jira = Jira_Stories.objects.all() return render(request, 'hello/Dependency_Management.html', {'JIRA': jira}) But i dont want the entire developer table as a foreign key , I just need one field i.e. Developer_name in my UI and also in database it is coming as object how to add only one field instead of whole table using foreign key ? -
Django updtae() is not working as expected
I have a function that changes the details of my models when triggered. I cannot get it to do the work I intend to have it do. I can't tell why this is so. Any help will greately be appreciated. @login_required(login_url='/login/') def move_students(request): try: Klass.objects.filter(school=request.user.school,name=1).update(name=2) except Exception as e: messages.info(request,f'erroerd at {e}') return redirect('/') The model class Klass(models.Model): name = models.IntegerField(validators=[MinValueValidator(1), MaxValueValidator(5),], help_text='E.g 1,2,3, 4') school = models.ForeignKey(School,on_delete=models.CASCADE) def __str__(self): return str(self.name) class Meta: verbose_name_plural = 'Classes' unique_together = ("school", "name") Traceback (most recent call last): File "C:\Users\FR GULIK\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\FR GULIK\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\FR GULIK\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\contrib\auth\decorators.py", line 21, in _wrapped_view return view_func(request, *args, **kwargs) File "D:\Python\Django\Completed Projects\lib_system\Library-System\libman\views.py", line 29, in move_students Klass.objects.filter(school=request.user.school,name=1).update(name=2) File "C:\Users\FR GULIK\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\query.py", line 784, in update rows = query.get_compiler(self.db).execute_sql(CURSOR) File "C:\Users\FR GULIK\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\sql\compiler.py", line 1522, in execute_sql cursor = super().execute_sql(result_type) File "C:\Users\FR GULIK\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\sql\compiler.py", line 1156, in execute_sql cursor.execute(sql, params) File "C:\Users\FR GULIK\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\backends\utils.py", line 98, in execute return super().execute(sql, params) File "C:\Users\FR GULIK\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\backends\utils.py", line 66, in execute return self._execute_with_wrappers(sql, params, many=False, executor=self._execute) File "C:\Users\FR GULIK\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\backends\utils.py", line 75, in _execute_with_wrappers return executor(sql, params, many, context) File "C:\Users\FR GULIK\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql, params) … -
Django REST Framework -- ALLOWED_HOSTS setting for a public open API -- What to enter?
I know this seems like a duplicate but this actually was intended to be a comment under an answer but I cannot comment with my current reputation score. I'm new when it comes to Django and REST-APIs. I am developing an open API that is publicly accessible. While researching about the CORS_ORIGIN_WHITELIST and ALLOWED_HOSTS setting in Django, I stumbled on this answer. The author suggests to set CORS_ORIGIN_ALLOW_ALL to True and says that if you do that, you also want to set a wildcard for the ALLOWED_HOSTS setting. I understand that for an open API, I want to set CORS_ORIGIN_ALLOW_ALL to True but I don't understand why I would want to set a wildcard for ALLOWED_HOSTS. From my understanding, you want to set only the hostname of the server(s) the API is running on, correct? I read the django documentation and some other sources but I feel like I don't understand this enough yet. Could you elaborate @tim-mccurrach? I unfortunately cannot comment under your answer in the original question because I don't have the 50 point reputation score yet. -
Save random integer into form of Django
I am trying to save po_id as a unique key of the "Order table". So I am generating a random number in the Order Form. But the issue is that somehow I can not save the form, even though all the fields are filled up. models.py def random_string(): return str(random.randint(10000, 99999)) class Order(models.Model): po_id = models.CharField(max_length=4, default = random_string) supplier = models.ForeignKey(Supplier, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) forms.py class OrderForm(forms.ModelForm): class Meta: model = Order fields = ['supplier', 'product', 'po_id'] widgets = { 'supplier': forms.Select(attrs={'class': 'form-control', 'id': 'supplier'}), 'product': forms.Select(attrs={'class': 'form-control', 'id': 'product'}), } views.py def create_order(request): from django import forms form = OrderForm() if request.method == 'POST': forms = OrderForm(request.POST) if forms.is_valid(): po_id = forms.cleaned_data['po_id'] supplier = forms.cleaned_data['supplier'] product = forms.cleaned_data['product'] order = Order.objects.create( po_id=po_id, supplier=supplier, product=product, ) return redirect('order-list') context = { 'form': form } return render(request, 'store/addOrder.html', context) Can help me with how I can solve the issue? -
Django Queryset GET (1 result) checking MAX value of one filed
Maybe the solution is to do it with Filter and then loop. But let's see if you guys can tell me a way to do it with GET I have this query with GET as I need to be sure I get only one result result = OtherModel.objects.get(months_from_the_avail__lte=self.obj.months_from_avail) Months_from_avail is an Integer value. Example months_from_the_avail = 22 In the other model there's 3 lines. A) months_from_the_avail = 0 B) months_from_the_avail = 7 C) months_from_the_avail = 13 So, when I query it returns all of them as all are less than equal the value 22 but I need to get the 13 as is the last range. range 1 = 0-6 range 2 = 7-12 range 3 = 13 ++ Is there any way that I haven't thought to do it? Or should I change it to filter() and then loop on the results? -
Is it possible to use template url tags from database?
For some reasons I've set a urls from database. models class Nav(models.Model): name = models.CharField(max_length=200) url = models.CharField(max_length=100) context_processors navs = Nav.objects.all() template <ul> {% for nav in navs %} <li> <a href="{{nav.url}}">{{nav.name}}</a> </li> {% endfor %} </ul> In the models if I set Nav url like this {% url 'dashboard:home' %} then when clicking url it returns path like this ..../%7B%%20url%20'dashboard:home'%20%%7D And if i set url like this dashboard:home and in template <a href="{% url '{{nav.url}}' %}"> it gives errror. Can we set urls in the navbar like this from database ? -
Auto update related objects in Django
I have two models in django - "Project" and "Task". Tasks are assigned to projects with foreign key. I'm trying to make that so, when I update Project to 'done' in Project Update View, it automatically updates all the tasks asigned to this project to also be "done". So far i tried to write custom function in model but it didn't seem to work. Here are my models: STATUS = ( (0, "ToDo"), (1, "Done"), ) class Project(models.Model): owner = models.ForeignKey('auth.User', on_delete=models.CASCADE) title = models.CharField(max_length=24, unique=True) status = models.IntegerField(choices=STATUS, default = 0) def __str__(self) -> str: return self.title class Task(models.Model): author = models.ForeignKey('auth.User', on_delete=models.CASCADE) project = models.ForeignKey('tasktrack.Project', related_name='Tasks', null=True, on_delete=models.CASCADE) title = models.CharField(max_length=24, unique=True) # author = models.ForeignKey(User, on_delete= models.CASCADE, related_name= 'tasks') updated_on = models.DateTimeField(auto_now = True) description = models.TextField(max_length=48) created_on = DateTimeField(auto_now_add=True) status = models.IntegerField(choices=STATUS, default = 0) class Meta: ordering = ['created_on'] def __str__(self) -> str: return self.title def update(self): self.updated_on = timezone.now() self.save() def is_week_old(self): return (timezone.now() - self.created_on).days > 5 ``` Project form class: class ProjectForm(forms.ModelForm): class Meta(): model = Project fields = ('title', 'status') widgets = { 'title': forms.TextInput(attrs={'class':'textinputclass'}), }``` and view class ProjectEditView(LoginRequiredMixin, generic.UpdateView): login_url = '/login/' model = Project form_class = ProjectForm template_name … -
How to create partial index in django 2.2 models
I have a model like this in Django 2.2 class Post(models.Model): class Meta: verbose_name = _('Post') verbose_name_plural = _('Posts') phone_number = models.CharField(max_length=11, verbose_name=_('Phone number'), db_index=True) token = models.CharField(unique=True, max_length=20, verbose_name=_('Token'), db_index=True) post_state = models.SmallIntegerField(choices=[ (PostState.NEW, _('New')), (PostState.PUBLISHED, _('Published')), (PostState.ARCHIVED, _('Archive')), (PostState.REMOVED_BEFORE_PUBLISH, _('Removed before publish')), (PostState.REJECTED_AFTER_PUBLISH, _('Rejected after publish')), ], default=PostState.NEW, verbose_name=_('Post state'), db_index=True) I want the index I have on phone_number and token to be partial based on post_state value, I know how to do it with SQL commands in Postgres shell but I don't know how to do it in django models so it goes into a migration file too. -
I'm unable to register my model in django rest framework
My code is working as expected but my model is not getting registered. This is my model class : create_models.py (model class) *from django.db import models class UserModel(models.Model): name = models.CharField(max_length=50, blank=False, default='') email = models.CharField(max_length=50, blank=False, default='') #phone = models.IntegerField(blank=False, default='') phone = models.CharField(max_length=10,blank=True, default='') company = models.CharField(max_length=50, blank=True, default='') def __str__(self): return self.name class Meta: ordering = ('id',)* This is my admin class: register_admin.py (admin class) *from django.contrib import admin from core.models.create_models import UserModel # Register your models here. admin.site.register(UserModel)* I ran commands : python manage.py makemigrations python manage.py migrate Still, the I'm unable to register the model. -
The extra function written for the DeleteView class does not work
I have added a function that if the post is deleted by the user, it will be deleted if there is an uploaded photo, but the function does not work. my view: class NewsDeleteView(LoginRequiredMixin, UserPassesTestMixin, DeleteView): model = News template_name = 'news/news_delete.html' success_url = reverse_lazy('news_list') def delete_header_image(self, pk): news = get_object_or_404(News, id = pk) header_image = news.header_image if header_image is not None: os.remove(str(header_image)) return HttpResponseRedirect(reverse('news_list')) else: return HttpResponseRedirect(reverse('news_list')) def test_func(self): obj = self.get_object() if self.request.user.has_perm('news.all') or self.request.user.has_perm('news.delete_news') or obj.author == self.request.user: return True urls: urlpatterns = [ path('<int:pk>/delete', NewsDeleteView.as_view(), name='news_delete'), ] models: def get_header_image_filepath(self, filepath): return f'images/news/header/{self.author.id}/{self.header_image}' class News(models.Model): title = models.CharField(max_length=255) header_image = models.ImageField(null=True, blank=True, upload_to=get_header_image_filepath) body = RichTextUploadingField() datetime = models.DateTimeField(auto_now_add=True) author = models.ForeignKey( AUTH_USER_MODEL, on_delete=models.CASCADE, ) def __str__(self): return self.title def get_absolute_url(self): return reverse("news_detail", args=[str(self.id)]) -
how to solve opencv issue working on my laptop but not after deploying on pythonanywhere
OpenCV(4.5.2) /tmp/pip-req-build-sl2aelck/opencv/modules/imgproc/src/color.cpp:182: error: (-215:Assertion failed) !_src.empty() in function 'cvtColor' Request Method: GET Request URL: http://motig.pythonanywhere.com/home/identfay/ Django Version: 3.2.4 Exception Type: error Exception Value: OpenCV(4.5.2) /tmp/pip-req-build-sl2aelck/opencv/modules/imgproc/src/color.cpp:182: error: (-215:Assertion failed) !_src.empty() in function 'cvtColor' Exception Location: /home/motig/pythonany/home/backEnd.py, line 114, in recognizeFace Python Executable: /usr/local/bin/uwsgi Python Version: 3.8.0 Python Path: ['/var/www', '.', '', '/var/www', '/home/motig/.virtualenvs/asho22/lib/python38.zip', '/home/motig/.virtualenvs/asho22/lib/python3.8', '/home/motig/.virtualenvs/asho22/lib/python3.8/lib-dynload', '/usr/lib/python3.8', '/home/motig/.virtualenvs/asho22/lib/python3.8/site-packages', '/home/motig/pythonany'] -
S3 bucket JSON CORS django
Expected params.CORSConfigurationRules to be an Array -
DJANGO ORM - Updating/adding a field using list of whens in cases
Model has a field with coordinates (Point(0,0)). Also, I have list of dictionaries where key is an 'id' and value is a Polygon object. Task is to check does coordinates intersect Polygon or not, if yes, I need to make annotation with a field where I want to put there an id from dict. I've made a solution and it works only if I have only one object in list, it's more than one, Django rewrite a value during applying another object while I need it to be added to the field. The main thing is I need to do that by using one single request because there can be many thousands constructions in database and many polygons. My Code: def get_specific_constructions_with_polygons(cls, ids, polygons): cases = [ When( coord__intersects=p, then=Value(_id) ) for polygon in polygons for _id, p in polygon.items() ] constructions = cls.objects.filter( pk__in=ids ).annotate( polygon_area=Case( *cases, output_field=IntegerField() ) ).order_by('-polygon_area') return constructions When I print polygon_area field from each object like that constructions = models.Construction.get_specific_constructions_with_polygons( ids=constructions_ids, polygons=polygons ) x = [i.polygon_area for i in constructions] print(x) the output will be [None, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, … -
django / ajax form submit gets 405 error but works?
What i want to do is adding photo in user album. I have gallery.html (template of ListView). It shows every photo in photo model. Each photo has button for adding photo to user album. click button -> shows form in modal -> select album -> submit then photo is added to album, with no refresh. It works... harf ;( photo is added to the album. it's nice. But i get 405 error page. what am i missing?? my code: form in gallery.html <form class='addphotoform' method="POST" id='addphotoform'> {% csrf_token %} select album.<br> <select class="form-select" id='album_pk' name='album_pk' aria-label="Default select example"> {% for album in user.albums.all %} <option value='{{album.pk}}'>{{album.album_name}}</option> {% endfor%} </select> <input type="hidden" name="photo_id" id="photo_id" value="{{photo.id}}"/> <button type="button submit" class="btn btn-danger">add</button> </form> ajax $('#addphotoform').on('submit', function(event){ $.ajax({ type: "POST", url: "{% url 'album:add_photo' %}", data: { csrfmiddlewaretoken: '{{ csrf_token }}', photo_id : $('#photo_id').val(), album_pk : $('#album_pk').val() }, success: function () { console.log('added'); }, error: function () { console.log('failed'); }, }); }) album/view.py @login_required def add_photo(request): if request.method == 'POST': photo_pk = request.POST.get('photo_id') album_pk = request.POST.get('album_pk') photo = get_object_or_404(Photo, pk=photo_pk) album = get_object_or_404(UserAlbum, pk=album_pk) album.album_photos.add(photo) return HttpResponse('add done') else: return HttpResponse('wrong approach') gallery/view.py class GalleryView(ListView): model = Photo template_name = 'gallery.html' context_object_name = 'photos' … -
Django Ajax: response renders in another page not same page
I'm having app that using ajax to submit model form. ISSUE: the submit works fine and edit the database. but the response renders in manage_user("users/manage" in another wod), not the same page I'm working on "users/" in urls.py: path('users/', views.manage_users, name = 'manage_users'), path('users/manage', views.manage_users, name = 'manage_users'), in views.py: @login_required(login_url="/login/") def users(request): #Defining Needed variables context = {} crud = CRUDHandler() queryset = Q() #if filters applied to crud or formset #Getting data for view crud.fields=['username','first_name','last_name','email','id'] dataset=crud.r_user() #Adding data to context context['dataset']=dataset context['dataset_title']= 'User' context['handle_url']='manage_users' return TemplateResponse(request,'table-view.html',context) @login_required(login_url="/login/") def manage_users(request): done = [] fail = [] form = None context = {} template_path = "" if 'edit'in request.POST: instance_id = request.POST.get('instance_id') user = get_object_or_404(User,pk=instance_id) form = UserInfoForm(request.POST or None,instance=user) if form.is_valid(): exsisting_user = form.save() if isinstance(exsisting_user,User): done.append("User "+exsisting_user.first_name+" updated successfully!") else: fail.append(exsisting_user) # returning errors else: fail.append("Somthing went wrong, check your input!") template_path = "components/forms/instance_edit_form.html" # reload users crud.fields=['username','first_name','last_name','email','id'] dataset=crud.r_user() # construct the context context['done'] = done context['fail'] = fail context['dataset'] = dataset context['form'] = form # load form template html_form = loader.render_to_string(template_path, context, request) # load table template html_table = loader.render_to_string( "components/tables/model-table-view.html", context, request ) return JsonResponse({'form':html_form,'table':html_table,'done':done,'fail':fail}) in handler.js: $(document).ready(function(){ /* save form */ var saveForm = function … -
How to customize Django-Jazzmin login pages
I'm using django-jazzmin package to customize the django-admin interface. However, I would like to have my own login form along with a password reset option. I've created the corresponding templates under templates/registration/ directory and added the corresponding url patterns to the url.py file: urlpatterns = [ path('admin/', admin.site.urls), url(r'^.*password_reset/$', auth_views.PasswordResetView.as_view(subject_template_name='registration/html_password_reset_subject.txt', html_email_template_name='registration/html_password_reset_email.html'), name='password_reset'), url(r'^.*password_reset/done/$', auth_views.PasswordResetDoneView.as_view(), name='password_reset_done'), url(r'^reset/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$', auth_views.PasswordResetConfirmView.as_view(), name='password_reset_confirm'), url(r'^reset/done/$', auth_views.PasswordResetCompleteView.as_view(), name='password_reset_complete'), url(r'^.*logout/$', logout,{'next_page': 'myapp:login'}), url(r'^.*accounts/login/$', LoginView.as_view(template_name='registration/login.html'), name='login'), url(r'^.*accounts/profile/', TemplateView.as_view(template_name='registration/profile.html'), name='profile'), url(r'^login/$', LoginView.as_view(template_name='registration/login.html'), name='login'), url(r'^logout/$', logout, name='logout'), ] However, I still get the Jazzmin login form. Any ideas? -
NoReverseMatch at / | Error during template rendering
Reverse for 'customer' with arguments '('',)' not found. 1 pattern(s) tried: ['customer/(?P[^/]+)/$'] This is the error, Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 3.2.4 Exception Type: NoReverseMatch Exception Value: Reverse for 'customer' with arguments '('',)' not found. 1 pattern(s) tried: ['customer/(?P[^/]+)/$'] Exception Location: C:\Users\user\AppData\Local\Programs\Python\Python39\lib\site-packages\django\urls\resolvers.py, line 694, in _reverse_with_prefix Python Executable: C:\Users\user\AppData\Local\Programs\Python\Python39\python.exe Python Version: 3.9.5 Python Path: ['C:\Users\user\Downloads\Git Project\firstwebsite', 'C:\Users\user\AppData\Local\Programs\Python\Python39\python39.zip', 'C:\Users\user\AppData\Local\Programs\Python\Python39\DLLs', 'C:\Users\user\AppData\Local\Programs\Python\Python39\lib', 'C:\Users\user\AppData\Local\Programs\Python\Python39', 'C:\Users\user\AppData\Local\Programs\Python\Python39\lib\site-packages'] Server time: Wed, 09 Jun 2021 06:20:15 +0000 This is code urls.py from django.urls import path from . import views urlpatterns = [ path('', views.dashboard, name="dashboard"), path('customer/<str:pk>/', views.customer, name="customer"), path('product/', views.product, name="product"), ] this is models.py from django.db import models # Create your models here. class Customer(models.Model): name = models.CharField(max_length=200, null=True) phone = models.FloatField(max_length=200, null=True) email = models.CharField(max_length=200, null=True) date_created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.name class Tag(models.Model): name = models.CharField(max_length=200, null=True) def __str__(self): return self.name class Product(models.Model): CATEGORY = ( ('Indoor', 'Indoor'), ('Outdoor', 'Outdoor') ) name = models.CharField(max_length=200, null=True) price = models.FloatField(null=True) tag = models.ManyToManyField(Tag) category = models.CharField(max_length=200, null=True, choices=CATEGORY) description = models.CharField(max_length=200, null=True) date_created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.name class Order(models.Model): #we create a dropbox like this STATUS = ( ('Pending', 'Pending'), ('Out Of Deliery', 'Out Of Delivery'), ('Deliverder', 'Delivered'), ) customer = … -
Running Celery and Flower on different servers
I'm currently running a django app with rabbitmq, celery and flower on the same machine (Ubuntu 20 + Apache server) and that's working fine. I know that I can move rabbitmq to another server and I already installed it there, but can I also run celery and flower on separate machines such that they can still communicate? What I'd ideally want is all of the above running on their own servers but I've read that at least celery needs the code of the entire django project to run tasks. Considering flower in turn needs celery I assume that means it would be the same situation. How would this affect the system? From what I can see the amount of system resources flower uses is pretty much negligible. -
how to pass start and end date from html page to views.py (django)
i am using daterangepicker in my django project , need to know how to pass the start date and end date to views.py (DJANGO) for processing further and get report. <script> var start = moment().subtract(29, 'days'); var end = moment(); $(function () { $('input[name="daterange"]').daterangepicker({ opens: 'left', showDropdowns: true, "drops": "auto", startDate: start, endDate: end, ranges: { 'Today': [moment(), moment()], 'Yesterday': [moment().subtract(1, 'days'), moment().subtract(1, 'days')], 'Last 7 Days': [moment().subtract(6, 'days'), moment()], 'Last 30 Days': [moment().subtract(29, 'days'), moment()], 'This Month': [moment().startOf('month'), moment().endOf('month')], 'Last Month': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')] } }, function (start, end, label) { console.log("A new date selection was made: " + start.format('YYYY-MM-DD') + ' to ' + end.format('YYYY-MM-DD')); }); }); </script> <div> <input type="text" name="daterange" /> {% csrf_token %} </div> -
Django full text on multiple related field search returning duplicate data
Consider I have a below model. class MailBoardStatus(models.Model): status = models.CharField(max_length=10, primary_key=True) class Board(models.Model): board_id = models.SlugField(db_index=True, max_length=10, unique=True) creator = models.ForeignKey(User, on_delete=models.CASCADE, related_name="board_creator", db_index=True) status = models.ForeignKey(Status, related_name="board_status", on_delete=models.CASCADE) class BoardData(models.Model): board = models.ForeignKey(Board, related_name="board_data", on_delete=models.CASCADE) ip = models.GenericIPAddressField(db_index=True) host = noa_mail_hostname = models.CharField(db_index=True, max_length=100) address = models.CharField(db_index=True, max_length=200, blank=True) Class BoardMailData(models.Model): board = models.OneToOneField(Board, related_name="board_mail_data", on_delete=models.CASCADE) subject = models.CharField(max_length=100, null=True, blank=True) For testing, I created 5 board objects with the same user and assigned the related tables to each board. Let's consider in the created test data, one of the boards has a subject (related field) "Test Subject". Now I want to do a full-text search on multiple related fields from the parent model i.e Board and I have the below query for that filter_status_qs = Board.objects.filter(status="some status") filtered_data.annotate( search=SearchVector( "creator__user_name", "board_mail_data__subject", "board_id", "creator__user_id", "board_data_host", "board_data__address" "board_data__ip" )).filter(search=SearchQuery("test subject", search_type='phrase')).distinct() So Even though I have given distinct, the search value should return a single record from the DB, but it is returning single duplicate records. What I mean here is that it is returning the same "test subject" multiple times. I'm really not sure what I'm doing wrong here. Please someone help me. -
job matching of candidate to job description using tfidf, cosine similarity returning low score
I am trying to match profiles of candidates to internships by the following approach: First I have formed a candidate's profile and a profile for each internship by concatenating relevant fields I have tokenised the respective profiles into words, removed stop words and punctuations. I then applied Porter Stemmer I have applied tfidfVectorizer on the two documents. Like candidate to each job Then, have performed cosine similarity on it. However, the match percentage is really low. Like the max is 16% How do I solve this issue? Here is my code snippet: (Project in Django) porter = PorterStemmer() stop_words = set(stopwords.words('english')) punctuations = '''!()-[]{};:'"\,<>./?@#$%^&*_~''' #TOKENISATION student_token_words = word_tokenize(student_profile) stem_student_profile = [] #Remove stopwords for word in student_token_words: if word in stop_words: student_token_words.remove(word) for word in student_token_words: if word in punctuations: pass else: stem_student_profile.append(porter.stem(word)) student_profile_stemmed = " ".join(stem_student_profile) #INTERNSHIP internship_profiles = [] internships = Internship.objects.all() for internship in internships: internship_profile = "" internship_title = internship.internship_title industry_type = internship.industry_type int_desc = internship.internship_desc inte_desc = strip_tags(int_desc) #strip html tages internship_desc = html.unescape(inte_desc) #remove html encodings such as &nbsp;.... internship_profile += internship_title internship_profile += " " internship_profile += industry_type internship_profile += " " internship_profile += internship_desc internship_profile += " " try: int_skills = InternshipSkill.objects.filter(internship=internship) … -
Django Admin add support for HEIC for ImageField
please has someone experience with adding support of new image formats to the Django Admin module? I want to use this one called pyheif-pillow-opener pyheif-pillow-opener for HEIC support. It should be registered, but I am not sure where exactly. I tried to install that module and then in Django Admin upload an image to ImageField, but still, I am getting a message: Upload a valid image. The file you uploaded was either not an image or a corrupted image. -
ModuleNotFoundError: No module named 'my_app'. Even with __init__.py
This is my project structure. ├─demo_data ├─findb │ └─__pycache__ ├─management └─tw_equity ├─migrations │ └─__pycache__ └─__pycache__ Now I try to insert demo data to my models. So I create commands.pyfor the process. # ./management/commands.py from datetime import datetime from tw_equity.models import ( TradingDate, Basic, Price, Holder, ) with open('demo_data/trading_date.csv') as f: for row in f: data = datetime.strptime(row, "%Y-%m-%d").date() trading_date = TradingDate( trading_date=data ) trading_date.save() print('Insert Successfully.') But the error keeps showing up. (Findb) C:\Users\ycyta\python-django-Findb>management\commands.py Traceback (most recent call last): File "C:\Users\ycyta\python-django-Findb\management\commands.py", line 2, in <module> from tw_equity.models import ( ModuleNotFoundError: No module named 'tw_equity' Already tried python manage.py shell, it is all good. (Findb) C:\Users\ycyta\python-django-Findb>python manage.py shell Python 3.7.3 (v3.7.3:ef4ec6ed12, Mar 25 2019, 22:22:05) [MSC v.1916 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) >>> from tw_equity.models import TradingDate >>> TradingDate <class 'tw_equity.models.TradingDate'> Mostly similar questions before were concerned about __ini__.py, but I already have. Thanks for helping. -
Application error: django deployment on heroku
NO web process running ie application error while deploying on heroku