Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Add Radio button in default Django form:
I think I have written the correct code. But this gender radio button is not appearing in my form. This is my model view. class Charter(models.Model): CHOICES = [('M', 'Male'), ('F', 'Female'), ('O', 'Others')] Gender = forms.ChoiceField(label='Gender', widget= forms.RadioSelect(choices=CHOICES)) created_at = models.DateField() First_name = models.CharField(max_length=200, unique=True) Last_name = models.CharField(max_length=200, unique=True) address = models.CharField(max_length=200, unique=True) Cell_no = models.CharField(max_length=200, unique=True) created_at = models.DateField() This is my forms.py from django.forms import ModelForm from .models import * class CharterForm(ModelForm): class Meta: model= Charter fields = '__all__' widgets = { 'Gender': forms.RadioSelect() } -
How to override/exempt django's django.middleware.clickjacking.XFrameOptionsMiddleware option
Hello I am making a website, which includes me having to embed Disqus comment system in the views But the thing is I use django==3.1.1 which includes the option django.middleware.clickjacking.XFrameOptionsMiddleware in the middleware That is fare enough for security, but what I want is just for the home view that renders the template to be excluded from django.middleware.clickjacking.XFrameOptionsMiddleware protection Also if possible how can I prevent the same issue in the django-admin I knew this in the web browser console saying X-Frame-Options is set to deny -
Elastic search in Django with no query, only filter
I have a Django project for which I'm converting the regular DB search to elastic search. What currently happens is that there is a select to retrieve data from the DB based only on a date, basically to retrieve the most recent items. I'm trying to reproduce this behaviour with the django_elasticsearch_dsl but it keeps failing. I need a queryset because of how the whole app is structured. The method to_queryset() works just fine if I have a query term, but I get an error object of type 'Search' has no len() if I there is no query term. Something I tried: search = document.search() if query: search = search.query("multi_match", query=query, fields=["title", "body", "excerpt"]) search = search.filter("range", modified_at={"gte": date_from}) search = search.filter("range", modified_at={"lte": date_till}) object_list = search.to_queryset() This is inside a django arctic app, if that's relevant. I also tried using search = search.query() (with no params) and then adding the filters, but I get the same error. It sounds silly but is this possible to do? -
how to access the header and data which is send with the url in django?
This below code calls the django url with the data and the header. ''' return new Promise((resolve, reject) => { $http({ url: servicesUrl + "testapi/", method: "POST", data: { reportStandardName: moduleName, moduleKey, reportFormat, intervalFromDays, intervalToDays, fromReportTime: moment(fromReportTime, "HH:mm:ss").format('HH:mm:ssZZ'), toReportTime: moment(toReportTime, "HH:mm:ss").format('HH:mm:ssZZ'), reportID, phononUUID, attemptID, requestID, queueIds, flowIds, callStatus, sourceOfRequest: "API", priority: 1, reportTime: new Date().toLocaleTimeString(), } ''' and below is the django urls file code. ''' urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^testapi/', views.getResponse) ] ''' so how to access the header and the data send with the URL? -
Passing variable value in url via views django
Not sure how to pass variable param value in url View.py def show_email(request, param): param = 'abc@oranization.com' return render(request, 'abc.html') HTML <a class="btn btn-primary" href="/url/<param>">Check Inbox</a> -
Why Django form_valid is calling twice?
I am using form_valid() to save my data from form and redirecting to specific page using a condition in get_success_url but form_valid() is calling twice. i saw some people resolved with: return HttpResponseRedirect(self.get_success_url()) and return HttpResponseRedirect(self.request.META['HTTP_REFERER']) But found no help with my condition. My code from views.py def form_valid(self, form): form.instance.closed_date = timezone.localtime(timezone.now()) context = self.get_context_data() invites = context['meetinginvites'] with transaction.atomic(): if invites.is_valid(): self.object = form.save() invites.instance = self.object invites.save() # Notification meeting = Meeting.objects.get(pk=self.object.id) guests = RSVP.objects.filter(meeting=meeting.id).values_list('responder__user', flat=True) users = User.objects.filter(pk__in=guests) notify.send(self.request.user, recipient=users, verb="Closed Meeting") return super().form_valid(form) def get_success_url(self): if self.request.POST.get('page') == 'meeting': id = self.request.POST.get('pass_id') return reverse_lazy('Event:meeting-detail', kwargs={'pk': id}) else: return reverse_lazy('Event:allmeeting_view') -
why are my django forms not showing up on my site
what i want to do: i want to have a login form that when details are entered they are saved on the admin side. my problem: the forms are not showing up on my local host page. see image below: here is the code from the login form app: admin.py: from django.contrib import admin # Register your models here. from .models import Contact admin.site.register(Contact) from apps.py: from django.apps import AppConfig class ContactConfig(AppConfig): name = 'contact' from forms.py from .models import Contact class ContactForm(forms.ModelForm): class Meta: model = Contact fields = ('username', 'password') from models.py: class Contact(models.Model): username = models.CharField(max_length=100) password = models.CharField( max_length=100, ) def __str__(self): return f'{self.username} {self.password}' ``` from views.py: ``` from django.shortcuts import render # Create your views here. from .forms import ContactForm def contact(request): template = "home2.html" if request.method == "POST": form = ContactForm(request.POST) if form.is_valid(): form.save() else: form = ContactForm() context = { 'form': form, } return render(request, template, context) ``` then finally from the login page: ``` {% load crispy_forms_tags %} {% load static %} <form method="post" class="form"> {% csrf_token %} {{ form }} <button type="submit" class="btn"><a href="£">Log In</a></button> </form> another thing forms ar connected to admin side but just do not appear on … -
How do I make my django application run on specific devices only?
I have created a django application, now I want to make sure that some of the pages in the application is not accessed by anyone who has the IP to the app. I want to make a list of devices by either giving them specific ID(the first time the app is run on the device) or by making a list of IP that are allowed to visit the application. How should I go about this? -
POST data only if you are authenticated and only to your user using django-rest-framework
i'm new to Django so sorry if this seems stupid. i want to add an item to a database only if the user is authenticated . here are the models: class SaleItems(models.Model): product_name = models.CharField(max_length=50) price = models.IntegerField() product_type = models.CharField(max_length=25) description = models.CharField(max_length=250 ,default='', blank=True) brand = models.CharField(max_length=25, null=True,blank=True) image_path = models.ImageField(upload_to='images/product_image') date_added = models.DateField(auto_now_add=True) in_stock = models.BooleanField(default=True) def __str__(self): return f"{self.product_name}, price={self.price}" class SaleHistory(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) product = models.ForeignKey(SaleItems, on_delete=models.RESTRICT, default=None) date_bought = models.DateTimeField(auto_now_add=True) def __str__(self): return f'{self.date_bought}, {self.product}, {self.user}' the serializers: class SaleItemSerializer(serializers.ModelSerializer): class Meta: model = SaleItems fields = '__all__' class SaleHistorySerializier(serializers.ModelSerializer): class Meta: model = SaleHistory fields = '__all__' urls: routes = routers.DefaultRouter() routes.register('api/saleitems', SaleItemViewSet, basename='saleitem') routes.register('api/salehistory', SaleHistoryViewSet, basename='salehistory') urlpatterns = [ path('',include(routes.urls)) ] and finally the apis class SaleItemViewSet(viewsets.ModelViewSet): queryset = SaleItems.objects.all() permission_classes = [permissions.AllowAny] serializer_class = SaleItemSerializer class SaleHistoryViewSet(viewsets.ModelViewSet): # queryset = SaleHistory.objects.all() permission_classes = [permissions.IsAuthenticated] serializer_class = SaleHistorySerializier def get_queryset(self): user = self.request.user return SaleHistory.objects.filter(user = user) so the problem, when i post to 'api/salehistory' i am able to add content to any user not only as the authenticated user. (using knox authtoken for authentication). Say for example i am authenticated as user1 and i have my auth token. Now … -
Django models create() and save() not persisting in database (pk / id attribute on instance is not set)
I am using Django 2.2 This is my model models.py class WebPage(models.Model): breadcrumb = models.CharField(blank=False, null=False, max_length=128, unique=True) slug = models.SlugField(blank=False, null=False, max_length=128, unique=True) content = RichTextField() creator = models.ForeignKey(User, blank=True, null=True, on_delete=models.SET_NULL) is_published = models.BooleanField() created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.breadcrumb def save(self, *args, **kwargs): if not self.id: self.slug = slugify(self.breadcrumb) ./manage.py shell >>> wp=WebPage.objects.create(breadcrumb='hello/there', content='<span></span>') >>> wp.id >>> wp.save() >>> wp.id >>> wp.slug 'hellothere' >>> wp.save(persist=True) >>> wp.id >>> Why is the object not being saved to the database - and how do I fix this? -
<int:pk> url mapping error , <int:pk> not passing
here is my html link from where i want to use int:pk <a href= "/main/profile/edit/{{ user.myprofile.id }}" >Edit Profile</a> when i click on the link i get a url mapping error Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/main/profile/edit/ Using the URLconf defined in lunarcodes.urls, Django tried these URL patterns, in this order: main/ home/ main/ profile/ main/ feed/ main/ profile/edit/<int:pk> here is my urls.py, urlpatterns = [ path('profile/edit/<int:pk>', views.MyProfileUpdateView.as_view(success_url="/main/profile")), ] this is my views.py, @method_decorator(login_required, name="dispatch") class MyProfileUpdateView(UpdateView): model = MyProfile fields = ["name", "description", "pic"] this is my models.py, class MyProfile(models.Model): name = models.CharField(max_length = 100) user = models.OneToOneField(to=User, on_delete=CASCADE) description = models.TextField(null=True, blank=True) pic= models.ImageField(upload_to = "images\\", null=True) def __str__(self): return "%s" % self.user i myself couldn't understand the problem properly as i am begginer. -
Django + React + Babel + Heroku deployment error: "App not compatible with buildpack: ... /heroku/python.tgz"
I have Django + React app I'm building to learn the latter framework better. It uses Django, ReactJS and Webpack and the folder structure is the following my-project-root-folder/ frontend/ /src/ /static/ ... .babelrc package.json webpack.config.js django-main-project/ ... settings.py wsgi.py other-django-app/ ... views.py manage.py Procfile requirements.txt it's all set up for auto deployments from Git on Heroku, where I have the following Buildpacks installed However, whenever I try to deploy, I get the following build error: -----> Subdir buildpack app detected -----> Subdir buildpack in frontend/ creating cache: /tmp/codon/tmp/cache created tmp dir: /tmp/codon/tmp/cache/subdirDtoAM moving working dir: frontend/ to /tmp/codon/tmp/cache/subdirDtoAM cleaning build dir /tmp/build_c9788563_ recreating /tmp/build_c9788563_ copying preserved work dir from cache /tmp/codon/tmp/cache/subdirDtoAM to build dir /tmp/build_c9788563_ cleaning tmp dir /tmp/codon/tmp/cache/subdirDtoAM -----> App not compatible with buildpack: https://buildpack-registry.s3.amazonaws.com/buildpacks/heroku/python.tgz More info: https://devcenter.heroku.com/articles/buildpacks#detection-failure ! Push failed I understand, I think, that Heroku expects certain files to exist within the project's root folder (hence why I installed Subdir Heroku Buildpack) but I don't understand what's wrong with the Python buildpack, since I'm providing Procfile and requirements.txt correctly (as usual). Any chance to make it work with this project's folder structure or do I have to deploy everything from the same folder? How would I go … -
Unable to delete object when using generic relationship and proxy model
I'm unable to delete object when using generic relationship and proxy model. Error snapshot Here is my model class GenericCategory(MPTTModel): content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) banner_image = models.ImageField(upload_to="category_images", null=True, blank=True) name = models.CharField(max_length=50) parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children') class MPTTMeta: order_insertion_by = ['name'] and here is my proxy model class Category(GenericCategory): class Meta: proxy = True verbose_name = 'Category' verbose_name_plural = 'Categories' def save(self, *args, **kwargs): self.content_type = ContentType.objects.get(app_label='award', model='category') return super().save(*args, **kwargs) -
Page not found 404 django 3
I got the error Page not found (404) when I try to reach the 'contact.html' and 'about.html' page I don't understand why I'm getting this. Here is my code: app/urls.py: urlpatterns = [ path('', views.frontpage, name="frontpage"), path('<slug:slug>/', views.article, name="article"), path('contact/', views.contact, name="contact"), path('about/', views.about, name="about"), # If I write '/about/' that's working but the url is 'http://127.0.0.1:8000/%2Fabout/' and not 'http://127.0.0.1:8000/contact/' as i want. Same issue for contact ] app/views.py: def contact(request): return render(request, 'contact.html') def about(request): return render(request, 'about.html') # Of course the html file are created, they are located in the template folder I'm trying to reach each page with this html code: <a href="{% url 'citrouille:frontage' %}">Home</a> # This is working <a href="{% url 'citrouille:contact' %}">Contact</a> # This is not working <a href="{% url 'citrouille:about' %}">Aboout</a> # This is not working (citrouille is my app's name) Here is the mysite/urls.py (root folder): urlpatterns = [ path('admin/', admin.site.urls), path('', include('citrouille.urls')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) I have others functions working perfectly such as the article page with the slug. But this two pages doesn't want to show. I'm pretty sure this is a stupid error but i can't point it. Thank you for the help -
How to add an attribute to the form tag itself and not just a field in Django?
I am having trouble stopping bots filling in spam while letting through legit users. I have a honeypot field with autocomplete="off" attribute but it doesn't seem to be working. From what i've read, the best cross browser solution is to add autocomplete="false" to the main form tag itself, e.g. <form autocomplete="false">...</form>. What is the best way to do this in Django? -
Django - create submodels of a model
I want to create submodels(I do not know if this is the correct term to use) of a model. For example, let's say I have a model called Post. But I want this model's fields changable by users. Like users select their Post type. Right now I want to create a two different types: first is a class TextBasedPost(models.Model): title = models.CharField(max_length=100) content = RichTextField() # which has been imported from ckeditor.fields author = models.ForeignKey(User, on_delete=models.CASCADE) datePosted = models.DateTimeField(default=timezone.now) def __str__(self): return self.title def get_absolute_url(self): return reverse('post_detail',kwargs={'pk':self.pk}) Other one is a post with only image attachment: class ImageBasedPost(models.Model): title = models.CharField(max_length=100) image_attachment = models.ImageField(default='default.png', upload_to='profile_pics') # there will not be a usage of default.png author = models.ForeignKey(User, on_delete=models.CASCADE) datePosted = models.DateTimeField(default=timezone.now) def crop_image(self): img = Image.open(self.image.path) # Image imported from PIL if img.height > 600 or img.width > 600: output_size = (600,600) img.thumbnail(output_size) img.save(self.image_attachment.path) def __str__(self): return self.title def get_absolute_url(self): return reverse('post_detail',kwargs={'pk':self.pk}) But like you see this is not good way to use since there are same fields and same functions in both models(only one fields and one function is different). But this is not a good practice. So is there a way to do this with better way? -
model obj is returning same object
Hope you are fine i have 2 models class Property(models.Model): .... city = models.ForeignKey(City,on_delete=models.CASCADE) class City(models.Model): img = models.ImageField(upload_to='city/img',blank=True,null=True) name = models.CharField(max_length=200,unique=True) i want to get 3 cities which has most count of properties means i want cities which has most properties so i use this query: city = City.objects.all().order_by("-property")[0:3] but this is not working, because it's returning same value here is the output: <QuerySet [<City: lahore>, <City: lahore>, <City: lahore>]> lahore has the highest count of properties so it's giving me only lahore i want three cities for example city1 , city2 , city3 with highest count of properties -
Is there a preferred way to store user settings in a SQL database
What is the best way to store user settings or preferences? e.g Like an Entity (blog post) with liking or comments disabled. I'm using Django with MariaDB, my currents thoughts are: Store settings as an entity and relate it to the blog post Store the settings as a JSON object in a field within the blog post Store the settings as fields in the 'POST' entity -
Django - Reply a Comment / Comment on Comment modeling
I'm currently trying to setup a reply on comment (comment on comment) function at my Django forum but for some reason the comment reply also needs the post object instead of just a comment where he/she is replying onto. Currently I get the following error if I try to use the comment_answere_new function like shown below: App.models.Comment.post.RelatedObjectDoesNotExist: Comment has no post. views.py def comment_answere_new(request, pk): comment = get_object_or_404(Comment, pk=pk) form = CommentForm() if request.method == "POST": form = CommentForm(request.POST) if form.is_valid(): comment_answere = form.save(commit=False) comment_answere.author = request.user comment_answere.published_date = timezone.now() comment_answere.comment = comment_answere comment_answere.post = comment_answere.comment.post comment_answere.save() messages.success(request, 'Comment reply has been published successfully') return redirect('post_view', pk=comment_answere.comment.post.pk) else: messages.error(request, 'Something went wrong ...') return render(request, 'post_comment_new.html', {'form': form, 'comment': comment}) else: return render(request, 'post_comment_answere_new.html', {'form': form, 'comment': comment}) models.py #Comment Model class Comment(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) author = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) content = models.TextField(max_length=1000, blank=False) published_date = models.DateTimeField(auto_now_add=True, null=True) class Comment_Answere(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) author = models.ForeignKey(User, on_delete=models.CASCADE) comment = models.ForeignKey(Comment, on_delete=models.CASCADE) content = models.TextField(max_length=1000, blank=False) published_date = models.DateTimeField(auto_now_add=True, null=True) does smb. has a hint for me on how I can get this chain working Post Model <--- Comment Model (Post is ForeignKey) … -
How can i register as school ,collage,course in django?
I am building a site in Django where user can register as school ,collecge,courese but i did not able to do,i have google but no luck can any one hepl me on that thanku -
Django 2.2 Forbidden: /documentation/index.html on Development
I don't know why, but am trying to generate sphnix docus which i did, but serving them has refused whenever i got to http://127.0.0.1:8181/documentation/index.html i get Forbidden: /documentation/index.html HTTP GET /documentation/index.html 403 [0.00, 127.0.0.1:40656] path('documentation/', include('docs.urls')), am using django-docs -
How to Access values from mydata.values() in django?
i am selecting data using django Query.Query is mydata=MyModel.objects.all().values() for newmydata in mydata: return HttpResponse(newmydata .values()) newmydata .values() is printing all my values.its not printing keys.i want to access each values.and also i Want to add some extra values into this (newmydata .values()) array.How to do that? -
How to use vim for python django?
I use pycharm for my django projects but now I am switching to vim so, how to setup django for vim? -
How can I get find the yearly, monthly, and daily avg
I am make a website the tracks all your expenses. And I am making it with Django. So I use Django models to store all the Expenses Here is the Django Model class Expenses(models.Model): user = models.ForeignKey(User, related_name="user_expenses", on_delete=models.CASCADE) date = models.DateTimeField(default=django.utils.timezone.now) item = models.TextField() quantity = models.TextField(default=1) price_per_quantity = models.TextField() total_amount = models.TextField() So I have the expenses the total_amount its the total_price for a expense. So what I want to do is to get the yearly, monthly, and daily expenses avg. How can I do that. -
How to disable automatic URL parameter decoding in Django?
I have a viewset with a retrieve view, which takes one parameter, which is a string url encoded, as it often has '/' in it. Now when I send a request to my local development server with the url encoded (every / replaced by %2F) I get a 404 from my server and in the "Request URL" I see my string but decoded - so it makes sense that there is no such route. The route shows up correctly in this debug view with api/ ^topic/(?P<pk>[^/.]+)/$. This is my viewset: class TopicAPI(viewsets.ViewSet): def retrieve(self, request, pk=None): if '%2F' in pk: pk = pk.replace('%2F', '/') # Data retrival which works (independently tested) return Response(topics) I tried different words and different replacement methods, i.e. '--' instead of '2%F' which works but isn't nearly as stable as url encoding.