Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
DetailView on custom user model on Django doesnt work
I have this link to 'My account' on my website {% if user.is_authenticated %} <a class="nav-link" href="{% url 'user_detail' id=request.user.id %}">My Account</a> {% endif%} on my urls.py i've this line url(r'^users/(?P<id>\d+)$', views.UserDetailView.as_view(), name='user_detail'), views.py class UserDetailView(DetailView): context_object_name = 'es_user' model = es_user models.py class es_user(models.Model): user = models.OneToOneField(User,related_name='es_user', on_delete=models.CASCADE) def get_absolute_url(self): print("self.user.id=",self.user.id) return reverse('user_detail', kwargs={'id': self.user.id }) But when I click on the 'My account' link I get this error AttributeError at /users/3 Generic detail view UserDetailView must be called with either an object pk or a slug in the URLconf. Here 3 is the id of currently logged in user since the user is logged in request.user.id on this line <a class="nav-link" href="{% url 'user_detail' id=request.user.id %}">My Account</a> is not returning any null values. I cannot find the error using the error message given by django. somebody help me -
Django Buy form (User to User payment)
At my application users are able to buy/sell specific posted elements. To later-on display a content_preview or the full content of a post i created a "helper_model" -> Post_Paid_Sell_Tut to check if a user has paid for the post or not. My target is that i can later on display the preview or full content accordingly to the paid or unpaid status but i dont clearly understand how to get those two models in relations at my views.py The second thing is that the user as to select a currency he wants to pay for the post at the template.html . I simply want to have a radiobutton and the user can do his selection for the currency his account is loaded with. views.py def post_sell_tut_buy(request, pk): post = get_object_or_404(Post_Sell_Tut, pk=pk) if request.user == post.author: messages.error(request, 'You cannot buy Post(s) you created by your own!') return redirect('post_sell_tut_detail', pk=post.pk) else: template = 'Post_Sell_Tut/post_sell_tut_buy.html' form = CurrencyBuySelectForm(instance=post) post.STATUS = 1 post.save() context = { 'post': post, 'form': form } return render(request, template, context) models.py class Post_Sell_Tut(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(verbose_name="Post Title", max_length=40) content_preview = models.TextField(verbose_name="Post Content Preview", max_length=500) content = EncryptedTextField(verbose_name="Post Content", max_length=10000) ... PAYMENT_STATUS = ( (0, 'unpaid'), … -
Getting post created by an user
I want to display all posts created from an user.the problem is that i dont know what to write in kwargs as i do use slug to display user urls. models class Post(models.Model): body_text=models.TextField() title=models.CharField(max_length=50) created_on=models.DateField(auto_now_add=True) slug=models.SlugField(max_length=50,unique=True) author=models.ForeignKey( get_user_model(), on_delete=models.CASCADE, ) def __str__(self): return self.title def get_absolute_url(self): return reverse('post_detail', kwargs={'slug': self.slug}) def save(self, *args, **kwargs): self.slug = slugify(self.title, allow_unicode=True) return super(Post, self).save(*args, **kwargs) views.py class ProfilPostView(ListView): model=Post template_name='profile.html' def get_queryset(self): return Post.objects.filter(author=self.kwargs['']).order_by('created_on') #return Post.objects.filter(author=self.request.user).order_by('created_on') urls.py path('post/<slug:slug>/profile', ProfilPostView.as_view(), name='profile'), -
how to format a a url to return something like this "product/4/improved-led-lamp" in the template
I'm trying to return a formatted url that will look like this "product/4/improved-led-lamp" using the {% url %} tag I've tried {% url 'shop:product' 4 slug %} here is my urls,py app_name = 'shop' urlpatterns = [ path('product/<int:id>/<slug:title>', views.ProductView.as_view(), name='product'), ] if I visit "shop/product/4/improved-led-lamp" in my browser, it resolves, but when I try to reproduce this in the view using {% url %} tag, it throws noReverseMatch error -
Django template: Could not parse the remainder: '['href']' from 'i['href']'
Im removing my app from Flask to Django. App - is a simple html parcer with web interface. Everything works great except templates. im trying to write some code, for parse html right in template: Original string is: <div class="list-companies__name"> <h3> <a href="/somecompany">somestring</a> </h3> </div> And i want to get: <a href="https://site.ru/somecompany">somestring</a> So im using Jinja right like in Flask: <div class="container"> <div class="row"> <div class="col-sm"><b> ({{ hh_total }})</b></div> <div class="col-sm"><b> ({{ rabota_count }})</b></div> </div> <div class="row"> <div class="col-sm"> {% for i in company_names %} <div class="row"> <a href="https://site.ru{{ i['href'] }}">{{ i.text }}</a> </div> {% endfor %} </div> <div class="col-sm"> {% for div in rabota_html %} <div class="row"> <a href="https://site2.ru{{ div.find('a')['href'] }}">{{ div.text }}</a> </div> {% endfor %} </div> </div> </div> But django throws TemplateSyntaxError: Could not parse the remainder: '['href']' from 'i['href']' Is it possible to parse html code right in django-template like in Flask? And whats the differense in Django Templates and Flasks? As i thought, both using same syntax. -
django application field loaded from already created database and not initialized from the django code
I see that you can initialize a new field type to be created in a new database from the django application code inside of models.py. Something like this: class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') If I already have a database created, and that database is already connected to my django instance running ... and lets say I have a table called product_colors that has the following columns coolerless_print boolean not null print_color varchar(20) id bigserial not null How do I load these already created columns into my newly created app? Does Djangos, i dont know the right terminology here, field initiation process have equivalencies for all possible sql data types, exceptions (not null), etc? Is there an easy way to say - load this table and all columns? https://docs.djangoproject.com/en/2.1/intro/tutorial02/ -
Django (or Django Rest Framework) adding trailing underscores to downloaded files?
I've got a rather odd situation happening, that I'm having difficulty tracking down in an existing Django application. One of the views, which inherits from APIView, returns with a file when a user makes a POST call. The endpoint works fine, but there's something odd happening when the downloaded file reaches the client machine. By the time the browser receives the file, the file extension has been renamed with a trailing underscore. (So suppose the file was originally "test.txt", the version that the client receives would be "test.txt_"). As near as I can figure, just before the response object is returned in the APIView, the content-type and content-disposition headers look correct. E.g.: Content-Type: application/octet-stream Content-Disposition: attachment;filename="test.txt" That same file, when it shows up in Chrome downloads, is named "test.txt_" - with the trailing underscore. This doesn't seem browser specific, as the same thing happens when the same POST call is made from a mobile app which uses that same back-end call. This also happens locally, when running through the Django development server (i.e.: manage.py runserver) as well as our production servers (running via Nginx and UWSGI on Linux). Something, somewhere, along the way, is forcing a rename of the file. … -
Django "less than" in dictionary key < value with vars
I have the following query Asiento.objects.filter(**code_filter).order_by(order) Where I want to do the following: code_filter = { "{}__lt".format('code'): 0 } (This one isn't filtering anything) I mean, I am filtering with vars in key=value, but I can't get how to filter for 'code' less than 0. If I do code_filter = { 'code' < 0 } It says "<" is not an operator for a str with an int, but it's wrong because code is not a string but an attribute of Asiento. How can I tell Django 'code' is an attribute and not a string? -
How to connect django settings.py with mongo db?
This is my code to connect my django application with mongo db atlas. DATABASES = { 'default': { 'ENGINE': 'djongo', 'NAME': 'db_name', 'USER': username, 'PASSWORD': password, 'HOST': 'mongodb+srv://%s:%s@save4thpillar-sonvx.mongodb.net/test?retryWrites=true'% (username, password), 'PORT': 27017, } } I am getting following error Performing system checks... System check identified no issues (0 silenced). Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x7f5b85e69a60> Traceback (most recent call last): . . . . . . . File "/home/nadeem/Documents/backendAPI/myvenv/lib/python3.6/site-packages/pymongo/topology.py", line 183, in select_servers selector, server_timeout, address) File "/home/nedeem/Documents/backendAPI/myvenv/lib/python3.6/site-packages/pymongo/topology.py", line 199, in _select_servers_loop self._error_message(selector)) Kindly help me to connect. -
deploying single app from django project on apache location
I'm trying to deploy my django project on apache, but I want to deploy a single app on a single location of my server. So, I want to know if it's possible, or do I need to run different django projects for different locations? -
How to solve "type object 'datetime.datetime' has no attribute 'timedelta'" when creating a new date?
I'm using Django and Python 3.7. I'm trying to calculate a new datetime by adding a number of seconds to an existing datetime. From this -- What is the standard way to add N seconds to datetime.time in Python?, I thought i could do new_date = article.created_on + datetime.timedelta(0, elapsed_time_in_seconds) where "article.created_on" is a datetime and "elapsed_time_in_seconds" is an integer. But the above is resulting in an type object 'datetime.datetime' has no attribute 'timedelta' error. What am I missing -
FileField with instance id in DRF
I don't know why filefield return string that include None when post data. like this http://example.com/room/None/1.jpg My instance id was null on save. In models.py def room_photo_path(instance, filename): return 'room/{}/{}'.format(instance.id, filename) class Room(models.Model): photo = models.FileField(upload_to=room_photo_path) In serializers.py class RoomSerializer(serializers.ModelSerializer): class Meta: model = Room fields = '__all__' -
DRF going from parent object to child object
I have models Printer And Check: class Printer(models.Model): name = models.Charfield() api_key = models.Charfield() class Check(models.Model): printer_id = models.ForeignKey(Printer, related_name='checks', on_delete=models.CASCADE) I need to return Printer object with 'api_key' as argument (i.e. http://127.0.0.1:8000/printers/123/ where '123' is printer object's api_key) I did it this way: serializers.py class PrinterSerializer(serializers.ModelSerializer): class Meta: model = Printer fields = ('name', 'checks') views.py class PrinterDetail(generics.ListAPIView): serializer_class = PrinterSerializer lookup_field = 'api_key' def get_queryset(self): api_key = self.kwargs['api_key'] return Printer.objects.filter(api_key=api_key) But now I need to go from this Printer object to one of his child (Check) object (i.e http://127.0.0.1:8000/printers/123/324) where 324 -- is check's pk. And I'm really stuck right now. Can someone point me the direction I should think? -
Create new accounts app for an existing system using a different authbackend
I have cloned the https://github.com/srct/bookshare book exchange system and I wanted to customise it to use vanilla authentication.It currently uses a custom backend for Mason University.I created a new accounts app and mapped my urls but cannot appear to get the login/register page to load. this is my change to the url conf url(r'^accounts/', include('accounts.urls')), #url(r'^login/$', 'cas.views.login', name='login'), #url(r'^logout/$', 'cas.views.logout', name='logout'), my views def register(request): if request.method == 'POST': # register new account if User.objects.filter(username=request.POST['username']).exists(): messages.add_message(request, messages.WARNING, "Username is already in use.") return redirect('register') user = User.objects.create_user( request.POST['username'], None, request.POST['password'] ) # login new account user = authenticate( request, username=request.POST['username'], password=request.POST['password'] ) login(request, user) messages.add_message(request, messages.SUCCESS, "Your Account got created.") return redirect('HomepageView') else: if not request.user.is_authenticated: # show register form context = { 'title': 'Register' } return render(request, 'register.html', context) else: # already logged in messages.add_message(request, messages.WARNING, "First you need to log out.") return redirect('HomepageView') and the error i get when i try to load the page Exception Type: NoReverseMatch at /accounts/login/ Exception Value: Reverse for 'HomepageView' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: [] Am just teaching myself django. What could i be doing wrong? -
Better way of creating static pages with *.html extensions in Django
I have a website which is fully in built in HTML (all the links have *.htm extension). I am developing a dynamic version of this website using Django, but I don't want the old links of the old website to be broken, because there may many people refer to those links. So what I am doing right now based on my knowledge is creating url patterns for each link like below: urlpatterns = [ # static pages below url(r'^children.html', TemplateView.as_view(template_name='home/children.html'), name='children'), ] It works fine, but I wonder whether this way is valid or not AND I want to know whether there is any other better way of doing it? -
Using method.post without data
I'm using a timer as part of my app. The user can press a button to start or stop it, which update its DurationField in the database. From the user I only get the action of submitting, which triggers my view to produce the data that enters the database. Question: is the post method required considering that the data entering the database is not a string or integer from the user, but generated from the view? Is there a better practice? models.py class Timer(models.Model): timer_start = models.DateTimeField(auto_now_add=True) final_duration = models.DurationField(null=True) def __str__(self): timer_start_f = self.timer_start.strftime("%Y-%m-%d %H:%M:%S") return f"Created: {timer_start_f}" def isActive(self): if self.final_duration is None: return True else: return False def stop(self): if self.isActive(): self.final_duration = timezone.now() - self.timer_start self.save() def time(self): if self.isActive(): timedelta = timezone.now() - self.timer_start return f"{timedelta}".split(".")[0] else: return f"{self.final_duration}".split(".")[0] def timer_start_f(self): return self.timer_start.strftime("%B %d, %Y, %H:%M %p") urls.py urlpatterns = [ path('', views.indexView, name='index'), path('account/', views.timerView, name='timer') ] views.py def timerView(request): try: timer = Timer.objects.latest('timer_start') except Timer.DoesNotExist: if request.method == 'POST': Timer.objects.create() return HttpResponseRedirect("/account/") else: return render(request, 'pomodoro/timer.html', {'button_label': "Start Timer"}) else: timer_list = Timer.objects.order_by('-timer_start')[1:] if request.method == 'POST': if timer.isActive(): timer.stop() else: Timer.objects.create() return HttpResponseRedirect("/account/") else: # "state" is used by javascript to run … -
Loading *.dll via ctypes works in django unit test but fails otherwise
In one of my Django models, I defined a function that loads an external *.dll library by changing into the directory and then importing the library via ctypes.CDLL... so in principle this is what I do in the function of the model: basepath = os.getcwd() _DIRNAME = os.path.dirname(__file__) dllspath = os.path.join(_DIRNAME, "dlls_x64") os.chdir(dllspath) __libx64 = ctypes.CDLL("libx64") ... os.chdir(basepath) I am sure changing the directories is not recommended during a function call and that this is bad design, but at this point I just want to understand what ctypes.CDLL is exactly doing. Because when I test this function in a unit test, the library can be found and no error is raised. But when I test the code interactively in a python console, the module cannot be found: OSError: [WinError 126] The specified module could not be found I run my unit tests with the module django-test-without-migrations and a sqlite backend because I can't create a unit test database for my production oracle backend. So for unit tests, I do: python manage.py test --nomigrations --settings=settings.unittests and settings.unittests.py contains: from settings.defaults import * DATABASES['default'] = { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db_unittests.sqlite3') } while for interactive python console, I go: python manage.py shell_plus … -
how to create a authentication system for two different users
I'm using Django and need to create a login for my website, where if the customer logs in it will bring them to the main homepage where they can use the website. And then if my worker uses the log in it will bring them to a orders page that only the worker can see. Im not sure how to differentiate the users to accomplish this. -
Sending message from Celery task to Channels
Django 2.1.1, Django Channels 2.1.3, Celery 4.2.1 I've set up a task in Celery and at the end of the task, I need to send a websocket message to the client(s). However, the websocket message is never sent. There are no errors thrown, it just simply doesn't send. I've set up a channel layer using Redis as the backend. Doing this from a normal Django view works fine. But when run in a Celery task, it sends the message to Channels and I can see that Channels does indeed run the code shown in my consumers.py code below, but the client never receives the websocket message. tasks.py def import_job(self): # (do task calculations, store in data dict) message = {'type': 'send_my_data', 'data': json.dumps(thecalcs) } channel_layer = get_channel_layer() async_to_sync(channel_layer.group_send)(self.group_name, message) consumers.py async def send_my_data(self, event): text = event['data'] # Send message to WebSocket await self.send(text_data=text) settings.py CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels_redis.core.RedisChannelLayer', 'CONFIG': { "hosts": [('127.0.0.1', 6379)], }, }, } Since there is no exception/error, I am completely at a loss as to which part of this process is failing. Celery triggers the task The task runs and sends a message to the channel layer The consumer receives the message … -
How to Call HTML code inside templatetags file
I wanted to call HTML inside a template tag file and display them in an HTML template file using template tags -
Django: filtering by value in [None, other]
I have the same problem as OP in this thread: Django - filtering by "certain value or None": I have a field in an data object that can be either null or set to some integer. I want, given an integer, to filter all the objects with that integer value OR none: MyElements.objects.all().filter(value__in=[myInt, None]) # Query 1 However, this line does not work for elements with null value. More precisely: MyElements.objects.all().filter(value__in=[None]) # Query 2 returns nothing. whereas MyElements.objects.all().filter(value = None) # Query 3 returns the null-valued elements. How can I rewrite the original query (which involves myInt) correctly? I am aware that OP has accepted an answer, but I would like to know why Query 2 did not yield any results. -
I'm having issues with mod_wsgi + Django + Apache
We deployed a Python 3 application in Django 2.1.2 in a Debian Stretch server. If we run "/usr/bin/python3 manage.py runserver 0:8000" into the application directory, it works correctly. Then, we are trying to serve the application using mod_wsgi for Apache. We aren't using a virtualenv. The version of mod_wsgi we are using is 4.6.5 and the version of Apache is 2.4. But mod_wsgi + Apache is not using Django, so the index.html seems to be like this: {% if user.is_authenticated %} Hello {{ user.first_name }}, instead of the page with css styles, images and so on. My /etc/apache2/sites-available/myapp.conf content is: Servername myapp DocumentRoot /home/project/myapp/myapp/templates/myapp WSGIScriptAlias /myapp /home/project/myapp/myapp/wsgi.py WSGIDaemonProcess myapp WSGIProcessGroup myapp AllowOverride All Require all granted -
How to search from different categories using 'Django Filter'?
I have used django_filters and here is code of it: from .models import Product import django_filters class ProductFilter(django_filters.FilterSet): product_name = django_filters.CharFilter(lookup_expr='icontains', label='Product Name') product_price = django_filters.NumberFilter() product_price__gt = django_filters.NumberFilter(field_name='product_price', lookup_expr='gt', label='Min Price') product_price__lt = django_filters.NumberFilter(field_name='product_price', lookup_expr='lt', label='Max price') hotel_location = django_filters.CharFilter(lookup_expr='icontains', label='hotel location') product_category = django_filters.CharFilter(lookup_expr='icontains', label='product category') class Meta: model = Product fields = ['product_name', 'product_price', 'vendor_name', 'hotel_location', 'product_category'] The view function contains the following code for displaying it in templates def searchTable(request): product_list = Product.objects.all() product_filter = ProductFilter(request.GET, queryset=product_list) return render(request, 'searchTable.html', {'filter': product_filter}) And the html code for this is: <form method="get"> ....... </form> <table class="table table-hover table-striped table-bordered table-dark" id="myTable"> <thead style="background-color: #3e4e6f; color: white"> <tr> <th>Image</th> <th>Product Name</th> <th>Price</th> <th>Vendor</th> </tr> </thead> <tbody > {% for lap in filter.qs|slice:":100" %} <tr> <td class="col-sm-3"> <div> <div class="product-image-wrapper"> <div class="single-products"> <div class="productinfo text-center"> <img src="{{ lap.product_image }}" alt=""/> </div> </div> </div> </div> </td> <td class="col-sm-5"> <h5><a href="{{ lap.product_url }}">{{ lap.product_name }}</a></h5> <br> <a href="{{ lap.product_url }}" class="btn btn-secondary" role="button" aria-pressed="true" style="background-color: #3e4e6f; color: white">See Details</a> </td> <td class="col-sm-2">{{ lap.product_price }} &#2547;</td> <td class="col-sm-2">{{ lap.vendor_name }}</td> </tr> {% empty %} <tr> <td colspan="5">No Result Found</td> </tr> {% endfor %} </tbody> </table> Now my question is let's say, I … -
In Django, how to index a field on a proxy model's original model?
I have a model that is a proxy model based on Django Comments' Comment model: from django_comments.models import Comment class Annotation(Comment): # ... class Meta: proxy = True The Comment model has a TextField() called comment and I'd like to add a GinIndex to this to speed up full text searching using Postgresql. However, I can't add an index on this field in Annotation's Meta class because I get this error: annotations.Annotation: (models.E016) 'indexes' refers to field 'comment' which is not local to model 'Annotation'. HINT: This issue may be caused by multi-table inheritance. And I can't add an index to the field definition itself, because it's in django_comments' Comment model. I guess I could write a migration to manually add an index to django_comments.models.Comment's comment field using SQL, but I wonder if there's some less messy way that I'm missing? -
Required = False Not Working Django Rest Framework Serializer
I am trying to update userprofile instance. But i am not passing user_groups in json it remove all foreign keys from my user_groups field. So for that i am setting(trying) this - if request.data.get('groups') == None: print('Groups is None') serializer2.instance.user_groups = userprofile.user_groups.all() But it is giving error Direct assignment to the forward side of a many-to-many set is prohibited. Use user_groups.set() instead This is the line where i have put required false groups = serializers.PrimaryKeyRelatedField(source='user_groups', queryset=Groups.objects.all(), many=True, required=False) But it is not working class EmployeeUpdateApiV2(APIView): def post(self, request, *args, **kwrgs): try: accesstoken=AccessToken.objects.get( token=self.request.META.get('HTTP_AUTHORIZATION').replace('Bearer ', '') ) except ObjectDoesNotExist: return Response ( { "status" : False, "error" : "Wrong Access Token", "error_message":"You have provided wrong access token.", } ) user_id = request.data['user_id'] user = get_object_or_404(User, id=user_id) print(user) userprofile = get_object_or_404(UserProfile, user=user_id) print(userprofile) serializer1 = EmployeeRegisterSerializer(user, data=request.data) serializer2 = EmployeeProfileSerializerUpdate(userprofile, data=request.data) if serializer1.is_valid() and serializer2.is_valid(): serializer1.save() if request.data.get('groups') == None: print('Groups is None') serializer2.instance.user_groups = userprofile.user_groups.all() serializer2.save() print('Inside Valid') return Response ( { "status" : True, "message":"Employee Updated Successfully.", "api_name" : "EmployeeUpdateApiV2", "result": serializer1.data, "result1": serializer2.data, } ) print('Out Valid') print('serializer1 ', serializer1.errors) print('serializer2', serializer2.errors) return Response(status=status.HTTP_404_NOT_FOUND) Serializer.py class EmployeeProfileSerializerUpdate(serializers.ModelSerializer): employee_id = serializers.CharField(source='user_employee_id', required=False) payroll_id = serializers.CharField(source='user_payroll_id', required=False) phone = serializers.CharField(source='user_phone', required=False) …