Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why is Django not publishing a valid form?
I am creating a website using Django. I'd like to give users the chance to comment on pictures they have posted. I have created a comment model and a comment form, and put the following code into the HTML document for the photo gallery: <h3>Leave a comment</h3> <form method="post" style="margin-top: 1.3em;"> {{ comment_form.as_p }} {% csrf_token %} <button type="submit" class="btn btn-primary btn-lg">Submit</button> </form However, the form is not displaying - there is nothing between 'Leave a comment' and the submit button on the page. I don't understand this as my form in forms.py appears to be configured correctly: class CommentForm(forms.ModelForm): body = forms.CharField(help_text="What is your comment?", widget=forms.TextInput(attrs={'size': '1000'}), required=True) class Meta: model = Comment fields = ('body',) def as_p(self): # Returns this form rendered as HTML <p>s. return self._html_output( normal_row='<p%(help_text)s<p></p>%(field)s</p>', error_row='%s', row_ender='</p>', help_text_html=' <span class="helptext">%s</span>', errors_on_separate_row=True)` So does my model in models.py: class Comment(models.Model): COMMENT_MAX_LENGTH = 1000 image = models.ForeignKey(Picture, on_delete=models.CASCADE, related_name="comments") user = models.ForeignKey(UserProfile, on_delete=models.CASCADE) body = models.TextField(max_length=COMMENT_MAX_LENGTH) created_on = models.DateTimeField(auto_now_add=True) active = models.BooleanField(default=False) class Meta: ordering = ['created_on'] def __str__(self): return 'Comment {} by {}'.format(self.body, self.user) I'd really appreciate any suggestions anyone could please offer. Thanks Jeff -
Django model with User, Profile and company
I am trying to build an app but have a hard time to figure out my model. I have already setup the User authentication. Next: Each User needs to be member of a Company (company has address info etc) Each User should have a Profile Invoices should be presented based on Company membership so every member gets the same page of invoices. So the tables (models) are: Profile Invoice Company User (this already exists and is the default django User) What would be the appropiate model relationships between those models. I would really appreciate the written model relationships like ForeignKey and ManyToMany e.d. -
django-keycloak | Set username as Keycloak Username (instead of Keycloak ID)
I am integrating Keycloak with Djnago https://github.com/Peter-Slump/django-keycloak/issues Keycloak Server This is what my keycloak User Screen looks like BUT when I log within django, user.email is proper (whats present in keycloak) user.username is getting set as ID from keycloak. Is there a way to retain djnago username as keycloak username? https://github.com/Peter-Slump/django-keycloak/issues/39 -
Loop through queryset and a dictionary with similar keys in order
I have a django queryset containing information about network things. Primary key is IP. Then, I have a dictionary with IPs as keys containing some data. I would like to display all IPs from either of the two sources in order, together with some info. For example, given: <Queryset[{'ip':'10.2.2.2', 'type':'laptop', ...}, {'ip':'10.4.4.4', 'type':'camera', ...}, {'ip':'10.5.5.5', 'type':'iot', ...}, {'ip':'10.8.8.8', 'type':'switch', ...}]> and: {'10.1.1.1': 'foo', '10.6.6.6': 'bar', '10.9.9.9': 'baz'} I want the following output: 10.1.1.1 foo 10.2.2.2 type: laptop ... 10.4.4.4 type: camera ... 10.5.5.5 type: iot ... 10.6.6.6 bar 10.8.8.8 type: switch ... 10.9.9.9 baz I could do nested loops, but is there a neat pythonic way? -
Django's Wagtail images have faulty S3 URL
I'm trying to upload images to my Django site's S3 storage using Wagtail. The images upload properly, but Wagtail appends ?AWSAccessKeyId= followed by a bunch of gibberish to the image URL. This causes the image to fail to load in both Wagtail's admin as well as the actual site. If I remove the appended text then the URL works properly. The problem is, I don't know how to stop Wagtail from appending the text in the first place. -
Error during template rendering - Required parameter name not set
I am a new developer that is stuck on this problem. The issue seems to be with the bootstrap code that I copied from their site, which is confusing. My site was working fine until I deployed it to Heroku. When I add a new post to my site I am presented with the following error: ERROR MESSAGE - ValueError - Required parameter name not set Thank you for your help! -
How to filter a Django model based on requirement from another model?
I'd like to retrieve all my contacts from my Contact model excluding those listed on my DoNotContact model. Is the following the most efficient way to do that: contacts = Contact.objects.filter(dont_contact=False) Wondering if this is going to take long to process, is there a more efficient way? class Contact(models.Model): email = models.CharField(max_length=12) first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) audience = models.ForeignKey(Audience, on_delete=models.CASCADE) def dont_contact(self): try: get_object_or_404(DoNotContact, email=self.email) return True except: return False def __str__(self): return self.email class DoNotContact(models.Model): email = models.CharField(max_length=12) #views.py def send_email(request): if request.method == "POST": contacts = Contact.objects.filter(dont_contact=False) -
How to redirect API call to another API which will return the response to the requester directly
CLIENT Side: UserA requests GET /file/from/some/location SERVER Side: UserA request will hit the API1 which will generate a URL and redirect the user to API2 the API will take the generated URL and return the file to the user directly without sending a response to the API1. -
Django: How to add model class inside class or refer?
I have a class called artist which is a profil for an artist class Artist_object(models.Model): surname = models.CharField(max_length=120) name = models.CharField(max_length=120) Biography = models.TextField(default='Bitte Biography eingfügen', null=False) now I want that this artist can have multiple paintings with a desrciption. class Artist_painting(models.Model): painting1 = models.ImageField() painting1_desc = models.CharField(max_length=120, default=None) painting2 = models.ImageField() painting2_desc = models.CharField(max_length=120, default=None) How can I put class Artist_painting inside the Artist_object that for every artist I view (i got def get_absolute_url(self): return f'/artist/{self.id}' ) it have an description for every image ? -
How to create a new record using a django form
I want to create a new record by using django form but I am stuck on it and i get this kind of error IntegrityError at /academy/add_academy/3/ null value in column "Student_name_id" violates not-null constraint DETAIL: Failing row contains (39, da10, 2020-03-06, A, 11, 11, null). Here is my view.py file def add_academy(request,pk): child = get_object_or_404(Child_detail, pk=pk) academic = Academic.objects.filter(Student_name=child) form=AcademicForm(request.POST) if form.is_valid(): form.save() return redirect('index') else: form=AcademicForm() context = { 'academic':academic, 'child':child, 'form':form, } return render(request,'functionality/more/academy/add.html',context) Also this is my form.py file class AcademicForm(forms.ModelForm): class Meta: model=Academic fields='Class','Date','Average_grade','Overall_position','Total_number_in_class' labels={ 'Average_grade':'Average Grade', 'Overall_position':'Overall Position', 'Total_number_in_class':'Total Number In Class' } Date = forms.DateField( widget=forms.TextInput( attrs={'type': 'date'} ) ) And here is my template file <div class="card"> <div class="card-header bg-primary text-white"> <h4> <i class="fas fa-user-plus"></i> Enter {{child.Firstname}} {{child.Lastname}} details </h4> </div> <div class="card-body"> <form action="" method="POST" autocomplete="on"> {% csrf_token %} <div class="form-group"> {{form}} <input type="submit" value="Save" class="btn btn-primary btn-block"> </form> </div> Thanks for your help -
Docker-compose can't import Django (ModuleNotFoundError)
I'm very new to Docker and I've been trying to get a very simple 'Hello World' program to run on docker. No matter what I do I always get "ModuleNotFoundError: No module named 'Django'" I've been stuck with this for two days now. Still no luck. Could you please point me in the right direction? What am I doing wrong? Here's the terminal output. C:\path\to\app\root>docker-compose up Creating network "hello-world_default" with the default driver Creating hello-world_web_1 ... done Attaching to hello-world_web_1 web_1 | Traceback (most recent call last): web_1 | File "/code/manage.py", line 10, in main web_1 | from django.core.management import execute_from_command_line web_1 | ModuleNotFoundError: No module named 'django' web_1 | web_1 | The above exception was the direct cause of the following exception: web_1 | web_1 | Traceback (most recent call last): web_1 | File "/code/manage.py", line 21, in <module> web_1 | main() web_1 | File "/code/manage.py", line 16, in main web_1 | ) from exc web_1 | ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? hello-world_web_1 exited with code 1 Here's the dockerfile # Pull base image FROM python:3.7 # Set environmental variables … -
Trying to display multiple image for my product
I'm trying to display multiple images for one product but the images won't display and i don't know why can anyone help. My Models. I have to image field one is used to display and product and if the user wants more detail the other is used to show more images of the product. class Product(models.Model): name = models.TextField() slug = models.SlugField(null=True, unique=True) description = models.TextField() stock = models.SmallIntegerField() price = models.DecimalField(max_digits=10, decimal_places=2) def __str__(self): return self.name def get_absolute_url(self): return reverse('single',args=[self.id,self.slug]) class ProductImage(models.Model): product = models.ForeignKey('Product', on_delete=models.CASCADE) image = models.ImageField(upload_to='images/', blank=True) featured = models.BooleanField(default=False) thumbnail = models.BooleanField(default=False) updated = models.DateTimeField(auto_now_add=False, auto_now=True) active = models.BooleanField(default=True) def __unicode__(self): return self.product.image Views def single(request, id, slug): try: # products = Product.objects.get(slug=slug) product = get_object_or_404(Product, id=id, slug=slug) images = ProductImage.objects.filter(product=product) return render(request, "single.html", {'product': product}, {'images':images}) except: raise Http404 How I tried to display the images on the Html page. {% for img in images %} {% if item.featured %} <img class="img-responsive"src="{{ MEDIA_URL }}{{ img.image.url }}" height="px" width="px" class="pr-5 mr-5"> {% endif %} {% if not item.featured %} <img class="img-responsive"src="{{ MEDIA_URL }}{{ img.image.url }}" height="px" width="px" class="pr-5 mr-5"> {% endif %} {% endfor %} -
Cannot run Django with active venv in zsh
I've got a properly activated venv in zsh, because I can see (venv) at the beginning of the prompt, but when I try to run Django with the command python manage.py runserver I've the error Traceback (most recent call last): File "manage.py", line 8, in <module> from django.core.management import execute_from_command_line ModuleNotFoundError: No module named 'django' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line 14, in <module> import django ModuleNotFoundError: No module named 'django' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line 17, in <module> "Couldn't import Django. Are you sure it's installed and " ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? If I run which which python I can see python: aliased to /usr/local/bin/python3.7 that it seems wrong, because I expect something like /Users/myuser/Python-Projects/test/venv/bin/python. In fact if I disable the venv the result of which python is the same. I tried to the same steps with bash and everything works fine, so I guess I've got something wrong with zsh, but I don't know what. … -
Django how can i make inner join
MY models.py class Forms_in_Document(models.Model): document_submit = models.ForeignKey(Document_submit, on_delete=models.CASCADE) class Document_data(models.Model): forms_in_document = models.ForeignKey(Forms_in_Document, on_delete=models.CASCADE) document_structure = models.ForeignKey(DocumentStructure , on_delete=models.CASCADE) date_created= models.DateTimeField(default=datetime.now(),null=False) string = models.CharField(null=True, max_length=100) integer = models.IntegerField(null=True) date_time = models.DateTimeField(null=True) class Application(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE, null=False) date_created = models.DateTimeField(default=datetime.now(),null=False) forms_in_document = models.ForeignKey(Forms_in_Document, on_delete=models.CASCADE, null=True) closed = models.BooleanField(default=False, null=False) new = models.BooleanField(null=False) media = models.BooleanField(default=True) Path_info = models.ForeignKey(Path_info, on_delete=models.SET_NULL,null=True) The raw SQL query that I am trying to do in Django views.py is "Select * from Application app inner join Document_data dd on dd.forms_in_document=app.forms_in_document" How can I do this using Django in my VIEWS.PY Thanks in Advance -
How can i get a url param for an updateview in django?
url: `path('my-domains/<str:domain_name>/dns-settings', login_required(DNSSettingsUpdateView.as_view()), name='dns_settings')` I want to get to use in my updateview: class DNSSettingsUpdateView(UpdateView): model = Domain form_class = NsRecordModelForm template_name = "engine/dns_settings.html" def get_object(self, queryset=None): return Domain.objects.get(name=[would insert it here]) def get_success_url(self): return reverse("my-domains") How can I do this? can anyone help? Thanks in advance -
Django AJAX delete object in deleteView
Good day. I'm trying to understand how to use ajax by deleting a object. Main problem, i don't understand how to pass slug argument to url in AJAX call. path('posts/<slug:slug>/delete/', DeletePost.as_view(), name='delete_post') class DeletePost(CsrfExemptMixin, DeleteView): queryset = Post.objects.all() def get_object(self, queryset=None): obj = super(DeletePost, self).get_object() profile = Profile.objects.get(user_id__exact=self.request.user.id) if obj.profile_id != profile.id: raise Http404 return obj def delete(self, request, *args, **kwargs): self.get_object().delete() payload = {'delete': 'ok'} return JsonResponse(payload) What i also want to understand, is the functionality correct? I've tested without json and get_object returns the correct object. {% for post in user_posts %} <tr id="post_table"> <th scope="row"> <input type="checkbox" aria-label="Checkbox" style="display: none"> </th> <td class="tm-product-name"><a href="{% url 'post:edit_post' post.slug %}">{{ post.title }}</a></td> <td class="text-center">145</td> <td class="text-center">{{ post.total_likes }}</td> <td>{{ post.created_at }}</td> <td><button class="delete-icon" onclick='deletePost({{ post.slug }})'>btn</button></td> {#<td><i class="fas fa-trash-alt tm-trash-icon delete-icon" id="{{ post.id }}"></i></td>#} <td> {#<form method="post" action="{% url 'post:delete_post' post.slug %}" id="delete">#} {#{% csrf_token %}#} {#<i class="fas fa-trash-alt tm-trash-icon"></i>#} {#</form>#} </td> </tr> {% endfor %} <script> function deletePost(slug) { let action = confirm('Are you sure you want to delete this post?'); if (action !== false) { $.ajax({ method: 'POST', url: '{% url 'post:delete_post'%}', success: function (data) { if (data.delete()) { $('#post_table').remove() } } }); } } </script> Obviously … -
what is the best way to implement operation-wise and row-wise authentication if there is something like this
I'm creating a project using DRF (Django Rest Framework), I'm stuck at a point while updating data in tables, I find it highly vulnerable to misuse. My code is below models.py from django.db import models from Mera.settings.common import AUTH_USER_MODEL from Mera.constant import UNIT_TYPES class Item(models.Model): owner = models.ForeignKey(AUTH_USER_MODEL, related_name='item_owner', null=True, on_delete=models.CASCADE) created = models.DateTimeField(auto_now_add=True) name = models.CharField(max_length=100) previous_code = models.CharField(max_length=100, blank=True, default="") short_name = models.CharField(max_length=100, blank=True, default="") serializers.py from rest_framework import serializers from commodity.models import Item from Mera.settings.common import AUTH_USER_MODEL class ItemSerializer(serializers.ModelSerializer): def create(self, validated_data): return Item.objects.create(**validated_data) def update(self, instance, validated_data): # instance.name = validated_data.get('name', instance.name) instance.save() return instance def to_representation(self, instance): response = super().to_representation(instance) response['owner'] = UserSerializer(instance.owner).data return response class Meta: model = Item fields = '__all__' class UserSerializer(serializers.ModelSerializer): items = serializers.PrimaryKeyRelatedField(many=True, queryset=Item.objects.all()) class Meta: model = AUTH_USER_MODEL fields = ['id', 'username', 'items'] views.py from rest_framework import generics from rest_framework import mixins from django.contrib.auth.models import User from commodity.models import Item from commodity.serializers import ItemSerializer, UserSerializer class ItemList(mixins.ListModelMixin, mixins.CreateModelMixin, generics.GenericAPIView): queryset = Item.objects.all() serializer_class = ItemSerializer def get(self, request, *args, **kwargs): return self.list(request, *args, **kwargs) def post(self, request, *args, **kwargs): return self.create(request, *args, **kwargs) def perform_create(self, serializer): serializer.save(owner=self.request.user) class ItemDetail(mixins.RetrieveModelMixin, mixins.UpdateModelMixin, mixins.DestroyModelMixin, generics.GenericAPIView): queryset = Item.objects.all() serializer_class = ItemSerializer def … -
why 404 in django url?
I made url for signUp page. but it returns 404 error. all of the other urls work well. I don't know the reason. main urls urlpatterns = [ path('admin/', admin.site.urls), path('', include('mobileWeb.urls')), path('api/', include('api.urls')), ] Application urls urlpatterns = [ path('', views.index, name='index'), path('index', views.index, name='index'), path('addComment', views.addComment, name='addComment'), # users path('signUp', views.signUp, name='signUp'), path('accounts/', include('allauth.urls')), path('martDetail/<int:martId>', views.martDetail, name='martDetail'), path('trade/<int:itemId>', views.trade, name='trade'), path('registerMart', views.registerMart, name='registerMart'), path('registerItem', views.registerItem, name='registerName'), path('delete', views.delete, name='delete'), path('deleteMart', views.deleteMart, name='deleteMart'), path('deleteItem', views.deleteItem, name='deleteItem'), path('purchaseItem', views.purchaseItem, name='purchaseItem'), path('selectItem', views.selectItem, name='selectItem'), path('addStatistics', views.addStatistics, name='addStatistics'), path('viewStatistics', views.viewStatistics, name='viewStatistics'), path('imtPosRegister', views.imtPosRegister, name='imtPosRegister'), path('imtPosRegisterTest', views.imtPosRegisterTest, name='imtPosRegisterTest'), path('imtPosSaleInfoTest', views.imtPosSaleInfoTest, name='imtPosSaleInfoTest'), path('imtPosSaleConfirmTest', views.imtPosSaleConfirmTest, name='imtPosSaleConfirmTest'), path('fsOe9ms1b', views.fsOe9ms1b, name='fsOe9ms1b'), path('fsOe9ms1b_ma', views.fsOe9ms1b_ma, name='fsOe9ms1b_ma'), path('ssOe9ms1b', views.ssOe9ms1b, name='ssOe9ms1b'), path('ssOe9ms1b_ma', views.ssOe9ms1b_ma, name='ssOe9ms1b_ma'), path('tsOe9ms1b', views.tsOe9ms1b, name='tsOe9ms1b'), path('tsOe9ms1b_ma', views.tsOe9ms1b_ma, name='tsOe9ms1b_ma'), path('writeChatting', views.writeChatting, name='writeChatting'), path('imageUploadChatting', views.imageUploadChatting, name='imageUploadChatting') ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) 404 in web browser 404 in console -
Render objects from two queries in single for loop in Django
I am trying to fetch objects from two different queries by using select_related() in order to get all of the related objects. In template, I am using For loop in order to render all objects of first model separately, as separate containers of the data. Inside each of these rendered objects of the first model, I need to show the corresponding data from both queries for the related second model. The issue is that, when I am using For loop in template, I can only get the objects for the first related query, but not for the second query which is also related to the first model (basically, what second query is doing is getting all of the objects based on date less then today.) Here is the code: # IN THE MODELS class BillType(models.Model): name = models.CharField(max_length=200) created_on = models.DateTimeField(default=datetime.now, blank=True) def __str__(self): return self.name class Bill(models.Model): bill_type = models.ForeignKey(BillType, on_delete=models.CASCADE, related_name='billtype') month = models.CharField(max_length=200) amount = models.IntegerField() due_date = models.DateField(blank=True) note = models.TextField(blank=True) recurring = models.BooleanField(default=True) currency = models.CharField(max_length=100) created_on = models.DateField(default=datetime.now, blank=True) def __str__(self): return self.month # IN THE VIEW # This will get all of the Bill Types needed for For Loop in the template bill_types … -
change verbose name of VISIT SITE in django 2.x admin
I only seem to find answers around changing the actual link of VISIT PAGE. How however can I change the verbose name to e.g. HOMEPAGE? Below code only changes the actual link: class AdminSite: admin.site.site_url = "/hompeage" What I'd like to achieve: -
Storing Images in PostgreSQL is good when I develop webapprication?
I'm wondering if it's a good idea to store a lot of images in PostgreSQL. The amount of images is more than 30,000. Those images are used in web application. Or should I store images in a folder to be retrieved from a web app? -
Problem with Djago {% extends %} templating
I am building a webapp with Django and Python 3.7 and I'm really confused by this simple thing: These are my templates. They are all in the same directory. When I try to call {% extends 'store.html' %} , I get TemplateDoesNotExist at /publicaciones/ and it points to store.html. This is in publicaciones.html. Here's the template: publicaciones.html: {% extends "store.html" %} {% load static %} {% load crispy_forms_tags %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" type="text/css" href="{% static 'css/style_reset-pass.css' %}"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous"> <title>Publicaciones</title> </head> <body> <div class="container"> {% block content %} {% for item in items %} {{ item|crispy }} {% endfor %} {% endblock content %} </div> </body> </html> What am I missing? Please ask if you need any other code. I'll answer immediately. -
Django rest framework, use none in model's field
I have a Django rest framework API, In one of the models, there is a field for GeoLocation's elevation, which defaults its value to None. The reason for that is that it can be passed in by the user or if left empty, obtained by a call to google's elevation API. So, I'm trying to use the create function in the serializer to define its value but I'm getting a key error: #app/models.py elevation = models.FloatField(name="Elevation", max_length=255, help_text="If known, Add location's sea level height. If not, Leave Empty.", null=False, default=None) #app/serializers.py from rest_framework.serializers import HyperlinkedModelSerializer from Project_Level.utils import get_elevation from .models import KnownLocation class KnownLocationSerializer(HyperlinkedModelSerializer): def create(self, validated_data): if validated_data["Elevation"] is None: # Using if not validated_data["Elevation"] results the same. validated_data["Elevation"] = get_elevation(validated_data["Latitude"], validated_data["Longitude"]) class Meta: model = KnownLocation fields = ('id', 'Name', 'Area', 'Latitude', 'Longitude', 'Elevation') Error: KeyError at /knownlocations/ 'Elevation' Exception Location: KnownLocation/serializers.py in create, line 9 -
Save into MongoDB from views in django
Hello i am facing a problem when im trying to store in my MongoDatabase some data via views.py My question may be silly cause im new to django... So i have a ModelForm in my forms.py class LanModelForm(forms.ModelForm): project_name = forms.CharField() target = forms.GenericIPAddressField() class Meta: model = UsersInput fields = ('project_name', 'target',) and my model in models.py class UsersInput(models.Model): project_name = models.CharField(max_length=15) ip_subnet = models.GenericIPAddressField() I submit the form and when i go to the admin page to inspect my (UsersInput) object only project name is passed. Target field is empty. Code in views.py def post(self, request): form = self.form_class(request.POST) if form.is_valid(): _target = form.cleaned_data['target'] project_name = form.cleaned_data['project_name'] form.save() return redirect('/passive_scanning.html') -
How to display a video in django
I want to do an HTML file in my django project that includes a video from the server computer. The video is in the server computer and the client that enter to the site should see the video. How should I do this?