Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Allow user to access some part of a project depending on the role they have - Django
I just finished coding a django app that helps music producers coordinate projects and I am trying to solve a small problem I am facing. On a given project, users have specific roles (sound tech, drummer, production manager et cetera). Depending on their role, I want them to be able to see only some informations of the project. For example, the production manager should be able to see the project budget but the drummer no. How can I do it? I thought about using groups but I am not sure yet how. -
Field 'id' expected a number but got <SimpleLazyObject: <User: username>>
I have been stuck on this error for some time and I can't wrap my head around the problem or what it even means. I found some answers but none really solved my issue. Here is a brief desciption of what I do: In Javascript, I call this function with an int as a parameter such as: function follow (user_id) { // retrieves post for current selection fetch(`/follow/${user_id}`, { method: 'PUT', body: JSON.stringify({ follow: true }) }) } My url path, from url.py, is as follow: path('follow/<int:user_id>', views.follow, name="follow") finally, in views.py, this function is called: def follow(request, user_id): user = User.objects.get(id = user_id) if request.method == "PUT": data = json.loads(request.body) if data.get("follow") is not None: followed = Followed( user_id = user.id, followed_by_id = request.user, ) followed.save() return HttpResponseRedirect(reverse("index")) else: return HttpResponseRedirect(reverse("index")) I have tried a few different approaches such as removing the .value but I keep getting the following error: Field 'id' expected a number but got <SimpleLazyObject: <User: username>> I check along the way and the ID is an int all the way until it is passed to the model to be saved. I am using the abstractUser model. Let me know if more information is needed. Kind … -
Django views Passing a variable thru an object
i have the following situation: def detail(request, pk): """User can view an active survey""" try: survey = Survey.objects.prefetch_related("question_set__option_set").get( pk=pk, creator=request.user, is_active=True ) except Survey.DoesNotExist: raise Http404() questions = survey.question_set.all() for question in questions: if question.type != 'Text': option_pks = question.option_set.values_list("pk", flat=True) total_answers = Answer.objects.filter( option_id__in=option_pks).count() for option in question.option_set.all(): num_answers = Answer.objects.filter(option=option).count() option.pct = 100.0 * num_answers / total_answers if total_answers else 0 else: total_answers = Answer.objects.filter( question_id=question.pk).count() answers = Answer.objects.filter( question_id=question.pk).values_list("text", flat=True) for answer in question.answer_set.all(): num_answers = Answer.objects.filter( question_id=question.pk, text=answer.text).count() answer.pct = 100.0 * num_answers / total_answers if total_answers else 0 In the case of the question.type != 'Text', i can use the percentage in the template... but after the "else": , the percentage is not available for me on the templates... when im using the answer_set of the question instead of option_set does anyone know why?? HELP!! -
django pwa manifest error not reading service worker
I am creating a django pwa. In my local host, when I run my pwa, in my manifest report I get "No matching service worker detected. You man need to reload the page, or check that the scope of the service worker for the current page encloses the scope and the start URL from the manifest. " , but when I click on my service worker its there. serviceworker.js var staticCacheName = 'djangopwa-v'+ new Date().getTime(); self.addEventListener('install', function(event) { event.waitUntil( caches.open(staticCacheName).then(function(cache) { return cache.addAll([ '/', ]); }) ); }); self.addEventListener('fetch', function(event) { var requestUrl = new URL(event.request.url); if (requestUrl.origin === location.origin) { if ((requestUrl.pathname === '/')) { event.respondWith(caches.match('')); return; } } event.respondWith( caches.match(event.request).then(function(response) { return response || fetch(event.request); }) ); }); manifest.json { "name": "Unlock Optimal Performance", "short_name" :"CMU", "description": "Fitness builder app", "theme_color" :"#639FCB", "background_color": "#fff", "display":"standalone", "start_url":"/", "icons":[ { "src": "/static/images/icons/icon-72x72.png", "sizes": "72x72", "type": "image/png", "purpose": "any" }, { "src": "/static/images/icons/icon-96x96.png", "sizes": "96x96", "type": "image/png", "purpose": "any" }, { "src": "/static/images/icons/icon-128x128.png", "sizes": "128x128", "type": "image/png", "purpose": "any" }, { "src": "/static/images/icons/icon-152x152.png", "sizes": "152x152", "type": "image/png", "purpose": "any" }, { "src": "/static/images/icons/icon-196x196.png", "sizes": "196x196", "type": "image/png", "purpose": "any" }, { "src": "/static/images/icons/icon-256x256.png", "sizes": "256x256", "type": "image/png", "purpose": "any" }, { … -
Filter queryset from beginning to a specific object
I know you can add [:n] on the end of a queryset to filter that queryset to be from the beginning to the nth object. E.g. qs = Item.objects.all() range = qs[:5] # Returns first five objects Is it possible to filter a queryset to be from the beginning to a specific object? e.g. qs = Item.objects.all() obj = Item.objects.get(pk="123") # How to return the qs from the beginning to obj? -
Delete all objects in Django except last N (N is big, about 1000)
What is fastest way to delete all objects except last 1000? I can do it slow way: last_events = Event.objects.filter(user=user).order_by('-created')[:1000].values_list('id', flat=True) Event.objects.filter(user=user).exclude(id__in=list(last_events)).delete() But I wouldn't like to load such long query to my DB. I thought I can't find ID of border element and delete all objects before that element: last_events = Event.objects.filter(user=user).order_by('-created')[:1000].last() But got: TypeError: Cannot reverse a query once a slice has been taken. I've also tried: last_events = Event.objects.filter(user=user).order_by('-created')[:1000][-1] But got: AssertionError: Negative indexing is not supported. -
Is there a way to upload images from ckeditor RichTextUploadingField to aws s3?
I am working on a personal portfolio website in Django and hosting it on heroku. I have been able to set up aws s3 for the static files and other images that will be uploaded to the website. The problem I am facing now is, images from the ckeditor are not being uploaded to aws s3. So the images vanish after a while. I read the ckeditor docs and it states to set 'AWS_QUERYSTRING_AUTH = False'. Doing this breaks my website's styling. Any ideas on how I could do this? It's been a while I worked with Django. Below is my settings.py. Thank you. import django_heroku import dj_database_url from pathlib import Path import os import environ # Initialise env variables env = environ.Env() environ.Env.read_env() # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # AWS S3 SETTINGS AWS_ACCESS_KEY_ID = '' AWS_SECRET_ACCESS_KEY = '' AWS_STORAGE_BUCKET_NAME = '' AWS_URL = '' AWS_DEFAULT_ACL = None AWS_S3_REGION_NAME = 'us-east-2' AWS_S3_SIGNATURE_VERSION = 's3v4' AWS_QUERYSTRING_AUTH = False # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '' # SECURITY WARNING: don't run with debug turned on … -
Redirecting back to instance variable django
It seems like this should be a very common occurrence but I can't find anything about doing it on the internet. I have a page that renders once I input two bits of info: state and brand the views.py looks like this: def detail(request): try: if request.method == 'POST': state = request.POST['state'] brand = request.POST['brand'] territory_manager = TM.objects.filter(State__icontains=state).filter(Brand__icontains=brand), return render(request,'homepage/detail.html', {'state': state, 'territory_manager':territory_manager}) else: state = request.POST['state'] brand = request.POST['brand'] return render(request,'homepage/detail.html', f"No Results for {state} or {brand}") except TM.DoesNotExist: raise Http404("Info Does Not Exist") That page shows a filtered view of all the territory managers in my db that meet those two criteria. Once on that page I have an update button next to each territory manager that redirects to an update_territory_manager page where I can make updates to the territory manager. Once done updating I have a button that the user can click that is supposed to save the updated info to the db then redirect. I am trying to redirect back to the filtered view of all the territory managers that meet that criteria but the view function for the update page has no knowledge of that because that instance is in the previous views function (pictured … -
How to execute fetch paths without interfering with webpage pathname?
I am working on a Django project and got stuck on url patterns and routes. On index.html, the pathname is "" and the JS functions are working great. The fetch url tweets/${tweetid} is matching with Django API route url pattern tweets/<int:tweetid> and is working fine. However, on profile.html, the pathname is "profile/<int:userid>" and JS is not working here. The fetch url tweets/${tweetid} results the final path profile/tweets/<int:tweetid>. Since that is not in urls.py, I am getting an error. How can I execute my fetch and JS functions on any html page in this web application? -
ModuleNotFoundError: No module named 'django_celery_beat' in Django even if is installed and running
I want to see the Beat statistics in the admin panel so I want to have the beat in included in settings.py but even if it installed and works (async tasks not related to the web interface), I cannot add the django_celery_beat to the INSTALLED_APPS. INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'apps.app', 'apps.pps', 'apps.taskmgr', 'django_celery_beat', 'django_celery_results', ] import_module(entry) File "c:\users\paul\appdata\local\programs\python\python38-32\lib\importlib\__init__.py", line 127, in import_module 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 'django_celery_beat' I use Python 3.8, celery 5.1.2, django-celery-beat 2.2.1, Django 3.26 and running on Windows 11. -
Django, python script run in page
I need run python script in backend i need to display it and catch user interact this on django page. Script is somthing like this: .... print("someting") if (input() == "y"): print("somethon") print("sas") data = input() It is possible to do something like this? I cant find solusions -
importing an exported list JSONField turns JSON to string if JSON list is empty
I am using this answer from a similar question. But I would like to treat any empty fields from the import-export file as an empty list instead of None. some_list_json= fields.Field(attribute='some_list_json', widget=JSONWidget(), column_name='some_list_json') When I try to export it, it doesn't show anything. And when I try to import and do some manipulation, it returns an exception. 'str' object has no attribute 'append' How do I get around this? -
Subdomain didn't send any data | ERR_EMPTY_RESPONSE | Heroku
I'm trying to connect my Heroku App via a custom GoDaddy subdomain. The subdomain is "subdomain" (for the sake of example). What I'm doing is, copying the DNS Target from Heroku and adding it in GoDaddy as a CNAME such that it is pointing to the DNS Target given by Heroku. Nonetheless, I'm getting the following error when going to www.subdomain.mysite.org I have previously created subdomains and connected them to GoDaddy with the DNS Target that Heroku provides. Don't know what I'm doing wrong. I tried to refresh the DNS but it's not working. -
Access Requests Method within Celery Task
Is it possible to access the requests.POST/GET methods within a celery task that's in a django project? I've read that it's not possible because celery can't serialized the requests JSON objects. Other than taking the data from the requests.POST['data'] object and passing them to the celery task, are there any other work arounds? def index(request): task = run_tasks.delay(request) # I would like to pass the request data to the task return render(request, 'example/index.html', {'task_id': task.task_id}) -
Do I need to do some registration of floatformat tag in django before using it?
I have the following piece of code <div>{{ context_findings["overdue_findings"] }} | {{ (context_findings["overdue_findings"] / context_findings["total_findings"] * 100)|floatformat }}%</div> but on executing it I get the error TemplateSyntaxError ("no filter named 'floatformat'",) I've tried doing something like <div class="pb-2">Overdue {{ 1.223|floatformat }}</div> to see if it works but I'm still getting the same error. Any ideas why this might happen? -
yaml: line 3: could not find expected ':' ERROR: failed to build: exit status 3
I get this error trying to deploy my django project on digital ocean. I really have no clue what to o from here. I don't know what code to post here as is required, but I need help. Trying to google elsewhere, I don't get the much needed help. yaml: line 3: could not find expected ':' ERROR: failed to build: exit status 3 -
Django download return
simple question please, my POST in the views returns a json format dictionary nested_data = { 'name': cleaned_data3['theme_name'], 'visualStyles': { 'barChart': { '*': { 'general': [{ 'responsive': cleaned_data2['responsive'], 'keepLayerOrder': cleaned_data2['maintain_layer_order'] }], 'legend': [{ 'show': cleaned_data['show'], 'position': cleaned_data['position'], 'showTitle': cleaned_data['show_title'], 'labelColor': { 'solid': { 'color': '#666666' } }, 'fontFamily': cleaned_data['font'], 'fontSize': cleaned_data['font_size'] }], } } } } then I am returning the code formatted into json using: return JsonResponse(nested_data) This shows me the json rendered in the browser, but how do I download this return? In my index.html the submit button is rendering the return from the view, but I need to submit the forms and to download the content into .json file, something needs to be put into the href? <input type="submit" value="Submit"> <a href="{{ xxx }}" download>DOWNLOAD</a> -
Could there be any issues naming a Django model "Model"?
I am looking through a new client's code and they named one of their Django models "Model." Could this cause any issues since all models are considered models or no? -
Updating django "notes" section with ajax
I've looked at docs and watched videos and asked another question on stack overflow but just can't understand how to use ajax with my django project. Essentially I have a list of territory managers that are returned from a for loop (here's the models.py, views.py and detail.html showing that): models.py class TM(models.Model): #Change this to territory manager and delete database and recreate Name = models.CharField(max_length = 200,null=True) Cell = models.CharField(max_length= 200, null=True) EmailAddress = models.EmailField(null=True) Notes = models.CharField(max_length=500, null=True) Distributor = models.CharField(max_length=200,null=True) State = models.CharField(max_length=200,null=True) Brand = models.CharField(max_length=200,null=True) def __str__(self): try: if self.Distributor is not NullBooleanField: return self.Name + ' - ' + self.Distributor + ' - ' + self.State except TypeError: return self.Name views.py def detail(request): try: if request.method == 'POST': state = request.POST['state'] brand = request.POST['brand'] territory_manager = TM.objects.filter(State__icontains=state).filter(Brand__icontains=brand) return render(request,'homepage/detail.html', {'state': state, 'territory_manager':territory_manager}) else: state = request.POST['state'] brand = request.POST['brand'] return render(request,'homepage/detail.html', f"No Results for {state} or {brand}") except TM.DoesNotExist: raise Http404("Info Does Not Exist") table in detail.html <table class= "content-table"> <thead> <tr> <th>Name</th> <th>Distributor</th> <th>State</th> <th>Brand</th> <th>Cell</th> <th>Email</th> <th>Notes</th> <th></th> </tr> </thead> <tbody> <tr> {% for tm in territory_manager %} <td style="white-space:nowrap;">{{ tm.Name }}</td> <td style="white-space:nowrap;">{{ tm.Distributor }}</td> <td style="white-space:nowrap;">{{ tm.State }}</td> <td style="white-space:nowrap;">{{ tm.Brand }}</td> … -
Ajax Post Request isn´t working in django
I have a problem with django. I have researched so much on other questions but their answers don´t work for me. I need to send a base64 string of an image to my view so that i can store the string instead of the image in my database. So, I want to send data via ajax to my django view. Due to whatever reason, the form gets already submitted by django automatically and i tried to stop it, but then ajax isn´t firing too. I would really appreciate help because it already has cost me so much time. add.html <form method="post" enctype="multipart/form-data" onsubmit="submitdata()"> {% csrf_token %} <input type="text" name="dish" required id="id_dish" placeholder="Rezeptname"> <img ><input type="file" name="image" required="" id="id_image" accept="image/*"> <div class="image-upload"><img id="img_id" src="#" style="display:none; height: 100%; width: 100%;"> </div><button type="submit">Upload</button> </form> <script> function submitdata() { $.ajax({ type: "POST", contentType: "application/json", url: "/add", data: JSON.stringify({ "dish": "test", "image": dataurl, "recipe": document.getElementsByName("recipe")[0].value, "caption": document.getElementsByName("caption")[0].value }), dataType: "json", }); } </script> views.py @login_required(login_url="login") def add(response): if response.method == "POST": form = AddForm(response.POST, response.FILES) if form.is_valid(): print(response.POST) current_user = Client.objects.get(id=response.user.id) current_user.post_set.create(poster=response.user.username, dish=form.cleaned_data.get("dish"), image=response.POST.get("image"), caption=form.cleaned_data.get("caption"), recipe=form.cleaned_data.get("recipe")) messages.success(response, "You successfully added a post.") return redirect("home") else: form = AddForm() return render(response, "main/add.html", {"form":form}) forms.py class AddForm(forms.ModelForm): … -
django rest framework return processed image url saved
The image has been received and processed by Django rest framework and saved to postgres. I can view the file saved locally, how can I send the URL of the image location back? Here is my views class ImageViewSet(viewsets.ModelViewSet): queryset = Image.objects.all().order_by('-uploaded') serializer_class = ImageSerializer @api_view(['POST']) def analyze_image(request): image_uploaded = request.data['picture'] ....#some processing img_model = Image() new_image = BytesIO() processed_image.save(new_image , format='PNG') img_model.analyzed_picture.save("fileName", content=ContentFile(new_image.getvalue()), save=False) # Above image is saved succesfully and I can view it locally return Response(img_model.data, status=status.HTTP_200_OK) I get AttributeError: 'Image' object has no attribute 'data' How can I fix the return statement so it returns the saved object information? -
Django - Unit test object's delection does not work as expacted
For 2 of my models, Users and Groups, I have a view to delete objects. The code is almost the same for each of them, it works in the application but unit test have different results: it works for users, not for groups. Thanks in advance for your advises. Here are the unit tests: class TestAdmUsers(TestCase): def setUp(self): self.company = create_dummy_company("Société de test") self.user_staff = create_dummy_user(self.company, "staff", admin=True) self.usr11 = create_dummy_user(self.company, "user11") self.usr12 = create_dummy_user(self.company, "user12", admin=True) self.usr13 = create_dummy_user(self.company, "user13") self.client.force_login(self.user_staff.user) def test_adm_delete_user(self): test_usercomp_id = self.usr13.id usrcomp = UserComp.objects.get(user__username="user13") self.assertEqual(usrcomp.id, test_usercomp_id) url = reverse("polls:adm_delete_user", args=[self.company.comp_slug, test_usercomp_id]) response = self.client.get(url) self.assertEqual(response.status_code, 302) with self.assertRaises(User.DoesNotExist): User.objects.get(id=test_usercomp_id) with self.assertRaises(UserComp.DoesNotExist): UserComp.objects.get(id=test_usercomp_id) class TestAdmGroups(TestCase): def setUp(self): self.company = create_dummy_company("Société de test") self.user_staff = create_dummy_user(self.company, "staff", admin=True) self.usr11 = create_dummy_user(self.company, "user11") self.usr12 = create_dummy_user(self.company, "user12", admin=True) self.usr13 = create_dummy_user(self.company, "user13") self.usr14 = create_dummy_user(self.company, "user14") user_list = [self.usr11.id, self.usr12.id, self.usr13.id, self.usr14.id] users = UserComp.objects.filter(id__in=user_list) self.group1 = UserGroup.create_group({ "company": self.company, "group_name": "Groupe 1", "weight": 40, }, user_list=users) def test_adm_delete_group(self): test_group_id = self.group1.id grp = UserGroup.objects.get(group_name="Groupe 1") self.assertEqual(grp.id, test_group_id) url = reverse("polls:adm_delete_group", args=[self.company.comp_slug, test_group_id]) response = self.client.get(url) self.assertEqual(response.status_code, 302) with self.assertRaises(UserGroup.DoesNotExist): UserGroup.objects.get(id=test_group_id) The test runs fine for users, but I have this fali for groups: Traceback (most recent … -
How to export a database's data to a new one(python/mysql)
lets say I have an old database in mysql and i want to export all of its data to a new mysql database with python(or Django). How can I do that? consider that the old database might not have some fields of some tables of the new database(for example there is a table called "product" in the old database, we have the same table in the new database but with an extra field called 'address'. so the old data base doesnt have the field address but the new one does). I just want to transfer the data, tables already exist in the new database -
Django: Heroku Failing to launch, at=error code=H10 desc="App crashed" path="/"
When I try to deploy the project to Heroku, It gives the application error. I tried to go through the log file but I can't identify the problem correctly. This is the repository that I tried to push https://github.com/sachin96Boy/covid-predict any help is appreciated. Thanks -
I'm getting an error message when making migration to db in django
hello guys I'm doing a django tutorial and i missed a change the instructor did in models.py so i fix it but when trying to make the migration to the db it gives me a code that I don't understand or i don't know what to do, here is what it says Please select a fix: 1) Provide a one-off default now (will be set on all existing rows with a null value for this column) 2) Quit, and let me add a default in models.py