Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Error:Not Found: /media/media/photos/e.jpg in django
I've deployed one project In web server. our project everything fine but i unable print image on profile page .in our local system working fine but in server error getting Not Found: /media/media/photos/e.jpg in django. models.py photo = models.ImageField(upload_to='media/photos/', null=True, blank=True) settings.py MIDIA_ROOT=os.path.join(BASE_DIR,'media') MEDIA_URL='/media/' urls.py if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) profile.html {% if user.matr.photo %} <img src="{{ user.matr.photo.url }}" width="330"> {% endif %} -
Django admin login error - Exception Value: no such table: auth_user
Steps: -Pycharm: Django template. python manage.py createsuperuser # succesful python manage.py makemigrations python manage.py migrate python manage.py runserver server is working, I am going to http://127.0.0.1:8000/admin/login putting credentials(doesn't matter correct or not), clicking Log in getting error: OperationalError at /admin/login/ no such table: auth_user User is created correctly because when I am trying to create another one with same credential db returns warning that superuser already exist. Also database is working, I can get into it through python manage.py shell here's some more logs if it's gonna help: Environment: Request Method: POST Request URL: http://127.0.0.1:8000/admin/login/?next=/admin/ Django Version: 2.2.5 Python Version: 3.7.4 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles'] 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'] -
Dynamic log filename based on logged in username
I would like to maintain independent user logs in django based on logged in username. Any assistance on configuring django logging callback filter will be appreciated I followed instructions from this link but could not get it to work Dynamic filepath & filename for FileHandler in logger config file in python def write_dynamic_log(record): def write_dynamic_log(record): now = datetime.datetime.now().strftime("%Y%m%d%H%M%S") dynamic_log_name = '/var/logs/django/test_%s.log' %now log_file = open(dynamic_log_name, "a") log_file.write(record.msg) log_file.close(); return True 'write_error_logs': { '()': 'django.utils.log.CallbackFilter', 'callback': write_dynamic_log, }, -
Django Rest Framework: Get singular object using the root API
I am trying to set up an API endpoint that returns a singular object. Right now I have: class ShoppingCartViewSet(viewsets.GenericViewSet, mixins.ListModelMixin): """ API endpoint that allows users to be viewed or edited. """ serializer_class = ShoppingCartSerializer authentication_classes = (TokenAuthentication,) permission_classes = (IsAuthenticated,) def get_paginated_response(self, data): return Response(data) def get_queryset(self): return ShoppingCart.objects.filter(user=self.request.user) Which uses the ListModelMixin and a filter to return one item, becasue each user has 1 shopping cart. The issue is the filter function returns a queryset, but I only want a single item. I attempted to use the RetrieveModelMixin but that doesn't run on the endpoint that I want. Retrieve runs on .../api/shopping-cart/id but I want to retrieve on .../api/shopping-cart because the filtering is done via the person who is logged in. Any solutions? -
django orm use inner jsoin use two table unique columns
I need to select from DB this data: Event e inner join FireMonitor f on e.event_id = f.event_id; Models in django: class Event(BaseModel): id = models.AutoField(primary_key=True) event_id = models.CharField(max_length=128, unique=True) receiver = models.CharField(db_column='Freceiver', db_index=True, max_length=512) class FireMonitor(BaseModel): id = models.AutoField(primary_key=True) event_id = models.CharField(max_length=128, unique=True) -
Update HTML text based on backend respond
I need to update html tag text, based on respond from backend. I am using Django server to run the app. In the backend, I am running a timer, measuring the amount of time, the process had taken. I need to get this amount of time to frontend, and display it. class Timer(): def __init__(self): self._start_time = datetime.datetime.now().replace(microsecond=0) print(self._start_time) def elapsed_time(self): return (datetime.datetime.now().replace(microsecond=0) - self._start_time).seconds urls.py: urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'^$', views.home, name='home'), url(r'^$', views.output, name='output') ] views.py: urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'^$', views.home, name='home'), url(r'^$', views.output, name='output') ] And my html looks this so far: <td class="value" id="elapsed-time">00:00</td> <script> var urlMappings = { url_elapsed_time : "{% url 'output' %}" } $.ajax({ type: "POST", url: urlMappings.url_elapsed_time }).done(function(data){ console.log("Done"); }).fail(function(data){ console.log("Fail"); }); </script> So far, I am only getting 403 error message. Any help? -
butttons of copy excel pdf do not shown in views?
hello my friends i'm new in datatables and django i try to make tables with buttons of save export excel csv and pdf and field for search and paginations filters but tables is show and other things is hidden with no errors i download all datatables packages i put it in static folder and i will show you my code thank you for help {% extends 'base.html' %} {% load static %} {% block content%} <caption>listes des Immobilisations</caption> <table id ="table_id" class = "table table-bordered"> <head class = "alert-success"> <tr> <td>Code immob</td> <td>Designation</td> <td>Quantite</td> <td>Date mes</td> <td>Compte immob</td> <td>Duree de vie</td> <td>Num aut</td> <td>Origine</td> <td>fournisseur</td> <td>N° facture</td> <td>Date Facture</td> <td>Valeur HT</td> <td>Monaie</td> <td>Taux cvt</td> <td>Taux contre valeur</td> <td>Frais d'approche</td> <td>Cout d'acquisition</td> <td>Reference commande</td> <td>Date commande</td> <td>Journee</td> <td>Compte analytique</td> <td>Local</td> <td>Mode_amort</td> <td>Code_r</td> <td>Val_amort</td> <td>Status</td> <td>Code_bar</td> <td>Service</td> <td>Cni</td> </tr> </thead> <tbody> {% for immob in all_immobs %} <tr> <td>{{ immob.immo_code}}</td> <td>{{ immob.immo_desig}}</td> <td>{{ immob.immo_qte}}</td> <td>{{ immob.immo_datemes}}</td> <td>{{ immob.immo_cptimmob}}</td> <td>{{ immob.immo_dureevie}}</td> <td>{{ immob.immo_numaut}}</td> <td>{{ immob.immo_origine}}</td> <td>{{ immob.immo_origine}}</td> <td>{{ immob.immo_fournisseur}}</td> <td>{{ immob.immo_nufact}}</td> <td>{{ immob.immo_datefact}}</td> <td>{{ immob.immo_valht}}</td> <td>{{ immob.immo_monaie}}</td> <td>{{ immob.immo_tauxcvt}}</td> <td>{{ immob.immo_tauxctrval}}</td> <td>{{ immob.immo_frais}}</td> <td>{{ immob.immo_coutacq}}</td> <td>{{ immob.immo_refcmde}}</td> <td>{{ immob.immo_datecmde}}</td> <td>{{ immob.immo_journee}}</td> <td>{{ immob.immo_cptanal}}</td> <td>{{ immob.immo_local}}</td> <td>{{ immob.immo_mode_amort}}</td> <td>{{ immob.immo_code_r}}</td> <td>{{ immob.immo_val_amort}}</td> <td>{{ immob.immo_status}}</td> … -
Celery: Getting unexpected run_command() takes 1 positional argument but 318 were given error
I am attempting to run an async task and am getting an unexpected error: run_command() takes 1 positional argument but 318 were given. I have a list of commands that I want to run from a celery task. run_command.chunks(iter(commands), 10).group().apply_async() @task def run_command(commands): for command in commands: print("RUNNING, ", command) print("Pid: ", os.getpid()) os.system(command) As shown above, I am attempting to break down my command into batches that will be executed in parallel. Thanks for the help -
how to display foreign key related info in template
I have two model called organization and staff.Staff model have onetoone relation with user and Foreignkey relation to the organization.The problem what i got is to filter the staffs by their related organization.I have tried liked this but didn't worked out. models.py class Staff(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='user') name = models.CharField(max_length=255, blank=True, null=True) organization = models.ForeignKey(Organization, on_delete=models.SET_NULL, blank=True, null=True, related_name='organization') .....other fields..... views.py def view_staff_users(request): staff_users = User.objects.filter(is_staff=True) organizations = Organization.objects.all() staffs_by_org = Staff.objects.select_related('organization') # tried this also: # staffs_by_org = [] # print('staffff',staffs_by_org) # for organization in organizations: # staffs = Staff.objects.filter(organization=organization) # staffs_by_org.extend(staffs) # print('staaa',staffs_by_org) template {% for user in staffs_by_org %} # tried this also: {% for u in user.organization_set.all %} {{user.user.name}} {{user.username}} {{user.email}} {{user.user.organization}} {% endfor %} -
Django :- Very Important Question about creating Queryset and add data on it
Models: class MyTeam(models.Model): user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) match = models.ForeignKey(Match, on_delete=models.SET_NULL, null=True, related_name='match_set') mega_league = models.ForeignKey(MegaLeague, on_delete=models.SET_NULL, null=True, blank=True, related_name='mega_league_set') captain_first_team = models.ForeignKey(FirstTeamPlayer, on_delete=models.SET_NULL, null=True, blank=True, related_name="captain_second_team_set") captain_second_team = models.ForeignKey(SecondTeamPlayer, on_delete=models.SET_NULL, null=True, blank=True, related_name="captain_second_team_set") team_player_first_team = models.ManyToManyField(FirstTeamPlayer, blank=True, related_name="team_player_first_team_set") team_player_second_team = models.ManyToManyField(SecondTeamPlayer, blank=True, related_name="team_player_second_team_set") First of all I need to add these captain_first_team & captain_second_team in one field (like add FirstTeamPlayer and SecondTeamPlayer in one field) . How? Views: def add_to_my_team_from_team_create(request, match_id): match = get_object_or_404(Match, pk=match_id) my_team = MyTeam.objects.create(match=match, user=request.user) return redirect('team_create', match.pk, my_team.pk) def team_create(request, match_id, team_id): match = get_object_or_404(Match, pk=match_id) my_team = get_object_or_404(MyTeam, pk=team_id) first_team_player = match.first_team.first_team_player.all() second_team_player = match.second_team.second_team_player.all() context = { 'match': match, 'my_team': my_team, 'first_team_player': first_team_player, 'second_team_player': second_team_player, } return render(request, 'main/team_create.html', context=context) def add_first_team_player(request, match_id, team_id, player_id): match = get_object_or_404(Match, pk=match_id) my_team = get_object_or_404(MyTeam.objects.filter(user=request.user, match=match.pk), pk=team_id) first_team_player = get_object_or_404(match.first_team.first_team_player, pk=player_id) my_team.team_player_first_team.add(first_team_player) return redirect('team_create', match.pk, my_team.pk) def remove_first_team_player(request, match_id, team_id, player_id): match = get_object_or_404(Match, pk=match_id) my_team = get_object_or_404(MyTeam.objects.filter(user=request.user, match=match.pk), pk=team_id) first_team_player = get_object_or_404(match.first_team.first_team_player, pk=player_id) my_team.team_player_first_team.remove(first_team_player) return redirect('team_create', match.pk, my_team.pk) In views, 1st I create a MyTeam using add_to_my_team_from_team_create function and then add data on the fields using add_first_team_player and also I can remove data from fields using remove_first_team_player. But I need the opposite one. … -
I want to store 8 digit random number in ID column of "auth_user" table in Django framework
Please help me, I don't want to create another column for that -
Using CheckboxSelectMultiple inside a form that uses input from DB related to User using ForeignKey. [See explaination]
I have a model called Level1 which is related to User model using ForeignKey class Level1(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) ans = models.CharField(max_length=1024) IT takes input from user and saves it in DB. I can get all the inputs that are given by the specific user by using user=request.user level1_answers=user.level1_set.all() (IF there is another method, please do share) Now what I want to do is to use these answers from level1 (level1_answers) and use them as an input for the Level2. Where Level 2 is a model same as Level1 with ForeignKey as User and ans except the fact that Instead of taking new answers as input, It uses the answers from level1 and presents the user with Checkboxes from those. class Level2(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) ans = models.CharField(max_length=1024) #I want ans to be presented as CheckboxSelectMultiple using Level1 answers. If user has answered 1,2,3,4,5,6,7 for Level1, I want to show Checkboxes to select from these and save this in DB in table Level2. -
Django application integration with Open edx LMS
We have a web application, Django https://sourceforge.net/p/schoolquiz/proctoringAPI/ci/master/tree/ I want to integrate that with the LMS of open edx https://sourceforge.net/p/schoolquiz/openedx/ci/master/tree/ I want to know how it can be done. -
How to use Global python environment instead of virtual on Azure App Service
I have a Django web app deployed on Azure App Service. I have integrated a bash script in it which is required for running some python notebooks for DataBricks. Problem is that when bash script is installing python packages in the virtual environment as expected but DataBricks notebook which it is calling is finding those packages in the global environment. I have tried deactivating the virtual inside bash script but that doesn't work. Is there any way to instruct azure app service to use global python environment instead of creating a virtual environment. Thanks -
Django, Can not migrate when change the default database engine to djongo
I'm new in django and facing a problem that I can not migrate changes in when I change the default sqlite3 engine to "djongo". I'm using ubuntu server, and I have done the following steps: $ pip3 install djongo # setup djongo DATABASES = { 'default': { 'ENGINE': 'djongo', 'NAME': 'zoo', } } I do not know what is the problem but when I migrate the changes I get the following error message: File "/usr/lib/python3.5/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "/home/karam/.local/lib/python3.5/site-packages/djongo/base.py", line 12, in <module> from .cursor import Cursor File "/home/karam/.local/lib/python3.5/site-packages/djongo/cursor.py", line 2, in <module> from .sql2mongo.query import Result File "/home/karam/.local/lib/python3.5/site-packages/djongo/sql2mongo/__init__.py", line 34 self.alias2op: typing.Dict[str, SQLToken] = alias2op SyntaxError: invalid syntax Any ideas what do I missed ? -
Django Tables 2 Filter field, but use the display name?
I've got this model: DRAFT = 'draft' IN_PROGRESS = 'in_progress' FINISHED = 'finished' STATUS_CHOICES = ( (DRAFT, 'Entwurf'), (IN_PROGRESS, 'In Arbeit'), (FINISHED, 'Erledigt'), ) class Invoice(TimeStampModel): status = models.CharField('Status', choices=STATUS_CHOICES, max_length=50) and this filter I've build with the django tables 2 plugin: class InvoiceFilter(django_filters.FilterSet): class Meta: model = Invoice fields = { 'name': ['icontains'], 'status': ['icontains'], } My filter gets rendered without a problem on my page and I can use it. The problem right now is though if I try to search for a status using the german word, like for example Entwurf the filter always returns me no item. BUT if I filter for draft I get all the items which have this status. So my question would be: how can I tell my filter to look for the display name of my status field? Or even better: would it be possible to just make a select out of the status field instead of a normal search? Thanks for any answers! -
How to enable setup python app on cpanel?
I want to start my new Django project on my server. so i install cpanel. but in software part, there is nothing related to python. Should i Do something in WHM? or install something in my server? thanks for helping me. -
How to apply filter on Many to many field without using for loop
I Model is like class Company(models.Model): name = models.CharField(max_length=400, blank=True, null=True) class Intership(models.Model): company = models.ForeignKey(Company) location = models.CharField(max_length=400, blank=True, null=True) class Student(models.Model): name = models.CharField(max_length=400, blank=True, null=True) intership = models.ManyToManyField(Intership,null= True, blank=True) I am looking forward to get all the student who done internship in a company with name "xyz". i have the code company_name = "xyz" stds for student in students: interships = student.intership.all() for intership in interships: if intership.company.name == company_name: stds.append(student) Is it possible to get it all this on a single query?? -
type object 'User' has no attribute 'objects django
i am trying to get list of user from api with jwt token so i generated the token and with email and pass and trying to make get request with token but i get this erro: File "/home/tboss/Desktop/environment/liveimages/backend/venv/lib/python3.7/site-packages/rest_framework_simplejwt/authentication.py", line 111, in get_user user = User.objects.get(**{api_settings.USER_ID_FIELD: user_id}) rest_framework.request.WrappedAttributeError: type object 'User' has no attribute 'objects' and i have created custom user views.py: from users.models import User from rest_framework import viewsets from rest_framework.decorators import api_view, permission_classes, authentication_classes from rest_framework.permissions import AllowAny, IsAuthenticated from rest_framework.status import ( HTTP_400_BAD_REQUEST, HTTP_404_NOT_FOUND, HTTP_200_OK) from . import serializers from rest_framework.response import Response from rest_framework.authentication import TokenAuthentication, SessionAuthentication class UserViewSet(viewsets.ModelViewSet): queryset = User.object.all() serializer_class = serializers.UserSerializers i'm using User.object its working fine but this error coming from jwt -
django admin like behaviour for app users
We have merchants with campaigns in our project. Currently, we - as superuser - manage all merchants' campaigns. However, some merchants require access to campaign management so that they can control the process and set new campaigns themselves. There is a possibility to create the second admin site and set permissions so that only merchants can log in. However, what we need is - to filter only the campaigns owned by logged in merchant and also, when creating a new one the merchant_id should be prefilled and readonly. Is it possible to do it using the second django admin site or should I create a special frontend interface for this purpose? Is it possible to set permissions per user-object pair (in django admin)? -
Is there a good way to mirror external (not model) DB table to django.contrib.auth.models.User?
I have a software that is written in Java that I can not modify. Because of it I'm making a wrapper in Django that will use said software's REST API. I'm new, but I learn as I go. I require exactly the same user ids and emails - they have to be mirrored from Java program's user table to django.contrib.auth.models.User. I thought about doing it by creating a database-side event that would periodically (every hour?) fill my django.contrib.auth.models.User with users that Java software created. I'm pretty sure this is not very efficient, since: It needlessly strains the database that is under a large stress as it is It's too slow, I would much prefer mirror to happen as soon as Java app creates an user Letting Django do it would probably be much cooler + would be more obvious for my replacement in case I leave my company That event will have to constantly move hundreds of users - this can't be good Does anyone have a better idea? Maybe I'm not looking at it correctly, or even overthinking it? -
Validation: clean() and clean_<fieldname> not working as expected
I have to validate a field if it's unique. I am not using unique=True in models. I am using clean() and clean_() in forms but are raising different errors. forms.py Case 1: clean() name = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Enter Package Name', 'class': 'form-control'})) def clean(self): name = self.cleaned_data.get('name') if Package.objects.filter(name=name): raise ValidationError(_("Package with this package name already exist.")) return name case 2: clean_name() name = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Enter Package Name', 'class': 'form-control'})) def clean_name(self): name = self.cleaned_data.get('name') if Package.objects.filter(name=name): raise ValidationError(_("Package with this package name already exist.")) return name views.py package.name = form.clean_name() or package.name = form.clean() in html template: <p style="color:red;">{{ form.non_field_errors.as_text }}</p> Problem: in case 1, validation is correct if I send duplicate name but if name is unique, this gives this error: 'str' object has no attribute 'get' In case 2: if name is valid, then everything ok. data is saving normally but if it's duplicate data, it's not showing error message. But validation is working as it's not submitting the form. -
Creating video thumbnails with imagekit and opencv
I have a model named "Post", which is going to refer to images and videos. I added ImageSpecField for thumbnail storage and created a function, that pulls the desired frame from uploaded video. Is there any way to use this function while generating thumbnail? Because right now ImageSpecField can only use FileField as an input. I have tried creating a new class inheriting from ImageSpecField, but I quickly realized that this is not going to work because this class was instanced only on server start, thus putting this function in constructor of it would not work. import cv2 as cv from django.conf import settings from django.db import models from imagekit.processors import ResizeToFit from imagekit.models import ImageSpecField def video_to_image(source, frame): vid_cap = cv.VideoCapture(settings.MEDIA_ROOT + source.__str__()) vid_cap.set(cv.CAP_PROP_POS_FRAMES, frame) success, image = vid_cap.read() vid_cap.release() return image class Post(models.Model): IMAGE = 'I' VIDEO = 'V' FILE_TYPES = [ (IMAGE, 'Image'), (VIDEO, 'Video') ] file_type = models.CharField(max_length=1, choices=FILE_TYPES) file = models.FileField(upload_to='post_images') thumbnail_frame = models.IntegerField(default=0) image_thumbnail = ImageSpecField(source='file', processors=[ResizeToFit(width=200, height=200)], format='JPEG', options={'quality': 60}) I want imagekit to generate thumbnail from video, and be able to get it via ImageSpecField. -
setting get_absolute_url when using a router
I'm working on a Comment app and I would like my Commentserializer to display the exact URL of each instance of Comment. I know that I have to use the get_absolute_url of the Comment model. But i cannot connect my viewnames from my router to the get_absolute_url. Here is my Model : class Comment(models.Model): content = models.TextField(max_length=150) author = models.ForeignKey( User, on_delete = models.CASCADE ) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField(blank=True) content_object = GenericForeignKey('content_type', 'object_id') parent = models.ForeignKey( "self", on_delete = models.CASCADE, blank=True, null=True ) datestamp = models.DateTimeField(auto_now_add=True) objects = CommentManager() def __str__(self): return str(self.content[:30]) def save(self): self.object_id = self.parent.id super(Comment, self).save() def children(self): return Comment.objects.filter(parent=self) def get_absolute_url(self): return reverse("comments-details", args=[str(self.id)]) @property def is_parent(self): if self.parent is None: return False return True and here is my router : router = router = routers.SimpleRouter() router.register('api/comments', CommentViewSet) urlpatterns = router.urls As you can see, I'm trying to use "comment-details" as a viewname. The end Goal is to display a JSON like that : { url : 'blabla/comments/{pk}/details } -
How to get parameter from user front-end in Django generic.ListView?
I am building an app where users will be able to search nearby locations. For this, I am using this function in my views.py: latitude = 23.734413 longitude = 90.4082535 user_location = Point(longitude, latitude, srid=4326) class NearbyServices(generic.ListView): model = Service context_object_name = 'services' queryset = Service.objects.annotate(distance=Distance('location', user_location)).order_by('distance')[0:6] template_name = 'services/nearby.html' I am currently using a hard-coded user location, but I want to let the users find nearby locations by first getting their location using the HTML5 GeoLocation API. Any help with how I can get their location from the front-end into the listview function would be really helpful!