Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Problem running single django files from VS Code
I have a big Django project that I work in, and I have a problem when I try to run a single .py file from the terminal (I have the correct env set in my VSCode), and it usually breaks when trying to import a module (another django app). When I try to run the same file from PyCharm I have no issues and runs perfectly (using the same env) Haven't tried much, I have no idea where to start to try and tackle this issue, all I find in google is people using the wrong env, which is not the case here. -
How can i push object value into array - javascript
This may seem like an easy question, but im stuck. Currently, I am passing an object over to my function, which in return is supposed to push an object's value to an array. As of now its not pushing INTO the array and it coming back as a count 0 and undefined if I try to get at the actual value explicitly. In my check file, i have a function call with a forloop that sends the object and the count for (let i=0; i< data.length; i++){ addtoList(i, data); } }); the forloop is looping through data returned from a Django object as such data = serialize("json", modelname.filter(username=...)) return HttpResponse(data) In my addto file, the actual function should handle adding the object to the list. var pushere = [] function addToList(i,data){ pushere.push(data[i].fields.title) console.log(data[i].fields.title) }; console.log(pushere) now i also logged a regular list to see the differences const testListt = ['a','b','v'] console.log(testListt) with that being said, how am i supposed to properly 'push' object values to an array, which is what i am needing before displaying it to the page. I've tried mapping objects with help from Mozilla Map and their help on Objects. When a user first logs in, it … -
add permissions to user on the serializer
i'm trying to add/update permissions for users by id on the serializer, but nothing changed (no add no update) and i dont get any errors so i can't know where is the problemes, i have tried those method and nothing works. thank u all. serializer (update): class UpdateSerializer(serializers.ModelSerializer): """Handle serialization and deserialization of User objects.""" # user_permissions = PermissionSerializer(many=True, write_only=True) # user_permissions = serializers.SlugRelatedField( # many=True, read_only=True, slug_field="id" # ) def get_user_permissions(self, user): return list(user.user_permissions.all().values_list("id", flat=True)) class Meta: model = User fields = [ "email", "password", "tel", "first_name", "last_name", "registration_id", "avatar", "is_deleted", "user_permissions", ] extra_kwargs = { "is_deleted": {"write_only": True}, "password": {"write_only": True}, } # override the update method to save the data def update(self, instance, validated_data): """Perform an update on a User.""" password = validated_data.pop("password", None) # permissions_list = self.get_user_permissions() # permissions = Permission.objects.filter(id__in=permissions_list) permissions = self.request.data["user_permissions"] # permissions = Permission.objects.filter(id__in=Permission.objects.all()).values instance.user_permissions.set(permissions) for (key, value) in validated_data.items(): setattr(instance, key, value) if password is not None: instance.set_password(password) instance.save() return instance user view: class UpdateUserView(generics.RetrieveUpdateAPIView): permission_classes = [IsAuthenticated] serializer_class = UpdateSerializer queryset = User.objects.all() def update(self, request, *args, **kwargs): instance = self.get_object() serializer = self.serializer_class(instance, data=request.data, partial=True) if serializer.is_valid(raise_exception=True): self.perform_update(serializer) return Response(serializer.data) if getattr(instance, "_prefetched_objects_cache", None): # If 'prefetch_related' has been … -
Why does the NoReverseMatch error pop up when trying to paginate my django website?
I have a list of data from my models that I would like to paginate as it looks flooded on one singular page and it generally takes a longer time for the page to load. However, when I tried to use a paginating method, it doesn't seem to work in my code. What I've already done for my code is: .../clubs/views.py class ClubListView(generic.ListView): model = Club paginate_by = 6 .../clubs/urls.py from django.urls import path from . import views app_name = "clubs" urlpatterns = [ path('', views.ClubListView.as_view(), name="club-list"), path('<int:pk>/', views.ClubDetailView.as_view(), name="club-detail"), ] .../clubs/club_list.html {% block group_content %} <hr> {% comment %} Complete making group display. {% endcomment %} <p></p> <div class="col-md-8"> <div class="container"> {% for club in club_list %} <a class="list-group-item" href="{{ club.get_absolute_url }}"> <h3 class="title list-group-item-heading">{{ club.name }}</h3> <span>{{ club.slogan|safe }}</span> </a> <p></p> <br> {% endfor %} </div> </div> {% endblock %} {% block pagination %} {% if page_obj.has_previous %} <a href="{% url 'club-list' page_obj.previous_page_number %}"> Previous Page </a> {% endif%} {% if page_obj.has_next %} <a href="{% url 'club-list' page_obj.next_page_number %}"> Next Page </a> {% endif%} {% endblock %} However, it still gives me the error of NoReverseMatch of 'club-list' in my html page even though it is given from … -
How to configure media root file for multitenant app in django
I am creating multitenant app in django. I have chosen "Isolated database with a shared app server" from this website - https://books.agiliq.com/projects/django-multi-tenant/en/latest/isolated-database.html. I am using django-storages with AWS S3 bucket. The problem I could not figure out how to configure MediaRoot file for different database in django settings file. Is there any option in the settings file to use mediaroot with if condition. For example, if I am using db_1 use this mediaroot_1 elseif using db_2 , then use mediaroot_2. This is basically to charge the client as per the aws bucket usage. settings.py DATABASE_ROUTERS = ["core.router.TenantRouter"] DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', }, 'db_1': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db_1.sqlite3', }, 'db_2': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db_2.sqlite3', }, } #### the below I need if statement for different database #### I want to use bucket_1 for db_1 and so on AWS_STORAGE_BUCKET_NAME = os.environ.get("AWS_STORAGE_BUCKET_NAME") AWS_S3_CUSTOM_DOMAIN = f'{AWS_STORAGE_BUCKET_NAME}.s3.amazonaws.com' I tried to bring get_current_db_name() from the middleware.py into settings.py but I could not do it. I have tried django-tenant-schemas and other similar packages but I would like to go without 3rd party packages. ######## middleware.py import threading from .utils import tenant_db_from_request THREAD_LOCAL = threading.local() … -
How can I add Datatables functions(flexible search, flexible order by, pagination) to Django GraphQL Union?
I have multiple problems but they are related. I have inherited models, I use Union for them because I want to return all sub models. DjangoFilterConnectionField only accept DjangoObjectType I can't use it that's why. I was going to use it by all datatables columns. I thought override functions but I dont know where should I start. Do you have any idea about it? -
How to return a group by query via Django REST API?
I have a Django REST API which works perfectly when I want to query some data from the database. Here I have an example: views.py class ProductListAPIView(generics.ListAPIView): def get_queryset(self): # Collect data from products table and filter it queryset = Product.objects.filter(name="Ferrari", date__lte="2022-08-01") # <- Substitute with line below return queryset serializer_class = ProductSerializer authentication_classes = [authentication.SessionAuthentication, authentication.TokenAuthentication] permission_classes = [IsOwnerPermission] serializers.py from rest_framework import serializers from insert_data.models import Product class ProductSerializer(serializers.ModelSerializer): class Meta: model = Product fields = ["name","category","date","price"] The output is what I expect i.e. a json response with the content of the database. The problems arise when I try to group the queryset in order to return the average price of a product. By doing some research in the internet I noticed that I just need to substitute the line of code in the views.py script with this: Product.objects.filter(name=params['name'], date__lte=query.date).values('name','category').annotate(price_average=Avg('price')).order_by() I am pretty confident that this does the work, however the API returns an error which I do not know how to fix: AttributeError: 'int' object has no attribute 'pk' I totally have no idea what this refers to. Would you be able to suggest a smart and elegant way to return the average price of a product … -
how to fix the text so that its code is not written?
I created a blog site. But when I create some style for the text in the blog, it is then displayed on the main page. for example, I create bold text when creating a blog example picture and the main page displays the code ex pic2 how to fix this? I created this form using Django code: def add_blog(request): form = AddBlogForm() if request.method == "POST": form = AddBlogForm(request.POST, request.FILES) if form.is_valid(): user = get_object_or_404(User, pk=request.user.pk) category = get_object_or_404(Category, pk=request.POST['category']) blog = form.save(commit=False) blog.user = user blog.category = category blog.save() messages.success(request, "Blog added successfully") return redirect('blog_details', slug=blog.slug) else: print(form.errors) context = { "form": form } return render(request, 'add_blog.html', context) -
Django large CSV export with celery (async)
I am trying to export a CSV file which takes a while to generate. I have written the export CSV view which is successfully working, however I needed to adapt it to use celery for it to work in production with large data volumes. I have written the following code (mostly following https://thoslin.github.io/async-download-with-celery/): View: from tasks import export_report @staff_member_required() def export_status_report(request): task = export_report.delay() return render(request, "admin/poll_for_download.html", {"task_id": task.task_id }) # Check if task is finished def poll_for_download(request): task_id = request.GET.get("task_id") filename = request.GET.get("filename") if request.is_ajax(): result = AsyncResult(task_id) if result.ready(): return HttpResponse(json.dumps({"filename": result.get()})) return HttpResponse(json.dumps({"filename": None})) try: f = open("/path/to/export/"+filename) except: return HttpResponseForbidden() else: response = HttpResponse(file, mimetype='text/csv') response['Content-Disposition'] = 'attachment; filename=%s' % filename return response Task: @app.task def export_report(): date = datetime.now() date = date.strftime("%m/%d/%Y") filename = "reoport"+date+".csv" response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename= "{}"'.format(filename) payouts = Payout.objects.all() writer = csv.writer(response) #instantiate writer # write headers writer.writerow(['Field1', 'Field2', 'Field3']) for payout in payouts: list = [payout.field1, payout.field2, payout.field3] writer.writerow(list) return filename HTML <script> $(function(){ $.ajaxSetup({ cache: false, timeout: 360000 }); var url = "admin/poll-for-download/"; var i = 0; (function worker() { $.getJSON(url+"?task_id=", function(data){ if(data.filename) { var file_url = url+"?filename="+data.filename; $("#content").html("If your download doesn't start automatically, please click … -
Responses is returned as string and not as json - Python
I am trying to send back (get requests) a json but instead is sending a json as string "{"series": [{"name": "Count of Signups", "type": "column", "data": [4, 29, 10]}, {"name": "Average of signups over last 3 Months", "type": "line", "data": [NaN, NaN, 14.0]}], "labels": ["2020-06", "2020-07", "2020-08"]}" The disire result its the same but as json without the quotes (not as string) { "series": [{ 'name': "Count of Signups", 'type': "column", 'data': [4, 29, 10], }, { 'name': "Average of signups over last 3 Months", 'type': "line", 'data': [NaN, NaN, 14.0], }], "labels": ["2020-06", "2020-07", "2020-08"] } here is my code, my view in django: def Apiname(request): start_date = request.GET.get('start') end_date = request.GET.get('end') res = { "series": [{ 'name': "Count of Signups", 'type': "column", 'data': [], }, { 'name': "Average of signups over last 3 Months", 'type': "line", 'data': [], }], "labels": [] } df = pd.read_csv("mycsvfile.csv") mask = (df['MonthYear'] >= start_date) & (df['MonthYear'] <= end_date) df = df.loc[mask] for i, row in df.iterrows(): res['series'][0]['data'].append(row['Count_of_signups']) res['series'][1]['data'].append(row['signups_3mth_moving_average']) res['labels'].append(row['MonthYear']) return HttpResponse(json.dumps(res), content_type="application/json") I tried with to_dict to parse it to json but got the same results, the most strage is that i have another APIs with the same structure and they return … -
How can I paginate a dictionary inside my model?
I have a model and I have a single page for each one. class Group(models.Model): name = models.CharField(max_length=150, unique=True, db_index=True) active = models.BooleanField(default=False) members = models.OrderedDictField(default=dict, blank=True) This is an example of a representation of members. { "Jeon Heejin": "Designer", "Kim Hyunjin": "Baker", "Jo Haseul": "Musician" } However, when I render a page that represents a group, some groups have more than 100 members. So, I want to paginate it, but I am not getting how to paginate a dictionary that is inside a model. I also tried to paginate my Views, but nothing had changed. class GroupView(DetailView): template_name = "tailwind/group_detal.html" model = Group slug_url_kwarg = "group_name" slug_field = "name" context_object_name = "project" paginate_by = 2 def get_object(self, queryset=None): try: return Group.objects.get(name=self.kwargs.get("group_name")) except Group.DoesNotExist: raise Http404 def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) return context And this is the way that I am returning my items. <div class="md:grow mt-6 flex flex-col space-y-8 overflow-x-hidden"> {% for key, value in project.members.items %} <div class="overflow-x-auto"> <div class="mt-4 px-4 py-4 bg-gray-100 rounded-md font-mono"> <div class="overflow-auto"> {{ value | linebreaksbr }} </div> </div> </div> {% endfor %} </div> I am still getting all the items on the same single page, but my goal is to paginate … -
Altering command in Django not working , i want to alter database in django?
I added a new coloumn in table and than run command 1. python3 manage.py makemigrations 2. python3 manage.py migrate it show that nothing to migrate but when i entered data it is showing table not found this is my models.py class name(models.Model): name = models.CharField(max_length=255) role = models.CharField(max_length=255) salary = models.IntegerField() def __str__(self): return f"naam = {self.name} and Kaam = {self.role} and tankhwa = {self.salary}" and this is 0001_initial.py operations = [ migrations.CreateModel( name='name', fields=[ ( "id", models.BigAutoField( auto_created=True, primary_key=True, serialize=False, verbose_name='ID' ), ), ( "name", models.CharField( max_length=75, ), ), ( "role", models.CharField( max_length=75, ), ), ( "salary", models.IntegerField( ), ), ], ), ] -
django subclass not calling superclass (derived from modelform) clean method
I have a django form (formA) that inherits from modelform. In another app, I have a form that derives from that form (formB). This all works ok, including obtaining fields from the base class formA, but when the clean method is called, it doesn't call the formA clean method. Instead it skips formA, and calls django's modelform.clean. I can create a clean method in formB and this is called, but calling the super().clean() method also steps immediately into django's modelform.clean. Why might this be happening and what do I have to do to get the correct inheritance chain for the clean method? MTIA -
Django auth group permission handling
I use Django auth groups. The groups contain permissions(https://docs.djangoproject.com/en/4.1/ref/contrib/auth/#group-model). Now groups are assigned to users based on their actual role. In my test setup one group contains the permission (market.xyz). This group is assigned to the logged in user. In the debugger I see that the group permission is assigned (line 88) But if I call user.has_perm(per1) I get False (line 87) I can not make sense of this result. Is it necessary to activate the auth group mechanism? Do I have to add some additional Middleware? -
Django - analyze query execution time before it gets executed
I have a web interface(in django), through which I execute sql queries on different MySQL DB servers. Can we analyze query execution time(how much time it will take to return the result set) and the size of result set before it actually gets executed? I am using Django and MySQL DB. If cpu utilization is not much and the result set is in few KBs or bytes then query should get executed. -
Counting object views in a ListView
How is it possible to track how many times an object has been viewed if it is shown in a ListView? Imagine the Facebook feed, I want to know how many times users actually see each post on their feed, without opening it. My only thought so far is making an AJAX call for each post when it comes into the user's view, but that seems like it would be too resource heavy. Or should I aggregate the post views and only make the AJAX call once in a while with a list of posts that have been viewed? Or is there any other better way? (Doing it server-side is not ideal, because I want to know that a user actually read the post, so if they spent at least 2-3 seconds reading it). -
Django API rename Model column from existing DB
I have a column ag_id and I want to show it as foo_ag_id on the returning from endpoint. class Foos(models.Model): ag_id = models.ForeignKey('Bars', on_delete=models.CASCADE, db_column='bars_ag_id') class Meta: managed = False db_table = 'foos' I can't change the column name directly at the DB (external). FROM: { "ag_id": 1, }, TO: { "foo_ag_id": 1, }, -
Can I navigate between iPad web applications running on different systems withou show the Safari's url address bar?
I’m a software developer and I developed a web application for iPad using Django. I have four embedded systems connected to the same network and each system run his web application. I added the apple meta-tags for the full-screen mode, which remove the url address bar of Safari. My problem is that i need to navigate between the system’s pages, but, when I load the page of another system, Safari show the address bar. There is a way to don’t show the address bar when I load a page from another system if it has the apple meta-tag too? I tried to automatically touch the screen on "done" to remove the bar on load, but i cannot find a way to persistent remove this bar. -
Using django form to display data
Im new to django and am doing a django project where the user can book appointment slots. I want the user to input a date from a datepicker and then see the slots available to book on that day. I've tried using get requests but i keep getting errors. These are my models class Slot(models.Model): title = models.CharField(max_length=50) def __str__(self): return f'There is a slot at {self.title}' class Booking(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) slot = models.ForeignKey(Slot, on_delete=models.CASCADE) booking_date = models.DateField(("Date"), default=date.today) def __str__(self): return f'{self.user} has booked a session at {self.slot.title} on {self.booking_date}' Where I set slots as available times (9-10am etc) These are my views def BookingView(request): form = BookingForm(request.POST or None) if form.is_valid(): form.save() form = BookingForm() context = { 'form': form } return render(request, "bookingapp/book_form.html", context) def DateView(request): form = DateForm(request.GET or None) if form.is_valid(): form.save() form = DateForm() context = { 'form': form } return render(request, "bookingapp/date_form.html", context) These are my Forms This is the form I will use when the user is booking the slot. class BookingForm(forms.ModelForm): class Meta: model = Booking fields = [ 'user', 'slot', ] And this is the form I have so far for the user inputting the date. class DateInput(forms.DateInput): … -
Django requests : response much slower than function itself
My application has performance issues (worsening during busy hours). I've noticed following strange behaviour : When I set up the django enviroment: os.environ.setdefault("DJANGO_SETTINGS_MODULE", "backend.settings.test") django.setup() and try to run the function itself: views.dataCheckFunction (9277 is entry parameter) for i in range(1,10): zac=datetime.now() views.dataCheckFunction(9227) kon=datetime.now() delta=kon-zac print(delta) It runs as expected and each run takes from 0.7s to 1s However when I try to call same function via for i in range(1,10): zac=datetime.now() views.dataCheckFunction(9227) res = requests.get(url='https://profiextra-test.generali.sk/api/policy/9227/dataCheckFunction/', headers={'Content-Type':'application/octet-stream'}) kon=datetime.now() delta=kon-zac print(delta) The duration of each call is very volatile and it can be from 2.3s to 10s The function makes approx 200 database calls. To reduce the traffic I use Memcache Any idea what can be the cause ? Thanks -
How to implement custom authentication on function based view in django rest framework?
if i have created a custom Authentication class CustomAuthentication(BaseAuthentication): def authenticate(self, request): return super().authenticate(request) how do I implement this in function based views? Normally we can use decorators as from rest_framework.authentication import SessionAuthentication, BasicAuthentication @authentication_classes([SessionAuthentication, BasicAuthentication]) def view(request): pass -
Why am I getting a "Cannot return null for non-nullable field" error when doing a query?
**FOLDER STRUCTURE ** models.py import graphene from graphene import ObjectType, relay from graphene_django import DjangoObjectType from general.models import Character, Director, Episode class CharacterType(DjangoObjectType): pk = graphene.Int(source="pk", required=True) class Meta: model = Character filter_fields = { "name": ["exact", "icontains", "istartswith"], "character_species": ["exact", "icontains"], "location": ["exact"], "status": ["exact"], } fields = "__all__" interfaces = (relay.Node,) class EpisodeType(DjangoObjectType): pk = graphene.Int(source="pk") class Meta: model = Episode filter_fields = { "name": ["exact", "icontains", "istartswith"], "directed_by__name": ["exact", "icontains"], "aired_date": ["exact"], } fields = "__all__" interfaces = (relay.Node,) class DirectorType(DjangoObjectType): pk = graphene.Int(source="pk", required=True) class Meta: model = Director filter_fields = { "name": ["exact", "icontains", "istartswith"], "first_directed_episode__name": ["exact", "icontains"], "last_directed_episode__name": ["exact", "icontains"], "age": ["exact"], } fields = "__all__" interfaces = (relay.Node,) types.py import graphene from graphene import ObjectType, relay from graphene_django import DjangoObjectType from general.models import Character, Director, Episode class CharacterType(DjangoObjectType): pk = graphene.Int(source="pk", required=True) class Meta: model = Character filter_fields = { "name": ["exact", "icontains", "istartswith"], "character_species": ["exact", "icontains"], "location": ["exact"], "status": ["exact"], } fields = "__all__" interfaces = (relay.Node,) class EpisodeType(DjangoObjectType): pk = graphene.Int(source="pk") class Meta: model = Episode filter_fields = { "name": ["exact", "icontains", "istartswith"], "directed_by__name": ["exact", "icontains"], "aired_date": ["exact"], } fields = "__all__" interfaces = (relay.Node,) class DirectorType(DjangoObjectType): pk = graphene.Int(source="pk", required=True) … -
Django filters startswith
filters by creating a very simple site. There is a view and the user searches an object that I added as an admin. Views.py from django.shortcuts import render from .filters import * def home(request): myqs = Kati.objects.all() myFilter = SearchForm(request.GET, queryset=myqs) return render(request, 'home.html', {'myFilter':myFilter}) Models.py class Kati(models.Model): name = models.CharField(max_length=200) product = models.CharField(max_length=200) timi = models.CharField(max_length=200) Filters.py import django_filters class SearchForm(django_filters.FilterSet): class Meta: model = Kati fields = ['name','product','timi'] Html <form action='' method='get'> {{myFilter.form}} <button>OK</button> </form> {%for i in myFilter.qs%} <p>{{i.name}}</p> <p>{{i.product}}</p> <p>{{i.timi}}</p> {%endfor%} It works but is there a way to show an object just by typing the first letter. For example if the name is abcd show the object if you write ab. Like __startswith__. -
Django Celery show return value of task
i have a problem to display the return value of my celery task to the client. Redis is my result backend. I hope someone can help me. Thats the code: tasks.py: @shared_task def create_task(task_type): sleep(int(task_type) * 5) data={ 'test':'test' } return data The task should return the data after sleep for the given time. views.py: def home(request): return render(request, "async_project/home.html") @csrf_exempt def run_task(request): if request.POST: task_type = request.POST.get("type") task = create_task.delay(int(task_type)) return JsonResponse({"task_id": task.id}, status=202) @csrf_exempt def get_status(request, task_id): task_result = AsyncResult(task_id) result = { "task_id": task_id, "task_status": task_result.status, "task_result": task_result.result, } return JsonResponse(result, status=200) urls.py: from django.urls import path from . import views urlpatterns = [ path("tasks/<task_id>/", views.get_status, name="get_status"), path("tasks/", views.run_task, name="run_task"), path("home", views.home, name="home"), ] settings.py: # Celery settings CELERY_BROKER_URL = 'redis://localhost:6379' CELERY_RESULT_BACKEND = 'redis://localhost:6379' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' home.html: {% load static %} <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Django + Celery + Docker</title> <link rel="stylesheet" type="text/css" href="/staticfiles/bulma.min.css"> <link rel="stylesheet" type="text/css" href="{% static 'main.css' %}"> </head> <body> <section class="section"> <div class="container"> <div class="column is-two-thirds"> <h1 class="title">Django + Celery + Docker</h1> <hr><br> <div> <h2 class="title is-2">Tasks</h2> <h3>Choose a task length:</h3> <div class="field is-grouped"> <p class="control"> <button class="button is-primary" data-type="1">Short</button> … -
Using signals in django while extending user model
Basically I have 2 models that are 1 to 1 related with User model, First model in Employee and second one is Customer. I am also using signals for updates #Signal functions inside each model @receiver(post_save, sender=User) def create_customer(sender, instance, created, **kwargs): if created: Customer.objects.create(user=instance) @receiver(post_save, sender=User) def update_customer(sender, instance, created, **kwargs): if created == False: instance.customer.save() When I register a user it gets duplicated both in customer and employee. Is there a way to prevent this?