Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ValueError: The QuerySet value for an exact lookup must be limited to one result using slicing
I have a models: class Product(models.Model): title = models.CharField(max_length=100) price = models.FloatField() category = models.CharField(choices=CATEGORY_CHOICES, max_length=2) slug = models.SlugField() description = models.TextField() image = models.ImageField() class Order(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True) products = models.ManyToManyField(Products, through='OrderItem', related_name='orders') being_delivered = models.BooleanField(default=False) class OrderItem(models.Model): order = models.ForeignKey(Order, on_delete=models.CASCADE, related_name='items') product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='order_items') quantity = models.IntegerField(default=1) And I have views for for creating Order and OrderItems attached to Order. I have views for cart/order_detail: what I do: from django.db.models import Sum, F def cart_detail(request): order = Order.objects.filter(user=request.user) order_item = OrderItem.objects.filter(order=order).annotate(total=F('quantity') * F('product__price')) total = order_item.aggregate(total=Sum(F('quantity') * F('product__price')))['total'] return render(request, 'cart/cart_detail.html', {'order':order, 'order_item':order_item, 'total':total} Template: <table class="table"> {% if order|length %} <thead> <tr class="alert alert-secondary" role="alert"> <th>Photo</th> <th>Product</th> <th>Quantity</th> <th>Remove from cart</th> <th>Unit price</th> <th>Total price</th> </tr> </thead> <tbody> {% for item in order %} {% with product=item.product %} <tr> <td> <a href="{{ product.get_absolute_url }}"> {% if product.photo %} <img src="{{ product.photo.url }}" class="img-fluid rounded-start" alt="..." width="250px"> {% else %} <img src="https://globalimpactnetwork.org/wp-content/themes/globalimpact/images/no-image-found-360x250.png" class="img-fluid rounded-start" alt="..." width="250px"> {% endif %}</a> </td> <td>{{ product.title }}</td> <td>{{ order_item.quantity }}</td> <td><a href="" class="btn btn-outline-danger">Delete</a></td> <td class="num">$ {{ }} </td> <td class="num">$ {{ }} </td> </tr> {% endwith %} {% endfor %} <tr class="alert alert-success" role="alert"> <td><b>Total … -
When deploying Django App on Heroku I get the error code H10
I am trying to deploy a django App on Heroku but I always get the H10 error at=error code=H10 desc="App crashed" method=GET path="/" and at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" this is my Procfile and Debug is turned of web: gunicorn VirtualResponsibilityBuddy.wsgi:application --log-file - --log-level debug -
Sql fetch whole table and then filter in python or fetch table in several querys
I'm developing a warehouse platform in flask with a PostgreSQL database. I have a products table, in which the state of the product is set(draft(0), pending(1) or crafted(2)). The model of the product looks more less like this: Product(id INT,lot INT,name VARCHAR(50),shelf INT,type INT,state INT,...) I have to display the products depending on its state, so, what would be better: SELECT * FROM Product; Fetch whole table and split it in three dicts in python once retrieved or SELECT * FROM Product WHERE state==0;SELECT * FROM Product WHERE state==1;SELECT * FROM Product WHERE state==2; Query the table once for any possible state so the table is already split. I'm assuming as a thumb rule that less queries is better than more, but on the other hand, I suppose sql filtering is faster than doing it in python. So, what would be the most suitable thing to do for performance terms? Thank you in advance -
How to send new form fields with data from Django views.py?
I am adding a new field named "user" to the "order" model. I did make migrations. (Bonus question is: why in the sql3db column "user_id" was made, instead of "user"? But ok, I change form.fields['user'] to form.fields['user_id'], as the machine wants...) I remove unneeded fields from the form in forms.py, and I try to add this fields in views.py (because I don't know how to send "user" to the forms.py, and I think it more secure like this). And as I can understand - my new fields is absent for "order", when I use form.save(). This field can't be null by design. -
How to Pass data from one view to another in django?
I have a view function("View A") thats gets called first and then I call the my payment gateway which is "paytm payment gateway" it after finishing the transaction calls "View B" So now what I want is the values that were submitted in the "view A " to be passed to "View B" Just for the information I'm using Django not Django rest Sollution that I have tried I have tried Using Session #To store value in a session variable View A:- request.session['message'] = request.POST.get("message") #to retrieve the value from session Variable View B:- request.session.get('message') Any help or guidance will be great as I have stuck for quite some time now. Thanks in advance. -
How to report a error to user without raising a exception from middleware in Django
my middleware def password_validator_middleware(get_response): def my_function(request): #converting bytes typeto dictionary type dict_str = request.body.decode("UTF-8") details_entered = ast.literal_eval(dict_str) #checking if that password exist in the database if pwned_passwords_django.api.pwned_password(details_entered['password']): return else: print("your password looks fine") response = get_response(request) return response return my_function Here if password entered is a pwned password i want to return and say to user that your password is pwned how can i do that , i want to return from there only without going ahead from the middleware -
Ajax jQuery serialize() & serializeArray() textarea not submitting in Django form
I have a form I'm trying to submit the data via AJAX & jQuery to an Django API. Submission through the Django admin works fine but through the form, the textarea field is the one cause problems. I have a similar form without the textarea and it works fine. The textarea content is not being submitted and I don't know why. Here is the form: <form id="addMaintenanceRecordsForm" action=""> {% csrf_token %} <div class="mb-3"> <div class="row"> <div class="col-md-12"> <label>Title <span style="color: #dd0000;">*</span></label> <input type="text" class="form-control" name="maintenance_title" placeholder="Enter Title" id="mr-title" required> </div> </div> </div> <div class="mb-3"> <div class="row"> <div class="col-md-12"> <label>Details <span style="color: #dd0000;">*</span></label> <textarea class="form-control" id="mr-summary" name="summary" placeholder="Describe the nature of maintenance repair..." rows="3" required></textarea> </div> </div> </div> <div class="mb-3"> <div class="row"> <div class="col-md-12"> <label>Repair Status <span style="color: #dd0000;">*</span></label> <select class="form-select" name="repair_status" id="mr-status" aria-label="Default select example" placeholder="Repair Status" required> <option selected disabled>Choose...</option> <option value="Complete">Complete</option> <option value="Ongoing">Ongoing</option> </select> </div> </div> </div> <button type="submit" class="btn btn-soft-primary btn-sm" id="mr-create">Create New Record</button> <button type="button" class="btn btn-soft-secondary btn-sm">Cancel</button> </form> This is my jQuery code $(function() { $('#addMaintenanceRecordsForm').on('submit', function(e) { e.preventDefault(); console.log($("#addMaintenanceRecordsForm").serializeArray()); let url = "http://127.0.0.1:8000/api/maintenance/add/"; $.ajax({ type : 'POST', url : url, data : $("#addMaintenanceRecordsForm").serializeArray(), dataType: "json", success: function(data){ alert("New Maintenance Records Added!"); location.reload(); }, error:function(data){ … -
Django ModelForm foreign key values are not displayed
Am new to django, and I am trying to create a form using modelform. The form has foerign key value (connection_type below in forms.py) and its not displaying the values it is referring to. For the image below, the columns, Connection name : displayed Connection type : text box has not appeared Endpoint : displayed Image from the browser forms.py class ConnectionForm(forms.ModelForm): connection_type = forms.ModelChoiceField(queryset=ConnectionTypes.objects.all(), to_field_name='connection_type_id') class Meta: model = ConnectionDetails exclude = ['connection_id','last_update_date'] Models.py class ConnectionDetails(models.Model): connection_id = models.IntegerField(primary_key=True,default=re_sequence('connection_seq')) connection_name = models.CharField(max_length=200) connection_type = models.IntegerField() endpoint = models.CharField(max_length=100) port = models.IntegerField() login_id = models.CharField(max_length=100) login_password = fields.CharPGPPublicKeyField(max_length=100) connection_string_1 = fields.CharPGPPublicKeyField(max_length=100) connection_string_2 = fields.CharPGPPublicKeyField(max_length=100) connection_string_3 = fields.CharPGPPublicKeyField(max_length=100) aws_region = models.CharField(max_length=20) owner_id = models.IntegerField() last_update_date = models.DateTimeField(default=dbcurr_ts) working_schema = models.CharField(max_length=100) service = models.CharField(max_length=100) def generate_enc(mystrenc): return 'pass' class Meta: managed = False db_table = 'connection_details' verbose_name = 'connection_details' verbose_name_plural = 'connection_details' class ConnectionTypes(models.Model): connection_type_id = models.IntegerField(primary_key=True,default=re_sequence('connection_type_seq')) connection_type_name = models.CharField(max_length=100) connection_type_desc = models.CharField(max_length=300) connection_type_category = models.CharField(max_length=100) last_update_date = models.DateTimeField(default=dbcurr_ts) class Meta: managed = False db_table ='connection_types' verbose_name = 'connection_types' verbose_name_plural = 'connection_types' Can you please let me know what is the mistake am making? -
how to solve django.db.utils.IntegrityError?
I am trying to migrate django sqlite database to mysql. So first I dumpdata by running python manage.py dumpdata > db.json after that I changed setting.py after this I created database at mysql and migrate python manage.py migrate and open shell python manage.py shell write from django.contrib.contenttypes.models import ContentType ContentType.objects.all().delete() but when I run python manage.py loaddata db.json I got error like this 👇👇 MySQLdb._exceptions.IntegrityError: (1062, "Duplicate entry '1-Downloads' for key 'filer_folder.filer_folder_parent_id_name_bc773258_uniq'") ............ ............. ............ ........... .......... django.db.utils.IntegrityError: Problem installing fixture '/var/www/html/Planning/SampleTemplate/db.json': Could not load filer.Folder(pk=23): (1062, "Duplicate entry '1-Downloads' for key 'filer_folder.filer_folder_parent_id_name_bc773258_uniq'") -
AttributeError at /admin/accounts/user/1/change/ 'User' object has no attribute 'profile'
I am creating an API. When i create a new user, or edit an existing user and save, i get this error "AttributeError at /admin/accounts/user/1/change/ 'User' object has no attribute 'profile" For clarity, I have a user model and a profile model lied o my User model with a onetoone relationship. Here is my User model artist_name = models.CharField( max_length=255, default='artist name', unique=True ) slug = models.SlugField(max_length=250, null=True, blank=True) email = models.EmailField(max_length=300, unique=True) active = models.BooleanField(default=True) staff = models.BooleanField(default=False) admin = models.BooleanField(default=False) date_joined = models.DateTimeField(auto_now_add=True) last_login = models.DateTimeField(auto_now_add=True) My Profile model class Profile(models.Model): user = models.OneToOneField( User, on_delete=models.CASCADE, related_name="user", default=1 ) first_name = models.CharField(max_length=255, blank=True, null=True) last_name = models.CharField(max_length=255, blank=True, null=True) country = models.CharField(max_length=500, blank=True, null=True) gender = models.CharField(max_length = 20, blank=True, null=True) record_label = models.CharField(max_length=255, blank=True, null=True) image = models.FileField() And my signals from .models import User, Profile from django.dispatch import receiver @receiver(post_save, sender=User) def create_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_profile(sender, instance, **kwargs): instance.profile.save() I should also mention that I don't have views for my user and profile yet. But i don't think that should affect the admin area. So far i have searched online but nothing worked. Thank you in anticipation. -
Django enum attribute equality
I'm using enums in a django model, like: class AwesomeNess(Enum): slight = "SLIGHT" very = "VERY" class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) awesomeness = models.CharField( max_length=255, choices=[(tag.value, tag.name) for tag in AwesomeNess], default=AwesomeNess.slight ) This works fine when I use Django's filter function, like: d = Choice.objects.filter(awesomeness=AwesomeNess.slight) However, it does not work if I do: choice_obj = Choice.objects.get(id=1) choice_obj.awesomeness == AwesomeNess.slight # will return False choice_obj.awesomeness == "AwesomeNess.slight" # will return True Since values are stored as strings, it looks like Django forgets to cast them back to an enum when returning the data. This gives inconsistencies when coding, since django model filters can query on the enum, while attribute equality filtering requires me to use the stringed representation of the enum. Is there a way around this? Am I doing something very wrong? Pointers appreciated! oh, bwt: this is on Django 2.2.24. Maybe later versions have improved enum support? -
filter users within a given distance in django rest framework
I'm trying to implement a custom filter in django rest framework, wich returns the users within a given distance, i'm using django filters. I am assuming that latitude and longitude are already provided by front end. this what i tried. I don't know if it's the right way to do it. I'm having the following error 'RenameAttributes' object is not iterable Here is my code Views.py def calculateDistance(lon1, lat1, lon2, lat2): lon1, lat1, lon2, lat2 = map(radians, [lon1, lat1, lon2, lat2]) return 6371 * ( acos(sin(lat1) * sin(lat2) + cos(lat1) * cos(lat2) * cos(lon1 - lon2)) ) class CustomFilter(django_filters.rest_framework.DjangoFilterBackend): def filter_queryset(self, request , queryset,view): alluser = queryset newQueryset = [] distparam = request.GET.get('distance') if distparam and bool(int(distparam)): for user in alluser: current_user_long = request.user.Longitude current_user_lat = request.user.Latitude alluser_long = user.Longitude alluser_lat = user.Latitude distance = calculateDistance(current_user_long, current_user_lat, alluser_long, alluser_lat) if distance > distparam: newQueryset.push(user) return newQueryset return queryset class UserFilter(filters.FilterSet): class Meta: model = User fields =['gender', 'last_name', 'first_name' ] class UserListView(generics.ListAPIView): queryset = User.objects.all() serializer_class = UserSerializer filterset_class = UserFilter filter_backends = CustomFilter Models.py class User(AbstractUser): username = None email = models.EmailField( max_length=100, verbose_name='email', unique=True) gender = models.CharField( max_length = 20, choices = GENDER_CHOICES, default = 'М' ) avatar= … -
How to get url from django to javascript with pk
I'm having trouble to get the url from django to JavaScript. How can I get the url with pk? the error that I receive Not found: "post/(?Pslug:pk\b[0-9A-Fa-f]{8}\b(-\b[0-9A-Fa-f]{4}\b){3}-\b[0-9A-Fa-f]{12}\b)/$' urls.py from django.urls import path from django.urls import reverse from . import views import twitter.views urlpatterns = [ path("chatbot/(?P<str:pk>\b[0-9A-Fa-f]{8}\b(-\b[0-9A-Fa-f]{4}\b){3}-\b[0-9A-Fa-f] {12}\b)/$'/", views.chatbot, name='chatbot_chatbot'), path("post/(?P<slug:pk>\b[0-9A-Fa-f]{8}\b(-\b[0-9A-Fa-f]{4}\b){3}-\b[0-9A-Fa-f]{12}\b)/$'", views.chatbot_process, name='post'), path("", views.landing, name='home') ] Javascript $.get("/post/(?P<slug:pk>\b[0-9A-Fa-f]{8}\b(-\b[0-9A-Fa-f]{4}\b){3}-\b[0-9A-Fa-f]{12}\b)/$')", {input_text: rawText, user_text: new_value}).done(function (data) { const msgText = data; appendMessage(BOT_NAME, BOT_IMG, "left", msgText); }); -
How to get parent element from child instance in django
I am trying to save assignment into the database but I also want the name of the teacher who created that assignment and the title of the assignment. now assignment is getting saved but I dont know how to get the name of teacher and assignment title. MODELS.PY: class Assignment(models.Model): assignment_creator = models.ForeignKey(Teacher, on_delete=models.CASCADE) assignment_title = models.CharField(max_length=30) assignment_details = models.TextField() assignment_date = models.DateField(auto_now_add=True) def __str__(self): return str(self.assignment_title) class Submissions(models.Model): submitted_by = models.ForeignKey(Student, on_delete=models.CASCADE) submission_file = models.FileField(null=False) submitted_to = models.ForeignKey( Teacher, on_delete=models.CASCADE, null=True) submission_title = models.ForeignKey( Assignment, on_delete=models.CASCADE, null=True, blank=True) submission_status = models.BooleanField(default=False) class Teacher(models.Model): teacher_username = models.OneToOneField(User, on_delete=models.CASCADE) t_full_name = models.CharField(max_length=20) is_Teacher = models.BooleanField(default=True) def __str__(self): return str(self.teacher_username) this is my template where I am uploading the file and i am using these two hidden fields to get the name of assignment and teacher in string format. <form enctype="multipart/form-data" action="{% url 'assignment' %}" method="POST"> {% csrf_token %} <input type="text" name="ass_name" hidden value="{{assignment.assignment_title}}" id=""> <input type="text" name="teacher_name" hidden value="{{assignment.assignment_creator}}" id=""> <input required type="file" name="inputFile" id="" placeholder="upload"> <button>Upload</button> ) I tried saving those two assignment name and teacher name in the database just like I saved the file but it isnt working because of the string. now I dont know how to … -
How to set-up wagtail pages
I am trying to configure a django project that uses the wagtail CMS to display the templates(the templates is already in the file) on the frontend but since it is my first time working with wagtail, I am having issues and don't know where to head to. I have checked some external sources like YouTube perhaps I will get any illustration of such but I don't seem to get any. The whole project structure is shown below and this shows that the whole templates and html files are intact but I don't know how to set it up. If I run the program using the python manage.py runserver, I get the project running and after opening the localhost:8000 on the browser, I only get a blank screen. The url.py file of the main project is show below: # django imports from django.conf import settings from django.conf.urls import include, url from django.conf.urls.i18n import i18n_patterns from django.contrib import admin # wagtail imports from wagtail.admin import urls as wagtailadmin_urls from wagtail.core import urls as wagtail_urls from wagtail.documents import urls as wagtaildocuments_urls urlpatterns = [ url(r'^django-admin/', admin.site.urls), url(r'^admin/', include(wagtailadmin_urls)), url(r'^robots\.txt$', TemplateView.as_view( template_name='robots.txt', content_type='text/plain' )), url(r'^documents/', include(wagtaildocuments_urls)), ] urlpatterns += i18n_patterns( url(r'', include(wagtail_urls)), ) The … -
Using MySQL REGEXP to filter string with Django ORM
I have a model which have FileField field and in this model we have millions of records. class MyModel(models.Model): media = models.FileField(upload_to=my_function, db_index=True) ... These media records are stored in database like; media/some/folder/filename.jpg media/filename.jpg media/2021091240-10328.JPG media/aXay-123.jpeg media/some/another/folder/202110-12-12.jpeg etc. and I need to find records which are not have nested path like /some/folder/ or /some/another/folder/ with django orm __iregex lookup. So, I tried something like; MyModel.objects.filter(media__iregex=r"^media/[0-9a-zA-Z\-][.][a-zA-Z]") but it does not match and I do not understand to write proper regex [mysql regexp]. How can I do filter with mysql regexp with using Django orm to get records with only have pattern like; media/filename.extension? -
Django: Display a PDF document in iframe or embed not working
I want to display a PDF on on a page in our website. The URL is correct and pointing to the PDF. I am seeing a display, but I see garbage characters instead of the PDF. In template using: <embed src="{{packet.certificate_pdf.url}}" ...> <iframe src="{{packet.certificate_pdf.url}}" ...> Then I see results on the page where the PDF is suppose to display: %PDF-1.3 %âãÏÓ 1 0 obj << /Type /Pages /Count 6 /Kids [ 3 0 R 4 0 R 5 0 R 6 0 R 7 0 R 8 0 R ] >> endobj 2 0 obj << /Producer (PyPDF4) >> endobj 3 0 obj << /MediaBox [ 0 0 595 842 ] /Type /Page /Parent 1 0 R /Contents [ 10 0 R ] /Resources << /ProcSet [ /PDF /Text /ImageC ] /XObject << /HiQPdf_mlpnjcimdfejkpcopajmiphnnjaiocbm 11 0 R >> >> >> endobj 4 0 obj << /MediaBox [ 0 0 .... etc Using in Production enviroment: Django 3.2 Python 3.8 Already using: X_FRAME_OPTIONS = 'SAMEORIGIN' I also tried converting to base64 then displaying it: <iframe src="data:application/pdf;base64,{{pdf_in_base64}} ... This used to work, but recently Chrome sometimes show the PDF and sometimes not, which I can't solve. Something in the base64 seems to … -
Cleaning up library from old Django migration
I have a Django migration which used the partial-index library. This is a fairly old migration in a long running project, created before Django supported partial indices, and now I need to upgrade the project from Django 2.2 to Django 3.2. The partial-index library is no longer necessary as Django now supports partial indices. Moreover, this library has code which does not seem to work with Django 3 as the model structures have changed (specifically related to the FieldDoesNotExist exception). I am trying to update the old partial index to the new Django format, using the condition system described here https://docs.djangoproject.com/en/2.2/ref/models/indexes/#condition The change itself is simple, it involves changing the index definition in the model from indexes = [Index(fields=['round'], name='round_index', condition=PQ(removed_at__isnull=True))] to indexes = [Index(fields=['round'], name='round_index', condition=Q(removed_at__isnull=True))] (note the change PQ which is from partial-index to Q which is Django's own construct) This results in a migration which drops and recreates the index, where everything looks ok. However, an earlier migration where this index was originally created, imported the partial-index library to reference the PQ object. This will fail with an ImportError if the library is removed from the project completely. What is the safest way to remove the reference … -
Email verification using django and firebase
I know want to implement a email verification and then check if the user has verified his/her email or not in Django and database being firebase. I have seen method to send emails using send_email_verification in python that works fine, But I cant seem to get the firebase.auth().current_user.emailVerified thing right. I get an error saying current_user has no key emailVerified. I have also tried to write in different forms and check the printed the user dictionary but couldn't find emailVerified parameter. What am I doing wrong here? -
How to ignore the HTTP response and post the form?
I have a form for user registration .After the users press the submit button , the user should receive a confirmation email .And the whole form will post to the db . But the problem is I use Gmail as the domain email and it causes lots of security prevention that I can't send the confirmation email when there is new registration. Therefore , the system can't post the form to the db . The user keep stucking in the #loading page. Now , I'm going to ignore the confirmation email process . Gmail system still send a confirmation email when there is a new registration . But the form will then post anyway, no matter the confirmation email successfully sends it out or not. How to amend the code ? HTML var form = $("#form_data")[0]; var data_item = new FormData(form); data_item.append("profile_img",document.getElementById("imgInp").files[0]) data_item.append("username",username) data_item.append("password",password) ..... $("#loading").show() $.ajax({ method : "POST", url : "/signup/", enctype : "mutipart/form_data", processData : false, contentType : false, cache : false, data : data_item, success : function(response){ console.log(response) $("#loading").hide() if (response == "success") swal("Registration Saved Successfully", { icon: "success", button: "Ok", closeOnClickOutside: false, }).then(function() { location.href = "/signin/"; }); else if (response == "email exists"){ $('#error_email_exists').show(); … -
print for loop data based on the item quantity given in django
Let us consider purchase_order_id = 199 for this purchase_order we are having 2 items (let us consider item_names as Samsung Note 3(item 1),Ear capsule(item 2)) Now item_1(Samsung Note 3) quantity is given as 2 and item_2(,Ear capsule) quantity is given as 3 now in the pdf how i need to print the labels is item_1 2 times as quantity is 2 and item_2 as 3 times as quantity is 3 Let us consider my views.py as class PrintLabels(View): def get(self, request, id, value): client = request.user.client order = OtherOrder.objects.get(client=client, id=id) items = order.otherorderitem_set.all() items_list = [] for c in items: item_dict = {} if c.batch_number: item_dict['batch_number'] = c.batch_number if c.due_date: item_dict['due_date'] = c.due_date if c.season_support: item_dict['season_support'] = c.season_support if c.flower_colour: item_dict['flower_colour'] = c.flower_colour .... .... .... items_list.append(item_dict) template = loader.get_template('po_labels.django.html') context_dict = { 'items_list' : items_list, 'items' : items, 'order' : order, } context = Context(context_dict) html = template.render(context) result = StringIO.StringIO() pdfkit.from_string(html, 'applicationpdf.pdf') pdf = open("applicationpdf.pdf") response = HttpResponse(pdf.read(), content_type='application/pdf') return response let us consider my template.html as <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Light Degree</title> {% load i18n crm_tags sekizai_tags widget_tweaks %} <style> html { background-color:#f4f4f4; } body … -
I need to create Hierarchical structured JSON file from Django Models for using create menu submenu
I need to create Hierarchical structured JSON file from Django Models for using create menu submenu Please give solution Experts class Menuandurls(models.Model): id = models.BigAutoField(primary_key=True) seqno = models.CharField(db_column='seqNo', max_length=20, blank=True, null=True) name = models.CharField(max_length=30, blank=True, null=True) type = models.CharField(max_length=20, blank=True, null=True) isdirecturl = models.BooleanField(db_column='isDirectUrl', blank=True, null=True) class Meta: db_table = '[masters].[menuAndUrls]' -
Python dict into HTML-template (Django)
I have a pythondict with the example format data ={"X":{"0":1234, "1":5678, "2":1234}, "X":{"0":4567, "1":1234,"2":4456}} Unfortunately, I don't know how to iterate through the nested data in an HTML template to create a table. Can you help me? -
How can I set ldap_user in a django test?
We have a django application with LDAP authentification (django-auth-ldap). In a custom permission we check if request.ldap_user.group_names contains a certain group (depending on request.data). Manual testing shows it is working. Now we want to write an automated test, but we keep getting "AttributeError: 'User' object has no attribute 'ldap_user' and we can not find anywhere how we can set the ldap_user and the ldap_user group names. This is the test so far: import pytest from django.urls import reverse from django.test import Client from django.contrib.auth.models import User import requests client = Client() url_create_artifact = reverse("artifacts/create-list") @pytest.mark.django_db() def test_post_artifacts_create_logged_in(): component = Component() component.id = "test_component" component.ldap_group = "test_group" component.save() user = User.objects.create(username="test_user") user.set_password("1234") user.save() client.login(username="test_user", password="1234") response = client.post( url_create_artifact, { "component_id": "test_component" }, ) assert response.status_code == 200 This is the custom permission: from rest_framework.permissions import BasePermission, SAFE_METHODS from django.shortcuts import get_object_or_404 class CustomPermission(BasePermission): def has_permission(self, request, view): component_id = request.data["component_id"] component = get_object_or_404(klass=Component, id=component_id) user = request.user if user.is_authenticated: user_ldap_groups = request.user.ldap_user.group_names component_ldap_group = component.ldap_group return component_ldap_group in user_ldap_groups else: return False Our view starts with from rest_framework.authentication import SessionAuthentication from our_app.permissions import ApplicationPermission from rest_framework import viewsets class ArtifactSetCreate(viewsets.GenericViewSet): authentication_classes = [SessionAuthentication] permission_classes = [CustomPermission] [...] urls.py contains from … -
accessing an element of a django database object
I am trying to access an element of a django database table object. My under standing is the structure is as follows: Database table -> object -> elements. I can access the Database object that i want by doing the following: wanted_object = WholeValues.objects.get(id=1) how can I access the the elements of this database object. I have tried wanted_element = wanted_object.get(id=2) when I try to access the first element I get an error. this error says WholeValues' object has no attribute 'get' My model for the object is as follows: class WholeValues(models.Model): a_count = models.FloatField() b_count = models.FloatField() c_count = models.FloatField() in my specific case I want to access the b_count value.