Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django CKEDITOR, Image Upload path different with ImageField upload path
I'm using django-ckeditor to load images.I can't merger my image upload path in model with django-ckeditor image upload path. I have already created a upload image path in models: image = models.ImageField(upload_to="news/%Y/%m") In order to merger it with django-ckeditor,I set this in settings.py MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') CKEDITOR_UPLOAD_PATH = 'news/%Y/%m' But although the image upload through django-ckeditor will also be in news directory,however the path will be different from the image that upload through models.ImageField.They both are in news directory but in two different sub directories. Is there any way that can merger the two path into one? -
Django Aggregate from 3 Models with 2 ManyToMany relations
I have the following Django structure: User has a ManyToMany relashionship to Genre and Movie has a ManyToMany relashionship to Genre as well. What I want to achieve is make a query that retrieves only the users that have genres available along with their movies (and movies to have distinct values). So the result would be like this: [{user_id: 1, movies_ids: [1, 2, 3]}, {user_id: 7, movies_ids: [2, 3]}, {user_id: 13, movies_ids: [5, 6, 7]}] I've searched a lot but haven't found a solution. My idea would be to use an ArrayAgg. Something like this: User.objects.filter(genres__isnull=False).annotate( movies_ids=ArrayAgg( Movie.objects.filter(genres__in=???), distinct=True ) ).values('id', 'movies_ids') But I don't know if this is optimal or possible. The number of users and movies are very large and the query would be very slow. -
Can't PUT from Android to DJANGO REST
I have a DJANGO REST server on my personal network that is set up to get and receive JSON strings to update "statuses" for a project I'm working on. I can GET the information down into my Android application just fine but when I try to PUT information up to the server, I get the error: Bad Request: /api/users/1/ [28/Oct/2019 21:23:23] "PUT /api/users/1/ HTTP/1.1" 400 107 I think it's the app because I can successfully do a PUT request via Windows Powershell, but it doesn't work on the Android app. Here is the code using the OKHTTP class: MediaType JSON = MediaType.parse("application/json; charset=utf-8"); String content = String.format("{'status':%s}", selectedStatus); RequestBody body = RequestBody.create(JSON, content); OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder() .url(IPAddress + "api/users/" + currentUserID + "/") .addHeader("Content-Type", "application/json") .put(body) //PUT .build(); client.newCall(request).execute(); I have tried using the standard HttpURLConnection class, which is what I did for the GET method, but I don't even get a response from the server when I do that. I've tried about a dozen ways to PUT something to the server, but nothing has worked. Any help achieving this goal would be appreciated. Thanks. -
Django Media Files - Failed to load resource: the server responded with a status of 403 (Forbidden)
I dont know how this can be possible I have a model with a user and image and 2 identical for-loops in my template, like: {% for object in object_list %} {{ object.user }} {{ object.image.url }} {% endfor %} This returns a list of users and images as expected. But in the second for-loop, the image of the 4th object in list throws this 403 Forbidden Error. No matter what I do, if I try to replace the file with one that was working before (3rd or 6th in list), the 4th object's image file wont show up. Thank you for any help -
Django REST Framework: Show only latest of nested object, return as un-nested JSON
What I'm trying to do in Django REST Framework: Return only latest nested object in list for an object and return it as JSON, with the sub-object un-nested. My models: class BaseObject(models.Model): name = models.TextField() object_type = models.ForeignKey(ObjectType) class ObjectStatus(models.Model): baseobject_id = models.ForeignKey('objects.BaseObject', related_name='status') object_status = models.IntegerField() object_status_timestamp = models.DateTimeField() My serializers: class ObjectStatusSimplifiedSerializer(serializers.ModelSerializer): #helper serializer to simplify status objects class Meta: model = ObjectStatus fields = ['object_status', 'object_status_timestamp'] class ObjectStatusListSerializer(serializers.ModelSerializer): #request for last status of several objects status = ObjectStatusSimplifiedSerializer(many=True) class Meta: model = BaseObject fields = ['id', 'name', 'object_type', 'status'] My current view: class ObjectStatusListView(generics.ListCreateAPIView): serializer_class = ObjectStatusListSerializer def get_queryset(self): queryset = BaseObject.objects.all() id = self.request.query_params.getlist('id') if id: queryset = queryset.filter(id__in=id) return queryset Current URL: url(r'^objectstatus/status/list$', views.ObjectStatusListView.as_view()), So now, when going to, for example, [...]/objectstatus/status/list?id=9, the result I get looks like this: [ { "id": 9, "name": "r5", "object_type": "router", "status": [ { "object_status": 1, "object_status_timestamp": "2019-10-24T09:40:15.605391Z" }, { "object_status": 2, "object_status_timestamp": "2019-10-24T09:40:28.133296Z" }, { "object_status": 3, "object_status_timestamp": "2019-10-24T09:40:40.829486Z" }, { "object_status": 1, "object_status_timestamp": "2019-10-24T09:40:53.333332Z" } ] } ] What I want is to display only the object status with the most recent timestamp. Also, I can't figure out how to flatten the JSON object, like this: [ … -
Unable to get supervisord celery worker process running on elastic beanstalk django app
I'm trying to get celery beat running on django within an elastic beanstalk environment. I've been following the deployment advice here: How to run a celery worker with Django app scalable by AWS Elastic Beanstalk? After deployment the supervisord process fails to work. This is what's show in the logs: ------------------------------------- /opt/python/log/supervisord.log ------------------------------------- 2019-10-28 19:58:35,321 CRIT Supervisor running as root (no user in config file) 2019-10-28 19:58:35,333 INFO RPC interface 'supervisor' initialized 2019-10-28 19:58:35,333 CRIT Server 'unix_http_server' running without any HTTP authentication checking 2019-10-28 19:58:35,334 INFO supervisord started with pid 3034 2019-10-28 19:58:36,338 INFO spawned: 'httpd' with pid 3118 2019-10-28 19:58:37,805 INFO success: httpd entered RUNNING state, process has stayed up for > than 1 seconds (startsecs) 2019-10-28 19:59:37,279 INFO spawned: 'celeryd-beat' with pid 3543 2019-10-28 19:59:37,289 INFO spawned: 'celeryd-worker' with pid 3544 2019-10-28 19:59:38,023 INFO stopped: celeryd-beat (terminated by SIGTERM) 2019-10-28 19:59:38,325 INFO spawned: 'celeryd-beat' with pid 3552 2019-10-28 19:59:38,383 INFO exited: celeryd-worker (exit status 1; not expected) 2019-10-28 19:59:38,932 INFO exited: celeryd-beat (exit status 1; not expected) I don't understand what these logs are telling me and haven't been able to shed any light on it through my own research. This is the shell script used to create … -
Converting Django project from Python 2 to Python 3: django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet
I am converting a Django website from Python 2 to Python 3. To do this, I ran 2to3 on the whole project. Now, upon running the server (which works fine in Python 2). Now, there appears to be an error django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. that seems to originate with an issue loading the django_comments app. It is not clear to me whether this is related to a templates/models issue or something else. Python3 was installed in the virtual environment for this project. (env) user:project user$ python3 manage.py check Traceback (most recent call last): File "manage.py", line 11, in <module> execute_from_command_line(sys.argv) File ".../src/project/env/lib/python3.7/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File ".../src/project/env/lib/python3.7/site-packages/django/core/management/__init__.py", line 357, in execute django.setup() File ".../src/project/env/lib/python3.7/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File ".../src/project/env/lib/python3.7/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File ".../src/project/env/lib/python3.7/site-packages/django/apps/config.py", line 90, in create module = import_module(entry) File ".../src/project/env/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked File … -
how to fix a populate models from csv? Primary key unhashable
I'm trying to populate some models from csv files. but when I try to save it I get "TypeError: Model instances without primary key value are unhashable". I already try with get_or_create() but I'm getting the same issue. Models class Clients(models.Model): client_name = models.CharField(max_length=30) def __init__(self, *args, **kwargs): super().__init__() class Products(models.Model): client = models.ForeignKey(Clients, on_delete=models.CASCADE) product_name = models.CharField(max_length=100) address_incl = models.BooleanField() def __init__(self, *args, **kwargs): super().__init__() def log_to_db(self): try: self.save() return 0 except DatabaseError as E: transaction.rollback() print("Add Job Model not saved to DB...transaction rolled back") print("Exception Reason" + E) return 1 Populate script if mode == MODE_CLEAR: return with open("./clientAvailable.csv") as csvfile: readCSV = csv.reader(csvfile, delimiter=',') for row in readCSV: client = Clients() # client.id = row[0] client.client_name = row[1] client.log_to_db() with open("./productsAvailable.csv") as csvfile: readCSV = csv.reader(csvfile, delimiter=',') for row in readCSV: product = Products() print(Clients.objects.get(client_name=row[1])[0]) # product.id = row[0] product.client = Clients.objects.get(client_name=row[1])[0] product.product_name = row[2] product.address_incl = row[3] product.log_to_db() -
How to link a Django model's property in HTML audio source tags?
I've managed to figure out this much thanks to the Django documentation and Stack Overflow of similar problems, but I can't seem to use song.audio as src in my html's <source> tags. The Goal: Display a list of songs with a playable audio file. This is only uploaded from the admin/ page. My Problem: When I inspect element, the <source>'s src prop appears to successfully point towards the audio file, but it does not load it as an actual playable 'thing' in the browser. Chrome inspect of the output of the following code: My Stuff: Folder Structure: song-viewer/ | media/ | | song1.mp3 | | song1_w784FH21.mp3 | | song2.mp3 | | song2_r8JJfq0.mp3 | | song-viewer/ | | __init__.py | | settings.py | | urls.py | | views.py | | songs/ | | migrations/ | | templates/ | | | songs/ | | | | song_list.html | | __init__.pyt | | admin.py | | apps.py | | forms.py | | models.py | | urls.py | | views.py | | static/ | | styles.css | | templates/ | | base_layout.html | | manage.py | README.md | requirements.txt song-viewer/settings.py: STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR,'static'), ] STATIC_ROOT = '' """ The above … -
Digital Ocen Internal Server Error on django project
I have a django project which i launched on digital ocean. This project uses a costume 404 page. The site works well except that when ever i type in a page that does not exit instead of getting a 404 page, i just get 'internal server error'. Locally, the 404 page works well. -
Colon removed from mail link button?
I send out and automated link like this: <a href="{{ protocol }}://{{ domain }}/offer/{{ offer.code }}/" target="_blank"> See Offer </a> But when I click on the link (rendered as button), I get this link: https://https//domain.com/offer/INW6/ The : is simply omitted. I tried replacing {{ protocol }}: with https:// but the same happens. Someone knows why? -
Specific user PKI to access admin login (Django)
I have a Django app with standard admin and users. I was recently told this wasn't enough to meet security standards at our site. In production, access to the site is already restricted by PKI. I was told I need to tie the admin account to a PKI, I'm assuming my own PKI. I'm assuming what they want is for anyone accessing the /admin page and trying to log in with the Admin account to provide PKI again, and if the PKI doesn't belong to me, the site maintainer, for login to fail. Maybe I'm a bit confused or ignorant, but is it even possible to do this? I have already been investigating django-pki. -
Example.com in django password reset
I have set up my django project to enable password reset but when the password reset mail is sent, i get the line https://example.com/accounts/reset/Mg/... . Exampple.com is not in any way related to my site. I have tried to remove it such that it reads my site url but to no avail -
Django: ERR_CONNECTION_REFUSED
I'm actually learning to use the Django framework with PostgreSQL with Docker and docker-compose. Regularly, when I make a mistake (for example a syntax error in the views.py file), I cannot reach my Django app anymore trough my web browser. Firefox tells me: Unable to connect Firefox can't establish a connection to the server at localhost:8000 Chrome tells me: This site can’t be reached localhost refused to connect. ERR_CONNECTION_REFUSED I had this several times and I always managed to find the error in my code, to correct it and then everything went well again. Currently, my code is working fine. But if I encounter this again (and this happens very often), I would like to be able to find the error quickly by myself. So here is my question: How can I see which file at which line contains the error ? I would like to have a correct error message telling me what went wrong instead of that annoying ERR_CONNECTION_REFUSED browser page over and over. I hope I explained my issue well because I struggled to describe it to Google. Thanks a lot in advance. :) FYI: Ubuntu 18.04.3 LTS Bionic (window manager i3wm) Docker 19.03.4 docker-compose 1.17.1 python … -
Django REST Framework serializer - turn id field into title while keeping the POST method
I am creating a cart with a list of products. I am trying to turn my product ids into titles while still being able to use my POST/ PUT methods on the products to be able to add/ remove the products. Previously my products in the cart was displayed as IDs, this was my serializer: class CartSerializer(serializers.ModelSerializer): url = serializers.HyperlinkedIdentityField( view_name='cart-api:cart-detail', read_only=True, lookup_field='id', ) class Meta: model = Cart fields = [ "id", "url", "products", "sub_total", "shipping", "total", ] After making some changes, I was able to turn the product ids into titles and several other fields related to each product. Here is my serializer code after the changes: But my products disappeared from my put method and I am no longer able to add/ remove products. (snippet 2) How can we keep the the POST/ PUT methods on my product while displaying them as the way I want in snippet 2? Thanks so much in advance! class MyPaintingSerializer(serializers.ModelSerializer): painting_url = serializers.HyperlinkedIdentityField( view_name='paintings-api:detail', read_only=True, lookup_field='slug' ) class Meta: model = Painting fields = [ 'id', 'title', 'painting_url', 'price', ] class CartSerializer(serializers.ModelSerializer): url = serializers.HyperlinkedIdentityField( view_name='cart-api:cart-detail', read_only=True, lookup_field='id', ) products = MyPaintingSerializer(many=True, read_only=True) class Meta: model = Cart fields = [ … -
Django silk deadlock (PostgreSQL)
I am receiving the following error on production server. How can I debug or fix this. I tried searching for answers but nothing makes sense. django: 2.2.3 django-silk 3.0.0 postgressql 9.5.14 django.db.utils.OperationalError: deadlock detected DETAIL: Process 11444 waits for ShareLock on transaction 28487795; blocked by process 11443. Process 11443 waits for ShareLock on transaction 28487803; blocked by process 11444. HINT: See server log for query details. CONTEXT: while deleting tuple (169,20) in relation "silk_response" -
how to access a field from a another in many to many relation?
I have two models "User" and "Role". Role model is like this: class Role(models.Model): ADMIN = 1 INFORMATIC = 2 REFEREE = 3 SPONSER = 4 STAFF = 5 PLAYER = 6 CUSTOMER =7 VISITOR = 8 ROLE_CHOICES = ( (1, 'admin'), (2, 'informatic'), (3, 'referee'), (4, 'sponser'), (5, 'staff'), (6, 'player'), (7, 'customer'), (8, 'visitor'), ) id = models.PositiveSmallIntegerField(choices=ROLE_CHOICES, primary_key=True , default=VISITOR) and here is my User model: class User(AbstractBaseUser,PermissionsMixin): username = models.CharField(max_length=150, unique=True, blank=True , null=True,) password = models.CharField(max_length=100, null=True , blank=True) roles = models.ManyToManyField(Role) now I have created some Role objects and some Users and assigned some Roles to some Users. now I want to know how can I determine which user has which roles? from request I have the user. I want to know if a User has a role, for example, sponsor, and grants him some permissions. how can i check this ? -
Using a variable in Django yesno template tag
This could rather be straightforward. However, allow me to ask. In the Django yesno inbuilt template tag, the syntax is given as {{ value|yesno:"yeah,no,maybe" }}. However, I want to out a variable value if it evaluates to true, something like: {{ request.user.profile.mobile_number|yesno:$variable1, 'string' }}. I have tried this {{ request.user.profile.mobile_number|yesno:"{{ request.user.profile.mobile_number }},No Contact" }} but I keep on getting an error: Could not parse the remainder: ':"{{ request.user.profile.mobile_number' from 'request.user.profile.mobile_number|yesno:"{{ request.user.profile.mobile_number' -
Django export multiple urls from same app and include on different prefix
I am trying to expose multiple routes from the same app to the top level urls file like so: # events/urls.py urlpatterns = [ path('', login_required(views.EventsList.as_view()), name='list'), ] # events/urls_admin.py urlpatterns = [ path('', admin_required(views.EventsAdminList.as_view()), name='admin-list'), ] # myproject/urls.py path('events/', include('events.urls')), path('admin/events/', include('events.urls_admin')), But that is giving me an error from the template finding the route: Reverse for 'admin-list' not found. 'admin-list' is not a valid view function or pattern name. Which is weird, since I can double check that python manage.py show_urls shows both events:list and events:admin-list. Please note that I want the final url to be admin/events and not events/admin, because if that was the cause Django docs explains how to do so. I know I could just hard code all the routes, but naturally I am trying to avoid that. I also looked into nested namespaces - something like admin:events:list and events:list - but didn't manage to get to work too. -
How to use dictionary keys as choices in Model?
I have many choice fields and each option corresponding to a number. This number will be used for later calculations. Here is an example. I defined a dictionary which defines the value to each input: driven_factors = { "Education":{ "A": 1.29, "B": 0.98, "C": 0.72, }, } and the model is like: Education_choices= list(driven_factors.get("Education").keys()) Education= models.CharField(max_length=50, choices=Education_choices) Unfortunately, it does not work, because Education_choices is like ['A', 'B', 'C'] other than a sequence of pairs like [('A', 'x'), ('B', 'y',...)] How should I fix this? Or are there other approaches to do this? -
Update the css of one loaded DOM asynchronously once another user clicks a button in his loaded DOM in a django webapp
I am developing a django webapp where I have one html that gets loaded for two different users (User1 and User2) with some slight changes in it. I want my user1 to disable/enable some of the fields (like field) of that html in runtime so that user2 can only update the ones that user1 has made enabled. Currently, user1 can disable/enable html elements via javascript but that changes are only being reflected in his html. User2 cannot see the changes in his html. What will be the perfect way to achieve this functionality? I am not very familiar with everything in Django. Pardon my obvious knowledge gaps. Thanks. -
FieldError at /registerdoctor.html Cannot resolve keyword 'email' into field. Choices are: experience, id, phone_no, user, user_id
I am trying to create a model 'Doctor' which has a OneToOne relationship with Django's builtin 'User' model. For some reason, the Doctor model isn't inheriting the email object from the User or at least that is what I think. Could someone tell me where my mistake is? Thanks! views.py from django.shortcuts import render,redirect from django.contrib.auth.models import User,auth from django.contrib import messages from app1.models import Doctor def HomePage(request): return render(request,'homepage.html') def RegisterUser(request): if request.method =="POST": first_name = request.POST["fname"] last_name = request.POST["lname"] email_id = request.POST["mail"] password1 = request.POST["pass1"] password2 = request.POST["pass2"] username = request.POST["username"] if password1==password2: if User.objects.filter(email=email_id).exists(): messages.info(request,"This Email ID is already Registered!") return redirect("registeruser.html") else: if User.objects.filter(username=username).exists(): messages.info(request,"Username taken!") return redirect("registeruser.html") else: user = User.objects.create_user(first_name=first_name,last_name=last_name, email=email_id,password=password1,username=username) user.save() return redirect("/") else: messages.info(request,"Passwords Not Matching!") return redirect("registeruser.html") return redirect("/") else: return render(request,'registeruser.html') def RegisterDoctor(request): if request.method =="POST": first_name = request.POST.get("finame") last_name = request.POST.get("laname") email = request.POST.get("emailid") password1 = request.POST.get("userpassword") password2 = request.POST.get("conpassword") username = request.POST.get("username") phone_no = request.POST.get("phno") exp = request.POST.get("docexp") if password1==password2: if Doctor.objects.filter(email=email).exists(): messages.info(request,"This Email ID is already Registered!") return redirect("registerdoctor.html") else: if Doctor.objects.filter(username=username).exists(): messages.info(request,"Username taken!") return redirect("registerdoctor.html") else: user = Doctor.objects.create_user(first_name=first_name,last_name=last_name, email=email_id,password=password1,username=username,experience=exp,phone_no=phone_no) user.save() return redirect("/") else: messages.info(request,"Passwords Not Matching!") return redirect("registerdoctor.html") return redirect("/") else: return render(request,'registerdoctor.html') models.py from … -
How do I get the value of CharField() during instansiation?
I want to pass model fields values as arguments to another field. trademark_class.get_default() method is close to what I want, but I do not want solely the default value. I am also unable to use __dict__.['trademark_class'] in this case as I need a 'this' reference to the class and do not know the proper way to achieve that for this case. class Form_33_Model(models.Model): trademark_number = models.CharField(default='default number', max_length=30) trademark_class = models.CharField(default='default class', max_length=30) trademark_date = models.DateField(default=datetime.date.today) html = models.TextField(default=Form33StringClass(trademark_class=trademark_class.get_default(), trademark_number=trademark_number.get_default()).form_33_string) Instead of the default value only, I would like to get either the actual value of the Charfield or its default value. So something like : trademark_class.get_current_value_or_default() would be ideal for what I want. -
can i search from multi database in my model using django?
i have this code and work perfect .. but i want search in all my models how to do that ? any idea for that ? mycode Models.py: class OpratingSystems(models.Model): # def etc .. class AndroidGames(models.Model): # def etc .. class Antivirus(models.Model): # def etc .. class AndroidApks(models.Model): # def etc .. class PCgames(models.Model): # def etc .. class PCprogram(models.Model): # def etc .. class Homepage(models.Model): # def etc .. Views.py : def search(request): if request.method == 'GET': query= request.GET.get('q') submitbutton= request.GET.get('submit') if query is not None: lookups= Q(name__icontains=query) | Q(app_contect__icontains=query) | Q(page_url__icontains=query) | Q(app_image__icontains=query) results= Homepage.objects.filter(lookups).distinct() context={'results': results, 'submitbutton': submitbutton} return render(request, 'html_file/enterface.html', context) else: return render(request, 'html_file/enterface.html') else: return render(request, 'html_file/enterface.html') html page : {% if submitbutton == 'Search' and request.GET.q != '' %} {% if results %} <h1> <small> Results for </small><b>{{ request.GET.q }}</b> : </h1> <br/><br/> {% for result in results %} <label id="label_main_app"> <img id="img_main_app_first_screen" src="{{result.app_image.url}}" alt="no image found !" height="170" width="165" > {{result.name}} <br><br> <p id="p_size_first_page"> {{result.app_contect}} <br> <br> <a href="{{ result.page_url }}" type="button" class="btn btn-primary"><big> See More & Download </big> </a> </p> </label> {% endfor %} {% else %} <h3> No results for this search </h3> {% endif %} {% endif %} this … -
Scheduling Emails with Django?
I want to schedule emails using Django. Example ---> I want to send registered users their shopping cart information everyday at 5:00 P.M. How would I do this using Django? I have read a lot of articles on this problem but none of them have a definite solution. I don't want to implement a workaround. Whats the proper way of implementing this? Can this be done within my Django project or do I have to use some third-party service? If possible, please share some code. Otherwise, details on how I can implement this will do.