Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Capturing users site coming from
I am trying to capture the website the user is coming from on a django app.... I have an anchor link on SITE A.COM (<a href='www.b.com'>Click here</a>) So on site B.COM I would like to know the user is coming from site A.COM.... Some analytics tool are able to capture it, but I am not sure how to do it... I am trying to captur it with the request on the view with: def myView(request): print(request.META.items()) And my output has no clue on the other domain! I have a Django app behind AWS Load Balancer, so not sure whats possible with that. I appreciate any help -
Starnge problem migrating database to the django psycopg
I have strange problem with my database... It is postgresql, any help would be awesome! I did following commands in terminal, I'm transfering from windows to centos 7 server: [ [/home/pro]]# source s_project/bin/activate (s_project) [ [/home/pro]]# cd projects (s_project) [ [/home/pro/projects]]# cd sc (s_project) [ [/home/pro/projects/sc]]# python3 manage.py makemigrations No changes detected (s_project) [ [/home/pro/projects/sc]]# python3 manage.py migrate Operations to perform: Apply all migrations: admin, auth, contenttypes, sessions Running migrations: Applying auth.0012_alter_user_first_name_max_length...Traceback (most recent call last): File "/home/pro/s_project/lib/python3.8/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) psycopg2.errors.NotNullViolation: null value in column "id" violates not-null constraint DETAIL: Failing row contains (null, auth, 0012_alter_user_first_name_max_length, 2020-08-25 17:53:12.869298+00). I would delete this row from database or would give an id to it. But the problem is, that is no where to find in my database... I suppose it is to be in django_migrations table, by the data of it... but it's not there. What could I do about it? It looks like discrepancy... It looks like database tried to set today's data of changes in migrations in 0 record/raw... Because I have logs from 1 to 24... which were made long time ago... How to fix it... I have fogged understanding of how to... Either … -
Problem with migrating a django server (syntax error)
I am trying to make a django server for a sociometric badge (https://github.com/HumanDynamics/openbadge-server) for our university's project. The code (and the whole badge) has been done by someone else and I have not myself changed anything. I am able to build the server but when trying to migrate or create a superuser, I get a syntax error. I've been trying to troubleshoot it by myself but I have very limited knowledge of python, django and Ubuntu so I'm probably missing something. I tried asking the original developer but he is busy with other stuff so haven't gotten a reply but as I have to get the project going, I'll try asking here. The error implies an error in the line 44 of /usr/local/lib/python2.7/site-packages/pkgconf/init.py but I cannot find the file so I cannot check it. In fact, the whole site-packages folder is empty so I wonder if I have installed modules in a wrong way? The code is written in python2.7 so I also wonder if the python2.7 being EOL could cause issues? It has already broken some parts, mainly how to get some of the modules. The code and docker files used in this project can be found here: https://github.com/HumanDynamics/openbadge-server … -
Django static files not being served by amazon s3 even though all the instructions have been strictly followed
This is my first time ever on this platform, so please don't mind me if I am breaching any rules. I just finished building my first django project and I am using an amazon s3 bucket to serve media and static files. I have deployed the app onto heroku but static and media files are not being loaded. When I inspect the page, I see that it is throwing a 403 error. All the policies of my bucket have been set as prescribed in the documentation. below is a picture of my relevant setting.py settings .py -
Create flexbox container one after another horizontally
I am trying to create 2 flexbox containers one after the other, I have applied a number of classes combination to make this work. Flexbox gets created but when I scroll, the lower one goes below upper one. The output is as shown here: Current Scenario Output. My requirement is those 2 horizontal bars to be fixed and one after another, irrespective of scrolling. <!DOCTYPE html> <html> <head> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous"> <link rel="stylesheet" type="text/css" href="{% static 'personal/mystyles.css' %}"> </head> <body> <div class="d-flex flex-column flex-md-row align-items-center pt-1 px-md-4 mb-3 border-bottom shadow-sm sticky-top" style="background-color: #80ccff;"> <h5 class="my-0 mr-md-auto font-weight-normal"> <p>Hello, User </p> </h5> <nav class="my-0 my-md-0 mr-md-3"> <a class="p-2 text-dark" href=""><b>Home</b></a> <a class="p-2 text-dark" href=""><b>Account</b></a> <a class="p-2 text-dark" href=""><b>Logout</b></a></p> </nav> </div> <!--This div will be used in different html file and first div will be included using 'include' keyword of django. --> <div class="d-flex flex-column flex-md-row align-items-center pt-5 px-md-4 border-bottom shadow-sm sticky-top" style="background-color: #80ccaa;"></div> </body> </html> -
Using a postgres docker as a database for django || Launching dockers before build of another one in the docker-compose.yml file
I know there have been similar questions on this site, but the answers to these are sadly outdated. So I have a django application and i want to use postgres as the underlying database. Additionally a want to separate both programs in separate dockers. Now the docker docs have a way to do it, but sadly it seems to be outdated: link The problem appears when i call manage.py migrate in the docker build function which is being run by the docker compose file. But i get the error that the host 'db' is unknown/invalid. Compose excerpt: services: db: image: postgres restart: always volumes: - DataBase:/var/lib/postgresql/data environment: - POSTGRES_DB=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres ports: - "5432:5432" app: build: FehlzeitErfassungProject restart: always volumes: - Logs:/app/logs - Backups:/app/Backups - Media:/app/MEDIA ports: - "5432:5432" depends_on: - db app dockerfile: FROM ubuntu WORKDIR /app ADD ./requirements.txt ./ RUN apt-get update && \ apt-get upgrade -y # getting tzdata to shutup ARG DEBIAN_FRONTEND=noninteractive ENV TZ=Europe/Berlin RUN apt-get -y install tzdata #installing all needed porgramms RUN apt-get install -y uwsgi python3 python3-pip RUN python3 -m pip install pip --upgrade RUN python3 -m pip install -r requirements.txt COPY ./ ./ RUN ./manage.py migrate CMD ["uwsgi", "uwsgu.ini"] PS: … -
How to use django-jalali calendar in tempates?
Im new to Django and im trying to use django in a Persian app, therefore I need users pick i a date(jalali date) and send it to server. I've used django-jalali in admin area and its working fine, but I need to use this in front-end too. I've set locale to Asia/Tehran and Time Zone to fa but default date picker shows up Gregorian calendar. please help me with that. How can I solve this? -
Seeing Django debug 404 page despite having DEBUG = False
I have been following this tutorial along to deploy my first Django site and have successfully reached the section 'Configure Nginx to Proxy Pass to Gunicorn' which all seems to be working. My problem is that, despite my settings.py file containing the following: # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False I am still getting Django's debug=true 404 page with the following error: "You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page." I changed the file to DEBUG = False after completing the 'Configure Nginx to Proxy Pass to Gunicorn' step in the tutorial by pulling the change from my GitHub repository. Am I missing an additional step with Nginx in order to turn debug off and serve a standard 404 page? -
Get data from frontend (vuejs) save it in django database and pass the data to local running API service outside of django
I'm trying to save the frontend data from the frontend(Vuejs) and save it in Django database with models.models and then pass the data to another API service running locally To give you an idea I'm using Vuejs as my frontend and Django as my backend but I have another API service running that has the following API calls that I want to make use of Lenght:"100" prefix: "some text here" temprature:"0.7" the data between the "" above is just used as an example When you do get a response with the above filled in it looks like this {"text":"this is the response data requested bla bla bla bla"} My data save in my database when I post from the frontend to Django with status code 200 with a class-based view and when it saves the data into Django and pass it to the local running API service it sends with a status code 200 that is showed on the local API service but then responds with an error in Django status code 500from the local running API and doesn't deliver the requested information to the frontend. the error in Django is as follow from the local running API Internal Server … -
Django: Display each user's profile
I'm new to Django and I'm trying to display each user's profile. So far, I've made a sign-in, sign-up system. User can also update their profiles but I'm really not able to show each user's profile as soon as the logged in user clicks on the other user's username. I was wondering if I could do something with the primary key/ID of the each profile and use it to get access to every profile. A little help would be really appreciated! Here's what my code looks like: The URL to the Profile's page: path('profile/', views.userprofile, name='userprofile'), My view to view the profile: @login_required def userprofile(request): Post = post.objects.order_by('-created') return render(request,'social_media/profile.html', {'Post':Post,'Profile':Profile}) Model for user's profile: class profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) desc = models.CharField(max_length=1000) pfp = models.FileField(default='images/profile.jpg', upload_to='profile_pics/', blank=True) cover = models.FileField(default='images/profile.jpg', upload_to='cover_pics/', blank=True) Link that take me to the profile URL: <div class="user-pfp-name"> <a href="{% url 'userprofile' %}"> <img src="{% static 'social_media/images/profile.jpg' %}" style="height: 35px; width: auto; border-radius: 100%;" alt=""> {{ i.user.first_name }} {{ i.user.last_name }} </a> </div> and lastly here's my profile page: <div class="profile"> <div class="coverpad"> {% if Profile.cover %} <img src="{{ Profile.cover.url }}"> {% endif %} </div> <div class="profilepic"> {% if Profile.pfp %} <img src="{{ Profile.pfp.url … -
After configuring the aws xray getting AttributeError: 'Settings' object has no attribute 'ROOT_URLCONF' in django
ROOT_URLCONF = 'apps.urls' XRAY_RECORDER = { 'AWS_XRAY_DAEMON_ADDRESS': '127.0.0.1:2000', 'AUTO_INSTRUMENT': True, # If turned on built-in database queries and template rendering will be recorded as subsegments 'AWS_XRAY_CONTEXT_MISSING': 'RUNTIME_ERROR', 'PLUGINS': (), 'SAMPLING': True, 'SAMPLING_RULES': 'Apps', 'AWS_XRAY_TRACING_NAME': 'apps', # the segment name for segments generated from incoming requests # 'DYNAMIC_NAMING': 'apps.urls', # defines a pattern that host names should match 'STREAMING_THRESHOLD': None, # defines when a segment starts to stream out its children subsegments } -
I'm unable to add another model in my django project and getting this error
WARNINGS: ?: (2_0.W001) Your URL pattern '^ckeditor/' has a route that contains '(?P<', begins with a '^', or ends with a '$'. This was likely an oversight when migrating to d jango.urls.path(). No changes detected Main Settings.py urlpatterns = [ path('admin/', admin.site.urls), path('',include('tutorial.urls')), re_path(r'^ckeditor/', include('ckeditor_uploader.urls')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) -
Convert the Django website to a progressive web App Django?
Convert the Django website to a progressive web application. Based on the title, would it work on mobile devices? What do I need, due to the loss of connection through Wifi, in a private network. I run Python with Django and postgresql, when I run: python3 manage.py runserver_plus 0.0.0.0:8000, within the same network I can connect with my mobile device, but I want to use the web application in offline mode, I was reading something from IndexdDB, It will work? Does anyone know of a video or manual where I can orient myself "Service Worker"? -
Django / Pandas - Create Excel file and serve as download
I am trying to create an Excel file using pandas and serving it to the user as a downloadable file via Django. I put together some different answers on the topic that I found on here and ended up with this code: collection = [{"title": "something", "price": 34, "quantity": 23}, {..}] output = BytesIO() df = pd.DataFrame(collection, columns=['title', 'price', 'quantity']) writer = pd.ExcelWriter(output, engine='xlsxwriter') df.to_excel(writer, sheet_name='Sheet1') writer.save() output.seek(0) workbook = output.getvalue() response = StreamingHttpResponse(workbook, content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') response['Content-Disposition'] = f'attachment; filename={output_name}.xlsx' return response It all works well until I try to open the resulting file - I can an error saying that the file is damaged or that there is something wrong with the data-format. I suspect that it could have something to do with the data being binary? How can I resolve this issue? -
Passing context to django admin index page
I'm trying to create a table on django admin's index page, listing all users registered in a specific timeframe. I've managed to already edit the index page to include my table but I now want to populate the table. I tried declaring the extra_context variable but it still doesn't pass it to the template. I've been on this issue for days and still can't figure out what I'm doing wrong. This is my admin.py file from django.contrib import admin from django.contrib.auth.models import Group from django.contrib.auth.admin import UserAdmin from .forms import SignUpForm, EditUserForm from .models import CustomUser from django.urls import path from datetime import datetime, timedelta from django.utils import timezone class CustomUserAdmin(UserAdmin): list_filter = ['created_at',] list_display = ['username', 'email', 'created_at', 'is_active'] # index_template = 'admin/my_index.html' def time_threshold(num): num = int(num) thresh = datetime.now(tz=timezone.utc) - timedelta(hours=num) return thresh print(time_threshold(30)) def get_urls(self): urls = super().get_urls() custom_urls = [ path("user_metrics/", self.user_metrics), ] return custom_urls + urls def user_metrics(self, request, extra_context=None): extra_context = extra_context or {} user_24 = CustomUser.objects.filter(created_at__gt=time_threshold(730)) extra_context['users_in_past_24_hours'] = CustomUser.objects.filter(created_at__gt=time_threshold(24)) extra_context['users_in_past_week'] = CustomUser.objects.filter(created_at__gt=time_threshold(168)) extra_context['users_in_past_month'] = CustomUser.objects.filter(created_at__gt=time_threshold(730)) print(user_24) return super(CustomUserAdmin, self).user_metrics(request, extra_context=extra_context) admin.site.register(CustomUser, CustomUserAdmin) admin.site.unregister(Group) admin.site.site_header = "Savests Custom Admin" And this is my index.html file I have inside template/admin folder {% extends "admin/base_site.html" … -
Django Rest Framwork with natural_key (unique_together fields)
I have an model that closely resemble the one from the doc: https://docs.djangoproject.com/en/3.1/topics/serialization/#natural-keys i.e.: from django.db import models class PersonManager(models.Manager): def get_by_natural_key(self, first_name, last_name): return self.get(first_name=first_name, last_name=last_name) class Person(models.Model): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) birthdate = models.DateField() objects = PersonManager() class Meta: unique_together = [['first_name', 'last_name']] def natural_key(self): return (self.first_name, self.last_name) The doc then shows how to serialize: >>> serializers.serialize('json', [book1, book2], indent=2, ... use_natural_foreign_keys=True, use_natural_primary_keys=True) However I can't figure out how should I use it in a DRF Serializer class. I know, if I had a single unique field, I could use a SlugRelatedField But in my case, it's a combination of two fields, and there seems to be no solution in the Relations DRF page referenced above. I there are way to use unique_together natural_keys in DRF Serialization? Can I override serialize method to include required natural_key options? If so, could you please show? May be another way? Or is this something fundamentally impossible? Thanks in advance! -
Path not accesible in Django
This is maybe a very silly doubt, but i can't seem to figure out the reason for my code not working. So this is my Django Project file directory structure. Now, my targeted HTML file (index.html) is in aboutme/templates/ folder. I want to render it from the view.py in my aboutme app. Now my css and js files are inside "assets" folder which will be used by my index.html. But when i run the server the CSS files are not taking any effect on my index.html page. I have added the static files path in my settings.py of my project and added the static path in my index.html while trying to refer to the CSS and JS files, but still the changes are not reflected in the html file. Below is the snippet of my settings.py file: And below is the snippet of the index.html file from where i am trying to access the CSS files. -
Multiple independent forms in a DetailView
I have these simplified models. One Order can have multiple OrderItems. The OrderItems have a status ("A", "B" or "C"). class OrderItem(models.Model): STATUS_CHOICES = ( ("A", "A"), ("B", "B"), ("C", "C"), ) name = CharField(max_length=100) status = models.CharField(choices=STATUS_CHOICES, blank=False, default="A", max_length=1) def __str__(self): return self.name class Order(models.Model): items = models.ManyToManyField(OrderItem) def __str__(self): return self.pk Currently i use a DetailView, that shows one Order and loop through the OrderItems. Each OrderItem has a link to an UpdateView, to update the status: views.py class DetailOrder(DetailView): model = Order template {% for orderitem in object.items.all %} {{orderitem}} <a href={% url 'some-updateview' orderitem.pk %}>Update Status</a> {% endfor %} Now to my question: how would I approach that for each orderitem an independent form is displayed to update the status directly in the DetailView instead of following a link to an UpdateView. Is that even possible? Something like this, just to show the idea: {% for orderitem in object.items.all %} {{orderitem}} {{form}} {% endfor %} -
Django Rest Framework - Edit related object set
I have a listing system in my Django project, with a Tag object that attaches a list of Tags to a Listing. Each object has its own standard Viewset which is passed to router.register(). The current way I'm editing or creating Tags is through a POST or PATCH to /tags/. Ideally, I'd do this by doing a PATCH /listings/[id]/ with a JSON body of {"tags": [{"type": "foo", "text": "bar"}]}. I've provided a slightly simplified version of my code below. serializers.py class NestedTagSerializer(serializers.ModelSerializer): class Meta: model = Tag fields = ['text', 'type'] class ListingSerializer(serializers.ModelSerializer): tags = NestedTagSerializer(many=True, read_only=False) class Meta: model = Listing fields = ['tags', 'title', 'id'] models.py class Listing(models.Model): title = models.CharField(max_length=255) description = models.TextField() class Tag(models.Model): listing = models.ForeignKey(Listing, on_delete=CASCADE) text = models.CharField(max_length=255) type = models.CharField(max_length=255) Is there a nice way to do this with Django Rest Framework? -
How to append hardcoded data to a serializer?
I put together a Django API with a serializer, that returns a specific object, with one "feature" per row returned. Now, I want to append to that object a kind of metadata, a list. An example is worth a thousand words, so: My API returns: [ [{"id":43680,"type":"Feature","geometry":{"type":"Point","coordinates":[39.79839999999999,30.1316]}},"2017-05-02","2017-05-02T00:00:00","event type 1","sub event 35","This is a test"], [{"id":47444,"type":"Feature","geometry":{"type":"Point","coordinates":[39.79839999999999,30.1316]}},"2017-02-13","2017-02-13T00:00:00","event type 1","sub event 24","This is a test"] ] What I actually want is: [ [{"id":43680,"type":"Feature","geometry":{"type":"Point","coordinates":[39.79839999999999,30.1316]}},"2017-05-02","2017-05-02T00:00:00","event type 1","sub event 35","This is a test"], [{"id":47444,"type":"Feature","geometry":{"type":"Point","coordinates":[39.79839999999999,30.1316]}},"2017-02-13","2017-02-13T00:00:00","event type 1","sub event 24","This is a test"], "fields": [ {'name': 'location', 'type': 'geojson', 'analyzeType': 'GEOMETRY'}, {'name': 'event_date', 'type': 'date', 'analyzeType': 'DATE'}, {'name': 'event_time', 'type': 'time', 'analyzeType': 'DATETIME'}, {'name': 'event_type', 'type': 'string', 'analyzeType': 'STRING'}, {'name': 'sub_event_type', 'type': 'string', 'analyzeType': 'STRING'}, {'name': 'notes', 'type': 'string', 'analyzeType': 'STRING'} ] ] I have tried a few methods to add that additional data to my serializer. I tried a "def save(self)" in the serializer class but it is not being called. I tried a "perform_create(self, serializer)" in the views.py but again, not called. I tried to manually append to the serializer.data in the views, but got "TypeError: 'property' object is not iterable" in response when trying to do "list(serializer_class.data)" or "mydict.update(serializer_class.data)" wheer mydict had my additional row. … -
Django get the list of checked checkbox from and process in views.py
I have a checkbox in template and want to get the lit of value from checked checkbox for rendering to pdf in views.py. Do I need to create a form for it? No idea how to combine it. html: {% for order in orders %} <div class="mb-3"> {% for item in order.items.all %} <input type="checkbox" name="item_checkbox" value="{{ item.item.id }}" >{{ item.item.product_name }}<br> {% endfor %} </div> <a href="{% url 'generate_pdf' id=order.id %}" class="btn btn-primary" target="_blank">PDF</a> {% endfor %} How do I get the checkbox value and pass it to views.py? pdf redering in views.py def generate_to_pdf(request, id): order = get_object_or_404(Order, id=id) time_now = timezone.now() template = get_template('invoice.html') context = { 'order': order, 'time_now': time_now } template.render(context) pdf = render_to_pdf('invoice.html', context) return HttpResponse(pdf, content_type='application/pdf') Should I do the Form post method in below funcion for get the value from html? views.py for the above html: def order_admin(request): orders = Order.objects.all().order_by('-id') context = { 'orders': orders, } return render(request, 'product_admin.html', context) -
Gracefully stopping celery tasks
I am using celery for async processing along with Heroku. I would like to be able to determine when Heroku sends SIGTERM prior to shutting down (when we are deploying new code, setting env vars, etc) in specific tasks. This will allow us to do any clean up on long running tasks greater than 10 seconds. I understand that we should strive for short idempotent tasks, but the data we are dealing with is too large to get to that level. I have ran into the following doc: https://devcenter.heroku.com/articles/celery-heroku#using-remap_sigterm But the documentation is lacking, and without much context. If someone could give me an example of how to handle this, I would greatly appreciate it! -
Add dataEmptyMessage in FusionCharts Django
How can I display status and error messages that can be set for any chart in the Django FusionCharts constructor? -
Use of Django Serializers
I have this endpoint which return list of dictionaries. step 1 :- def db_data: return list(table_name.objects.all().values()) The same can be achieved by DRF serializers(Django Rest Framework) as follows. step 2 :- serializers.py from rest_framework import serializers from .models import table_name class IdMetricsSerializer(serializers.ModelSerializer): class Meta: model = table_name fields = '__all__' views.py from rest_framework import generics from models import table_name from serializers import IdMetricsSerializer class IdMetricsView(generics.ListAPIView): queryset = table_name.objects.all() serializer_class = IdMetricsSerializer If step1 and step2 gives the same result, what is the use of django serializers? -
is there any length function for the Django Model Objects?
I've hard coded this 3 in my loop range because I was unable to get the actual length. I tried listing the available features but didn't found any print(dir(Todo_Item.objects)). Maybe is there any other better way to iterate over the object and stop when it ends? This is my code with hard coded 3 in loop range. def home_view(request): display_list = [] for i in range(3): display_list.append(Todo_Item.objects.get(id=i+1).task) .......some code below as well....... My Todo app runs fine without any error but the only problem is this non-dynamic loop.