Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to join(not raw) tables in Django?
I have this models class Product(models.Model): name = models.CharField(max_length=70) category = models.ForeignKey(InnerCategory, null=True, on_delete=models.SET_NULL) slug = models.SlugField(unique=True) class Price(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) price_tag = models.IntegerField() date = models.DateTimeField(auto_now_add=True) In view i get category_slug argument with whom i need to find quary with all Products that belongs to this Category and latest Price for every Product. Can i somehow find it with only one(not raw) query request -
I want to find the location of a user, so i decited to get from there IP address
I found a code and it works perfectly, but I am not very clear about the function. x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR') if x_forwarded_for: ip = x_forwarded_for.split(',')[0] else: ip = request.META.get('REMOTE_ADDR') so this is the function, i jut want to know how accurate and clear the function is. If anyone can advice me how to modify or how perfect my code i it will be very helpful. Thank you -
How to Override or Hide Django admin model form field value
Currently, I'm having a problem when overriding a form field value on my (Django==4.0.3) django admin form. The objective is : I have a specific user table that I'm connecting to AWS Cognito. And when the admin creates a new user in django, the system must create a request to create a new Cognito user. Once the Cognito user is created it generates a "sub" code, and then the sub should be saved in django Code Follows Model class BuyerUser(BaseModel): buyer = models.ForeignKey( Buyer, on_delete=models.RESTRICT, related_name="%(class)s_buyer" ) cognito_sub = models.CharField(max_length=50) given_name = models.CharField(max_length=50) family_name = models.CharField(max_length=50) preferred_username = models.CharField(max_length=50) email = models.EmailField(blank=False) terms_conditions_accepted_datetime = models.DateTimeField(null=True, blank=True) def __str__(self): return self.preferred_username admin class BuyerUsers(admin.ModelAdmin): list_display = ('id', 'buyer', 'given_name', 'family_name', 'preferred_username', 'available') list_filter = ('buyer', 'available',) list_display_links = ('id', 'preferred_username',) search_fields = ('buyer__name', 'preferred_username', 'available') list_per_page = 20 form = BuyerUserChangeForm add_form = BuyerUserAddForm # It is not a native django field. I created this field and use it in get_form method. def get_form(self, request, obj=None, **kwargs): """ Use special form during foo creation """ defaults = {} if obj is None: defaults['form'] = self.add_form defaults.update(kwargs) return super().get_form(request, obj, **defaults) admin.site.register(BuyerUser, BuyerUsers) and my forms class BuyerUserAddForm(forms.ModelForm): grupo = forms.CharField() def … -
TypeError at /admin/imgUploader/images/add/
This is the models.py from distutils.command.upload import upload from email.mime import image from django.db import models from django.contrib.auth.models import User # def user_directory_path(instance, filename): # return 'user_{0}/{1}'.format(instance.user.id, filename) # Create your models here. class Images(models.Model): file = models.ImageField(#upload_to=user_directory_path, width_field=100, height_field=100, blank=True, null=True) name = models.CharField(max_length=30) description = models.TextField(help_text="Give a short description of the image", max_length=100) def __str__(self): return self.name This is the admin.py from django.contrib import admin from .models import Images # Register your models here. admin.site.register(Images) When I try to upload an image from the admin site, this is the error I get. TypeError at /admin/imgUploader/images/add/ getattr(): attribute name must be string -
How to print dict key value dinamically?
I'm trying to print a dict key value dynamically. EX: print(data['waninfo']['1']['user']['_value']) ->"teste" print(data['waninfo']['1']['pw']['_value']) -> "teste123" As we see the key 'waninfo' and '1' are fixed and i would like to use the keys after dinamically, like this: fixedKey = "['user']['_value']" print(data['waninfo']['1']+fixedKey) How can i do this? -
Ajax Like Button.(When I click the like button, only the 1st post is liked. Even if I click the 2nd post, the 1st post changes)
My problem is in the title. I don't know where the problem comes from but I think something is missing in my code. what should i add to the code ? I don't think there is an error in importing from my other html templates I think I need to make changes in the def or ajax code to solve the problem. models.py class Post(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) content = models.ManyToManyField(PostFileContent, related_name='contents') caption = models.TextField(max_length=1500, verbose_name='Caption') posted = models.DateTimeField(auto_now_add=True) tags = models.ManyToManyField(Tag, related_name='tags') user = models.ForeignKey(User, on_delete=models.CASCADE) likes = models.ManyToManyField( User, related_name='like', default=None, blank=True) like_count = models.BigIntegerField(default='0') görünümler.py @ login_required def like(request): if request.POST.get('action') == 'post': result = '' id = request.POST.get('postid') post = get_object_or_404(Post, id=id) if post.likes.filter(id=request.user.id).exists(): post.likes.remove(request.user) post.like_count -= 1 result = post.like_count post.save() else: post.likes.add(request.user) post.like_count += 1 result = post.like_count post.save() return JsonResponse({'result': result, }) urls.py urlpatterns = [ path('like/', like, name='like'), ] Myscript <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <script> $(document).on('click', '#like-button', function (e) { e.preventDefault(); $.ajax({ type: 'POST', url: '{% url "like" %}', data: { postid: $('#like-button').val(), csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val(), action: 'post' }, success: function (json) { document.getElementById("like_count").innerHTML = json['result'] }, error: function (xhr, errmsg, err) { } }); }) </script> myLikeButton {% if request.user.is_authenticated %} <button … -
Capture Unique Constraint on POST in DRF
I have a model with a unique field like so: models.py class MyModel(...): name = models.CharField(max_length=32, ...) key = models.CharField(max_length=32, ...) class Meta: constraints = [ UniqueConstraint( fields = ['name', 'key'], ... ), ] If I send a POST request where name is more than 32 characters, I get back a proper error response: {"name": ["Ensure this field has no more than 32 characters."]} However, if I send a POST request where the combination of name and key is not unique, an exception is raised and no message is sent back to the client. How can I capture when a unique constraint is violated and send back a message to the client? -
Django not receiving any request in backend after submit the form
Hi Everyone I am trying to submit the form in Django. but I am not getting any response in Backend. when I clicked on submit. the form is not getting submitted. The code Models class JobListing(models.Model): position = models.CharField(max_length=250) slug = models.SlugField(max_length=250, blank=True) company_name = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) about_company = models.TextField(blank=True) description = models.TextField() city = models.CharField(max_length=250) job_location = models.CharField(max_length=250) KeySkill = models.TextField() eligiblity = models.TextField(blank=True) resposibility = models.TextField(blank=True) min_experience = models.FloatField() max_experience = models.FloatField() last_date_to_apply = models.DateField(default=timezone.now) min_salary = models.PositiveIntegerField() max_salary = models.PositiveIntegerField() shift_time = models.CharField(max_length=15, choices=shiftDetail) posted = models.DateField(default=timezone.now) number_of_position_opening = models.PositiveIntegerField(default=1) job_post_status = models.IntegerField(default=1, choices=job_post_status) def save(self, *arg, **kwargs): if not self.slug: self.slug = slugify(self.position) super(JobListing, self).save(*arg, **kwargs) def __str__(self): return str(self.position) + " -- " + str(self.company_name) Form.py class JobList(forms.ModelForm, forms.Form): job_location = forms.ModelChoiceField(queryset=CountryAndState.objects.filter(country__isnull=False).distinct()) Key_Skill = forms.ModelMultipleChoiceField( queryset=skill.objects.all().values_list('name', flat=True).distinct().order_by('name'), widget=forms.SelectMultiple, required=False, blank=True) class Meta: model = JobListing fields = ['position', 'number_of_position_opening', 'company_name', 'about_company', 'description', 'eligiblity', 'resposibility', 'city', 'job_location', 'KeySkill', 'Key_Skill', 'min_experience', 'max_experience', 'min_salary', 'max_salary', 'shift_time', 'last_date_to_apply'] exclude = ['slug', 'posted'] widgets = { 'KeySkill': forms.TextInput(attrs={'type':'text'}), 'about_company': forms.Textarea(attrs={'rows': 100, 'cols': 15}), 'last_date_to_apply': forms.DateInput(attrs={'type':'date'}) } def __init__(self, user, *args, **kwargs): super(JobList, self).__init__(*args, **kwargs) for field in self.fields.keys(): widget = self.fields[field].widget if 'cols' in widget.attrs and 'rows' in widget.attrs: … -
Django - using href to link to another view
In my home page i have 2 links that i would like to bring the user to different pages. How would i make the href link to a view i have created in views.py? Putting in the html file name in as the href and clicking it would make the url in the search bar appear as http://127.0.0.1:8000/qualifications/qualifications.html when i want it to be http://127.0.0.1:8000/qualifications/ (qualifications is my view / qualifications.html is my html page) HTML: <div id="nav_bar"> <ul> <li><a href="home.html">Home</a></li> <li><a href="qualifications.html">Qualifications</a></li> </ul> </div> views.py def qualifications(request): context = {"title": "Qualifications"} return render(request, "myApp/qualifications.html", context) urls.py urlpatterns = [ path("", views.home, name="home"), path("qualifications/", views.qualifications, name="qualifications"), ] -
Mongodb ID integer to Binary UUID format
The ID values of my objects are int format. I want to turn it into binary uuid format. For example, my old IDs: "id": 18, I want to new ID format like below: "id": { "$binary": { "base64": "0M8jsEQ2Sqii/MGhZ7lFFw==", "subType": "03" } }, And if possible, the new IDs should form automatically. I don't write one by one. Actually this question subject is Django. Because I used Mongodb in my django project. -
Adding Folium Popup Information to table beside map
I am building a map website using Pandas, Django and Folium, with popups displaying information about servers in locations. I am looking to include all the information that would display on a popup beside the map in a table. Here is an example popup I want it in a table like this table view Currently the table is a for loop iterating over a pandas dataframe. But that displays each row in the dataframe, not information about the specific marker, like the popup does. The code look like: locations = Location.objects.values() loc_data = pd.DataFrame(locations) for index, location_info in loc_data.iterrows(): # Popup design through Iframe - html variable contains basic html to redesign the popup html=f""" <h1>{location_info['hostname']}</h1> <p>Node Attributes: <ul> <li>Structure Name: {location_info["structurename"]}</li> <li>Domain: {location_info["domain"]}</li> <li>IP Address: {location_info["ip"]}</li> <li>Persona: {location_info["personas"]}</li> </ul> {location_info["cube"]} </p> <a href={location_info["cubeurl"]} target = "_blank">Login to cube</a> """ # Initialise the iframe as a variable and set the popup to be the iframe iframe = folium.IFrame(html=html, width=350, height=270) popup = folium.Popup(iframe, max_width=2650) # Add Markers to the map based on criteria if location_info["cube"] == "Industrial Cube North": folium.Marker([location_info["latitude"], location_info["longitude"]], popup=popup, icon=folium.Icon(color='darkred'), tooltip=f'''{location_info["hostname"]}''').add_to(m) elif location_info["cube"] == "Industrial Cube South": folium.Marker([location_info["latitude"], location_info["longitude"]], popup=popup, icon=folium.Icon(color='green'), tooltip=f'''{location_info["hostname"]}''').add_to(m) m=m._repr_html_() #updated context = {'map': … -
For loop on Django Template
I'm having a huge issue on making for loop on django templates, here are my files: urls.py app_name = 'statenews' urlpatterns = [ path('', views.home, name="home"), path('', views.category, name = 'category'),] models.py class Category(models.Model): name = models.CharField(max_length=65) ... class News(models.Model): ... category = models.ForeignKey( Category, on_delete=models.SET_NULL, null=True, blank=True, default=None, ) views.py def category(request): categories = Category.objects.all() return render(request,'partials/footer.html',{ 'categories': categories }) html template <div class="col-lg-3 col-md-6 mb-5"> <h4 class="font-weight-bold mb-4">Tags</h4> {% for category in categories %} <div class="d-flex flex-wrap m-n1"> <a href="" class="btn btn-sm btn-outline-secondary m-1">({category.name})</a> </div> {% endfor %} </div> -
Unable to update DateTimeField field with None value in Django
Background I am using django-post-office to create and queue email objects and use send_queued_mail django command (shipped with module) to process queued emails. I observed a bug when: MAX_RETRIES is either not set in settings or set to 0 When processing queued emails, at least one email failed to be sent. In my case it was due to the incorrect recipient address. It then used bulk_update to update failed emails i.e. Email.objects.bulk_update(emails_failed, ['status', 'scheduled_time', 'number_of_retries']) - Values used to update emails_failed are 1,None,0 Snippet of bug - django.db.utils.DataError: ('22018', '[22018] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Operand type clash: int is incompatible with datetime2 (206) (SQLExecDirectW); [22018] [Microsoft][ODBC Driver 17 for SQL Server][SQ L Server]Statement(s) could not be prepared. (8180)') I believe the cause of the error is updating scheduled_time column with value None since it is a DateTimeField however null=True is set in Email model. Please refer to snippet below to see schema of Email model (again shipped with django-post-office module). Snippet of Email Model scheduled_time = models.DateTimeField(_("Scheduled Time"),blank=True, null=True, db_index=True,help_text=_("The scheduled sending time")) status = models.PositiveSmallIntegerField(_("Status"),choices=STATUS_CHOICES, db_index=True,blank=True, null=True) number_of_retries = models.PositiveIntegerField(null=True, blank=True) Versions Django==3.2.13 Python==3.7 django-post-office==3.6.0 DB - SQL server Questions Is it reasonable to believe that SQL … -
Django Rest Framework call custom function when model is created
Suppose I want to do some extra stuff whenever a model is created in my Django App: models.py: class MyModel(models.Model): name = models.CharField(max_length=255) def do_some_extra_stuff(self): // whatever... return "I did some extra stuff" Suppose the extra stuff is some long-running asynchronous task. I am using Django Rest Framework and have a standard ModelSerializer and ViewSet. My question is where is the best place to put the call to do_some_extra_stuff ? I can think of the following options: In the serializer.create method In the viewset.create method In the model.save method In a post_save signal I am leaning towards #1 or #2 b/c I only want this fn to be called when normal users interact w/ the API - not when using the Django Admin or the shell. -
Unable to Run Django-Spirit raise InvalidTemplateLibrary( django.template.library.InvalidTemplateLibrary
I am trying to Run django-spirit and followed the documentation https://spirit.readthedocs.io/en/latest/installation.html and using version django-spirit 0.12.3 i followed as bellow Get started New in Spirit 0.5 Latest version can be installed through pip: Install Spirit: pip install django-spirit Start your site: spirit startproject mysite Set up the database: cd mysite python manage.py spiritinstall Create an administrator account: python manage.py createsuperuser python manage.py runserver python manage.py makermigrations python manage.py migrate when i push python manage.py runserver command it thorugh the bellow error. i have checked out the database too and its empy no tables/database is created i am using python 3.9 and the requirements versions as per the project requirements struggling since yesterday but no success PS C:\Users\gsminfinity.com\Desktop\gsminfinity.com\Spirit-master\community> python manage.py runserver Performing system checks... Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\gsminfinity.com\AppData\Local\Programs\Python\Python39\lib\site-packages\django\template\utils.py", line 66, in __getitem__ return self._engines[alias] KeyError: 'django' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\gsminfinity.com\AppData\Local\Programs\Python\Python39\lib\site-packages\django\template\backends\django.py", line 121, in get_package_libraries module = import_module(entry[1]) File "C:\Users\gsminfinity.com\AppData\Local\Programs\Python\Python39\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line … -
Can't make my registration form work properly
So I am watching youtube course wich name is "Python Backend Web Development Course (with Django)" and I ran into some problems here. I wrote the same code as in video but my registration form does not work. When I press Submit button no error-messages pops up and user does not register. Can you help me to solve this problem please? views.py def register(request): context = {} if request.method == 'POST': username = request.POST['username'] email = request.POST['email'] password = request.POST['password'] password2 = request.POST['password2'] if password == password2: if User.objects.filter(email=email).exists(): messages.info(request, 'Email is already used') return redirect('register') elif User.objects.filter(username=username).exists(): messages.info(request, 'Username is already used') return redirect('register') else: user = User.objects.create_user( username=username, email=email, password=password) user.save(); return redirect('login') else: messages.info(request, 'Password does not match') return redirect('register') else: return render(request, 'register.html') register.html <!DOCTYPE html> <html lang="en"> {% load static %} <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> </head> <body> <h1>Sign up</h1> <style> h5 { color: red; } </style> {% for message in messages %} <h5>{{message}}</h5> {% endfor %} <form mehod="POST" action="register"> {% csrf_token %} <p>Username:</p> <input type="text" name="username" /> <p>Email:</p> <input type="email" name="email" /> <p>Password:</p> <input type="password" name="password" /> <p>Confirm password:</p> <input type="password" name="password2" /><br /> <input … -
How to perform filtration in django and vuejs?
Currently , I have two inputs field , one for staff filtration and medical package filtration in the website. I can filter based on the staff but i cant filter based on the medical package. I had declared medical_package__in in filters.py. However, it still doesn't return any results if I filter based on medical package. Could anyone help me on this ? Backend - filters.py class StaffMedicalPackageFilter(FilterSet): staff__in = BaseInFilter(field_name="staff", lookup_expr='in') staff__username_in = BaseInFilter(field_name="staff__username", lookup_expr='in') department__in = BaseInFilter(field_name="staff__department", lookup_expr='in') medical_package__in = BaseInFilter(field_name="medical_package__id", lookup_expr='in') created_at__gte = DateTimeFilter(field_name="created_at", lookup_expr='gte') created_at__lt = DateTimeFilter(field_name="created_at", lookup_expr='lt') class Meta: model = StaffMedicalPackage fields = [ 'staff', 'staff__in', 'staff__username_in', 'medical_package__in', 'department__in', 'created_at__gte', 'created_at__lt',] Backend - view.py class StaffMedicalPackageList(generics.ListCreateAPIView): queryset = StaffMedicalPackage.objects.all() serializer_class = StaffMedicalPackageSerializer filterset_class = StaffMedicalPackageFilter permission_classes = [permissions.IsAuthenticated,] @decorators.api_view(['OPTIONS']) @decorators.permission_classes([permissions.IsAuthenticated,]) def staffmedicalpackage_filters(request): result = { "actions": { "POST": { "staff__in": { "type": "field", "required": False, "read_only": True, "label": "Staff" }, "medical_package__in": { "type": "field", "required": False, "read_only": False, "label": "Medical package", } } } } return response.Response(result) Backend - serializers.py class StaffMedicalPackageSerializer(serializers.ModelSerializer): staff_detail = StaffSerializer(read_only=True, source='staff') medical_package_detail = MedicalPackageSerializer(read_only=True, source='medical_package') current_year = serializers.ChoiceField(choices = YEARS, source = 'created_at', required=False) class Meta: model = StaffMedicalPackage fields = [ "id", "created_at", "updated_at", "current_year", "medical_package", "medical_package_detail", "staff", "staff_detail", … -
How to perform filtration in django and vuejs?
Currently , I have two inputs field , one for staff filtration and medical package filtration in the website. I can filter based on the staff but i cant filter based on the medical package. I had declared medical_package__in in filters.py. However, it still doesn't return any results if I filter based on medical package. Could anyone help me on this ? Backend - filters.py class StaffMedicalPackageFilter(FilterSet): staff__in = BaseInFilter(field_name="staff", lookup_expr='in') staff__username_in = BaseInFilter(field_name="staff__username", lookup_expr='in') department__in = BaseInFilter(field_name="staff__department", lookup_expr='in') medical_package__in = BaseInFilter(field_name="medical_package__id", lookup_expr='in') created_at__gte = DateTimeFilter(field_name="created_at", lookup_expr='gte') created_at__lt = DateTimeFilter(field_name="created_at", lookup_expr='lt') class Meta: model = StaffMedicalPackage fields = [ 'staff', 'staff__in', 'staff__username_in', 'medical_package__in', 'department__in', 'created_at__gte', 'created_at__lt',] Backend - view.py class StaffMedicalPackageList(generics.ListCreateAPIView): queryset = StaffMedicalPackage.objects.all() serializer_class = StaffMedicalPackageSerializer filterset_class = StaffMedicalPackageFilter permission_classes = [permissions.IsAuthenticated,] @decorators.api_view(['OPTIONS']) @decorators.permission_classes([permissions.IsAuthenticated,]) def staffmedicalpackage_filters(request): result = { "actions": { "POST": { "staff__in": { "type": "field", "required": False, "read_only": True, "label": "Staff" }, "medical_package__in": { "type": "field", "required": False, "read_only": False, "label": "Medical package", } } } } return response.Response(result) Backend - serializers.py class StaffMedicalPackageSerializer(serializers.ModelSerializer): staff_detail = StaffSerializer(read_only=True, source='staff') medical_package_detail = MedicalPackageSerializer(read_only=True, source='medical_package') current_year = serializers.ChoiceField(choices = YEARS, source = 'created_at', required=False) class Meta: model = StaffMedicalPackage fields = [ "id", "created_at", "updated_at", "current_year", "medical_package", "medical_package_detail", "staff", "staff_detail", … -
Render different ids for fields
forms.py class DateForm(forms.Form): date = DateField(widget=SelectDateWidget) views.py class TreatyDetail(View): def get(self, request, *args, **kwargs): template = loader.get_template('nonverbis_treaties_treaties/treaty_detail.html') toponym_name_set = ToponymName.objects.filter(toponym=treaty.toponym) context = { 'party_1_form': PartyForm(), 'party_2_form': PartyForm(), } return HttpResponse(template.render(context, request)) treaty_detail.html <p>{{ party_1_form }}</p> <p>{{ party_2_form }}</p> Rendered html <select name="party" required="" id="id_party"> <option value="" selected="">---------</option> <option value="1">USA</option> <option value="2">Japan</option> </select> <select name="party" required="" id="id_party"> <option value="" selected="">---------</option> <option value="1">USA</option> <option value="2">Japan</option> </select> I'd like to distinguish the two fields in JavaScript. And by the way, id is duplicated, which is a pretty nasty thing. Could you help me how to make the ids to be different? -
Celery Send Email on Due_date
Sending email to the users based on the due date in model using the celery, the due_date is something different from data when a task is created Models.py class Task(BaseModel): name = models.CharField(max_length=255) due_date = models.DateField(blank=True, null=True) -
api.urls are not working after using django-hosts for subdomain
i'm trying to use sub-domain for api in my project and using django-hosts for that.but after implementing it as documented there is Page not found (404) error is coming when I'm accessing any URL of my app 'api' project/hosts.py from django_hosts import patterns, host from .settings import base as settings host_patterns = patterns('', host(r'www', settings.ROOT_URLCONF, name='www'), host(r'api', 'apps.api.urls', name='api'), ) project/settings.py def ip_addresses(): ip_list = [] for interface in netifaces.interfaces(): addrs = netifaces.ifaddresses(interface) for x in (netifaces.AF_INET, netifaces.AF_INET6): if x in addrs: ip_list.append(addrs[x][0]['addr']) return ip_list ALLOWED_HOSTS = ip_addresses() ALLOWED_HOSTS.append('.localdemo.in') ALLOWED_HOSTS.append('.api.localdemo.in') INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'apps.core', 'apps.api', # Third party 'django_hosts', ] MIDDLEWARE = [ 'django_hosts.middleware.HostsRequestMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'drf_api_logger.middleware.api_logger_middleware.APILoggerMiddleware', 'django_hosts.middleware.HostsResponseMiddleware', ] ROOT_URLCONF = 'project.urls' ROOT_HOSTCONF = 'project.hosts' DEFAULT_HOST = 'www' project/urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('apps.core.urls')), ] handler404 = "apps.core.views.customerrors.custom_handler404" handler403 = "apps.core.views.customerrors.custom_handler403" apps/api/urls.py from django.urls import path, include, re_path from django.conf.urls import url from .views import statisticsview urlpatterns = [ path('v1/statistics', statisticsview.StatisticsListView.as_view(), name='statistics_list'), re_path(r'^statistics/$', statisticsview.StatisticsListView.as_view(), name='statistics_list'), re_path(r'statistics/', statisticsview.StatisticsListView.as_view(), name='statistics_list'), hosts file inside windows/system32/drivers/etc/hosts 127.0.0.1 localdemo.in 127.0.0.1 api.localdemo.in now when I'm accessing localdemo.in:8000 its working fine but I'm … -
Django: How would I create a secondary ID field that is grouped (ranked) by a given foreign key?
The output could look like this, for example: id secondary_id fk 1 1 1 2 2 1 3 3 1 4 1 2 5 2 2 For context: (see models below) I have a commission structure which will have brackets depending on how much a user is earning in a month. Ideally, I need to know in my Commission Bracket model, the bracket index for a given structure. Here are my models. class CommissionStructure(APIBaseModel): advisor = models.ManyToManyField(AdviserDetail) name = models.CharField(max_length=20, blank=True, null=True, default='default') company = models.ForeignKey(Company, on_delete=models.CASCADE) start_dt = models.DateTimeField(auto_now_add=True) end_dt = models.DateTimeField(default=timezone.datetime.max) objects = CommissionStructureManager() class CommissionBracket(APIBaseModel): <secondary_id ???> commission_structure = models.ForeignKey(CommissionStructure, on_delete=models.CASCADE, related_name="brackets") lower_bound = models.DecimalField(decimal_places=2, default=0.00, max_digits=20, null=True, blank=True) upper_bound = models.DecimalField(decimal_places=2, default=0.00, max_digits=20, null=True, blank=True) Please note, I may not have to store it on my model if I can add an annotation to an aggregate set, but my preference is to follow DRY. Thank you -
problems with testing the Django REST Framework
I'm trying to perform the tests that are within the Django Rest Framework documentation. And it always gives the same error, regardless of what I'm testing. Test example: class TestRequestFactory(APITestCase): def test_request(self): factory = APIRequestFactory() request = factory.post('/list_user/', json.dumps({'title': 'new idea'}), content_type='application/json') The error I'm referring to is this django.db.utils.ProgrammingError: relation "user" does not exist LINE 1: ...ted_by", "user"."created_ts", "user"."is_active" FROM "user" I've looked in many places and the solution has always been the same, do manage.py migrate or manage.py migrate --fake bots zero, I can do everything, but in the end it gives the same error -
Azure SDK for Python: Reading blobs without downloading
I'm currently using the Azure Blob Storage SDK for Python. For my project I want to read/load the data from a specific blob without having to download it / store it on disk before accessing. According to the documentation loading a specfic blob works for my with: blob_client = BlobClient(blob_service_client.url, container_name, blob_name, credential) data_stream = blob_client.download_blob() data = data_stream.readall() The last readall() command returns me the byte information of the blob content (in my case a image). With: with open(loca_path, "wb") as local_file: data_stream.readinto(my_blob) it is possible to save the blob content on disk (classic downloading operation) BUT: Is it also possible to convert the byte data from data = data_stream.readall() directly into an image? It already tried image_data = Image.frombytes(mode="RGB", data=data, size=(1080, 1920)) but it returns me an error not enough image data -
How can I use reverse relation items in templates django
{% for order in orders %} <li>{{order.customer.last_name}} - {{ order.orderitem_set.product.unit_price }}</li> {% endfor %} How can I get products unit_price in browser, last_name shows but when I am trying to use django reverse relation created item the value don't showing