Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to filter data from two django class
I have two Django class,I want to filter VCDUnavailAudit by site_key in Django Get method, how could I do enter code here class VCDUnavailAudit(models.Model): user_key = models.IntegerField() user_name = models.CharField(max_length=40) class User(models.Model): user_key = models.AutoField(primary_key=True) site_key = models.IntegerField() @api_view(['GET']) def get_unavail_audit_records_by_site(request, site_key: int): availability_audit_records = VCDUnavailAudit.objects.filter serializer = VCDUnavailAuditSerializer(availability_audit_records, many=True) return Response(serializer.data, status=status.HTTP_200_OK) -
Postgres backup database
I'm working on a django project and i'm using postgres for database. I want to backup the database and i tried to use dbbackup library. While in development env works fine in production i got an error of no password. The command i'm running is the same in both environments and also the configuration, the only difference is the database credentials Backing Up Database: database CommandConnectorError: Error running: pg_dump --host=localhost --username=databaseuser --no-password --clean database pg_dump: error: connection to database "database" failed: FATAL: password authentication failed for user "databaseuser" FATAL: password authentication failed for user "databaseuser" Any suggestions? -
How to Force Current User to a Field in Django Rest Framework
Consider I have models, a serializer and a viewset as below: # models.py class Foo(models.Model): owner = models.ForeignKey(User, models.CASCADE, related_name="bars") # serializers.py class FooSerializer(serializers.ModelSerializer): owner = serializers.PrimaryKeyRelatedField( default=serializers.CurrentUserDefault(), queryset=User.objects.all(), ) class Meta: fields = ["pk", "owner"] # viewsets.py # registered to /api/foos/ class FooViewSet(viewsets.ModelViewSet): serializer_class = FooSerializer permission_classes = [permissions.IsAuthenticated] queryset = Foo.objects.all() So, when I send a POST request to /api/foos/ with an empty body, it creates a Foo instance with its owner field set to the current logged-in user, which is fine. However, I also want to totally ignore what the currently authenticated user sends as a value to owner. For example, if I do a POST request to /api/foos/ with body user=5 (another user, basically), CurrentUserDefault sets the Foo.owner to that user, which is not the behavior I want to have. I always want to have the current authenticated user as the value of the field owner of a new Foo instance, or, in other words, I want FooSerializer.owner field to be set as currently authenticated user as a value and ignore what is sent on POST request as a value of owner. How do I do that? Thanks in advance. Environment django ^2.2 djangorestframework ^3.12.4 -
Django-python3-ldap problem to connect admin/login - SyntaxError at /admin/login/
I've just tried to connect to my Active Directory LDAP server. I'm sure, that everything in configuration (like IP and DN) is OK. But If I want to go to admin page, it shows me error (it's below). I don't know how to do it. AUTHENTICATION_BACKENDS = ( 'django_python3_ldap.auth.LDAPBackend', 'django.contrib.auth.backends.ModelBackend', ) LDAP_AUTH_URL = "ldap://srv.ext.cz" LDAP_AUTH_USE_TLS = None LDAP_AUTH_SEARCH_BASE = "OU=Users,OU=Temp,OU=SRC,DC=example,DC=cz" LDAP_AUTH_OBJECT_CLASS = "user" LDAP_AUTH_USER_FIELDS = { "username": "sAMAccountName", "first_name": "givenName", "last_name": "sn", "email": "mail", } LDAP_AUTH_USER_LOOKUP_FIELDS = ("username",) LDAP_AUTH_CLEAN_USER_DATA = "django_python3_ldap.utils.clean_user_data" LDAP_AUTH_SYNC_USER_RELATIONS = "django_python3_ldap.utils.sync_user_relations" LDAP_AUTH_FORMAT_SEARCH_FILTERS = "django_python3_ldap.utils.format_search_filters" LDAP_AUTH_FORMAT_USERNAME = "django_python3_ldap.utils.format_username_active_directory_principal" LDAP_AUTH_ACTIVE_DIRECTORY_DOMAIN = "xxx.cz" LDAP_AUTH_CONNECTION_USERNAME = None LDAP_AUTH_CONNECTION_PASSWORD = None LOGGING = { "version": 1, "disable_existing_loggers": False, "handlers": { "console": { "class": "logging.StreamHandler", }, }, "loggers": { "django_python3_ldap": { "handlers": ["console"], "level": "INFO", }, }, } Error: > File > "C:\Users\fc\.virtualenvs\projekt-O8yDgQSj\lib\site-packages\django\core\handlers\exception.py", > line 47, in inner > response = get_response(request) File "C:\Users\fc\.virtualenvs\projekt-O8yDgQSj\lib\site-packages\django\core\handlers\base.py", > line 181, in _get_response > response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\fc\.virtualenvs\projekt-O8yDgQSj\lib\site-packages\django\views\decorators\cache.py", > line 44, in _wrapped_view_func > response = view_func(request, *args, **kwargs) File "C:\Users\fc\.virtualenvs\projekt-O8yDgQSj\lib\site-packages\django\contrib\admin\sites.py", > line 398, in login > **self.each_context(request), File "C:\Users\fc\.virtualenvs\projekt-O8yDgQSj\lib\site-packages\django\contrib\admin\sites.py", > line 316, in each_context > 'available_apps': self.get_app_list(request), File "C:\Users\fc\.virtualenvs\projekt-O8yDgQSj\lib\site-packages\django\contrib\admin\sites.py", > line 505, in get_app_list > app_dict = self._build_app_dict(request) File "C:\Users\fc\.virtualenvs\projekt-O8yDgQSj\lib\site-packages\django\contrib\admin\sites.py", > line 450, … -
Access Django context data in get_initial
I have an expensive call in my view's get_context_data to calculate a field for the template. I would like to use this result in the view's get_initial_data to set the initial value of my_field but I cannot see how to access the context_data from within get_initial_data or how to pass it as a parameter. def get_context_data( self, *args, **kwargs ): context = super().get_context_data( **kwargs ) context['expensive_result'] = expensive_function() return context def get_initial( self ): initial = super().get_initial( **kwargs ) # Initialise my_field with expensive result calculated in get_context_data initial['my_field'] = context['expensive_result'] # How to do this? return initial -
Failed - network error when downloading a file
I have configured the apache webserver for my Django application for https redirection and its working fine. When i was testing my application I found out that it sometimes shows Failed -Network error when trying to download a xlsx file .Downloading a tarfile does not give any error.. Tried in different browser but got the same result.. Not sure what is wrong Please Help. Thanks -
Posting Dynamic table Form values using Jquery and fetching that post in django view
I know this is not the conventional method but I wanted to try this out and make it successful. Here is a html file that I am rendering using a django view. {% extends 'base.html' %} {% block table_name %}Invoice{% endblock %} {% block table_view %} <form method="POST" action="/submit" id="myForm"> {% csrf_token %} <table border="1" class="center table-responsive table table-striped" width="100%" cellspacing="0" style="padding-left:418px" id="table"> <thead> <tr> <th colspan="6">INVOICE</th> </tr> </thead> <tr> <th COLSPAN="3">INVOICED TO</th> <td colspan="4" class="center"> <input list="show" type="text" class="center" style="width:100%" name="client_name"> <datalist id="show"> {% for client in clients %} <option value="{{ client.first_name }}"></option> {% endfor %} </datalist> <br><br><textarea type="text" name="client_address" placeholder="Address" style="width:100%" rows="3"></textarea></td> </tr> <tr> <th COLSPAN="3">INVOICED FROM</th> <td colspan="4" class="center"><input type="text" name="company_name" style="width:100%" placeholder="Company Name"><br> <br><textarea type="text" name="company_address" placeholder="Address" rows="3" style="width:100%"></textarea></td> </tr> <tr> <th COLSPAN="3">VESSEL NAME</th> <td colspan="4" class="center"><input name="vessel_name" style="width:70%" type="text" placeholder="Vessel Name"></td> </tr> <tr> <th COLSPAN="3">PO NUMBER</th> <td colspan="4" class="center"><input type="text" name="po" style="width:70%" placeholder="PO number"></td> </tr> <tr> <th COLSPAN="3">INVOICE NUMBER</th> <td><input name="invoice_number" type="text" placeholder="#/2021" disabled></td> <th>DATE</th> <td colspan="" class="center"><input type="date" name="date"></td> </tr> <tr CLASS="CENTER"> <th>S. NO.</th> <th COLSPAN="2">PARTICULARS</th> <th COLSPAN="1">GST</th> <th colspan="2">TOTAL AMOUNT</th> </tr> <tr CLASS="CENTER"> <td class="center">1</td> <td COLSPAN="2" class='center'><input type="text" name="product1" placeholder="Name of product"></td> <td><input type="number" name="gst1" placeholder="gst"></td> <td COLSPAN="2"><input name="cost1" type="number" placeholder="cost"></td> </tr> … -
Filter model by datetime in django
I need to filter model with (datetime.now() < end) My model class Quiz(models.Model) : title = models.CharField(max_length=50) start = models.DateTimeFieldField(default="2021-10-10") end = models.DateTimeFieldField(default="2021-10-11") My view class GetQuizView(generics.ListAPIView) : def get_queryset(self): now = datetime.now() return Quiz.objects.filter(start = now) serializer_class = QuizListSerializer But I can only filter with equal time, I can't use > or < -
compare objects in views.py of 2 different models objects in Django
I am trying to compare 2 objects (skills of a job posting such as web development, marketing, etc to the same skills of a logged-in user), if matched will display that job posting. The goal is to display multiple job postings that match the user. Currently, jobmatch.html does not display any jobs. Thank you for taking the time!! views.py from apps.job.models import Job from apps.userprofile.models import User_profile def match_jobs(request): match_jobs = {} for job in Job.objects.all(): if job.product_management == User_profile.product_management: match_jobs['product management'] = job elif job.web_development == User_profile.web_development: match_jobs['web development'] = job elif job.user_experience == User_profile.user_experience: match_jobs['user experience'] = job elif job.marketing == User_profile.marketing: match_jobs['marketing'] = job elif job.finance == User_profile.finance: match_jobs['finance'] = job return render(request, 'jobmatch.html', match_jobs) Job.models.py class Job(models.Model): title = models.CharField(max_length=255) location = models.CharField(max_length=255, blank=True, null=True) description = models.TextField() requirements = models.TextField(blank=True, null=True) product_management = models.BooleanField(default=False) web_development = models.BooleanField(default=False) user_experience = models.BooleanField(default=False) marketing = models.BooleanField(default=False) finance = models.BooleanField(default=False) User.models.py class User_profile(models.Model): user = models.OneToOneField(User, related_name='userprofile', on_delete=models.CASCADE) is_employer = models.BooleanField(default=False) resume = models.ImageField(default='default.jpg', upload_to='resume') full_name = models.CharField(max_length=255, default='Enter full name') relevant_background = models.TextField() product_management = models.BooleanField(default=False) web_development = models.BooleanField(default=False) user_experience = models.BooleanField(default=False) marketing = models.BooleanField(default=False) finance = models.BooleanField(default=False) jobmatch.html {% for job in match_jobs %} <div class="colum is-4"> … -
Difficult to run VS code
PS E:\learning\project\django\restaurant> python manage.py runserver Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). You have 18 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions. Run 'python manage.py migrate' to apply them. October 22, 2021 - 09:21:08 Django version 3.2.8, using settings 'restaurant.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. -
Django REST Framework: How do I save query set if I use the same Prepetch object multiple times in prefetch_related?
We need to use the queryset saved by annotate in two models in prefetch_related as follows, but if we use it as follows, the prefetch queryset will be called unnecessarily as many times as specified in prefetch_related If you use Is this the correct behavior? #views.py prefetch = Prefetch( "user", queryset=User.objects.annotate( is_verified=Max( Cast( "emailaddress__verified", output_field=IntegerField(), ) ) ), ) queryset = queryset.prefetch_related( Prefetch( "reply_set", queryset=Reply.objects.prefetch_related(prefetch) ), prefetch, ) #serializers.py class UserDetailSerializer(serializers.ModelSerializer): is_verified = serializers.SerializerMethodField() class Meta: model = User fields = ( "is_verified", ) def get_is_verified(self, user): return bool(user.is_verified) class CommentSerializer(serializers.ModelSerializer): user = UserDetailSerializer(read_only=True) replies = serializers.SerializerMethodField() class Meta: model = Comment fields = ( "replies", ) def get_replies(self, obj): queryset = obj.reply_set if queryset.exists(): replies = ReplySerializer(queryset, context=self.context, many=True).data return replies else: return None class ReplySerializer(serializers.ModelSerializer): user = UserDetailSerializer(read_only=True) class Meta: model = Reply fields = ("user") -
How to pass data to serializers in django
I want to pass user_id from view to serializer I have model Answer class Answer(models.Model) : text = models.CharField(max_length=500) question_id = models.CharField(max_length=25) user_id = models.CharField(max_length=25, default=1) This is my Serializer class CreateAnswer(generics.CreateAPIView) : def get_serializer_context(self): context = super().get_serializer_context() context["id"] = self.request.user.id return context serializer_class = AnswerQuestionSerializer queryset = Answer.objects.all() What I need to write in my view to take user_id and create model with this user_id ? -
ModuleNotFoundError: No module named 'dj_rest_authcore' => dj-rest-auth
I have followed the documentation(https://dj-rest-auth.readthedocs.io/en/latest/installation.html). Installed the package using pip install dj-rest-auth Added dj_rest_auth app to INSTALLED_APPS in your django settings.py: Added path('dj-rest-auth/', include('dj_rest_auth.urls')) in urls.py When I am doing python manage.py migrate. I am getting the below issue. return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 973, in _find_and_load_unlocked ModuleNotFoundError: No module named 'dj_rest_authcore' What I am doing wrong here? -
Can't change user password for Django user model using ModelViewSet
I was using Django user model using the ModelViewSet. When I am making a request to update the password for the current user that is logged in. Although I get a 200 OK response but my password never changes to the new one that I changed. I also tried making the request from my admin user and when I made the PUT request with the password, it got changed to something else and I was logged out from the django admin panel. Here is my views.py class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer permission_classes = [IsAuthenticated, IsOwnerOfObject] authentication_classes = (TokenAuthentication,) serializers.py class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['id', 'username', 'password'] extra_kwargs = { 'password' : { 'write_only':True, 'required': True } } def create(self, validated_data): user = User.objects.create_user(**validated_data) Token.objects.create(user=user) # create token for the user return user urls.py router = DefaultRouter() router.register('articles', ArticleViewSet, basename='articles') router.register('users', UserViewSet, basename = 'users') urlpatterns = [ path('api/', include(router.urls)), ] permissions.py class IsOwnerOfObject(permissions.BasePermission): def has_object_permission(self, request, view, obj): return obj == request.user Here is how I am making the request, with Authorisation token in the Headers field Response : -
Django 3: Unable to generate dynamic object view
I have successfully created the expected structure for my model and in the error variables I can see that the DB object was returned but I am not able to resolve the page. I am getting error " TypeError at /ticket-edit/2 - init() got an unexpected keyword argument 'instance'" - am I referencing the object incorrectly? Is there an approach allowing appTicketID=appTicketID (I use aTicketID instead but the DB field is appTicketID)? In the error the local var shows that the expected ticket was retrieved: Variable: Value aTicketID: '2' context: {} obj: <Ticket: 2 2021-10-06 Ticket Title Ticket Desc> request <WSGIRequest: GET '/ticket-edit/2'> Urls.py (I use URL instead of path to generate the ID link) urlpatterns = [ url(r'^ticket-edit/(?P<aTicketID>\d+)', views.ticket_edit, name='ticket-edit') ] Models.py class Ticket(models.Model): #---Base Meta----------------------------------------- appTicketID = models.AutoField(primary_key=True) date_submitted = models.DateTimeField( max_length=20, auto_now_add=True) issue_title = models.CharField(max_length=90) issue_description = models.CharField(max_length=1000) def __str__(self): return (f"{self.appTicketID} " f"{self.date_submitted} " f"{self.issue_title} " f"{self.issue_description} " def get_absolute_url(self): return reverse_lazy('ticket-edit', kwargs={'aTicketID': self.appTicketID} Views.py @login_required def ticket_edit(request, aTicketID): context = {} obj=Ticket.objects.get(appTicketID=aTicketID) updateform=TicketForm(instance=obj) if aTicketID == None: aTicketID = 1 aticket = Ticket.objects.filter(appTicketID=aTicketID) print('\n-----------------------------------------------------------------') print('TicketFiltered: ', aticket) print('-----------------------------------------------------------------\n') context = { "has_error": False, "updateform": updateform, "aticket": aticket } return render(request,'appname/ticket-edit.html', context) -
Django custom model - field username gets removed
Hi I am writing a custom user model on django and i have username field along with email field when i set USERNAME_FIELD = 'username' i get this error raise FieldDoesNotExist("%s has no field named '%s'" % (self.object_name, field_name)) django.core.exceptions.FieldDoesNotExist: User has no field named 'username' when i checked the migrations for the model i find that the username field does not exist among the model fields when i change the field name to something other than username it works here is my model: from django.db import models from django.contrib.auth.models import BaseUserManager, AbstractBaseUser from django.db.models.enums import Choices from django.utils.translation import gettext_lazy as _ class User(AbstractBaseUser): class Role(models.TextChoices): User = 'USER', _('User') Admin = 'ADMIN', _('Admin') Stuff = 'STUFF', _('Stuff') username = models.CharField(max_length=64, unique=True) email = models.EmailField(max_length=256, unique= True, verbose_name="Email") full_name = models.CharField(max_length=256, verbose_name= "Full Name", null=True, blank=True) active = models.BooleanField(default=True, verbose_name= "Active") role = models.CharField(max_length=10, choices = Role.choices, default = Role.User, verbose_name= "Role") created_at = models.DateTimeField(auto_now_add=True) modified_at = models.DateTimeField(auto_now=True) USERNAME_FIELD = 'username' REQUIRED_FIELD = ['username', 'email','password'] def __str__(self): return self.username @property def role(self): return self.role @property def admin(self): return (self.role == self.Role.Admin) @property def stuff(self): return (self.role == self.Role.Stuff) @property def username(self): return self.username -
Django warnings "Not found XXXX" when re-rendering html pages
I collect html from search engine result pages (baidu, sogou, Google, Bing) and use Django to re-render them. It is successful when rendering pages from Baidu or Sogou, but for pages from Google or Bing, there are lots of warnings about "not found XXX". For example, in rendering Bing pages, some warnings: [21/Oct/2021 22:15:44] "GET /sa/simg/Roboto_Regular.woff2 HTTP/1.1" 404 2484 Not Found: /s/ac/25308934/MsnJVData/HoverTranslationV2.css [21/Oct/2021 22:15:44] Not Found: /th "GET /th?id=OVP.amkWCd5lEnKAiv3c6hEoiQEsCo&w=197&h=110&c=7&rs=1&qlt=90&o=6&pid=1.7 HTTP/1.1" 404 2508 Not Found: /th [21/Oct/2021 22:15:44] "GET /rp/4q26YP9oX8_7FiOTRx6BpR60bSg.png HTTP/1.1" 404 2502 Not Found: /fd/ls/lsp.aspx I have more own scripts for these rendered pages such as adding some popup windows. I also tested my script on static pages and it worked. However, when rendering the page, my script didn't work at all, so I wonder if these warnings hold my own scripts. I am looking for a way to ignore or skip these warnings. -
Django how to display model objects in HTML
Hi,I'm new to Django, I have a question here, it would be great if anyone can help. I have a table in Django, there are team and task in the table, I want to display all the tasks under a team in HTML. Now I can only display all task and all team together, I can't display them in a well-classified way. Is it the tamplate tags in the assign.html that I need to make some changes? Please give me some hints, thanks in advance. models.py ''' class Todo(models.Model): status_option = ( ('to_do', 'to_do'), ('in_progress', 'in_progress'), ('done', 'done'), ) status = models.CharField(max_length=20, choices=status_option, default='to_do') # todo_list's content team = models.ForeignKey('Team', on_delete=models.CASCADE) project = models.ForeignKey(Project, on_delete=models.CASCADE) name = models.CharField(max_length=20) create_date = models.DateTimeField(auto_now_add=True) start_date = models.DateTimeField(default=datetime.datetime.now) due_date = models.DateTimeField(default=datetime.datetime.now) project_code = models.CharField(max_length=20) details = models.TextField() def __str__(self): return self.status # return self.team['team'].queryset def update_status(self): if self.status == 'to_do': self.status = 'in_progress' elif self.status == 'in_progress': self.status = 'done' self.save() class Team(models.Model): name = models.CharField(max_length=20) employeeID = models.CharField(max_length=20) email = models.CharField(max_length=50) position = models.CharField(max_length=50) password = models.CharField(max_length=20) projects = models.ForeignKey(Project, on_delete=models.CASCADE) def __str__(self): return self.name ''' views.py ''' def assign(request): team = Team.objects.all() todos = Todo.objects.all().order_by('team') # progresses = team.todo_set.filter(status='in_progress') # dones = … -
js onbeforeunload I want to submit the form after page refresh or close, but failed
I want to submit my form data to database when user refresh or close the window. I tried this, but it didn't work. The p demo1 will change to No when refresh or close. But will change to Yes after refresh or close. But the sumbit part is not trigger. I tried this two method, both of them didn't work document.getElementById("all_questions").submit(); $('#save').click(); It can work if I click the submit button, use Django as framework <script> window.onbeforeunload = function(e){ document.getElementById("demo1").innerHTML="No"; document.getElementById("all_questions").submit(); $('#save').click(); } </script> <form method = "POST" name = "answer_question" id="all_questions"> <p id="demo1">Yes</p> data <div class="save-item1"><button class="save-button" type="submit" id="save" name="Complete">Save</button></div> </form> -
sock failed (111: Connection refused) while connecting to upstream using nginx + uwsgi for django
I'm making a django server. The server uses nginx and uwsgi. The following error occurred in the server performance test. 2021/10/07 02:23:03 [error] 31#31: *9168 connect() to unix:/run/uwsgi/xxxx.sock failed (11: Resource temporarily unavailable) while connecting to upstream, client: xx.xxx.xxx.xx, server: xxxx.xxx.com, request: "GET /xxxx HTTP/1.1", upstream: "uwsgi://unix:/run/uwsgi/xxxx.sock:", host: "xxxx.xxx.com" I did some research on this problem and found that I could just adjust the uwsgi socket queue size. (Resource temporarily unavailable using uwsgi + nginx) However, if I add the listen option to the uwsgi configuration, I get the following error: 2021/10/19 06:34:16 [error] 31#31: *69 connect() to unix:/run/uwsgi/xxxx.sock failed (111: Connection refused) while connecting to upstream, client: xx.xxx.xxx.xxx, server: xxxx.xxx.com, request: "GET /health-check HTTP/1.1", upstream: "uwsgi://unix:/run/uwsgi/xxxx.sock:", host: "xx.xxx.xxx.xxx" Tried many ways to solve this problem but it didn't work. I need help. Here is my nginx, uwsgi, etc configurations. uwsgi.ini [uwsgi] project = xxxx project_root = /xxxx wsgi_path = xxxx_server_site chdir = %(project_root) module = %(wsgi_path).wsgi:application master = true processses = 4 listen = 4096 # Problem occurred after adding this option. If removed, it works normally. socket = /run/uwsgi/%(project).sock chmod-socket = 666 vacuum = true logto = /var/log/uwsgi/%(project).log /etc/nginx/conf.d/default.conf server { listen 80; server_name xxxx.xxx.com; location / { … -
Django access file by path in FileSystemStorage
I'm trying to use virus totals api to scan a uploaded file to django website, i'm using the Djangos FileSystemStorage to store the uploaded files. I have set the Media path to /media/ in settings MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') and tested adding a url for the uploaded files and it was accessible at /media/{{file name}} eg through www.domain.com/media/{{file name}} urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Although when i attempt to access this file within script to attach to a request i receive the file not found at this directory error. to get the path i am currently using the fs.url(name) command which returns /media/{{file name}} I understand the FileStorageSystems /media/ path does not actually exist within the folder suggested eg app/media is there a alternative command to retrieve the true path? or do i need to use a different storage system for this purpose? thanks Current Script uploaded_file = request.FILES['file'] # getting file from form fs = FileSystemStorage() # initlize FileSystemStorage name = fs.save(uploaded_file.name, uploaded_file) # Save Uploaded file to storage params = dict(apikey=API_KEY) # add api key for request with open(fs.url(name), 'rb') as file: # context manager opening saved file files = dict(file=(fs.url(name), file)) # create dict of … -
Display image from external link in Django Admin Change Form
I am trying to display an image from online source (e.g. facebook) which is not a field in the model in the User Change Form. I can successfully display it in the user list page or in a separate Model page but I want to add this image to the existing user editing page below username and password fields. -
ReactJS: Javascript fetch works on desktop browsers but returns a 403 error which says (authentication credentials not provided) on IOS safari
I'm working on a project using Create-react-app with a backend API written in Django(Python) where I used fetch to make my API calls. API calls run fine on android browsers and on desktop browsers but on IOS Browsers(both safari and chrome) the API returns the 403 error with response (authentication credentials not provided). this issue is a bit more tasking for me as it is quite difficult for me to perform remote debugging for IOS using my windows PC. I was only able to view the error due to JavaScript console using chrome://inspect on IOS and consoling the API response to the Iphone's console I would like some help on this issue. -
I have a huge but not complex sql query that must convert to django orm query
I have to convert the following sql query but i don't know how to convert it to equal query in django orm I would be very happy if you can :))) select dialog_messages.*, sender.first_name as sender_first_name, sender.last_name as sender_last_name, sender.cell_number as sender_cell_number, sender.avatar_full_path as sender_avatar_full_path, receiver.first_name as receiver_first_name, receiver.first_name as receiver_first_name, receiver.last_name as receiver_last_name, receiver.cell_number as receiver_cell_number, receiver.avatar_full_path as receiver_avatar_full_path from dialog_messages`` inner join user sender on ``sender``.``user_id`` = dialog_messages``.``sender_id`` inner join user receiver on receiver``.``user_id`` = ``dialog_messages``.``receiver_id`` where `dialog_id`` = ? order by ``dialog_messages``.``id`` desc -
Deploy django on apache server is not working
I'm trying to setup an apache server running django but I have have some troubles to make it run it well. At this moment it seems to be correctly configures but i can not access now. this is how my apache log file looks apache: [Thu Oct 21 22:29:36.608487 2021] [suexec:notice] [pid 16400] AH01232: suEXEC mechanism enabled (wrapper: /usr/lib/apache2/suexec) [Thu Oct 21 22:29:36.946497 2021] [:notice] [pid 16414] mod_ruid2/0.9.8 enabled [Thu Oct 21 22:29:36.991981 2021] [mpm_prefork:notice] [pid 16414] AH00163: Apache/2.4.29 (Ubuntu) mod_fcgid/2.3.9 OpenSSL/1.1.1 configured -- resuming normal operations [Thu Oct 21 22:29:36.992010 2021] [core:notice] [pid 16414] AH00094: Command line: '/usr/sbin/apache2' [Thu Oct 21 22:29:49.610060 2021] [mpm_prefork:notice] [pid 16414] AH00169: caught SIGTERM, shutting down [Thu Oct 21 22:29:49.759118 2021] [suexec:notice] [pid 17390] AH01232: suEXEC mechanism enabled (wrapper: /usr/lib/apache2/suexec) [Thu Oct 21 22:29:49.868100 2021] [:notice] [pid 17393] mod_ruid2/0.9.8 enabled [Thu Oct 21 22:29:49.886537 2021] [mpm_prefork:notice] [pid 17393] AH00163: Apache/2.4.29 (Ubuntu) mod_fcgid/2.3.9 OpenSSL/1.1.1 configured -- resuming normal operations [Thu Oct 21 22:29:49.886565 2021] [core:notice] [pid 17393] AH00094: Command line: '/usr/sbin/apache2' [Thu Oct 21 22:29:51.173110 2021] [mpm_prefork:notice] [pid 17393] AH00171: Graceful restart requested, doing restart [Thu Oct 21 22:29:51.355561 2021] [:notice] [pid 17393] mod_ruid2/0.9.8 enabled [Thu Oct 21 22:29:51.355846 2021] [mpm_prefork:notice] [pid 17393] AH00163: Apache/2.4.29 …