Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Altering the database with only one pytest-django session
I am using pytest-django 4.1 with Django 2.2 in my app. I have two databases for my tests: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'default_db', 'USER': '', 'PASSWORD': '' }, 'second': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'second_db', 'USER': '', 'PASSWORD': '' }, } During each test session these two databases are created: Creating test database for alias 'default' ('file:memorydb_default?mode=memory&cache=shared')... Creating test database for alias 'second' ('file:memorydb_default?mode=memory&cache=shared')... I don't want to use them all the time, only for a few tests. So I am looking for a way to enable creation of second database only for some sessions. Unfortunately I couldn't find a way to do this. Django documentation about tests recommends to use modify_settings or override_settings but it's not working for pytest-django. I tried to use django_db_setup fixture or pytest_sessionstart hook but I ended up with the situation where the db_router is correctly changed but the database is not, so the django configuration isn't really reset by editing settings.DATABASES after pytest is configured. I could make it work only for the whole configuration like: # project/conftest.py def pytest_configure(config): from django.conf import settings settings.DATABASE_ROUTERS = [] settings.DATABASES.pop('second', None) Is there a way to alter the django.conf.settings.DATABASES between the sessions in … -
Send post request using data from mapbox
How can I send data from marker on the map by POST request. I'm using Django and I want to get coordinates from marker which set by user. -
Is there a Ternary Operator in python
I'm trying to do a ternary like operator for python to check if my dictionary value exist then use it or else leave it blank, for example in the code below I want to get the value of creator and assignee, if the value doesn't exist I want it to be '' if theres a way to use ternary operator in python? Here's my code : in_progress_response = requests.request("GET", url, headers=headers, auth=auth).json() issue_list = [] for issue in in_progress_response['issues'] : # return HttpResponse( json.dumps( issue['fields']['creator']['displayName'] ) ) issue_list.append( { "id": issue['id'], "key": issue['key'], # DOESN'T WORK "creator": issue['fields']['creator']['displayName'] ? '', "is_creator_active": issue['fields']['creator']['active'] ? '', "assignee": issue['fields']['assignee']['displayName'] ? '', "is_assignee_active": issue['fields']['assignee']['active'] ? '', "updated": issue['fields']['updated'], } ) return issue_list -
django: Dynamically and securely change form value from template for loop for form saving to database
So I have a database of "stuff" that is essentially static and not editable by users, this is a repo of things that users are allowed to save. However, users can save copies of this stuff to a separate "user_stuff" database as the user unique stuff will have data that is unique to each user. class public_stuff(models.Model): name = models.CharField(max_length=100, unique=True) description = models.TextField(blank=True) def __str__(self): return self.name class user_stuff(models.Model): name = models.CharField(max_length=100) stuff = models.ForeignKey(public_stuff, on_delete=models.DO_NOTHING) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) description = models.TextField() def __str__(self): return self.name On my actual page I am rendering a list of all public stuff (for now, I only have two things in public_stuff at the moment for test purposes), as well as a list of all of a users stuff. For each public stuff entry, I would ideally like to have a button that the user can click to "save" a copy of that entry to their stuff, but the problem is I am not sure how to do this securely. The main roadblack is that I would ideally like to display each entry via a foor loop, as the list will be dynamic in both size and composition. As a result, I … -
format count integar into percentage inside annotate in Djnago rest
I have to send the percentage of counts in the api call in DRF. I have calculated the counts and attach to the queryset using annotate. But actaully I need the percentage rather than the count. TYPES = ((1,'cold'), (2,'humid'), (3,'hot')) from django.db.models import Q,Count class Destinations(models.Model): continent = models.CharField() /............/ class Packages(models.Model): location = models.Foreignkey(Destination,on_delete=models.CASCADE,related_name='packages') place_type = models.CharField( max_length=1, choices=TYPES, default="" My view: I have use list function inside modelviewset, something like this: Destiantion = Destination.objects.all().annotate(total_packages=Count('packages'), cold_count=Count('packages',filter=Q(packages__place_type=1)), humid_count=Count('packages',filter=Q(packages__place_type=2)), hot_count =Count('packages',filter=Q(packages__place_type=3))) Here I get the response as counts of package types in the attributes, but I want is the percentage of package type like 25% by doing cold_count*100/total_packages but cant use this inside annotate. There is a count() method which might be useful but if I used that I have to make 4 separate queries and might be writing another api just for that. So I have to use annotate. But how?? -
Django Admin Sortable 2 - Inline Tabular - not save order and display hidden field
I was using Python 3.9, Django 3.2.8, and Django-admin-sortable2 1.0.3. I was facing issue that my custom order field (I named it "sort_order") was visible in inline tabular forms but it should have been hidden as per Django-admin-sortable2 implementation. And although I was able to drag-and-drop items, but upon saving the parent object, the sort order wasn't getting saved. What worked for me? -
Why does Django's union mess up the column order?
If I have 2 models: class Hero(models.Model): hero_name = models.CharField(max_length=50) hero_age = models.PositiveSmallIntegerField() hero_identity = models.TextField(max_length=50) def __str__(self): return self.hero_name class Villain(models.Model): villain_name = models.CharField(max_length=50) villain_age = models.PositiveSmallIntegerField() villain_identity = models.TextField(max_length=50) def __str__(self): return self.villain_name and I create some test instances: Hero(hero_name="Superman", hero_age=30, hero_identity="Clark Kent").save() Hero(hero_name="Iron Man", hero_age=35, hero_identity="Tony Stark").save() Hero(hero_name="Spider-Man", hero_age=18, hero_identity="Peter Parker").save() Villain(villain_name="Green Goblin", villain_age=45, villain_identity="Norman Osborn").save() Villain(villain_name="Red Skull", villain_age=38, villain_identity="Johann Schmidt").save() Villain(villain_name="Vulture", villain_age=47, villain_identity="Adrian Toomes").save() Listing them individually works fine, but listing them using a union breaks the order somehow: >>> from django.db.models import F >>> from myapp.models import Hero, Villain >>> for hero in Hero.objects.all().annotate(name=F("hero_name"), age=F("hero_age"), identity=F("hero_identity")).values("name", "age", "identity"): ... print(hero) {'name': 'Superman', 'age': 30, 'identity': 'Clark Kent'} {'name': 'Iron Man', 'age': 35, 'identity': 'Tony Stark'} {'name': 'Spider-Man', 'age': 18, 'identity': 'Peter Parker'} >>> for villain in Villain.objects.all().annotate(name=F("villain_name"), age=F("villain_age"), identity=F("villain_identity")).values("name", "age", "identity"): ... print(villain) {'name': 'Green Goblin', 'age': 45, 'identity': 'Norman Osborn'} {'name': 'Red Skull', 'age': 38, 'identity': 'Johann Schmidt'} {'name': 'Vulture', 'age': 47, 'identity': 'Adrian Toomes'} >>> all = Hero.objects.all().annotate(name=F("hero_name"), age=F("hero_age"), identity=F("hero_identity")).union(Villain.objects.all().annotate(name=F("villain_name"), age=F("villain_age"), identity=F("villain_identity"))) >>> for person in all.values("name", "age", "identity"): ... print(person) {'name': 1, 'age': 'Green Goblin', 'identity': 45} {'name': 1, 'age': 'Superman', 'identity': 30} {'name': 2, 'age': 'Iron Man', 'identity': 35} {'name': 2, … -
How do I match a title of post and text of post in django
I started learning django a few weeks ago and I have run in to a problem that I can't figure out. Here is the exercise:enter image description here Models.pyenter image description here Views.pyenter image description here Blogs.htmlenter image description here Blog.html enter image description here urls.pyenter image description here Thanks in advance! -
Django: render a word document that is saved in a query object
I have an app where in my models.py I included a welcome text: welcome_text = models.FilePathField(path="/text") The file is located at app/static/text/welcome_text.docx I thought I could use {{app.welcome_text}} in my html-template, but it doesn't give anything back. Which pre-and suffix can be used to define a word document? Is it possible to render the word document that is correctly saved in the database ? -
unable to pass data from views to js file having chart js codes, shows unexpected syntax error
I am trying to make analytics for my webapp, where it whould show data from db graphically. I am using chart js for this. I am learning how to do it from youtube. Strangely they are not getting any error where as I am getting this Uncaught SyntaxError: Unexpected token '{' these are the codes that I have written views.py monthly_visitor = VisitorCount.objects.all().values( 'date_of_record__month' ).annotate( total_in_month=Count('ip') # take visitor_id or whatever you want to count ).order_by() yearly_visitor = VisitorCount.objects.all().values('date_of_record__year').annotate( total_in_year= Count('ip') ).order_by() print("\nthe values of monthly visitors are", monthly_visitor, "\n") visitorMonthNumber = [] visitorNumberMonthly = [] for i in range(len(monthly_visitor)): visitorMonthNumber.append(monthly_visitor[i]['date_of_record__month']) visitorNumberMonthly.append(monthly_visitor[i]['total_in_month']) print("\nthis is the list of month number =", visitorMonthNumber, "\n", "\nthis is the number of visitors", visitorNumberMonthly, "\n") context = { 'visitorMonthNumber': visitorMonthNumber, 'visitorNumberMonthly': visitorNumberMonthly } return render(request, "chart.html", context) In the above code I am querying a model named visitor count to get the number of visitors on every month. js file var visitorMonthNumber = {{visitorMonthNumber}}; var visitorNumberMonthly = {{visitorNumberMonthly}}; const visitorM = document.getElementById('visitorMonthly').getContext('2d'); const visitorMonthly = new Chart(visitorM, { type: 'bar', data: { labels: visitorMonthNumber, datasets: [{ label: 'Monthly Visitors', data: visitorNumberMonthly, backgroundColor: [ 'rgba(255, 99, 132, 0.2)', 'rgba(54, 162, 235, 0.2)', 'rgba(255, 206, 86, 0.2)', … -
Need a Solution for my scenario with Python and Django
I have a Django web app, we have a code that pulls the sales data from API with to and from date and also we want to store it in data base(MYSQL) or data warehouse. I need some help how to design the below part of avoiding duplication and optimized code? Lets say the database or data-warehouse already contains data in it. How can we avoid writing duplicate data to DB or DW if the API pulls the existing data? Even if we compare with the existing records, it usually takes so much of time what is the best optimized way? Thank you -
Django website unabale to register new users
I am following Antoinio Mele's -Django by example to build a Social Website but everythime I try to register a new user through the register.html template all I get is a blank form ,neither does the webiste create a new user. I've followed everything that's said in the tutorial. My views.py from django.shortcuts import render from django.http import HttpResponse from django.shortcuts import render from django.contrib.auth import authenticate, login #from .forms import LoginForm,UserRegistrationForm from .forms import LoginForm,UserRegistrationForm from django.contrib.auth.decorators import login_required def user_login(request): if request.method == 'POST': form = LoginForm(request.POST) if form.is_valid(): cd = form.cleaned_data user = authenticate(request,username=cd['username'], password=cd['password']) if user is not None: if user.is_active: login(request,user) return HttpResponse('Authenticated successfully') else: return HttpResponse('Disabled account') else: return HttpResponse('Invalid login') else: form = LoginForm() return render(request,'account/login.html',{'form':form}) @login_required def dashboard(request): return render(request, 'account/dashboard.html', {'section':'dashboard'}) def register(request): if request.method == 'POST': user_form = UserRegistrationForm(request.POST) if user_form.is_valid(): # Create a new user object but avoid saving it yet #new_user = user_form.save(commit=False) new_user = user_form.save() # Set the chosen password new_user.set_password( user_form.cleaned_data['password']) # Save the User object new_user.save() # Create the user profile # Profile.objects.create(user=new_user) return render(request, 'account/register_done.html', {'new_user': new_user}) else: user_form = UserRegistrationForm() return render(request, 'account/register.html', {'user_form': user_form}) My urls.py from django.urls import path from django.contrib.auth … -
How i can to pass instance to docxtpl in django framework?
I have a models with relationship such as ForeignKey, ManyToManyField and model method for calculate something. When i query a data from database i got a instance. i want to pass instance to docxtpl because it fast in develop. example code in models.py class Customer(models.Model): uuid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=50,,null=True,blank=True) birthdate = models.DateField(max_length=100,null=True,blank=True) status = models.ForeignKey('status ',on_delete=models.CASCADE) something = models.ManyToManyField('Something',blank=True) def get_age(self): diff = relativedelta(datetime.date.today(),self.birthdate ) return diff example code in generate_docx.py. I know doc.render() require a dictionary but i want to pass instace because it easy to use in template.docx from docxtpl import DocxTemplate def generate_document(instance): doc = DocxTemplate("template.docx") doc.render(instance) doc.save("generated_doc.docx") # example generate docx customer = Customer.objects.get(uuid="UUID_CUSTOMER") generate_document(customer) example template.docx Lorem Ipsum is simply dummy text of the printing and typesetting industry. {{customer.name}} age {{customer.geta_age}} {% for c in customer.somthing.all %} {{c}} {% endfor %} I want to know how to pass instance to docxtpl or convert instance that have relationship and model method to dict use for docxtpl in compatible. thank for expert -
How to get all the messages (or the data) from a group in django channels?
I am a bit new to Django and have been trying to work on a chat application utilizing Django Channels. Recently, I got stumbled upon an issue where there is a need to get all the data (if any) associated with a group. I have searched in the docs and other places for a workaround but was unable to find anything useful. Is it possible to interact with the Redis databases associated with the channel layers being used via something like Redis client for Python and get data in that way? Or should I try to store any newly generated messages separately for each group in the cache? (I think the latter technique will create unnecessary overhead since an extra copy of all the messages associated with a group will be there) Can someone help me with this problem? Thanks for reading! -
How to solve this loop to print all the values?
It should print 5,3.33 but it is only printing 3 ?How to print both values bucket_data22={1: {'key': 'Security Awareness Overview', 'value': 20, 'start_date': '13/07/2021', 'end_date': '12/08/2021', 'id': 155}, 2: {'key': 'Security Awareness Overview', 'value': 0, 'start_date': '13/07/2021', 'end_date': '12/08/2021', 'id': 159}, 3: {'key': 'Security Awareness Overview', 'value': 30, 'start_date': '24/09/2021', 'end_date': '27/09/2021', 'id': 174}} completed_data={155: 1, 174: 1} for z in completed_data: print(z) for i in bucket_data22: if (bucket_data22[i]['id']==z): print((completed_data[z]/bucket_data22[i]['value'])*100) -
manage.py error after Wagtail 2.15 upgrade
After upgrading to Wagtail 2.15 (or 2.15.1) from 2.14.2 my production website with postgres and database search breaks and commands run with manage.py give an error despite me adding the required WAGTAILSEARCH_BACKENDS to settings. I have to web apps with separate settings running from the same Wagtail version. One of the apps (putkeep) has a search bar and the other (secretgifter) does not. After upgrading Wagtail from 2.14.2 to 2.15 putkeep gives a 404 error but secretgifter does not. If I use pip to switch back to 2.14.2 the 404 error goes away and the site loads (although results from a search give a 500 error). If I run makemigrations (or any other command that uses manage.py for secretgifter it works fine. For putkeep (with the search) it gives the following error: File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/home/th-putkeep.net/putkeep/lib/python3.8/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/home/th-putkeep.net/putkeep/lib/python3.8/site-packages/django/core/management/__init__.py", line 395, in execute django.setup() File "/home/th-putkeep.net/putkeep/lib/python3.8/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/th-putkeep.net/putkeep/lib/python3.8/site-packages/django/apps/registry.py", line 122, in populate app_config.ready() File "/home/th-putkeep.net/putkeep/lib/python3.8/site-packages/wagtail/search/apps.py", line 21, in ready set_weights() File "/home/th-putkeep.net/putkeep/lib/python3.8/site-packages/wagtail/search/backends/database/postgres/weights.py", line 44, in set_weights BOOSTS_WEIGHTS.extend(determine_boosts_weights()) File "/home/th-putkeep.net/putkeep/lib/python3.8/site-packages/wagtail/search/backends/database/postgres/weights.py", line 32, in determine_boosts_weights boosts = get_boosts() File "/home/th-putkeep.net/putkeep/lib/python3.8/site-packages/wagtail/search/backends/database/postgres/weights.py", line 26, in get_boosts boosts.add(boost) TypeError: unhashable type: … -
How can we create object in desire database in rest framework
I'm creating project but that project is saving in the default database. I want to create that project in other database... I'm using CreatApiView.. class CreateProjectAPIView(generics.CreateAPIView): """This endpoint allows for creation of a Project""" queryset = Project.objects.using('notification_dev').all() serializer_class = serializers.ProjectSerializer def get_serializer(self, *args, **kwargs): serializer_class = self.get_serializer_class() kwargs["context"] = self.get_serializer_context() draft_request_data = self.request.data.copy() print("draft_request_data :",draft_request_data) kwargs["data"] = draft_request_data return serializer_class(*args, **kwargs) I don't get it how can i use that .using("otherdataName") in get_serializer -
TemplateDoesNotExist graphene/graphiql.html
I'm trying to setup Graphene, but have a following exception raised when open http://localhost:8000/graphql/ in browser: TemplateDoesNotExist at /graphql/ graphene/graphiql.html Request Method: GET Request URL: http://localhost:8000/graphql/ Django Version: 3.2.10 Added did whole setup, added to urls, configured schema, queries and mutations. But still not work. And even don't remember that ever needed to configure templates for Graphene. -
How do I add an image to the imagefield in django model that is present in the static folder?
Basically, I have an image file certificate.png in the static folder. I have written a view that will access this image and then write the student's name on it. I now want to add this image to the ImageField 'certificate' in the Model 'My_course'. I am not able to figure out how to do that. Please help. This is the view: def certificate(request, slug): course = My_course.objects.get(course=Course.objects.get(slug=slug), user=request.user) try: course.certificate.url except ValueError: image = Image.open('course/static/course/images/Certificate.png') draw = ImageDraw.Draw(image) font = ImageFont.truetype('course/static/course/fonts/Oswald-Medium.ttf', size=100) (x, y) = (700, 570) name = request.user.first_name + ' ' + request.user.last_name color = 'rgb(0, 0, 0)' draw.text((x, y), name, fill=color, font=font) image.save('course/static/course/images/Certificate'+str(course.id)+'.png') certimage = urllib.request.urlretrieve(static('course/images/Certificate'+str(course.id)+'.png')) course.certificate.save(os.path.basename(course.url), File(open(certimage[0], 'rb'))) course.save() return render(request, 'course/certificate.html', {'image':course.certificate,'msg':'Error did not occur'}) This is the model: class My_course(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) course = models.ForeignKey(Course, on_delete=models.CASCADE) payment = models.ForeignKey(Payment, on_delete=models.CASCADE, blank=True, null=True) certificate = models.ImageField(blank=True, null=True) -
kubernetes create a persistent volume and use in my django app
I wouldd to create a persistent volume on my kubernetes (gcp) cluster and use it in my django app as , for example, media folder. On my kubernetes side i do: First create a volumes claim: apiVersion: v1 kind: PersistentVolumeClaim metadata: name: pvc-zeus namespace: ctest spec: accessModes: - ReadWriteOnce resources: requests: storage: 5Gi , then in my deployments.yaml i create a volume and associate to the pod: apiVersion: apps/v1 kind: Deployment metadata: name: django namespace: ctest labels: app: django spec: replicas: 3 selector: matchLabels: app: django template: metadata: labels: app: django spec: volumes: - name: cc-volume persistentVolumeClaim: claimName: pvc-zeus containers: - name: django image: gcr.io/direct-variety-3066123/cc-mirror volumeMounts: - mountPath: "/app/test-files" name: cc-volume ... then in my django settings: MEDIA_URL = '/test-files/' Here my Dockerfile: FROM python:3.8-slim ENV PROJECT_ROOT /app WORKDIR $PROJECT_ROOT COPY requirements.txt requirements.txt RUN pip install -r requirements.txt COPY . . RUN chmod +x run.sh CMD python manage.py runserver --settings=settings.kube 0.0.0.0:8000 when i apply volume claim on my cluster all was done (volume claim was created) but whe apply deployment.yaml no volume was created for the pods (also if i connect in bash to my pods, no folder test-files exist). How can i create a volume on my deployments pods … -
One specific module shows import error while other modules are imported in venv python
I have installed Django in venv and then installed suntimes, suntime and astral (all latest versions) in the same venv. But only Django is getting imported, other 3 modules are showing import error. I have a Mac with default python 2.7 and I have installed python 3.6 from python website long time back. PATH variable is set to 3.6 via nano editor and I have been using alias for python = python3. Django works fine with the alias or without alias, but other 3 modules just don’t get imported no matter I remove the alias too. I have tried putting the site_packages folder from my venv directly into my project folder and then the modules work fine, but this is not the right way. When I did like this and removed alias, the modules work with python3 and not the default python 2.7. So I am guessing the problem is somewhere with my venv and not PATH, but then why would Django get imported even with venv or without venv and others just won’t? I have tried basic troubleshooting of restarting the Mac and recreating venv and reinstalling Django and other modules but I am still back to where i … -
Django rest framework custom renderer in testing response
I'm trying to make my testing code in my django app. My app has a custom renderer class so the response will look like this: { "code": 422, "message": "Unprocessable Entity", "data": { "non_field_errors": [ "Unable to log in with provided credentials." ] } } My test code: class AuthenticationTestCase(TestCase): """Test login and registration""" def setUp(self): self.client = APIClient() def test_login_success(self): """Test success login""" payload = { 'email': 'test@test.com', 'password': 'password', 'is_active': True } create_user(**payload) res = self.client.post(LOGIN_URL, payload) self.assertEqual(res.data['code'], status.HTTP_200_OK) The client response only return: "non_field_errors": [ "Unable to log in with provided credentials." ] Question is, can I make my testing client response using my custom renderer class as well? -
Can we buld a django project with out source code?
I am building a django project in a business moto then I want to sold my project but I want to encrypt my source code. If any possibilities to build my project like (.pyc ,.exe or something else...). -
Access sql dump inside docker container django postgres
I'm using Django with Postgres database so I've created separate docker containers for Django and Postgres, now I want to share the dump file with my team but I'm unable to access the dump file, please let me know how can I access the dump file and after accessing it how can we import it using the container? docker-compose.yml version: "3.8" services: pgdb: image: "postgres" restart: always volumes: - postgres_data:/var/lib/postgresql/data/ ports: - "5432:5432" location inside db docker container -
Using absolute online location for Django templates
I am currently working on a django project, I have hosted it on heroku.And I don't really want to keep pushing to heroku unless really necessary, so i thought of pushing the templates to github , where i can change at ease and no extra zipping and host timer is needed. My problem is I am unable to set a link to a file online as template location in django. Is this possible? how to alter the following lines in settings.py TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [T], 'APP_DIRS': False, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] to get template from say https://gitcdn.link/cdn/KarthikRaja2k1/ieeesb_public/master/home_templates/500.html