Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to get m2m field in validated_data?
I've a model: class ListingPrice(Timestamps): price = models.ForeignKey("Price", on_delete=models.CASCADE) location = models.ForeignKey("location", on_delete=models.CASCADE) class Meta: unique_together = ["price", "location"] class Price(Timestamps): package = models.ForeignKey("products.Package", on_delete=models.CASCADE) locations = models.ManyToManyField("location", through="ListingPrice") price = models.DecimalField(max_digits=11, decimal_places=3) with a serializer: class LocationSerializer(serializers.ModelSerializer): name = LocalizedField() class Meta: model = location fields = ['id', 'name'] class PriceSerializer(serializers.ModelSerializer): locations = LocationSerializer(many=True, read_only=True) class Meta: model = Price fields = ['package', 'locations', 'price'] def create(self, validated_data): print("validated_data, validated_data) and viewset: class PriceViewSet(ModelViewSet): queryset = Price.objects.all() serializer_class = PriceSerializer ordering = ['id'] permissions = { "GET": ["view_minimum_listing_price", ], "POST": ["add_minimum_listing_price", ], 'PUT': ['update_minimum_listing_price', ], 'DELETE': ['delete_minimum_listing_price', ], } In testing I'mm using the following: data = { "price": 12, "package": self.package.id, "is_enabled": False, "location": self.location } response = self.client.post(path=self.url, data=data, format='json') locations doesn't appear in validated_data? How to get it to assign locations to the instance with post requests? I also tried to send it with as ids list, but non works. I only field price, package, is_enabled in validated}_data, but location doesn't appear! -
Django admin drop down with very long description/text
just like the pic in admin panel when creating some post: that basically one of dropdown menu options, it is so long, is there any idea on how i can change it to be multi-line? or maybe change the drop down menu to a "select table", the admin in this case need to read the description, so it is unwise for it to be formatted like that. I have a code example: models.py class CreatePost(models.Model): subject = models.CharField(max_length=99) desc = models.TextField(max_length=9000) isSolved = models.BooleanField(default=False) # a button user = models.ForeignKey(User, on_delete=models.CASCADE,related_name="user_post") def __str__(self): return format_html('SUBJECT : {} <br/> DESCRIPTION : {} <br/> Email : {} <br/> ',self.subject, self.desc, self.user.username) # remember to show the name of ticket sender class RespondToPost(models.Model): ticket = models.ForeignKey(CreatePost,on_delete=models.CASCADE) to = models.EmailField(max_length=320) content = models.TextField() def __str__(self): return format_html('SUBJECT : {} <br/> DESCRIPTION : {} <br/> EMAIL : {} <br/> ',self.post.subject, self.post.desc, self.post.user.username) admin.py class CreatePostAdmin(admin.ModelAdmin): list_display = ('id', '__str__') class Meta: model = models.CreatePost class RespondToPostAdmin(admin.ModelAdmin): list_display = ('id', '__str__', 'to', 'content') class Meta: model = models.RespondToPost any idea? -
Django: UserAuthentication | ModuleNotFoundError: No module named 'userAuthentication'
I've been trying to create a user login and logout with django's bulid-in authenticated views. I changed the project-level URL pattern urlpatterns = [ path('admin/', admin.site.urls), path('accounts/',include('django.contrib.auth.urls')), path('', include('home.urls')), ] added template registration/login.html enter image description here and updated LOGIN_REDIRECT_URL in settings.py but still getting ModuleNotFoundError: No module named 'userAuthentication'.i dont know if iam missing anything in these it would be appreciated if anyone can give the heads up. note: i was trying the recreate exactly this go to :https://docs.djangoproject.com/en/4.0/topics/auth/default/ ctrl+f : Authentication Views -
React Django CSRF token missing or incorrect
In action file the code: ... const config = { headers:{ 'Content-type': 'application/json' } } const {data} = await axios.post('http://localhost:8000/api/register/', {'email':email, 'password':password}, config) ... It's working; then localhost:8000 put to package.json as a proxy, after that got an issue CSRF token missing or incorrect, how to fix that, thanks. Application was restarted with no changes. -
How to ADD for loop result in templates
views.html {% for products in product %} <tr> <td>{{ products.quantity_deliver1 }}</td> <td>{{ products.quantity_deliver2 }}</td> <td>{{ Code Here }}</td> </tr> {% empty %} <tr> <td colspan="3" class="text-center bg-warning">No Products</td> </tr> {% endfor %} How do I add products.quantity_deliver1 + products.quantity_deliver2 and output the sum in the 3rd data cell. -
News API in django python?
Iam Using a newsapi key in my website, when I try to access only one news I having trouble? How can I access Only one Particular news in my page? (not whole news using loop) views.py API_KEY = '1099d3305d5c43f0ba9706b17dd1fe1c' def sports(request): url = f'https://newsapi.org/v2/top-headlines?language=en&category=sports&apiKey={API_KEY}' url2 = f'https://newsapi.org/v2/top-headlines?language=en&apiKey={API_KEY}' response = requests.get(url) response2 = requests.get(url2) data = response.json() data2 = response2.json() articles = data['articles'] articles2 = data2['articles'] context = { 'articles' : articles, 'articles2' : articles2 } return render(request, 'app/sports.html', context) -
Invalid literal for int() with base 10 in my views after it worked a while
I'm keep getting this error Invalid literal for int() with base 10 from the views in my django project after it worked for a while , Traceback (most recent call last): File "/srv/cc/env/lib/python3.7/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/srv/cc/env/lib/python3.7/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/srv/cc/env/lib/python3.7/site-packages/django/contrib/auth/decorators.py", line 21, in _wrapped_view return view_func(request, *args, **kwargs) File "./core/views.py", line 133, in send_message if int(uid2) == uid: Exception Type: ValueError at /msg/new Exception Value: invalid literal for int() with base 10: '4,016' Here is My views.py looks like def chat_detail(request, pk): chat = Chat.objects.get(pk=pk) added, lm = chat.new(request.user) if lm: lm.msg = chat.current_last_msg lm.save() recepient = chat.recepient(request.user) return render(request, 'core/chat.html', {'chat': chat, 'recepient': recepient}) def chat_with_user(request, uid): chat = Chat.get_or_create(request.user.id, int(uid)) return redirect(f'/chat/{chat.id}') def chats(request): user_chats = [] for c in Chat.of_user(request.user): user_chats.append({'rec': c.recepient(request.user), 'unread': len(c.new(request.user)[0]), 'chat': c}) return render(request, 'core/chats.html', {'user_chats': user_chats}) def send_message(request): if request.method == 'POST': m = Message() uid = request.user.id uid2 = request.POST.get('uid2', None) if uid2 is None: return {} if int(uid2) == uid: return {} m.chat = Chat.get_or_create(uid, int(uid2)) m.sender = request.user m.text = request.POST.get('text') m.save() return redirect(f'/chat/{m.chat.id}') else: return {} And here all the message models.py class LastMessage(models.Model): chat … -
how to use @property in Django models? how to get the details of company models and futsalusers in to single table?
class FutsalUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField(verbose_name='email address', max_length=255, unique=True) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) is_staff = models.BooleanField( _('staff status'), default=True, help_text=_('Designates whether the user can log into this admin site.'), ) objects = FutsalUserManager() USERNAME_FIELD = 'email' def __str__(self): return self.email @property def company_details(self): company_data = Company.objects.filter(user= self) if company_data : company_data.name return company_data else: return None class Company(TimeStampedModel): name = models.CharField(max_length=200) hr_name = models.CharField(max_length=200) hr_email = models.CharField(max_length=200) user = models.ForeignKey( settings.AUTH_USER_MODEL, models.DO_NOTHING) hr_verified = models.BooleanField(default=False, blank=True) primary_phone = models.CharField(null=True, max_length=200) followed_by = models.CharField(max_length=200,default="Not assigned") comments = models.TextField(default="") def __str__(self): return self.name -
Django add new line (break line) to display list of some foreign key
This is what i have done so far to break a line: class CreatePost(models.Model): subject = models.CharField(max_length=99) desc = models.TextField(max_length=9000) user = models.ForeignKey(User, on_delete=models.CASCADE,related_name="user_post") def __str__(self): return format_html('SUBJECT : {} <br/> DESCRIPTION : {} <br/> Email : {} <br/>', (self.subject, self.desc, self.user.username)) for admin.py class CreatePostAdmin(admin.ModelAdmin): list_display = ('id', 'subject', 'desc') class Meta: model = models.CreatePost class RespondToPostAdmin(admin.ModelAdmin): list_display = ('id', 'post', 'to', 'content') class Meta: model = models.RespondToPost I am dealing with RespondToPostAdmin and i am getting error regarding the formatting in string dunder method: Exception Type: IndexError Exception Value: Replacement index 1 out of range for positional args tuple ``` i am not sure why, any help is appreciated, if there is better solution to format my string dunder method to add breaklines/new lines, please suggest me -
Multiple image upload in Django admin
I am having a lot of trouble trying to code the correct model to upload multiple images to my Django app. I want to be able to upload these images via the django admin. I have tried using ImageField but it only allows one pic at a time and I also want to be able to resize the image. Here is my models.py: class Lesson(models.Model): DRAFT = 'draft' PUBLISHED = 'published' CHOICES_STATUS = ( (DRAFT, 'Draft'), (PUBLISHED, 'Published') ) ARTICLE = 'article' QUIZ = 'quiz' CHOICES_LESSON_TYPE = ( (ARTICLE, 'Article'), (QUIZ, 'Quiz') ) course = models.ForeignKey(Course, related_name='lessons', on_delete=models.CASCADE) title = models.CharField(max_length=255) slug = models.SlugField() short_description = models.TextField(blank=True, null=True) long_description = models.TextField(blank=True, null=True) status = models.CharField(max_length=20, choices=CHOICES_STATUS, default=PUBLISHED) lesson_type = models.CharField(max_length=20, choices=CHOICES_LESSON_TYPE, default=ARTICLE) Serializer.py: class LessonListSerializer(serializers.ModelSerializer): class Meta: model = Lesson fields = ('id', 'title', 'slug', 'short_description', 'long_description') Admin.py: class LessonAdmin(admin.ModelAdmin): list_display = ['title', 'course', 'status', 'lesson_type'] list_filter = ['status', 'lesson_type'] search_fields = ['title', 'short_description', 'long_description'] inlines = [LessonCommentInline] -
Django Ajax jquery 404 (Not Found)
could someone help me find a way to make my ajax request work? I found some of the same questions on this site but didn't solve them. I want to Ajax the process to show modal I'm using the latest Django version. I have never used ajax, so I don't really know what I'm doing. Please help What should I specify for the url? Url to display Ajax? Url to process Ajax? app.urls.py urlpatterns = [ path('admin/', admin.site.urls), path('test/', include('test.urls')), ] test/urls.py urlpatterns = [ path('rex/', IndexView.as_view(), name='rex_index'), ] test/templates/test/rex.html {% extends 'main/layout.html' %} {% block content %} {% load crispy_forms_tags %} <!--modal--> <script> $(function(){ $('#edit_foo').on('click', function () { console.log("test") $.ajax({ type: 'POST', url: '/rex_index/', data: { html: '<form id="form_foo"><textarea></textarea><input type="submit"></input></form>', delay: 1, }, success: function (data, textStatus, jqXHR) { $('#foo_modal').find('.modal-body').html(data); $('#foo_modal').modal('show'); }, }); }); }); // Handle submit. Here we return an error regardless of the // input given: $("#foo_modal").on('submit', '#form_foo', function (e) { $.ajax({ type: 'POST', url: '/rex_index/', data: { html: '<form id="form_foo_2"><span class="error">You must write something silly here:</span><textarea></textarea><input type="submit"></input></form>', delay: 0, }, success: function (data, textStatus, jqXHR) { $('#foo_modal').find('.modal-body').html(data); }, }); e.preventDefault(); return false; }); // Handle second submit. Here we close the modal. // In a … -
Django: how to make other changes when I am deleting an object?
I did some searching and knew there is something like post_delete signal I can play with. But are there any other ways to do the same thing like the save() function in a Model but in the other way round? Something like this, probably? class MyModel(models.Model): my_field = models.CharField() def delete(self, *args, **kwargs): # instead of save() # do something here return super(MyModel, self).delete(*args, **kwargs): # instead of save() -
Adding an aliasName for url name app django
In a django project, I have an app : app_signup. INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'app_signup', Is it possible to add an alias to the app in order to see the alias (http://localhost:8000/alias/) instead of the name of the app(http://localhost:8000/app_signup/) in the url on the browser. -
Django Tabs Not Becoming Active
When the user logins he can select different tabs to display. The current issue is that none of the other tabs are selected except for the current active tab. How would I open each tab? {% block content %} <div class="col-3"> <h1>Hi {{ user.username }}!</h1> <img class="profile-pic" src="{{user.avatar.url}}" style='object-fit: cover; border-radius:50%;'> {% include 'form.html' %} <div class="nav flex-column nav-tab" id="nav-tab" role="tablist" aria-orientation="vertical"> <a class="nav-link active" id="nav-home-tab" data-toggle="tab" href="#home" role="tab" aria-controls="nav-home" aria-selected="true">Dashboard</a> <a class="nav-link" id="nav-messages-tab" data-toggle="tab" href="#messages" role="tab" aria-controls="nav-messages" aria-selected="false">Messages</a> <a class="nav-link" id="nav-documents-tab" data-toggle="tab" href="#documents" role="tab" aria-controls="nav-documents" aria-selected="false">Documents</a> <a class="nav-link" id="nav-logout-tab" data-toggle="tab" href="{% url 'logout' %}" role="tab" aria-controls="nav-logout" aria-selected="false">Log out</a> </div> </div> <div class="col-9"> <div class="tab-content" id="nav-tabContent"> <div class="tab-pane fade show active" id="nav-home" role="tabpanel" aria-labelledby="nav-home-tab">Home</div> <div class="tab-pane fade" id="nav-messages" role="tabpanel" aria-labelledby="nav-messages-tab">Messages</div> <div class="tab-pane fade" id="nav-documents" role="tabpanel" aria-labelledby="nav-documents-tab">Documents</div> </div> </div> {% endblock %} -
How to render string literal with html tags in django?
I've wrote a custom view to parse markdown files using regex and I'm passing content as a string literal to the template context = "Django is a web framework written using <a href='https://www.python.org/'>Python</a>" return render(request, "blog/post.html", {"context": context}) And in template: <p>{{ context }}</p> But the engine renders content as a plain text. How to make links to be links and paragraphs to be paragraphs? -
Django TemplateView + From does not upload files
I created a dynamic form to upload data to a jsonfield: class ProductForm(forms.Form): def __init__(self, product, *args, **kwargs): super().__init__(*args, **kwargs) self.fields["number"] = forms.IntegerField(required = True) self.fields["number"].widget.attrs.update({'class': 'form-control'}) for key in product.data.keys(): keyname, keytype = key.split("___") if keytype == "str": self.fields[key] = forms.CharField(required = False) elif keytype == "file": self.fields[key] = forms.FileField(required = False) self.fields[key].widget.attrs.update({"class": 'form-control'}) class Meta: model = Product fields = ["id", "number", "data"] I have a TemplateView in place that deals with the request: class ProductUpdateView(TemplateView): template_name = "appName/EditProduct.html" def post(self, request, *args, **kwargs): print(request) ... return render(request, self.template_name, context) But the request I get back looks like this: <QueryDict: {'number': ['3'], 'name___str': ['testname'], 'upload_1___file': ['[object File]']}> and thus request.FILES reads <MultiValueDict: {}> empty. How can I obtain the file? -
Django DetailView form dont save data
I have a DetailView, and need add a form to user contact. views.py class ProductView(FormView, DetailView): model = Product template_name = 'product_detail.html' form_class = NotificationForm success_url = '/products/' def post(self, request, *args, **kwargs): return FormView.post(self, request, *args, **kwargs) forms.py class NotificationForm(ModelForm): ..."""some fields""" class Meta: model = Notification fields = [ 'usernameclient', 'emailclient', 'emailclient_confirmation', 'phoneclient', 'messageclient', ] The model Notification is where is stored the data from that form models.py class Notification(models.Model): ..."""some fields""" I dont understand yet how django workflow with forms. After the submition is correct rediretc to success_url, but nothing is save in db... What is missing? -
Javascript async send query to Django query database then update the same html template
Assuming I have something need to be sent by javascript asynchronously without refreshing the page. name.html {%if names%} {%for name in names%} <h4>{{name}}</h4> {%endfor%} {%endif%} In name.html, I am going to send "Joe" to my Django backend for querying let crsf = '{{csrf_token}}' fetch('{%url "name"%}', { credentials: 'same-origin', headers: { 'X-CSRFToken': crsf, 'Content-Type': 'application/json', 'Accept': 'application/json, text/plain, */*'}, method: 'POST', body: JSON.stringify({ data: "Joe", }),}).then(res=>console.log(res)) Now "Joe" has been sent to the backend In views.py: def name(request): names = Names.objects.all() paginator = Paginator(names, 100) page = request.GET.get('page') paged_names = paginator.get_page(page) context = { 'names':paged_names, } if request.method == 'POST': data = json.loads(request.body.decode("utf-8")) joe = data.get("data") names = Names.objects.all() names = names.filter(name__iexact=joe) context = { 'names':names, } # return render(request, 'cool/names.html', context) return render(request, 'cool/names.html', context) Now I have all names named "Joe" queried out from the database. Question: How do I then render all "Joe"s in name.html and also making pagination work as intended assuming there are over 20k "Joes". -
Django: Form for icalendar to create ics
I am working on a Django application for my friends to organize some tournaments. I want to have an overview of upcoming events and for every event there should be the possibility to download an ics-file with the details. I came across this post How can I dynamically serve files and then make them downloadable in Django? but I was wondering if anyone has an idea how the get_calendar_details(name) function has to look like as I am struggling with the right format. Currently I have the following within my application: models.py class Events(models.Model): title = models.CharField(max_length=64, unique=True) description = models.TextField(default=None) start = models.DateTimeField() end = models.DateTimeField() To render the page with all the events that are upcoming: views.py def events(request): today = datetime.today() events = Events.objects.filter(date__gte=today) return render(request, "events.html", { "events": events }) and my html <table> <thead><tr> <td>start</td><td>end</td><td>title</td><td>description</td><td>link</td> </tr></thead> {% for event in events %} <tr><td>{{ event.start }}</td> <td>{{ event.end }}</td> <td>{{ event.title }}</td> <td>{{ event.description }}</td> <td><a href={% url 'serve_calendar' %}>ics</a></td></tr> {% endfor %} </table> Any input is appreciated, especially if I am on the write track with my model. Many thanks in advance! -
how to integrate XML Schema, XML gateway API in django
i am working in a web application to register a company online via API. but i know how to work with restful API's, basically my mind set is to get an http link to make POST and GET request as per API type. but in this case i have a link contains of XSD schemas, here is the link. i dont have any idea how to test and get started. please anyone know how to work with XML gateway, or any link to follow where may i get the process to integrate XML gateway with django to make a POST request. will be thankful for your answer. -
Django Add object Count and Raw SQL in Javascript
def dashboard(request): employee = Employee.objects.count() position1 = Posit.objects.raw('SELECT employee.stat, count(posit.position_id) as NO FROM employee, posit WHERE employee.id = posit.employee_id AND posit.position_id="1" GROUP BY employee.stat') context = { 'employee ': employee , 'position1': [pos for pos in position1] , } return render(request, 'dashboard/dashboard.html', context) I can use employee count inside the javascript. var x = JSON.parse("{{employee}}"). How do I add position1 into a variable in javascript. Because when I add var y = JSON.parse("{% for pos in position1 %}{{pos.NO}}{% endfor %}"). I got this error Invalid block tag on line 96: 'endblock', expected 'empty' or 'endfor'. Did you forget to register or load this tag? Here is the whole error 86 87 } 88 } 89 }; 90 window.onload = function () { 91 window.myRadar = new Chart(document.getElementById("canvas"), config); 92 }; 93 var colorNames = Object.keys(window.chartColors); 94 </script> 95 96 {% endblock %} 97 {% block content %} -
hello i want to start a function when the server is starting and re execute it every 30 seconds in python
apps.py class MyappConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'myapp' def ready(self): if 'runserver' not in sys.argv: print("server down") else: from .models import Dht11 asset = Dht11.objects.select_related('asset').order_by('-id').first() print(str(asset.dt)+" / "+str(asset.id)) time.sleep(10) # you must import your modules here # to avoid AppRegistryNotReady exception # from .models import MyModel # startup code here while True: ready() This is my code in apps.py but it gives me an exception: TypeError: ready() missing 1 required positional argument: 'self' -
Django update related objects on save using signals
I am coming across an issue that I cannot figure it out. I have created a simple multi step form to help the user to create a Project. A brief explanation: Project is the main model ProjectDetails add information to the Project. There can be 'n' ProjectDetails to one Project. Every details include a Trade that is a ForeignKey of ProjectDetails. There can be only one Trade for every ProjectDetail class Trade(models.Model): ... shipped_quantity = models.IntegerField(default=0) status = models.IntegerField( choices=Status.choices, default=Status.CREATED ) class Project(models.Model): ... quantity = models.IntegerField(default=0) status = models.IntegerField( choices=Status.choices, default=Status.INIT ) class ProjectDetail(models.Model): project = models.ForeignKey(Project, on_delete=models.CASCADE, default='', blank=True, null=True, related_name='details') trade = models.ForeignKey(Trade, on_delete=models.SET_NULL, default='', blank=True, null=True, related_name='project') quantity = models.IntegerField() Once the user complete the last step and finalize the creation of the Project, I would like to update some related fields: a) adding up all the Trades quantity and update the Project Quantity b) update for each Trade the shipped_quantity c) update status of each Trade Here it is my view.py code: def project_create_complete(request, *args, **kwargs): # Final step to complete the project creation # update the status to SAVED and delete the session if request.POST: project = Project.objects.get(id=request.POST['project_id']) if project.status < Project.Status.SAVED: project.status … -
How To: For...Else in a Django template (if/else inside a for loop)
I apologize in advance if this has already been asked, but I couldn't find any answers that answered the problem I'm having: I need to do something similar to a For...Else loop in a Django template. I need to show a button on a template base on an if condition: If the user has already bought this product, then show button 1 If the user has not bought this product, then show button 2 For each product, I have to go through the user's purchases, and then show one button or the other depending on whether they have already bought the product or not. A simplified (and wrong) version of the code would be like: {% for product in products %} //other code here {% for purchase in purchases %} {% if purchase.service_id.id == product.id %} // show button 1 {% else %} // show button 2 {% endif %} {% endfor %} {% endfor %} However, this code doesn't work, as it shows both buttons as it goes through the for loop. I can't do a For...Empty because the user may have other purchases (so the for loop wouldn't be empty), but none of them coincide with this product. … -
Django Rest Framework Filtering does not response 'No Data Found' when no data found
I have a very simple DRF ListApiView which is using filters.SearchFilter as filter_backend. But the problem is it is returning an empty list if no data is found on the queryset. My Code: serializers.py class PhoneSerializer(serializers.ModelSerializer): brand_name = serializers.CharField(source='brand') class Meta: model = models.Phone fields = '__all__' views.py class PhoneApiView(generics.ListAPIView): filter_backends = [filters.SearchFilter] serializer_class = serializers.PhoneSerializer queryset = models.Phone.objects.all() search_fields = ['model_name', 'jan_code'] Result for a successful search [ { "id": 6, "brand_name": "Oppo", "model_name": "Oppo Reno 5", "image": "http://127.0.0.1:8000/media/phone/reno-5-black-2.jpg", "colors": "Red, Blue", "jan_code": "785621716768184", "brand": 6 } ] Expected Result if nothing found (Currently returning an empty list []) { "response": 'No Data Found' } Now, How do I do that? Thanks