Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Running django application via SSH on Windows
This question is related to the testdriven.io series of articles on how to build and deploy your Django application. In detail, my question is relatad to the second article of the three. Everything works fine as we build locally the application with nginx and gunicorn. Then, he uses a linux command ssh user@your-ip-or-domain to connect to the host, which I think might be the name of the domain he suggests to create with freenom.com. Now, I am on a Windows machine and have no idea how to perform this operation that he does not explain (should we copy the project on a virtualbox with linux? should you run an image of linux with docker?). The article I am referring is this in the "Running the Containers" paragraph. I am looking for a deeper explanation of that phase. Thanks a lot. which I do not know how to perform on Windows. -
Remove all items from cart after checkout in Django
I have a simple e-commerce app, and I'm trying to clear the cart after pressing the 'Proceed to checkout' button. After pressing it I should redirect to cart and I shouldn't see any OrderItem in the cart. Also the database instance should be deleted. How can I do? store/models.py class Item(models.Model): name = models.CharField(max_length=50) price = models.FloatField() def __str__(self): return self.name class OrderItem(models.Model): item = models.ForeignKey(Item, on_delete=models.CASCADE) quantity = models.PositiveIntegerField(default=1) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) ordered = models.BooleanField(default=False) def __str__(self): return f"{self.quantity} of {self.item.name}" def get_total_item_price(self): return self.quantity*self.item.price def get_final_price(self): return self.get_total_item_price() class Order(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) items = models.ManyToManyField(OrderItem) start_date = models.DateTimeField(auto_now=True) ordered_date = models.DateTimeField() ordered = models.BooleanField(default=False) def __str__(self): return self.user.username def get_total(self): total = 0 for order_item in self.items.all(): total += order_item.get_final_price() return total store/views.py class HomepageView(generic.ListView): model = Item template_name= 'store/index.html' context_object_name = 'item_list' class DetailView(generic.DetailView): model = Item template_name='store/detail.html' class CartView(generic.View): def get(self, *args, **kwargs): try: order = Order.objects.get(user=self.request.user, ordered=False) context = { 'object': order } return render(self.request, 'store/cart.html', context) except ObjectDoesNotExist: messages.warning(self.request, "You do not have an active order") return redirect("/") def checkout(request, user_id): #code to remove all items from cart return redirect('store:cart', user_id=user_id) -
Why do my if condition is not executing as expected in Django template?
what i am supposed to do? Okay, so I have a registration form and I want to verify if django message == "password not strong enough" and if this condition is true then execute this HTML code snippet <div class="alert alert-danger alert-dismissible fade show" style="margin-bottom: 0; font-size: 13px; margin-top: 0;" role="alert"> <p style="margin-top: 0; margin-bottom: 0rem; text-align: center;"> Your password is not strong enough. New passwords must: <li>Be at least minimum eight to maximum 16 characters long.</li> <li>Contain one or more numbers.</li> <li>With at least one small and one capital letter.</li> <li>Include at least one special character like: [@#(/)+]</li> </p> <button type="button" class="close" data-dismiss="alert" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> and if the above code doesn't execute then show a message coming from my Django views, which is written as follows <div class="alert alert-danger alert-dismissible fade show" style="margin-bottom: 0; font-size: 13px; margin-top: 0;" role="alert"> <p style="margin-top: 0; margin-bottom: 0rem; text-align: center;" {% if message.tags %} {% endif %}> {{ message }} </p> <button type="button" class="close" data-dismiss="alert" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> message conditions from views.py file if username_exists: messages.warning(request, "Username is not available") if email_exists: messages.warning(request, "Email id is already registered") if not pass_match: messages.warning(request, "Grr.. password does not match") if not … -
TypeError: expected str, bytes or os.PathLike object, not TemporaryUploadedFile while using eyed3
so i was using eyed3 to show information about song like artist and etc. but when i tried using it in django, it goes error : TypeError: expected str, bytes or os.PathLike object, not TemporaryUploadedFile i just tried like example, but it's not work. here's my views.py: def homepage(request): form = AudioForm() last_audio = Audio_store.objects.all().last() if request.method == "POST": form = AudioForm(request.POST, request.FILES) if form.is_valid(): audio = form.cleaned_data.get("audio") print(audio) audios = eyed3.load(audio) print (audios.tag.artist) print (audios.tag.album) print (audios.tag.title) context={'form':form, 'last_audio':audio} print(context) form.save() return render(request, "homepage.html", context=context) context={'form':form, 'last_audio':last_audio} return render(request, "homepage.html", context=context) -
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 …