Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ImportError: cannot import name 'force_str' from partially initialized module 'django.utils.encoding' (most likely due to a circular import)
I went to my utils.py and added and replaced their corresponding fields this: from django.utils.encoding import force_str plus this def _camelize_django_str(s): if isinstance(s, Promise): s = force_str(s) return to_camel_case(s) if isinstance(s, six.string_types) else s But I still get the same error, what can I do? -
Django rest how to do pagination with PageNumberPagination
I wrote the following codes. But when I go to the url posts?page=1, it still shows all of the Post model objects. What should I do? settings.py REST_FRAMEWORK = { 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination', 'PAGE_SIZE': 10 } ursl.py path('posts', views.posts_view, name='posts_view') views.py @api_view(['GET']) def posts_view(request): posts = Post.objects.all() serializer = PostSerializer(posts, many=True) return Response(serializer.data) -
Django allauth return Account Inactive page after login
I am new to programming and I don't fully understand how allauth work and what exactly to do. I have an application where the user is inactive after signing up and he must click on the confirmation email so that he becomes active. I tried to configure allauth so that a user can also log in with google, but when a new user logs in he is redirected to a page that says Account Inactive.In admin I can see that it creates an account (inactive) and also an entry in social accounts but it doesn't generate a social application token. On the other hand when a user that already has an acount tries to log in with google it redirect to allauth sign up page. And so I don't understand how activation with allauth works. Did I make something wrong with my allauth configuration? Should I edit my login function or something else? -
upload a file and get celery progress bar using ajax in django
I want to upload a file, process it in a Celery task, and show a progress bar using AJAX. but I did not get the solution. Can you help me with this task? Views.py def index(request): cntx = {} if request.method == 'POST': form = RawFileAddressForm(request.POST, request.FILES) if form.is_valid(): file = request.FILES['file'] fs = FileSystemStorage() file_name = fs.save(file.name, file) task = process_file.delay(file_name=file.name) cntx['task_id'] = task.id # return render(request, 'index.html', cntx) return HttpResponseRedirect(reverse('get_task_info') + '?task=' +task.id) else: return render(request, 'index.html', {'form':form}) else: form = RawFileAddressForm() return render(request, 'index.html', {'form': form}) get_task_info file def get_task_info(request): if 'task' in request.GET: task_id = request.GET['task'] else: return HttpResponse('no job id given') task = AsyncResult(task_id) data = { 'state': task.state, 'result': task.result, } return HttpResponse(json.dumps(data), content_type='application/json') forms.py class RawFileAddressForm(forms.Form): file = forms.FileField() Task.py @shared_task(bind=True) def process_file(path, file_name): print('Uploading image...') sleep(10) fs = FileSystemStorage() instance = Tooltype(image=file_name) instance.save() fs.delete(file_name) print('Uploaded!') index.html <body> <h1>select your file to process it!</h1> <progress id="progress-bar" value="0" max="100" style="display:none; margin-bottom: 1em;"></progress> <form id="process-raw-data" action="" method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form }} <input type="submit" value="Submit" /> </form> {% if task_id %} <script type="text/javascript"> var taskid = "{{task_id}}"; var frm = $('#process-raw-data'); var pgrbar = $('#progress-bar'); get_task_info(taskid); function get_task_info(tid) { $.ajax({ type: 'get', url: … -
How to design to avoid duplicate column in two models that have the same ForeignKey?
I have the following models where a User has many Photo objects and many Album objects. However, after a User has added a given photo they may choose to put it in a single Album (a Photo does not have to have an album linked to it). They may also choose to take it out of the album and or put it in a different album. class User(models.Model): id = ... class Photo(models.Model): id = ... user = models.ForeignKey(User, ...) album = models.ForeignKey(Album, null=True...) class Album(models.Model): id = ... user = models.ForeignKey(User, ...) How do I get around the redundant user column (Album.user and Photo.user) when a Photo is associated with an Album to avoid db anomalies? I can't get rid of the user column on Photo since I wouldn't be able to get it if it is not linked to an album. The same goes for Album. I have some experience with normalizing tables but I don't know how to avoid this without using db constraints. -
Django: relation between permissions and group
Why this works: g = Group.objects.get(pk=1) p = g.permissions.first() Out[43]: <Permission: onboarding | controller | Can add controller> But this doesn't work: p.group AttributeError: 'Permission' object has no attribute 'group' When I do: p._meta.__dict__ I see: 'fields_map': {'Group_permissions+': <ManyToOneRel: auth.group_permissions>, 'group': <ManyToManyRel: auth.group>, 'User_user_permissions+': <ManyToOneRel: core.user_user_permissions>, 'user': <ManyToManyRel: core.user>} So my question is, why can't I do p.group ? -
Django ORM annotation to find how many objects have any related object
I am currently trying to find out what % of a set of objects have a related object with certain values. Specifically, I have a table of objects and a one to many relationship to a table of comments, and I am trying to figure out what percentage of those objects have comments in a specific length. Both of these tables are ETL output from a separate dataset to allow easier metric calculations. # Models class Data(models.Model): id = models.AutoField(primary_key=True) creator_id = models.IntegerField() # Not a real foreign key class DataCommenter(models.Model): do_id = models.ForeignKey(Data) creator_id = models.IntegerField() # Not a real foreign key short_comments = models.IntegerField() medium_comments = models.IntegerField() long_comments = models.IntegerField() From these models, I have some queryset annotations that are being performed to try and get the average as shown below: # QuerySet class DataQuerySet(models.QuerySet): def extensive_comments(self): """Get extensive comment raw selection.""" inner_query = DataCommenter.objects.exclude( creator_id=OuterRef("creator_id") ).filter( Q(medium_comments__gte=1) | Q(long_comments__gte=1), do_id=OuterRef("id") ) return self.annotate( raw_extensive_comments=Case( When( Exists(inner_query), then=1 ), default=0, output_field=FloatField() ) ) def annotate_period(self): """Annotation to allow average without aggregation.""" return self.annotate(period=Value(value=True, output_field=BooleanField())) The QuerySet is attached to the Data model and is used as follows: Data.objects.all().annotate_period().extensive_comments().values("period").annotate( extensive_comments=ExpressionWrapper(Avg(raw_extensive_comments) * 100, output_field=FloatField()) ) The data that we have … -
django chunk query set
i need to chunk my data for 8 items in every tr in my HTML file how can i do that in Django {% for pr in portfolio %} <td> <img src="{{ pr.logo.url }}" class="img-responsive" title="{{ pr.title }}"> </td> {% if forloop.counter %} </tr> <tr> {% endif %} {% endfor %} -
Multiple tables operation causes dead lock
When I was doing performance tunning on an api backended by django. I found it was easy to raise an error like this: dead lock found... Code causing deadlock(I've simplicified for clarity): @require_POST def create_sop_task(request): try: with transaction.atomic(): save_id = transaction.savepoint() db_tpl_obj = SopTemplate.objects.filter(id=template_id).values("type", "status").first() db_new_st = SopTask.objects.create(**req_args) for i, item in enumerate(message): SopMessage.objects.create(**kwargs) SopTemplate.objects.filter(id=template_id).update(version_time=version_time) SopTask.objects.filter(template_id=template_id).update(version_time=version_time) SopMessage.objects.filter(template_id=template_id).update(version_time=version_time) transaction.savepoint_commit(save_id) return JsonResponse({"code": 0, "msg": "success", "data": {"id": db_new_st.id}}) except Exception as e: # ... Manipulating order in transaction: create SopTask create SopMessage update SopTemplate update SopTask update SopMessage If tweak the order like this, everything goes well: create SopTask update SopTask create SopMessage update SopMessage update SopTemplate But I can not figure it why this will cause dead lock. Someone could explain that? I'll appreciate a lot. I am using MySQL 5.7 with isolution level: READ COMMITTED. -
How to create a django form field with html
at the moment the html page looks something like this: <form action="{% url 'sequence_details' %}" method="post"> {% csrf_token %} <div class="container pb-3"> <table class="table"> {{ form.as_table }} <tr><th><input type="text" id="extrafield"></th></tr> </table> </div> <div class="container"> <input type="submit" class="btn btn-primary" value="Download"> </div> </form> extrafield appears as a text field but any text entered into it does not get sent to the backend, i.e. the result of form.cleaned_data.get("extrafield") is always None, no matter what was entered. I would like to be able to customise extrafield and write my own html for it, which is why I'm not just adding it to the form object. How can I get the result of extrafield's input to show up in form.cleaned_data? -
Insert a foreign key in my database using django
I want to insert a foreign key from a campaign table in a task table.I want get this foreign key from the url. Here is my models : Campaign Model : class Campaign(models.Model): title = models.CharField(max_length=255) channel = models.CharField(max_length=255) start_date = models.DateField() end_date = models.DateField() Task Model : class Task(models.Model): title = models.CharField(max_length=255) description = models.CharField(max_length=255) task_manager = models.CharField(max_length=255) start_date = models.DateField() end_date = models.DateField() resource = models.ManyToManyField(Resource,related_name='resources') campaign = models.ForeignKey(Campaign,on_delete=models.CASCADE) And here is my view : def campaign_tasks(request,pk): tasks = Task.objects.all() managers = TaskManager.objects.all() context = {"tasks": tasks,"managers":managers} if request.method == 'POST': title = request.POST['title'] description = request.POST['description'] task_manager = request.POST['task_manager'] start_date = request.POST['start_date'] end_date = request.POST['end_date'] campaign_id = request.GET['pk'] Task.objects.create(title=title,description=description,task_manager=task_manager,start_date=start_date,end_date=end_date,campaign_id=campaign_id) return render(request,'CampaignManagement/campaign_tasks.html',context) -
How handle pip and pip cache in windows?
I'm stuck in pip installation process.. 1.how can ignore pip cache 2.how can remove all packages for pip 3.can pip/cache folder deletion is safe -
TypeError at /MultipleChoiceQuestions/ MultipleChoiceQuestions() missing 1 required positional argument: 'id'
def MultipleChoiceQuestions(request,id): # return HttpResponse("Hii Here loveQutes are available") post = MCQ.objects.filter() print(post) print(post[0]) question = MCQ.objects.get(pk=id) output = ', '.join([ print(q) for q in question]) # return render(request, "blog/blogHome.html", context) return render(request, "index.html",{'output': output} ) -
Special characters change when exporting django
I'm using django import export package and MySQL for the database. Everything works fine, except for one thing. When I exported, the data that has "special characters" changed. For example Château will be changed to Château. Even though, everything is displayed correctly in the admin. How can I fix this? Any solutions? Thanks. -
Get timezone by Country and State/Province in Python
Is there a way to retrieve timezone information based on Country and State/Province in Python? E.g. The United States and New York will get EST (Eastern Standard Time). If that's not possible or efficient, is there a way to get timezone based on Country and City instead? I'm using Python Django in my project. Thanks in advance. -
Cannot check if user is in specific queryset in template
I'm working on an app similar to twitter. I have pages with detail tweet and it's ancestors and descendants, and in template i want to check if current user have liked tweets which are displayed on the page. My tweet model is: class Tweet(MPTTModel): text = models.CharField(max_length=140, db_index=True) pub_date = models.DateTimeField(auto_now_add=True) likes = models.ManyToManyField(User, blank=True, related_name='liked_tweets') retweets = models.ManyToManyField(User, blank=True, related_name='retweeted_tweets') user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='tweets') parent = TreeForeignKey('self', null=True, blank=True, on_delete=models.CASCADE, related_name='children') In template i use if clause: {% if user in tweet.likes.all %} # do smth here {% else %} # do smth else {% endif %} Although i have access to user instanse in template with {{ user }}, if clause always returns false even if user in queryset. -
Update django model objects from editable dash data-table
I want to update my models by an editable plotly dash-table (populated by a dataframe, himself populated by sqlconnection with models) in Django but I don't know how to :/ You will see my trials in code comments, but obviously, it doesn't work. Any solution for this pls? Here a class in exemple in models.py (same structure for each class): class interventions_acm1(models.Model): date_debut = models.CharField(max_length=30, null=True) date_fin = models.CharField(max_length=30, null=True) titre_intervention = models.CharField(max_length=30, null=True) cout = models.CharField(max_length=30, null=True) responsable_acm = models.CharField(max_length=30, null=True) entreprise_exec = models.CharField(max_length=30, null=True) descriptif = models.CharField(max_length=150, null=True) And views.py which contain table and connection with models: from django_plotly_dash import DjangoDash import dash_html_components as html import dash_table import dash_core_components as dcc from dash.dependencies import Input, Output, State import pandas as pd from django.db import connection from django.db.models import Q from django.shortcuts import render from django.http import HttpResponse from .models import interventions_acm1, interventions_acm4, interventions_acm5, interventions_acm9, interventions_acm10 #from sqlalchemy import create_engine # Create your views here. def interventions(request): #table_data = table_donnees() app = DjangoDash('Tableau_intervention') Magasin_interventions_real = request.GET.get('Magasin_interventions_real') Annee_mois_dispo_interv = request.GET.get('Annee_mois_dispo_interv') #if Magasin_data_query != '': query = str(interventions_acm1.objects.all().query) if Magasin_interventions_real == 'ACM1': query = str(interventions_acm1.objects.all().query) elif Magasin_interventions_real == 'ACM4': query = str(interventions_acm4.objects.all().query) elif Magasin_interventions_real == 'ACM5': query = str(interventions_acm5.objects.all().query) elif Magasin_interventions_real … -
AttributeError: module 'django.db.models' has no attribute 'ArrayField'
hola tengo un problema al intentar crear una coleccion de colecciones en django dice que no reconoce AttributeError: module 'django.db.models' has no attribute 'ArrayField' from django.db import models class Link(models.Model): source = models.IntegerField() target = models.IntegerField() label = models.CharField(max_length=200) class Node(models.Model): ide = models.IntegerField() name = models.CharField(max_length=200) x = models.IntegerField() y = models.IntegerField() class Root(models.Model): links = models.ArrayField(model_container=Link) nodes = models.ArrayField(model_container=Node) class Graph(models.Model): root = models.ArrayField(model_container = Root) -
Error 404 was reported in the django tutorial [closed]
https://docs.djangoproject.com/zh-hans/4.0/intro/tutorial01/ Djangos official documentation for creating a voting application enter image description here enter image description here enter image description here -
Django: TemplateSyntaxError at /category/2/
1. Summarize the problem I great custom tag. In file news_tags.py from django import template from news.models import Category register = template.Library() @register.simple_tag() def get_categories(): return Category.objects.all() I called the tag in the sidebar.html file {% load news_tags %} {% get_categories %} <div class="list-group"> {% for item in categories %} <a href="{% url 'category' item.pk %}" class="list-group-item list-group-item-action">{{ item.title }}</a> {% endfor %} </div> This my folder structure My Error: TemplateSyntaxError at /category/2/ 'news_tags' is not a registered tag library 2. Describe what you’ve tried I looked at this question. But there was an error in an unclosed quote I looked at this question. I write in settings.py TEMPLATES.options.context_processors 'mainsite.news.template_tags.news_tags',. But error No module named 'mainsite.news' -
Django Question: How can i submit a form with logged in user as default?
After you sign up, you are prompted to the login page, and after you login, you are redirected to another page that contains a form used for gathering additional information about the new user. The problem is that the form doesn't submit if i don't specify the {{form.user}} instance in the html file. Probably because the user_id is not recognized by default. When i specify it, the form let me chooses from already existing users, and i would like it to go with the logged in user by default. models class AdditionalInfoModel(models.Model): objects = None skill_choices = (('Beginner', 'BEGINNER'), ('Intermediate', 'INTERMEDIATE'), ('Expert', 'EXPERT')) user = models.OneToOneField(User, on_delete=models.CASCADE) location = models.CharField(max_length=30, blank=True) assumed_technical_ski_level = models.CharField(max_length=30, choices=skill_choices) years_of_experience = models.PositiveIntegerField(blank=True) money_to_spend = models.PositiveIntegerField(blank=True) def __str__(self): return self.user.username the log in and sign up are done using standard django models -
TypeError: list indices must be integers or slices, not dict
I'm trying to return all the JSON data from the payload but its giving an error as TypeError: list indices must be integers or slices, not dict. When I print(request.data) it's just returning all the JSON data but when I do the for loop its giving the error Here, what I tried views.py: @api_view(['POST']) def SaveUserResponse(request): if request.method == 'POST': for i in request.data: print(request.data) auditorid =request.data[i]['AuditorId'] print('SaveUserResponse auditorid---', auditorid) ticketid =request.data[i]['TicketId'] qid = request.data[i]['QId'] answer = request.data[i]['Answer'] sid = request.data[i]['SID'] print('sid--', sid) cursor = connection.cursor() cursor.execute('EXEC [dbo].[sp_SaveAuditResponses] @auditorid=%s,@ticketid=%s,@qid=%s,@answer=%s,@sid=%s', (auditorid,ticketid,qid,answer, sid,)) result_st = cursor.fetchall() for row in result_st: print('sp_SaveAuditResponse', row[0]) return Response(row[0]) return sid JSON payload: [ 0: {AuditorId: 122, Agents: "", Supervisor: "", TicketId: "12111111", QId: 1, Answer: "2", SID: 3982,…} 1: {AuditorId: 122, Agents: "", Supervisor: "", TicketId: "12111111", QId: 2, Answer: "2", SID: 3982,…} 2: {AuditorId: 122, Agents: "", Supervisor: "", TicketId: "12111111", QId: 3, Answer: "2", SID: 3982,…} 3: {AuditorId: 122, Agents: "", Supervisor: "", TicketId: "12111111", QId: 4, Answer: "2", SID: 3982,…} 4: {AuditorId: 122, Agents: "", Supervisor: "", TicketId: "12111111", QId: 5, Answer: "5", SID: 3982,…} 5: {AuditorId: 122, Agents: "", Supervisor: "", TicketId: "12111111", QId: 6, Answer: "5", SID: 3982,…} 6: {AuditorId: 122, … -
Django dictionary for annotations works or not depending on the order of the most complex annotation and/or the aliases of the other annotations
So I came across this issue described in the title of this post. I have this dynamically created dictionary: dict= {'sale_qty': Sum('sale_qty'), 'sales_override': Sum(F('sales_override')), 'colab_ventas': Sum(F('colab_ventas')), 'Historia Ajustada': Sum(Case(When(sales_override=None, then=F('sale_qty')),When(sales_override__gte=0, then=F('sales_override'))))} This is the query: Venta.objects.values('item').annotate(**dict) and when I try to run it, it fails with error: Exception Type: FieldError Exception Value: Cannot compute Sum('<Case: CASE WHEN <Q: (AND: ('sales_override', None))> THEN F(sale_qty), WHEN <Q: (AND: ('sales_override__gte', 0))> THEN F(sales_override), ELSE Value(None)>'): '<Case: CASE WHEN <Q: (AND: ('sales_override', None))> THEN F(sale_qty), WHEN <Q: (AND: ('sales_override__gte', 0))> THEN F(sales_override), ELSE Value(None)>' is an aggregate BUT if I change the order of the elements in the dictionary moving the complex annotation 'Historia Ajustada' to the beggining it works just fine: dict= {'Historia Ajustada': Sum(Case(When(sales_override=None, then=F('sale_qty')),When(sales_override__gte=0, then=F('sales_override')))),'sale_qty': Sum('sale_qty'), 'sales_override': Sum(F('sales_override')), 'colab_ventas': Sum(F('colab_ventas')) } It also works fine if I keep the original order of the dictionary and change the aliases of the simple annotations like this (for example adding a '1' to the alias): dict= {'sale_qty1': Sum('sale_qty'), 'sales_override1': Sum(F('sales_override')), 'colab_ventas1': Sum(F('colab_ventas')), 'Historia Ajustada': Sum(Case(When(sales_override=None, then=F('sale_qty')),When(sales_override__gte=0, then=F('sales_override'))))} What could be the cause of this ? Is this a django bug or expected behaviour? I have to give special treatment to some parts of the … -
Save data into a postgres db with Serializer
My problem is that I am trying to save into a postgres db some arrays, but it seems that it does not work, since the db is empty. My models.py is as follows: from django.db import models from django.contrib.postgres.fields import ArrayField from django.contrib.auth import get_user_model CustomUser = get_user_model() class Event(models.Model): user_id_event = models.ForeignKey(CustomUser, on_delete=models.CASCADE, null=True) dr_notice_period = models.IntegerField(blank=True, null=True) dr_duration = models.IntegerField(blank=True, null=True) dr_request = models.FloatField(blank=True, null=True) class Result(models.Model): event_id_result = models.OneToOneField(Event, on_delete=models.CASCADE, null=True) hvac_flex = ArrayField(models.FloatField(blank=True, null=True)) dhw_flex = ArrayField(models.FloatField(blank=True, null=True)) lights_flex = ArrayField(models.FloatField(blank=True, null=True)) My serializers.py is as follows: from rest_framework import serializers from vpp_optimization.models import Event, Result class EventSerializer(serializers.ModelSerializer): class Meta: model = Event fields = ('__all__') class ResultSerializer(serializers.ModelSerializer): class Meta: model = Result fields = ('__all__') And my views.py as follows: from rest_framework.response import Response from rest_framework.decorators import api_view, permission_classes from rest_framework.permissions import IsAuthenticated from rest_framework import status from vpp_optimization.importer import DR_event_import_data from vpp_optimization.utils import optimization_solution from vpp_optimization.serializers import EventSerializer, ResultSerializer from vpp_optimization.models import Event, Result @api_view(['POST']) @permission_classes([IsAuthenticated,]) def event(request): serializer = EventSerializer(data=request.data) if serializer.is_valid(): serializer.save(user_id_event=request.user) return Response({"status": "success", "data": serializer.data}, status=status.HTTP_200_OK) else: return Response({"status": "error", "data": serializer.errors}, status=status.HTTP_400_BAD_REQUEST) @api_view(['GET']) def optimization(request): last_event = Event.objects.last() if not last_event: return Response({"res": "Object Event does not exists"}, status=status.HTTP_400_BAD_REQUEST) … -
Django FieldError at /admin/ in Multidropdown Filter
In the django i am geeting this error, my models.py class User(MasterDataBaseModel): user_name = models.CharField(max_length=255,verbose_name=_("username")) gender = models.ForeignKey(Gender, null=True, blank=True, on_delete=models.CASCADE, verbose_name=_("Gender")) the admin.py class Useradmin(DuplicateMixin, MasterDataBaseAdmin): form = forms.UserForm search_fields = ["user_name","Gender"] ordering = ["user_name"] list_filter = [ "users_name", ("Gender",MultiSelectDropdownFilter), ] list_display = [ "user_name", "Gender",] getting this error ,FieldError at /admin/registration/user/