Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
NoReverseMatch at /posts/list/ Reverse for 'post_detail' not found. 'post_detail' is not a valid view function or pattern name
Well I am working on a simple project and I am stuck on this error. I have tried several way to fix it but non of them work. Maybe you can see and point out my mistake in my code. I am using everything right according to my concept of djnago. But i am new that is my concepts are not so strong i guess. App/urls.py app_name = 'posts' urlpatterns = [ path('about/',views.AboutView.as_view(),name ='about'), path('new/',views.PostCreateView.as_view(),name= 'create'), path('<int:pk>/detail/',views.PostDetailView.as_view(),name ='post_detail'), path('list/',views.PostListView.as_view(),name ='post_list'), path('<int:pk>/remove/',views.PostDeleteView.as_view(),name ='post_remove'), path('<int:pk>/update/',views.PostUpdateView.as_view(),name ='update'), ] App/views.py class PostListView(ListView): model = Post class PostDetailView(DetailView): model = Post class PostCreateView(LoginRequiredMixin,CreateView): form_class = PostForm model = Post class PostUpdateView(LoginRequiredMixin,UpdateView): form_class = PostForm model = Post class PostDeleteView(LoginRequiredMixin,DeleteView): model = Post success_url = reverse_lazy('post_list') post_detail.html {% extends 'base.html' %} {% block content %} <div class='jumbotron'> <h1>Welcome to grabPublic site</h1> <p>Title :{{post.title}}</p> <a class= "btn btn-primary" href="{% url 'posts:post_remove' pk=post.pk %}">del me </a> </div> {% endblock content %} post_list.html {% extends 'base.html' %} {% block content %} <div class="jumbotron"> {% for post in post_list %} <div class="post"> <h1><a href="{% url 'post_detail' pk=post.pk %}">{{ post.title }}</a></h1> <div class="date"> <p> Published on: {{ post.published|date:"D M Y" }} </p> {% endfor %} </div> {% endblock content %} App/models.py … -
How to get a model object using another model object in a template in django
I am trying to get a model object using another model object in my template but i am unable to do so. Please help me to do so. this is my models.py class roomuser(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) date = models.DateTimeField(auto_now_add=True) room = models.ForeignKey(rooms, on_delete=models.CASCADE) class profile(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=100) status = models.TextField(max_length=200, default='Hey, I\'m using twitter') img = models.ImageField(default='default.png', upload_to='profile_pics') private = models.BooleanField(default='False') this is my views.py def room(request, name): myroom = rooms.objects.get(name=name) roomusers = roomuser.objects.filter(room=myroom) myuser = profile.objects.all() return render(request, 'room.html', {'room':myroom, 'users':roomusers, 'myuser':myuser}) this is my template view {% for user in users %} {{user.user}}<br> {{user.user.username.myuser.name}} {% endfor %} i want to access a profile object by using a object of roomuser model as they both have a user class in common. Please help me to do so. Thankyou very much. -
TypeError 'bool' object is not callable in django
I am implementing login function using simple-jwt module in django. At this time, only users who have authenticated their e-mail can log in, and the following error occurs in this conditional sentence. TypeError 'bool' object is not callable in django I don't know why I can't bring in a bool type variable. How can I fix this error? Here is my code. views.py from .models import User from .utils import Util from .serializers import customRegisterSerializer, customLoginSerializer, customTokenRefreshSerializer, userProfileSerializer from rest_framework.permissions import IsAuthenticated from rest_framework.generics import GenericAPIView from rest_framework_simplejwt.tokens import RefreshToken from rest_framework_simplejwt.views import TokenObtainPairView, TokenRefreshView from rest_framework.viewsets import ModelViewSet from rest_framework.response import Response from django.urls import reverse from django.conf import settings from django.contrib.sites.shortcuts import get_current_site import jwt class customSignUpView (GenericAPIView) : serializer_class = customRegisterSerializer def post (self, request) : user = request.data serializer = self.serializer_class(data=user) serializer.is_valid(raise_exception=True) serializer.save() user = User.objects.get(email=serializer.data['email']) token = RefreshToken.for_user(user).access_token current_site = get_current_site(request).domain relativeLink = reverse('emailVerify') absurls = F'http://{current_site}{relativeLink}?token={token}' email_body = F'Hi {user.username} Use link below to verify your email \n{absurls}' data = {'email_body': email_body, 'to_email': user.email, 'email_subject': 'Verify your email'} Util.send_email(data) return Response({'message': '이메일을 확인하세요'}, status=201) class customLoginView (GenericAPIView) : serializer_class = customLoginSerializer def post (self, request) : serializer = self.serializer_class(data=request.data) serializer.is_valid(raise_exception=True) try : user = … -
django-modeltranslation: how to disable showing objects (e.g. posts) the languages where it is not defined?
I am developing a django multilingual app and using django-modeltranslation to translate the models. It works fine except one thing: when translation is not available in a specific language, it still shows the objects (let's say posts). I have some posts that are available in tajik while not available in russian, and vice versa. My goal is to disable showing the posts in the language which I do not have translation. May be by showing 404 or any other way, but it should not show the posts at all, not partially Here are my settings: settings.py LANGUAGES = [ ('ru', _('Russian')), ('tg', _('Tajik')), # ('en', _('English')), ] EXTRA_LANG_INFO = { 'tg': { 'bidi': False, 'code': 'tg', 'name': 'Tajik', 'name_local': u'Тоҷикӣ', }, } # Add custom languages not provided by Django LANG_INFO = dict(list(django.conf.locale.LANG_INFO.items()) + list(EXTRA_LANG_INFO.items())) django.conf.locale.LANG_INFO = LANG_INFO global_settings.LANGUAGES = global_settings.LANGUAGES + [("tg", 'Tajik')] LANGUAGE_CODE = 'ru' # from modeltranslation.settings import ENABLE_REGISTRATIONS MODELTRANSLATION_LANGUAGES = ('tg','ru') MODELTRANSLATION_DEFAULT_LANGUAGE = ('tg') MODELTRANSLATION_FALLBACK_LANGUAGES = ('ru', 'tg') transation.py from modeltranslation.translator import translator, TranslationOptions from blog.models import Post, Matlab class BlogPostTranslationOptions(TranslationOptions): fields = ('Title', 'ShortDesc', 'Content') translator.register(Post, BlogPostTranslationOptions) models.py: class Post(models.Model): STATUS_CHOICES = ( ('draft', 'Черновик'), ('published', 'Опубликованно'), ) POST_TYPE_CHOICES = ( ('image', 'Image'), ('video', 'Video'), … -
Is there any difference Dockering fullstack Django vs. Django Rest framework application?
There are many instructions for rest framework dockering, but is it similar to normal django with templates (=html pages) ? Also I use mongodb atlas cloud db with djongo. It works locally, but will it work with dockerized django app? Reason why Im dockering is that any app service I have tried doesn´t accept mongo with django the same way as it works locally. -
Django-React/Redux-Apache project: Can't resolve url
first time building a web app. decided to use django/react with redux and django rest framework for api routing and component state. decided to implement apache as a production server and test locally. when I used the django development server everything worked fine but when I switched to apache I hit an issue. I can get the static content to display at the root url "http://localhost" but can't get any further urls to resolve. On the main page of this app there's a component that, when it mounts, calls a url (GET) ".../api/buildings" to populate the component with some data but the server responds with a 404 or 500 but didn't when I used django dev server. I can't figure out what I'm doing wrong and seeing as I'm pretty new to this I'd appreciate some help! here's some code references and lmk if I can provide anything else. thanks in advance! building component that makes the call during mount: export class Buildings extends Component { static propTypes = { buildings: PropTypes.array.isRequired, getBuildings: PropTypes.func.isRequired, deleteBuildings: PropTypes.func.isRequired, }; componentDidMount() { this.props.getBuildings(); }; render() { return ( <Fragment> <h2>Buildings</h2> <table className="table table-striped"> <thead> <tr> <th>Id</th> <th>Name</th> <th>Code</th> <th>Last_Inspection</th> <th /> </tr> </thead> … -
How to set up a Celery Server on AWS for Django
I made a Django project and want to implement async tasks. My Django project is hosted on AWS Elastic Beanstalk with a Postgres DB on AWS RDS. I want to set up a Celery server that can read from my DB periodically and execute tasks. However, I don't know the first thing about how to host my Celery server on AWS. Where should I begin? Thanks! -
cannot unpack non-iterable CustomerPurchaseOrderDetail object
I am getting the correct computation of quantity and price it shown in my terminal, but when i tried to save it to my database i receive this error cannot unpack non-iterable CustomerPurchaseOrderDetail object I have this code in my views.py def addtocart(request): userID = request.POST.get("userID") client = Customer(id=userID) vegetables_id = request.POST.get("id") quantity = request.POST.get("quantity") percentage = request.POST.get("percentage") price = request.POST.get("price") v = Product(id=vegetables_id) total = float(quantity) * float(price) print(total) insert, created = CustomerPurchaseOrderDetail( profile=client, products = v, quantity = quantity, unitprice=price, discount_percentage = percentage, amount = total ) if not created: insert.quantity += 1 insert.save() this is my models.py class CustomerPurchaseOrderDetail(models.Model): profile = models.ForeignKey(Customer,on_delete=models.SET_NULL, null=True, blank=True, verbose_name="Client Account") products = models.ForeignKey(Product,on_delete=models.SET_NULL, null=True, blank=True,verbose_name="Product") quantity = models.IntegerField(null=True, blank=True, default=1) unitquantity = models.FloatField(max_length=500, null=True, blank=True) totalquantity = models.FloatField(max_length=500, null=True, blank=True) unitprice = models.FloatField(max_length=500, null=True, blank=True) discount_percentage = models.FloatField(max_length=500, null=True, blank=True) discounted_unitprice = models.FloatField(max_length=500, null=True, blank=True) discounted_amount = models.FloatField(max_length=500, null=True, blank=True) amount = models.FloatField(max_length=500, null=True, blank=True) this is my traceback Traceback: File "C:\Users\User\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\exception.py" in inner 34. response = get_response(request) File "C:\Users\User\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\base.py" in _get_response 115. response = self.process_exception_by_middleware(e, request) File "C:\Users\User\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\base.py" in _get_response 113. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\User\Desktop\LastProject\OnlinePalengke\customAdmin\views.py" in addtocart 926. amount = total Exception Type: TypeError at /addtocart/ Exception … -
Django: How to add to an ArrayField?
I have some questions about the ArrayField mentioned here: https://docs.djangoproject.com/en/3.1/ref/contrib/postgres/fields/#django.contrib.postgres.fields.ArrayField How do you add to an ArrayField? It's clear you can treat it like a regular field and do things like my_array_field = [] my_array_field.save() But what's confusing is I'm seeing everyone mention my_array_field.append("something") in StackOverflow questions. This isn't mentioned in the documentation at all. Moreover, if an arrayfield is .append()ed to, does it still require .save()? -
How to implement such a custom rollback in Django or DRF?
Out system accesses to a middle platform(I do not know how to call it in English, we call it 中台 in Chinese) which is for authentication like logging in, JWT verifying, etc. Then, We have encoutered questions when it is neccessary to rollback actions because of unexpected program errors. Like code below, the program will crash when running at 1 / 0, then AdminPermission.objects.create can be rolled back, but do_user_actions can not, cause it is a RPC function. So, we need to override transaction.atomic or something like this to implement our requirements. But, I do not know how to implement it. Pls give me some suggestions or sample code. Thx a lot. @transaction.atomic # can not rollback remote func call `do_user_actions` def create(self, request, *args, **kwargs): # call a remote func here to create a admin account. user_dict = do_user_actions(query_kwargs=query_kwargs, action='create-admin') user_id = user_dict.get('id') permission_code = 'base_permission' AdminPermission.objects.create(user_id=user_id, permission_code=permission_code) # some unexpected errors, like: 1 / 0 return Response('success') -
How can i make the following video objects using django
How to use django to make the objects in the following video Need model https://www.youtube.com/watch?v=AtS8hlbx3Bc -
Django - how to encode URL parameters with forward slash only once in template?
I am having a very specific issue in my template when creating an anchor tag with the {% url %} templatetag. One of the parameters I pass to it can include a forward slash, and I want to encode that. However, if I use |urlencode:"" as is mentioned in the docs (https://docs.djangoproject.com/en/3.1/ref/templates/builtins), this leads to the variable being double encoded when it arrives in the view. This is what I have in the template: <a href={% url 'myapp:myview' param1=param1 paramWithSlashes=paramWithSlashes|urlencode:"" %}> Then in my view function, the variable paramWithSlashes comes in double encoded. Meaning in order to get back the original string I have to call: import urllib.parse def myView(request, param1, paramWithSlashes): originalStr = urllib.parse.unqoute(urllib.parse.unquote(paramWithSlashes)) This is a really hacky solution and I'm sure double encoding/decoding is unwise in the long run. How can I ensure the url template tag only encodes once, with '/' included in the encoding? -
rest framework django "detail": "Method \"GET\" not allowed."
i am using django rest framework. am getting error "detail": "Method \"GET\" not allowed." i also trying two ways but error is still there. can anybody know how can i solve this error. serializer.py from rest_framework import serializers from .models import Book class BookSerialzer(serializers.ModelSerializer): class Meta: model = Book fields = ['id', 'name', 'price'] views.py 1 class BookCreateView(CreateAPIView): queryset = Book.objects.all() serializer_class = BookSerialzer OR: i am trying two ways for solving this issue but error is still there views.py 2 class BookCreateView(APIView): def post(self, request, format=None): serializer = BookSerialzer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) urls.py from django.urls import path from .views import BookCreateView urlpatterns = [ path('create/', BookCreateView.as_view()), # path('create/', BookCreateView.as_view(), name='create-repo') /// same error with that ] -
Displaying pdf in object tag using HTML5
While displaying the pdf using django's static url, below code works perfectly fine with object tag. <object data="{% static 'v.pdf' %}" type="application/pdf" height="800" width="650"></object> But it does not work with media <object data="{{ media}}/v.pdf" type="application/pdf" height="800" width="650"></object> So, even I tried sending absolute url (http://localhost:8000/v.pdf) in a separate variable {{media_pdf_url}}, but no luck. <object data="{{media_pdf_url}}" type="application/pdf" height="800" width="650"></object> I could see an error in the browser console - Refused to display 'http://localhost:8000/v.pdf' in a frame because it set 'X-Frame-Options' to 'deny'. but could not find any solution, what exactly I need to do to allow 'X-Frame-Options' in the media urls? -
Why do I get "AssertionError: May not set both `read_only` and `required`" in Django Rest Framework?
Why am I getting AssertionError: May not set both 'read_only' and 'required' when I try to access the TestViewSet? Here is the MRE: models.py: class Channel(models.Model): id = models.CharField(max_length=12, primary_key=True) class Test(models.Model): channel = models.ForeignKey(Channel, on_delete=models.PROTECT) foo = models.IntegerField(default=1) class Meta: unique_together = ( ('channel_id', 'foo'), ) views.py: from rest_framework import routers, viewsets, serializers class TestSerializer(serializers.ModelSerializer): class Meta: model = Test fields = [ 'channel_id', 'foo', ] class TestViewSet(viewsets.ModelViewSet): queryset = Test.objects.all() serializer_class = TestSerializer router = routers.DefaultRouter() router.register('test', TestViewSet) If you remove the unique constraint on Test, or set fields='__all__', on the serializer, the view magically starts working again. I'd prefer not to use fields='__all__' for 2 reasons: it will result in a lot of unused data on my real serializer the channel_id column ends up being rendered as channel, which is inconvenient, and will force me to update my frontend code to reference channel, or I will have to append _id to the data. I would just create an alias on the serializer: class TestSerializer(serializers.ModelSerializer): channel_id = serializers.CharField(source='channel_id') ... but doing so results in another error... AssertionError: It is redundant to specify `source='channel_id'` on field 'CharField' in serializer 'OrderSerializer', because it is the same as the field name. … -
How to make a PDF downloadable on a click of a button in Django?
I've tried this as a View: def download_file(request, filename): fl = open(filename, 'r') response = HttpResponse(fl, content_type='pdf') response['Content-Disposition'] = "attachment; filename=%s" % filename return redirect(reverse('index.html')) and in my HTML I just give the file's name to the url but it says no ReverseMatch at /. Is there a solution for this? -
E-Commerce Django View that will find an object by its id and redirect to an html with the '/id'
I am looking to implement a Django view function that will redirect me to a standard "products.html", however I want it to go to "products/" depending on which product I want to view in my e-commerce website. I understand that each product gets an id but how do you use that to get an object and send that context to a new page with the field attributes. Would appreciate some advice. Thankyou -
Django Database Duplicates
I don't exactly know how to diagnose this issue of mine, but I believe I have duplicate tables in my Postgres database. The reason I say this, is because When I go to my admin page, I see entries from my projects table that are also part of the blog post table. I want to separate these. I also found issues when trying to search through my blog. Here are the error messages: Exception Type: VariableDoesNotExist Exception Value: Failed lookup for key [username] in '' This leads me to believe the search algorithm is having trouble looking through duplicates, especially since the blog posts aren't even being found in my search results. Only project objects are found. How can I take a look into the Postgres database or further diagnose my issue? -
Django - how to prevent a user to access url if not superuser?
How can I check if a User that is already logged is superuser and prevent to access some urls or views if he's not a superuser? Is it also possible to prevent a user of adding/removing a data from a model? -
Django - One model divided in two forms, how can I relate the two with the ID?
I have a Locatario model that has two main attributes: one one them concerns to the personal attributes of the person (first form - LocatarioPfForm) and the second one the details about the civil contract we have (the second form - ContratForm). class LocatarioPfForm(ModelForm): class Meta: model = Locatario fields = ['unidade', 'locatario_nome', 'locatario_genero', 'locatario_rg', 'locatario_cpf', 'locatario_estado_civil', 'locatario_bens', 'locatario_conjuge', 'fiador_boolean', 'fiador_genero', 'fiador_nome', 'fiador_rg', 'fiador_cpf', 'fiador_estado_civil', 'fiador_bens', 'fiador_conjuge'] class ContratoForm(ModelForm): class Meta: model = Locatario fields = ['data_de_inicio', 'data_de_termino', 'valor_bruto', 'valor', 'epoca_pagamento', 'vencimento', 'multa_compensatoria', 'carencia_multa', 'pdf_contrato'] widgets = { 'data_de_inicio': DateInput(), 'data_de_termino': DateInput(), 'carencia_multa': DateInput(), } help_texts = { 'multa_compensatoria': '<span class="text-muted">O Valor da multa pode ser tanto em número absoluto, como aluguéis inteiros (ex: 1300 ou 3900), ou pode ser em porcentagem. No último caso, coloca-se a porcentagem em números decimais. 10% é 0.10, por exemplo.</span>', } In views.py, I created two views to reference the two forms: def pessoaFisicaCadastro(request, pk): loc = locatario_pk(pk) form = LocatarioPfForm() if request.method == 'POST': form = LocatarioPfForm(request.POST) if form.is_valid(): form.save() return redirect('contrato-cadastro', pk=pk) context = { 'form': form, def contratoCadastro(request): c_form = ContratoForm() if request.method == 'POST': c_form = ContratoForm(request.POST, request.FILES) if c_form.is_valid(): c_form.save() return redirect('condominio') context = { 'c_form': c_form, } return … -
Django: Combine multiple saves into one database action
I have a function like this– is there a way to wrap this function so that both saves are combined into one? def foobar(self, created_at=None): changed = False if created_at: changed = True self. created_at = created_at self.save() if self.active: changed = True self.active = False self.save() return self The reason I don't unindent self.save() is to avoid updating the updated_at field on my object if no change occurred. -
How to manually unmount volumes after recovering files in Azure?
In Azure portal "File Recovery" functionality provides us a simple 3-step process: Select the restore point (date) Generate the password and download the script to mount the restore point drives. Unmount the drives after file recovery. We perform the steps to mount the volumes and take some time to review the backup, and at the same time we are working in azure portal and for any reason (accidentally or deliberately) we close this tab and lose the unmount button. How to execute step 3 manually? (to unmount the volumes). This is a temporary volume mount but how can we do it any time manually? -
Django and the import error after OSX update
After some major update on MacOSX I have some problem with doing almost anything with my django project that previously ran well. Even my python version was downgraded to 2.7. I installed python 3.8 and try to run project and I have such error: Error: Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 13, in main raise ImportError( 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? Everything is activated venv. Can't install djagno with pip because I have message that "Requirement already satisfied" - so it is installed. sys.path: /Library/Frameworks/Python.framework/Versions/3.8/lib/python38.zip /Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8 /Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/lib-dynload /Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages What's going on? -
Proper way to do a robust search in Django models via REST framework
I'm writing a web application (DRF + Vue.js) where frontend should have an ability to narrow down GET request results via different filters. For example, I have a model like this: class Human(models.Model): first_name = models.CharField(_('first name'), max_length=50, null=True, blank=True) last_name = models.CharField(_('last name'), max_length=50, null=True, blank=True) birth_date = models.DateField(_('birth date'), blank=True, null=True) city = models.ForeignKey('City', on_delete=models.SET_NULL, blank=True, null=True) phone_number = models.ForeignKey('Contact' on_delete=models.SET_NULL, blank=True, null=True) @property def full_name(self): # Last name + First name return ' '.join(str(x) for x in (self.last_name, self.first_name) if x) @property def is_adult(self): now = timezone.now() if self.birth_date: if now.year - self.birth_date.year - \ ((now.month, now.day) < (self.birth_date.month, self.birth_date.day)) >= 18: return True return False Now I have simple CRUD ViewSet where I can use a list of search_fields to search by all needed fields (in my case that's birth_date, city, phone_number and full_name/is_adult). But here next problems arise: Using search_fields I can do a search only by all fields specified in the ViewSet's search_fields (frontend can't search only by city or other distinct fields if it wants to) - other way I'll need to create a separate ViewSet (and separate URL?) for every combination of fields to filter by. Terrific. So it looks like the … -
how i can get number of customer for each hour django rest framework
i would get number of customer for each hour in day . this my model: class Client(models.Model): id_track=models.IntegerField(default=0) temps_attente=models.CharField(max_length=50) date_entree = models.DateTimeField(auto_now_add=True) camera = models.ForeignKey("Camera", on_delete=models.CASCADE) class Meta: verbose_name = "Client" ordering = ['camera'] def __str__(self): return self.temps_attente i want something like this : [ {date:02/09/2020 , hour:"09" ,nbrCustumer:30} {date:02/09/2020 , hour:"10" ,nbrCustumer:22 } {date:02/09/2020 , hour:"11" ,nbrCustumer:10} {date:02/09/2020 , hour:"12h,nbrCustumer:12} ]