Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django database model relationships
I need to work on something like grade viewing in my web app, for example, my model looks like this: class Subjects(models.Model): subject = models.CharField(max_length= 255) class Student(models.Model): student = models.Foreignkey(Student,related_name="student", on_delete=models.CASCADE) enrolled_subjects = models.ManyToManyField(Subjects) class StudentGrade(models.Model): student = models.Foreignkey(Student,related_name="student", on_delete=models.CASCADE) subject = models.ForeignKey(?) grade = ... period = models.ForeignKey(SchoolPeriod) how can I access the enrolled_subjects of the Student object in Student Grades model? should i do something like: (im not sure if I can do something like this in models.py) class StudentGrade(models.Model): ENROLLED_SUBJECTS_CHOICES = Student.objects.filter(//some filter here) student = models.Foreignkey(Student,related_name="student", on_delete=models.CASCADE) subject = models.ChoiceField(choices= ENROLLED_SUBJECTS_CHOICES, default= None,) grade = ... period = models.ForeignKey(SchoolPeriod) -
Is there any possibility to add fields inside the fields of a Model
Assume I have a model named MyModel and I have a Field Named field Now I want to add three more fields inside the prescription like one field_a , field_b and field_c . Does Django Allow that in any way or we have to make another model for this purpose and then link with Foreign Key to MyModel? -
What is the difference between Geodjango , Geoserver or GeoNode?
I know its a broad spectrum question but I am confused about these three big geospatial technology stack (i don't know is it right to say even individual technology as stack). Does GeoDjango, geoserver and Geodjango all have same objective for making a Webgis application? Who has more capabilities and options to make a full fledge geospatial analysis tool or GIS application ? Are they competitors of each other or can be opt at a time in a single geospatial application or tool? Looking for detailed answer if one can anticipate the pros and cons of each technology it would be a great contribution in this domain? I have searched alot over the internet but not found any useful answer, and finally decided to use this forum. -
Like or dislike comments on Django
I want the comments section to be liked or disliked like the image of the comment when the user clicks on the desired button. in django enter image description here -
AttributeError at /BRMapp/view-books/
I am developing Book Record Management system as my first project on django but after performing all my functionalities I got a problem in my views.py file in a function name view-book in a line(books=models.Book.objects.all()).Although i have made a class name 'Book' in models.py and i also have imported models in my views.py file with a line(form django.db import models).Although it is not working.Kindly help Error showing like this::: module 'django.db.models' has no attribute 'Book' Request Method: GET Request URL: http://localhost:8000/BRMapp/view-books/ Django Version: 3.2.5 Exception Type: AttributeError Exception Value: module 'django.db.models' has no attribute 'Book' Exception Location: G:\Django projects\firstproject\BRMapp\views.py, line 41, in viewBooks Python Executable: C:\Users\amann\AppData\Local\Programs\Python\Python39\python.exe Python Version: 3.9.2 Python Path: ['G:\Django projects\firstproject', 'C:\Users\amann\AppData\Local\Programs\Python\Python39\python39.zip', 'C:\Users\amann\AppData\Local\Programs\Python\Python39\DLLs', 'C:\Users\amann\AppData\Local\Programs\Python\Python39\lib', 'C:\Users\amann\AppData\Local\Programs\Python\Python39', 'C:\Users\amann\AppData\Roaming\Python\Python39\site-packages', 'C:\Users\amann\AppData\Local\Programs\Python\Python39\lib\site-packages'] Server time: Thu, 12 Aug 2021 10:19:08 +0000 -
True or false validation to check whether web compiled user input is equal to a locally stored value
My question title does not succinctly explain my objective. Let me improve on that. I am mildly familiar with extending an IDE functionality in a web application. Lets assume that in I somehow manage to store a predetermined value, the correct output of a certain formula; a sorted list of x int values -[1, 2, 3, 4, 5, 6, 7, 8, 9, 10] . It can be sorted using any sorting algorithm. An example shell_sort algo: def shell_sort(list): gap = len(list) // 2 while gap > 0: for i in range(gap, len(list)): temp = list[i] j = i while j >= gap and list[j-gap] > temp: list[j] = list[j-gap] j = j - gap list[j] = temp gap = gap // 2 list = [10,9,8,7,6,5,4,3,2,1] shell_sort(list) print(list) The output of the above function should be: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]. Please note that I somehow have figured a way to store the correct output of the algorithm. False or True, for now. How can, when a user using a web-ide integrated platform solving for example the algorithm above, be able to programmatically determine the correctness of the users output against one stored locally? -
How To View Mysql Blobs In Flutter Using Django
I saved some images in Mysql DB as "Medium Blob" and I am using Django to create the rest api. this is the output I'm receiving from the api: blob image this is my "views" file in Django: from django.shortcuts import render import base64 from django.shortcuts import render from rest_framework.views import APIView from rest_framework.response import Response from .serializers import PlaceSerializer from .models import Place # Create your views here. class TestView(APIView): def get(self, request, *args, **kwargs): qs = Place.objects.all() serializer = PlaceSerializer(qs, many=True) return Response(serializer.data) def post(self, request, *args, **kwargs): serializer = PlaceSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors) I want to convert the image column to an image in flutter. Looking forward for your help, thanks. -
Force Django related_name return another queryset
I have two models: from django.db import models class Task(models.Model): name = models.CharField(max_length=20) class CascadedTask(models.Model): task = models.ForeignKey('tasks.Task', on_delete=models.CASCADE, related_name='cascaded_from') cascaded_from = models.ForeignKey('tasks.Task', on_delete=models.CASCADE) Data examples: model Task: id name ------------ 1 Task #1 2 Task #2 3 Task #3 4 Task #4 5 Task #5 6 Task #6 7 Task #7 model CascadedTask: id task_id cascaded_from_id ----------------------------- 1 4 1 2 4 2 3 4 3 4 6 2 5 6 3 6 6 5 7 7 4 8 7 6 My goal is to get QuerySet of Task objects but not CascadedTask objects when using related_name as it is now: task = Task.objects.last() # <Task: Task object (7)> task.cascaded_from.all() # <QuerySet [<CascadedTask: CascadedTask object (7)>, <CascadedTask: CascadedTask object (8)>]> I would like task.cascaded_from.all() return <QuerySet [<Task: Task object (4)>, <Task: Task object (6)>]>. How could I reach that? -
Vimeo integration in open-edx
i want to integrate Vimeo in my open-edx platform (open-release/koa.master). I tried below xblock but not working. https://github.com/appsembler/xblock-video https://github.com/sporedata/xblock-vimeo If anyone could help me I would really appreciate it. -
django didn't return HttpResponse Object
I saw many answers about this subject of HttpResponse object in Django, but i can't resolve it. Normally, the user enters the information and the database is saved. def place_order(request, total=0, quantity=0): current_user = request.user # If the cart count is less than or equal to 0, then redirect back to shop cart_items = CartItem.objects.filter(user=current_user) cart_count = cart_items.count() if cart_count <= 0: return redirect('store') grand_total = 0 tax = 0 for cart_item in cart_items: total += (cart_item.product.price * cart_item.quantity) quantity += cart_item.quantity tax = (2 * total)/100 grand_total = total + tax But this is not happening since I get this error. Is there that can help? if request.method == "POST": form = OrderForm(request.POST) if form.is_valid(): # Store all the billing information inside Order table data = Order() data.user = current_user data.first_name = form.cleaned_data["first_name"] data.last_name = form.cleaned_data["last_name"] data.phone = form.cleaned_data["phone"] data.email = form.cleaned_data["email"] data.address_line_1 = form.cleaned_data["address_line_1"] data.address_line_2 = form.cleaned_data["address_line_2"] data.country = form.cleaned_data["country"] data.state = form.cleaned_data["state"] data.city = form.cleaned_data["city"] data.order_note = form.cleaned_data["order_note"] data.order_total = grand_total data.tax = tax data.ip = request.META.get("REMOTE_ADDR") data.save() # Generate order number yr = int(datetime.date.today().strftime("%Y")) dt = int(datetime.date.today().strftime("%d")) mt = int(datetime.date.today().strftime("%m")) d = datetime.date(yr, mt, dt) current_date = d.strftime("%Y%m%d") # 20210305 order_number = current_date + str(data.id) data.order_number … -
how to filter related objects for each post django
i'm trying to display current booking in rooms show in my main page for admins my models.py class Room(models.Model): room_no = models.IntegerField(unique=True) some_fields = models.CharField(max_length=20,choices=my_choices) beds = models.IntegerField(default=2) #others class Booking(models.Model): admin = models.ForeignKey(User,on_delete=models.CASCADE) room_no = models.ForeignKey(Room,on_delete=models.CASCADE,related_name='rooms') check_in = models.DateTimeField(default=timezone.now) check_out = models.DateTimeField(blank=True,null=True) #others show only that booking which is checkout is none or greater than current date , i need filter related objects for each room to if not_checked_out = Q(check_out__gte=timezone.now()) and not_selected = Q(check_out__isnull=True) my views.py @login_required def all_rooms(request): not_checked_out = Q(check_out__gte=timezone.now()) not_selected = Q(check_out__isnull=True) rooms_show = Room.objects.all().order_by('room_no') return render(request,'rooms/rooms.html',{'rooms':rooms_show}) i dont know how to annotate that! i need to show current booking for each rooms in my template <div class="group cursor-pointer"> <a href="{% url 'booking:add_booking' i.room_no %}"> <div class="overflow-hidden transform transition duration-400 hover:scale-90 "> <img src="{% static 'img/iconbed.png' %}" class="rounded-full w-24 mx-auto" alt=""> </div> </a> <div class="border border-gray-900 rounded-xl overflow-hidden -mt-12"> <div class="p-2 rounded-xl bglightpurple pt-12 items-center"> <div class="text-center rounded bggray text-xs md:text-base"> <p class="inline textorange "><i class="bi bi-list-ol"></i> room no:</p> <p class="inline text-white text-white">{{i.room_no}}</p> </div> <div class="grid grid-cols-2 mt-3 gap-2"> <div class="p-1 text-center text-xs rounded bggray"> <span class="text-white"><i class="bi bi-columns-gap"></i> {{i.room_type}}</span> </div> <div class="p-1 text-center text-xs rounded bggray"> <span class="text-white"><i class="bi bi-columns-gap"></i> {{i.beds}} beds</span> </div> <div … -
Wagtail: How to display streamfield block options/type in a dropdown/autocomplete list
I want to create a generic page with around 100 or more block options in stream field. But to access such long list of block types, would like to display it in a dropdown/autocomplete. Once user select the item from dropdown it should add the streamblock. The block interface should be easily accessible. I can fetch the list of blocks using below code, but how to display that list and add block on selection? def get_context(self, request): context = super().get_context(request) list_of_blocks = list(self.body) return context -
Exclude Django admin fieldsets
Whats the best way of excluding fieldsets, I have been reading different posts like the one's below : Question. but I couldn't get it working with them. I want to negelect the following fieldsets when it's not superuser : Cooperation Partner Settings. email_user (This is an Inline not a field set) Below is the admin.py code @admin.register(CooperationPartner, site=admin_site) class CooperationPartnerAdmin(model.Admin): inline_type = 'stacked' inline_reverse = [( 'email_user', {'fields': [ 'salutation', 'title', 'first_name', 'last_name', 'email', ]}, )] reverse_delete_user = True form = CooperationPartnerAdminForm fieldsets_add = ( (_('Personal Data'), { 'fields': ( 'birthday', 'private_address_street', 'private_address_house_n', 'private_address_extra', 'private_address_postcode', 'private_address_city', ), }), (_('Cooperation Partner Settings'), { 'fields': ( 'pool', 'custom_policy_type', 'custom_database_structure', 'custom_attachments', ) }), (_('Company Data'), { 'fields': ( 'company', 'legal_form', 'business_address_street', 'business_address_house_n', 'business_address_extra', 'business_address_postcode', 'business_address_city', 'international_prefix', 'phone_number', 'career_position', 'loan_intermediary_permission', 'agreed_provision', 'bank_name', 'iban', 'bic', 'account_holder', 'sepa_direct_debit_mandate', 'status_decision_feedback', ), }), ) fieldsets_change = ( (None, { 'fields': ( 'cooperation_partner_id', 'account_state', ), }), ) + fieldsets_add def get_form(self, request, obj=None, change=False, **kwargs): """Overwrite get_form method.""" self.fieldsets = self.fieldsets_change if obj else self.fieldsets_add return super().get_form(request, obj, change, **kwargs) -
getting .count(), .exist() from cached queryset without hitting database
I am working on a Django app and I want to make several lookups in a queryset. My problem is subsequent database hits in finding .count() I tried using Django's cache framework but it doesn't seem to work. This is what I've done so far # app/models.py from django.core.cache.backends.base import DEFAULT_TIMEOUT from django.views.decorators.cache import cache_page from django.core.cache import cache class my_table(models.Model): class Meta: db_table = 'table_name' name = models.CharField(max_length=200, blank=True) date_created = models.DateTimeField(auto_now_add=True, blank=True) ip_address = models.CharField(max_length=100, null=True, blank=True) user = models.ForeignKey(User, on_delete=models.CASCADE) def save(self, *args, **kwargs): cache.set(self.user , my_table.objects.filter(user=self.user)) super(my_table, self).save(*args, **kwargs) I am updating the cache every time the database is updated. I tried printing connection.queries in my views # views.py def myview(request): print(len(connection.queries)) # prints 0 records = my_table.objects.filter(user=request.user) print(records) print(len(connection.queries)) # prints 1 if record.count() > 0: # ... some code here print(len(connection.queries)) # prints 2 print() and .count() making extra db hits. Now I tried getting results from the cache # views.py def myview(request): print(len(connection.queries)) # prints 0 records = cache.get(request.user) print(records) print(len(connection.queries)) # prints 0 if record.count() > 0: # ... some code here print(len(connection.queries)) # prints 1 There was no extra query for print() but .count() still hitting database. how can I perform … -
How to set and manage a variable in django database without a parent Model
Let's assume I'm running a company, so I need to keep track how much money I have in my inventory, so I need a unique variable which stores an integer which contains the total money in my inventory... To be precise, I want a variable in my database without a parent model, like we generally do like this class ModelName(models.Model): How do I achieve that? Feel free to ask questions in the comments if I am not clear somehow. Thanks in advance :) -
Failed to fetch content for the given url - Django CKEditor on Heroku
I am using Django-CKEditor as a rich text editor for one of my applications. The problem is with the Media Embed plugin on Heroku. When I insert any URL in the Media Embed option it works fine in my local environment. But when I insert URL in my deployed application (on Heroku), It shows me a - "Failed to fetch content for the given url." error. Does anybody know why is this happening ? This are my CKEDITOR Configurations in settings.py file. CKEDITOR_CONFIGS = { 'default': { 'toolbar': 'Custom', 'width': 'auto', 'toolbar_Custom': [ ["Format", "Bold", "Italic", "Underline", "Strike", "SpellChecker"], ['NumberedList', 'BulletedList', "Indent", "Outdent", 'JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock'], ["Image", "Table", "Link", "Unlink", "Anchor", "SectionLink", "Embed"], ['Undo', 'Redo'], ["CodeSnippet"], ["Maximize"] ], # Remove these dialog tabs (semicolon separated dialog:tab) 'removeDialogTabs': ';'.join([ 'image:advanced', 'image:Link', 'link:upload', 'table:advanced', #'tableProperties:advanced', ]), # Extra plugins to be used in the editor 'extraPlugins': ','.join([ 'mathjax', # Used to render mathematical formulae 'codesnippet', # Used to add code snippets 'image2', # Loads new and better image dialog 'embed', # Used for embedding media (YouTube/Slideshare etc) 'tableresize', # Used to allow resizing of columns in tables ]), } } -
Django REST detail view put form not filling correctly on POSTed content
I am having a strange error. I have a view called WrongMatch, which people using my app can suggest a change if a link is wrong. This is done over a POST request. When I make a WrongMatch inside the browsable API, I can enter its detail view and the PUT html form is filled correctly, but for the ones coming from the POST request, the first field in the PUT html form defaults to the first entry in the database. However, both entries looks identical to me. This picture shows two entries, the first one is POSTed from the app, and the second is made in the browsable API. This shows the detail view of the first entry, but as seen in the PUT html form, the beer defaults to the first in the database and not the one in the entry. This shows the detail view of the second entry, added from the browsable API. Here the field in the PUT html form shows correctly. The viewset used is quite simple. class WrongMatchViewSet(ModelViewSet): queryset = WrongMatch.objects.all() serializer_class = WrongMatchSerializer pagination_class = Pagination permission_classes = [permissions.AllowAny] And the serializer: class WrongMatchSerializer(serializers.ModelSerializer): url = serializers.HyperlinkedIdentityField(view_name="wrongmatch-detail") beer_name = serializers.CharField(read_only=True, source="beer.vmp_name") current_untpd_url … -
custom pagination not woking in apiview of Django rest
I have a custom pagination class in a separate file and until now I have been importing it in a ListAPIView, but this time I tried with APIView, but it didn't work. My pagination class: class CustomPagination(PageNumberPagination): def get_paginated_response(self, data): return Response({ 'links': { 'next': self.get_next_link(), 'previous': self.get_previous_link() }, 'count': self.page.paginator.count, 'page_size' : 15, 'results': data }) I am trying to use custom pagination because I can have the count of the objects as well. My view where I try to implement the pagination: from apps.products.api.pagination import CustomPagination class CouponView(APIView): permission_classes = [AllowAny] #pagination_class = CustomPagination def get(self,request,pk = None,*args,**kwargs): id = pk if id is not None: abc = Coupons.objects.get(id=id) serializer = CouponSerializer(abc) return serializer.data else: abc = Coupons.objects.all() paginator = CustomPagination() result_page = paginator.paginate_queryset(abc, request) serializer = CouponSerializer(result_page,many=True) return Response (serializer.data,status=status.HTTP_200_OK) -
how to display current booking for each room django reverse connection
i'm trying to display current booking in rooms show in my main page for admins my models.py class Room(models.Model): room_no = models.IntegerField(unique=True) some_fields = models.CharField(max_length=20,choices=my_choices) beds = models.IntegerField(default=2) #others class Booking(models.Model): admin = models.ForeignKey(User,on_delete=models.CASCADE) room_no = models.ForeignKey(Room,on_delete=models.CASCADE,related_name='rooms') #others my views.py @login_required def all_rooms(request): rooms_show = Room.objects.all().order_by('room_no') return render(request,'rooms/rooms.html',{'rooms':rooms_show}) i need to show current booking for each rooms in my template <div class="group cursor-pointer"> <a href="{% url 'booking:add_booking' i.room_no %}"> <div class="overflow-hidden transform transition duration-400 hover:scale-90 "> <img src="{% static 'img/iconbed.png' %}" class="rounded-full w-24 mx-auto" alt=""> </div> </a> <div class="border border-gray-900 rounded-xl overflow-hidden -mt-12"> <div class="p-2 rounded-xl bglightpurple pt-12 items-center"> <div class="text-center rounded bggray text-xs md:text-base"> <p class="inline textorange "><i class="bi bi-list-ol"></i> room no:</p> <p class="inline text-white text-white">{{i.room_no}}</p> </div> <div class="grid grid-cols-2 mt-3 gap-2"> <div class="p-1 text-center text-xs rounded bggray"> <span class="text-white"><i class="bi bi-columns-gap"></i> {{i.room_type}}</span> </div> <div class="p-1 text-center text-xs rounded bggray"> <span class="text-white"><i class="bi bi-columns-gap"></i> {{i.beds}} beds</span> </div> <div class="p-1 text-center text-xs rounded bggray"> <span class="text-white">{{i.price}}</span> </div> <div class="p-1 text-center text-xs rounded"> <a href="{% url 'rooms:update_room' i.room_no %}" class=" px-3 pt-1 rounded-lg text-white bg-yellow-500"><i class="fas fa-eye"></i></a> </div> </div> </div> <!--- display booking list here--> <div class="p-1 rounded-xl text-xs mt-1 items-center"> <p class="text-white text-center">16-6-2021 - 19-6-2021</p> </div> </div> i need to … -
With format='multipart' in test client, data of nested dict been ignored or removed
I have a nested serializer containing, containing an Image Field in the nested serializer, the serializers are:- class FloorPlanLocationSerializer(serializers.ModelSerializer): class Meta: model = FloorPlan fields = ( 'floor', 'image', ) extra_kwargs = {'floor': {'required': False}, 'image': {'required': False}} class LocationSerializer(FilterSerializerByOrgManaged, serializers.ModelSerializer): floorplan = FloorPlanLocationSerializer(required=False, allow_null=True) class Meta: model = Location fields = ( 'id', 'organization', 'name', 'type', 'is_mobile', 'address', 'geometry', 'created', 'modified', 'floorplan', ) read_only_fields = ('created', 'modified') def to_representation(self, instance): request = self.context['request'] data = super().to_representation(instance) floorplans = instance.floorplan_set.all().order_by('-modified') floorplan_list = [] for floorplan in floorplans: dict_ = { 'floor': floorplan.floor, 'image': request.build_absolute_uri(floorplan.image.url), } floorplan_list.append(dict_) data['floorplan'] = floorplan_list return data def create(self, validated_data): floorplan_data = None if validated_data.get('floorplan'): floorplan_data = validated_data.pop('floorplan') instance = self.instance or self.Meta.model(**validated_data) with transaction.atomic(): instance.full_clean() instance.save() if floorplan_data: floorplan_data['location'] = instance floorplan_data['organization'] = instance.organization with transaction.atomic(): fl = FloorPlan.objects.create(**floorplan_data) fl.full_clean() fl.save() return instance With this above serialzier, it works fine with DRF Browsable page, but when I try to send the data with the test client in multipart format, the nested data gets removed while send the POST request, this is how I wrote the tests:- def test_create_location_with_floorplan_api(self): path = reverse('geo_api:list_location') coords = json.loads(Point(2, 23).geojson) image = Image.new("RGB", (100, 100)) with tempfile.NamedTemporaryFile(suffix=".png", mode="w+b") as tmp_file: … -
Django form set placeholder in CharField instead of value
Suppose I have a following simple form: class UserForm(Form): first_name = CharField(label='First Name') last_name = CharField(label='Last Name') And there is some custom validation. When a user submitted invalid data, Django renders the form with invalid values inside the fields. Is it possible to render empty CharFields but with placeholders that show the entered data? -
change django-avatar default photo
I'm using django-avatar. and I want to change the default image of the dajngo-avatar. I tried AVATAR_DEFAULT_URL="https://path-to-image.jpg" but it's not working. -
Writing query inside a model
I want to write a query where if the Complete Status is all true , complete inside model Order should be automatically true. Can i write a query inside Order model using some methods or anything ? And can you suggest some help. class Order(models.Model): customer = models.ForeignKey(Customer , on_delete=models.SET_NULL , null= True , blank = True) date_ordered = models.DateTimeField(auto_now_add = True) complete = models.BooleanField(default=False) transaction_id = models.CharField(max_length= 100 , null=True) class CompleteStatus(models.Model): order = models.ForeignKey('Order', on_delete=models.SET_NULL , null=True) seller = models.BooleanField(default=False) warehouse =models.BooleanField(default=False) pickup = models.BooleanField(default=False) delivered = models.BooleanField(default=False) received_by_customer = models.BooleanField(default=False) -
Django Check constrain prevent save string in json fileld
How can I prevent saving string literal in JSON field? class MyModel(models.Model): settings = JSONField("Additional settings", default=dict, blank=True) Now I can do this inst = MyModel.objects.get() inst.settings = 'some string' inst.save() but some login expect dict. now I need check dict in code. I add simple constrain class Meta: ordering = ['-updated_at'] constraints = [ CheckConstraint( check=~(Q(settings='') | Q(settings='{}')), name='reduce_sats_process_check_settings_must_be_json_object' ) ] but this not prevent saving all string variants. -
django permissions instead of groups
We have multiple positions in the hierarchy of the company : such as director of sales, salesperson, restaurant director and let say maitre d'hotel, however if we have a follow up or a memo some might be a good fit for the whole staff to see but if the memo concern the pricing strategy of a particular quote, we don't want the maitre d'hotel to see this particular follow up, or quote, or detail in the dashboards as of now I understand that the permission system allow us to briefly avoid that tier be able to edit or delete a particular model instance from the database : should I do a attribute level of permissions such as writing a model with level 1, 2 , 3 , 4 , 5 (permissions ) and attribute one to each user and add template tags that will display a different html page or is there a better way to do it, thanks