Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django rest framework - Creating and returning multiple instances of an object instead of one
What I'm doing is posting a list of primary keys with other data to an endpoint and I'm creating an instance of an object per id that is in the list. The problem is that I want to then return all the objects I created but only one instance of the object is expected so it doesn't work. The data I'm posting to /convo/:id/members/ looks like this: { member_ids = [5,1,2,6] } Then in the view I'm passing the current user to my serializer (needed for the object I'm creating because it has an added_by field. I'm doing this by overriding perform_create. It looks ca like this: def perform_create(self, serializer): serializer.save(added_by = self.request.user) Then I'm overriding the create method in the serializer, take each id in the data received and create a member in the conversation. This is how that looks like ca (pseudocode) def create(self, validated_data): added_by = validated_data.pop('added_by') users = validated_data.pop('member_ids') added_members = [] for u in users: added_members.append(ConvoMember.objects.create(convo = x, user = u, added_by = added_by)) return added_members // this fails because its expecting only one instance of ConvoMember // but i still need to be able to do this somehow. How do I go about returning … -
Reverse foreign key relation in Django ORM
How to return all objects instances of a particular model that are being addresed as Foreign key by ANY object instance of a different model ? Lets say there is a model Item and a model ItemRequested that has foreign key relation to Item. How to print all Items that are being mentioned as foreign key in the ItemRequested table/model ? basically this is the SQL query that i want to execute in Django: select * from backend_item where id in (select id from backend_itemrequested); Obviously i want to avoid executing raw SQL commands from inside Django ORM -
Django Admin: How do I serialize data and store it in a model so that it can be restored by the user?
So what I have so far is a model called Registration and a model called Deleted Registration. I overrode the deleted_selected admin action for Registration so that instead of deleting the query, it would make Deleted Registrations. The thing is, it only saves the most important parts. Registrations have a few foreign keys and one-to-one fields. Apparently just saving the most important data isn't good enough and we want to serialize all the data in the selected registration models and store it with the deleted registration. This way, when you select a few deleted registrations, you can click on Restore deleted registrations I'll reiterate what I want so it's a little but more clear: I want to be able to "delete" registrations, where a new deleted registration is created. This way, they can view deleted registrations and, if need be, restore them. Here is the registration model: class Registration(models.Model): objects = RegistrationManager() # Used to identify this object securely in urls without giving the actual primary key uuid = models.UUIDField(default=uuid.uuid4, editable=False) sibs_event = models.ForeignKey("EventInstance", null=True, blank=True) date_registered = models.DateTimeField(auto_now_add=True) # sibs event for this registration sibs_weekend = models.ForeignKey(SibsWeekend, null=False) payment_delegation = models.OneToOneField("PaymentDelegation", null=True, blank=True, related_name="registration", on_delete=models.SET_NULL) Here is the deleted … -
Change ModelChoiceField Initial Value dynamically dependent on user selection
I have three ModelChoiceFields. After the user has set a value in the first checkbox (level), the initial value of the other two checkboxes should change. Views.py def index(request): form = SettingsForm() context = { 'form' : form } return render(request, 'app/settings.html', context) settings.html <form method="post"> {% csrf_token %} <table> {{ settings_form }} </table> <button type="submit" class="button">Apply</button> </form> forms.py class SettingsForm(forms.ModelForm): class Meta: model = Setting fields = '__all__' level = forms.ModelChoiceField( widget = forms.Select, queryset = Level.objects.all() ) language = forms.ModelChoiceField( widget = forms.Select, queryset = Language.objects.all(), initial = 0 ) country = forms.ModelChoiceField( widget = forms.Select, queryset = Country.objects.all() ) # I know I can do something like this in __init__: # self.fields['language'].initial = Language.objects.filter(level=self.level).first() # but that is not dynamically Example User selects level = 2, so language.initial should be set to 'German' and county.initial to 'Germany'. If user selects level = 1, so language.initial should be set to 'English' and county.initial to 'USA'. Can one of you guide me to this goal? -
Group list by specific key in that list
I have the following QuerySet result as a list: <QuerySet [{'answer__question__focus': 'hearing_about_the_event', 'name': 'Facebook', 'count': 1, 'total_salience': 1.0}, {'answer__question__focus': 'hearing_about_the_event', 'name': 'Instagram', 'count': 1, 'total_salience': 1.0}, {'answer__question__focus': 'hearing_about_the_event', 'name': 'friends', 'count': 1, 'total_salience': 1.0}, {'answer__question__focus': 'missing_event_information', 'name': 'Line-up', 'count': 2, 'total_salience': 2.0}, {'answer__question__focus': 'missing_event_information', 'name': 'food', 'count': 1, 'total_salience': 1.0}, {'answer__question__focus': 'reason_for_attending', 'name': 'girlfriend', 'count': 1, 'total_salience': 1.0}, {'answer__question__focus': 'type_of_people_attending', 'name': 'incomes', 'count': 3, 'total_salience': 2.26287645101547}, {'answer__question__focus': 'type_of_people_attending', 'name': 'people', 'count': 1, 'total_salience': 1.0}]> I now attempt to group this result in my Django application by answer__question__focus with Python. However, I struggle to get my data in the right order/format. Does anyone know how to do so in an efficient way? [ 'hearing_about_the_event': # question.pk [ { 'name': 'Leonardo Di Caprio', 'count': 4, 'salience': 3.434 }, { 'name': 'titanic', 'count': 5, 'salience': 1.12 }, { 'name': 'music', 'count': 3, 'salience': 1.12 } ], 'missing_event_information': # question.pk [ { 'name': 'Leonardo Di Caprio', 'count': 5, 'salience': 1.5 }, { 'name': 'titanic', 'count': 4, 'salience': 1.12 }, { 'name': 'music', 'count': 2, 'salience': 1.12 } ] ] -
Django framework python
I'm making a registration system for students in Django When the user enters the student number, the system retrieves all the student data. How can I work in this def search(request): if request.method== 'POST': srch = request.POST['srh'] if srch: match = Regiest_Form.objects.filter(Q(std_name__iexact=srch)) if match: return render(request, 'Regiest_app/search.html', {'sr':match}) else: messages.error(request,'no result') else: return HttpResponseRedirect('/search/') else: return render(request, 'Regiest_app/search.html') -
Need to add images and text in a single box in Django
I am currently working on creating a fully functioning blog app in Django, but at the moment, I seem lost on how to create a functionality whereby users can use a single textbox to add images, text and videos without creating separate models, which can then be formatted properly using spaces. An example of what I mean is the textarea in Wordpress where all you have to do is type or copy in your text, upload images and videos and format them using the space bar. -
How to display dynamic django data from views in html?
I have three django models: ProjectName,TaskBudget and TaskActualCost. ProjectName stores the project name (ie Project X). BudgetName stores the project_name(as a foreign key(FK)),budget_name and the total_budget and date for each task ie (Project X, Hotel,600),(Project X, Rental,500). '600' refers to $600. TaskActualCost stores each cost as it is incurred(itemized costs) (ie Hotel: 100, Rental: 50, Food:100) and its date. So it stores the 'task_name'(as FK),'budget_name'(as FK),actual_amount_used and date. ie (Project X,Hotel,100,10/03/2019),(Project X,Hotel,100,10/06/2019), (Project X,Rental,50,04/10/2019) I'm trying to render the 'Task Name', 'Task Budget' and 'Task Actual Cost' in an html table. 'Task Name' and 'Task Budget' are rendering correctly,but 'Task Actual Cost' only displays one amount for all cost item. Models: class ProjectName(models.Model): project_name = models.CharField('Name',max_length = 15,blank = False) def __str__(self): return self.project_name class TaskBudget(models.Model): project_name = models.ForeignKey(ProjectName,on_delete = models.CASCADE, null = True) budget_name = models.CharField('Budget Name'max_length = 50 total_budget = models.DecimalField('Total Budget',max_digits = 9,decimal_places=2) def __str__(self): return self.budget_name class TaskActualCost(models.Model): project_name = models.ForeignKey(ProjectName,on_delete = models.CASCADE, null = True) cost_description = models.ForeignKey(ProjectCost,on_delete = models.CASCADE,null=True) actual_used = models.DecimalField('Actual Used',max_digits = 15,decimal_places = 2) Views: def budgetview(request,project_id): budget_items = TaskBudget.objects.filter(project_name_id = project_id) for budget in budget_items: budget_id = budget.id actual_cost = TaskActualCost.objects.filter(cost_description_id=task_budget_id).aggregate(Sum(' actual_used')).get('actual_used__sum') or 0 print(budget.cost_description,":",actual_cost)#To test the output on StatReloader … -
Django send authenticated user to another django server with the same db
I know question sounds strange, I will explain it here. I have two Django servers which share the same DB. One is a light front/back server and the order one takes the heavy computing part. They share the same database. I am currently securing the web, and I have a couple of views in the light server requiring user login: @login_required() @permission_required('auth.can_upload', login_url='/accounts/login/') This works nicely in the light server since the user is authenticated (request.user returns a valid user in the views). The problem comes when I have to send the uploaded data to the other server since it is protected as I showed earlier, I do not know how to pass it the user that is already logged (user is valid since servers share the DB). # send an upload request using requests s = requests.Session() r1 = s.get(upload_process_url) csrf_token = r1.cookies['csrftoken'] a = s.post(upload_process_url, files=request.FILES, data={'csrfmiddlewaretoken': csrf_token}, headers=dict(Referer=upload_process_url)) I cannot ask every time the user and password or save them. The thing is I want to pass the user that is already logged in a request. The user was logged using the default django accounts/login page and authentication. Any clues and what could I try? I think … -
Log SQL queries even if DEBUG=False
This is my logging config in settings.py LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'console': { 'class': 'logging.StreamHandler', }, 'file': { 'class': 'logging.FileHandler', 'filename': os.path.join(BASE_DIR, 'logs', 'django.log'), }, }, 'loggers': { 'django': { 'handlers': ['file', 'console'], 'level': 'DEBUG', }, 'django.template': { 'handlers': ['file', 'console'], 'level': 'INFO', }, 'App': { 'handlers': ['file', 'console'], 'level': 'DEBUG', }, }, } There's a behavior that I can't explain: if I run with debug=True I can see all SQL queries being logged to the console, but when debug=False that doesn't happen, even if I don't change the configuration above. Why is this? How can I control in my logging config wether or not SQL queries are logged to the console? -
Django - Admin - Add link in a change_form that redirect to another change_form - set field with a value
I have open a post dealing with this subject but had no answer... to resume: I have a form #1 with a link when I click on this link, a new form #2 with a sub-form open now, I would like a field of the form #2 (open after clicking on the link of form #1) to be pre-filled with a value that come from the form #1 all this take place in the admin part of Django admin.py from django.contrib import admin from .models import Participante, Visite, Inclusion, BilanBiologique, ExamenBiologique class ExamenBiologiqueInline(admin.TabularInline): model = ExamenBiologique extra = 0 class BilanBiologiqueAdmin(admin.ModelAdmin): inlines = [ExamenBiologiqueInline,] class BilanBiologiqueLinkInline(admin.TabularInline): readonly_fields = ('examen', ) model = BilanBiologique extra = 0 fields = ('bio_ide', 'vis', 'bio_dat',) class VisiteAdmin(admin.ModelAdmin): inlines = [BilanBiologiqueLinkInline,] class InclusionAdmin(admin.ModelAdmin): readonly_fields = ('examen',) model = Inclusion fields = ('vis',('inc_tdr','examen'),) admin.site.register(Participante) admin.site.register(Visite, VisiteAdmin) admin.site.register(BilanBiologique, BilanBiologiqueAdmin) admin.site.register(Inclusion, InclusionAdmin) models.py from django.db import models from django.urls import reverse from django.utils.safestring import mark_safe from django.core.validators import RegexValidator class Participante(models.Model): pat_ide = models.AutoField(primary_key=True) pat_ide_prn_cse = models.CharField("Identifiant Princesse", max_length=14, validators = [ RegexValidator( regex='^SP[M|F][0-9]{11}$', message= 'L\'identifiant doit être au format requis', code='invalid_participant_id' ), ], unique=True ) pat_inc_dat = models.DateField("Date d'inclusion") def __str__(self): return f"{self.pat_ide_prn_cse}" class Visite(models.Model): vis_ide = … -
React Native with python
I want to make program using python(Django) and React Native. And I have some questions about how to connect them. I want pass text that user will write to Django server. I have question how to do this? I know the method fetch() in React Native but I do not know how to pass exactly that data the user have written. If in fetch I will put link like this: 'http://example.com/?dataId={dataToPass}' but how then I can get exactly this data in Django? Please help me) -
SyntaxError:invalid syntax
I am trying to run server in terminal but it returns a syntax Error, am using Django This is the command response File "C:\Program Files\Python37\lib\site-packages\django\__init__.py", line 22 '/' if settings.FORCE_SCRIPT_NAME is not None force_text(settings.FORCE_SCRIPT_NAME) ^ SyntaxError: invalid syntax '/' if settings.FORCE_SCRIPT_NAME is not None force_text(settings.FORCE_SCRIPT_NAME) -
how to fix dynamic image tag in html
I am rendering an image tag in HTML and i got error like {% for events in events %} <div> <h2><a href="">{{ events.event_title }}</a></h2> <p>published: {{ events.event_release_date }}</p> <p>{{ events.event_description|linebreaksbr }}</p> <img src={{ events.event_title_image }} alt="diagram" " /> views def index(request): return render(request, 'polls/home.html', {}) "model class name and function name should not be samm" def Event(request): events=Events.objects.filter(event_release_date__lte=timezone.now()).order_by('event_release_date') return render(request, 'polls/events.html', {'events':events}) i expect image need to display in web page -
Django ORM Group By Date Range
I've got a Django Model where users can be assigned a status for a specific period, e.g. 'Absent' from 2019-10-01 to 2019-10-20: class Status(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='statuses') status = models.CharField(max_length=100, choices=status_choices) valid_from = models.DateField() valid_to = models.DateField() What I'm trying to calculate: the status for each user, for each week: Mr. A Week 1 Absent Mr. A Week 2 Present Mr. A Week 3 Present Mr. B Week 1 Absent Mr. B Week 2 Absent Mr. B Week 3 Present The only thing I can come up with, is to create a for loop and iterate over all the dates that I want to include: for date in dates: Status.objects.filter(valid_from__lte=date, valid_to__gt=date).values('user__username', 'status')[:1] But as one can imagine, it creates way too many queries.. anyone that knows a way to to this in a single ORM query? -
How can I use pagination when I am using a form to input a date and submitting that form sends a post request and pagination accepts get request?
I am using django to display a webpage. I want to display details of files from database. These files can be of any number. I am using a form to input a date from HTML file which is accepted by a django view function. This function checks if the request is of type POST and returns the data between the mentioned date. Now when I use pagination to display these pages, pressing the next doesn't show anything as this time the request gets changed to GET. In my django view function, data is fetched in a list. Every file's data is in a list. So, all the data consists lists of lists. How will I be able to display these lists using pagination without sending the requests again. Is it possible to do so? -
How to add custom permissions on GET,POST,PATCH,DELETE separately in function based view Django
I am working on a project which has several user types like Admin,coordinator,sub-coordinator and each user can work as a different role in different division. Eg. user A can be a coordinator in DIVISION XX then A can be a admin in DIVISION YY but he cannot have a same role in same division. I am planning to write custom permissions and roles for this. what I have written is something like this: def coordinator(request, uid): if request.method == 'GET': //some logic if request.method == 'POST': //some logic if request.method == 'PATCH': //some logic if request.method == 'DELETE': //some logic what i dont want to do is the below approach: def coordiantor_delete(request, uid): if request.method == 'DELETE': def coordiantor_detail(request, uid): if request.method == 'GET': def coordiantor_create(request): if request.method == 'POST': def coordiantor_update(request, uid): if request.method == 'PATCH': Is there a way to add permissions to specific HTTP methods of a view function without splitting it in various views. Because I only want to have one API endpoint like /coordinator/ and /coordinator/id/ which should support above HTTP methods but with permissions like admin can also delete coordinator from a division and a coordinator himself can also leave a division and no … -
Django channel - logged in but self.scope['user'] is AnonymousUser
I am trying to create a chatweb using django-channel. Right now i am doing the checking user online -offline. When i check the current user it is AnonymousUser. The routing for check user online-offline is localhost:8000/new_user/ In the routing i used AuthMiddlewareStack: source routing from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, URLRouter import chat.routing application = ProtocolTypeRouter({ # (http->django views is added by default) 'websocket': AuthMiddlewareStack( URLRouter( chat.routing.websocket_urlpatterns, ) ), }) chat app routing from django.urls import re_path from django.urls import path from . import consumers websocket_urlpatterns = [ re_path(r'ws/chat/(?P<room_name>\w+)/$', consumers.ChatConsumer), re_path("new_user/", consumers.NewUserConsumer), ] code consumer.py class NewUserConsumer(AsyncJsonWebsocketConsumer): async def connect(self): print('connect') user = self.scope['user'] print(user) # This print out AnonymousUser await self.accept() await self.channel_layer.group_add("users", self.channel_name) print(f"Add {self.channel_name} channel to users's group") user = self.scope['user'] if user.is_authenticated: await self.update_user_status(user, True) await self.send_status() async def receive_json(self, message): print("receive", message) async def disconnect(self, close_code): await self.channel_layer.group_discard("users", self.channel_name) print(f"Remove {self.channel_name} channel from users's group") user = self.scope['user'] if user.is_authenticated: await self.update_user_status(user, False) await self.send_status() async def send_status(self): users = User.objects.all() html_users = render_to_string("chat/new_user.html", {'users': users}) await self.channel_layer.group_send( 'users', { "type": "user_update", "event": "Change Status", "html_users": html_users } ) async def user_update(self, event): await self.send_json(event) print('user_update', event) @database_sync_to_async def update_user_status(self, user,status): return ChatUser.objects.filter(username_id=user.id).update(status=status) … -
Check if variable exists in template, without causing errors in loggers if it doesn't
I have enabled 'level': 'DEBUG' in LOGGING in settings.py. I'm aware that the proposed solutions to check if a variable exists is using the if template tag {% if variable %} This is proposed in the documentation and questions asking how to check if a variable exists are closed as off-topic and pointed in that direction. Another solution offered here is to compare with None. {$ if variable is not None %} however, in both cases, although it works fine on the user end, the logger saves that as a KeyError, cluttering my log files. How can I avoid this? -
How can I install drivers for MSSQL in CloudFoundry?
I am trying to host Django application on CloudFoundry. The application uses MSSQL in backend. After the application's state changes to "started", When I browse the URL I get ERROR: Exception Value: ('01000', "[01000] [unixODBC][Driver Manager]Can't open lib 'ODBC Driver 13 for SQL Server' : file not found (0) (SQLDriverConnect)") I have followed a Solution for this error here: Pivotal/Django settings for user provided MSSQL database But, still not able to resolve this. The path is not getting set correctly for the driver. How can I resolve the error? -
Serve django media files locally in Development environment
I use Amazon S3 to store my media files in production using boto3 package, but I don't want to create a bucket for a local development environment. So I was wondering if there is a way to serve media files locally. My storage related settings: if USE_S3: # aws settings AWS_ACCESS_KEY_ID = os.environ.get('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = os.environ.get('AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = os.environ.get('BUCKET_NAME') AWS_S3_REGION_NAME = os.environ.get('BUCKET_REGION') DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' STATIC_URL = '/django_static/' STATIC_ROOT = os.environ.get('DJANGO_STATIC_ROOT') MEDIA_URL = '/media/' if not USE_S3: MEDIA_URL = "http://localhost:8000" + MEDIA_URL MEDIA_ROOT = os.path.join(BASE_DIR, 'media') In urls I added this: urlpatterns = [ # usual urls... ] if not settings.USE_S3: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) It turns out that static method returns empty array if its first parameter has 'http' inside, meaning that I can not use it for serving from my server. If you have faced the same issue and solved it or you know where to look up the solution, plz let me know. -
Give style value from database django
I want to give my progress bar a value from the value that I saved in the my model, but I have a syntax error and don't know how to solve it. the status field is an intfield so when I print x.status outside the class progress-bar I get for example 10 {% for x in info %} <div class="progress mt-2"> <div class="progress-bar bg-warning" style='width:{{x.status}}%;'>In Progress</div> </div> {% endfor %} -
'>=' not supported between instances of 'NoneType' and 'float'
I want to run my code, however, I keep on getting error messages. It is about a form field in which they type in their value. If the value is within a specific range, they'll get 1 Euro. The code is: class Guess(Page): form_model = 'player' form_fields = ['guess'] def is_displayed(self): return self.round_number == 2 def vars_for_template(self): if self.player.guess >= 11.25 and self.player.guess <= 13.75: self.player.cumulative_guthaben = self.player.cumulative_guthaben + 1 else: self.player.cumulative_guthaben = self.player.cumulative_guthaben return { 'current_credit': self.player.cumulative_guthaben, 'anzahlspieler': Constants.number_of_players, 'round_number': self.round_number,} I do know that it is a type error, but I was not successful in fixing it -
Why form field didnt save correct?
I am trying to automatically convert the first character of the model form field to upper case, but the original value is saved. class TechnologyCreatePopup(CreateView): model = Technology form_class = TechnologycreateForm template_name = 'technology_create.html' def form_valid(self, form): """If the form is valid, save the associated model.""" self.object = form.save(commit=False) if form.cleaned_data['name'][0].isupper(): self.object.save() else: name = form.cleaned_data['name'] c_name = name[0].capitalize() + name[1:] print(c_name) ---> print me name with uppercase! form.cleaned_data['name'] = c_name self.object.save() return HttpResponse( '<script>opener.closePopup(window, "%s", "%s", "#id_technology");</script>' % (self.object.pk, self.object)) I also think that this is not a nice solution (I mean using slices, an additional variable and string concatenation). Maybe there is a more interesting way? -
Django rest framework: how to fetch a foreign key based on a specific field (= not id)
I have this relation that works perfectly. The only problem is that DRF filters TaskAppointmentState based on its pk (or id). I would like to filter on another field: not state. To be more precise, instead of doing instance.status_id = state.id in the following code, I would like to do this pseudo code instead: instance.status_id = "SELECT id FROM TaskAppointmentState WHERE state=request.GET['state'] class TaskAppointmentStateSerializer(BaseSerializer): class Meta: model = TaskAppointmentState class TaskAppointmentSerializer(BaseSerializer): owner = SerializerMethodField() performer = SerializerMethodField() state = TaskAppointmentStateSerializer(required=False) @staticmethod def get_owner(obj): return BaseSerializer.get_person_description(obj.owner, None) @staticmethod def get_performer(obj): return BaseSerializer.get_person_description(obj.performer, None) def update(self, instance, validated_data): try: state = validated_data.pop('state') instance.status_id = state.id raise Exception("WWWWWWOOOOOOOOOOOOOOOORKED") except KeyError: pass # ... plus any other fields you may want to update return instance class Meta: model = TaskAppointment fields = ['id', 'owner', 'performer', 'date_start', 'date_end', 'agenda', 'state'] read_only_fields = ['id', 'owner', 'performer', ]