Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Given File Path, Open in File Explorer (Windows) or Finder (Mac) with HTML/Javascript
From a Django web application, given a file path from the user, how do I "Show in Explorer" or "Reveal in Finder". For example, if I have /path/to/file/on/user/computer, I would want when a user clicked a button for a File Explorer or Finder window to pop open that would locate/reveal the file. Also, I do not want the file to be opened in the browser. Thanks you! Your future feedback is much appreciated! -
QuerySet could behave more 'python-typical'
Assuming results is a Queryset, the check if not results or len(results) should not return into and error like AttributeError: 'QuerySet' object has no attribute 'get_compiler'. There should be some kind of standard behaviour. -
How to make a lightbox image in django?
How to make a lightbox image in django? I have here this code: <div class="gallery-wrapper less-gutter"> <div class="gallery-item mix"> <div class="image-block"> <div class="image"><img src="{% static 'site/2.jpg' %}" alt="gallery-image" class="img-fluid"> <div class="primary-overlay"> <a class="image-popup" data-effect="mfp-with-zoom" href="{% static 'site/2.jpg' %}"><i class="fa fa-picture-o"></i></a> </div> and it works but I need this effect to work not with certain pictures but with pictures that drag on with the admin, here with this code: {% for img in page.img_item.all %} {% image img.image fill-400x300 as img %} <li><img src="{{ img.url }}" alt="image" title="" id="wows1_{{ forloop.counter0 }}"/></li> -
The searchbar of my django website isnt working
This is the code in my base site(i.e base.html) for search bar: <form method="get" class="navbar-form navbar-right" role="search"> <div class="input-group"> <input id="search_box" type="text" name="q" class="form-control" placeholder="Search this site" style="width:550%"> <span class="input-group-btn"> <button type="submit" id="s1" class="btn btn-default"> <span class="glyphicon glyphicon-search"></span> </button> </span> </div> url of the searchbar view(present in "urls.py" of "myapp": url(r'^search/?$', views.search) view of the searchbar: def search(request): query= request.GET.get("q") if query: queryset_list= queryset_list.filter(title__icontain=query) I dont know why it's not working. im able to see search item in web browser url bar. but it's not showing any results in the webpage. -
looping over a list and a dictionary django
I have a list and a dictionary and i want to display the list and some information from the dictionary here is my codes so far <div class="container"> <div class="row"> <div class="col-sm-4 mt-2"> {% for file in files%} <div class="card"> <div class="card-header "> {{filename}} </div> <div class="card-body"> #i cant make such thing here {%for document in documents%} <p class="card-text">{{document.description}}</p> # how can i display this one here ? <a href="http://127.0.0.1:8000/media/documents/{{filename}}/{{file}}" class="btn btn-primary" download>Download</a> </div> </div> {% endfor %} </div> i want to display the description of the document here i have tryied everything i can think of but i havent succeeded at all here is a snippet of my views.py context = { "documents": documents, "crs_names": crs_names, "files": [], } -
Which is the best way to store website images in Django?
I'm building a news website using Django, which has been deployed in digitalocean ubuntu. Since there will be tons of image files in this news website. So I'm wondering is there any good way to store the images files? what does the big news website usually do to solve this problem? I heard one option is to store the image files in amazon-s3. I think I need compressed image size too, right? What's your suggestion?Thank you so much! -
Heroku wont find my .txt files
I've deployed my app to Heroku and as part of my app, I have a text file with data for pre-populating the database. I've written a shot Python script to try and populate the database but for some reason the script is unable to locate the text file in question. I've ran "heroku run bash" to check if the file is there and to my surprise the file is there. And when I run print(os.path.exists(settings.BASE_DIR+"/Miscellaneous/datafile.txt")) it returns false. I am in testing stage, so I am still using the free version of Heroku. What could be causing this problem, please assist. -
Changing Bootstrap nav-item active class (of dropdown) within Django
For some reason Django blocks aren't properly extending 'active' for me. I copied verbatim, the only difference is I'm trying it with a dropdown. So this works: <li class="nav-item dropdown active"> But this doesn't: <li class="nav-item dropdown {% block 'index_active' %}{% endblock %}"> An example of my index or about html: {% extends "client_side_app/base.html" %} {% block about_active %} active {% endblock %} What's odd about this is that I have content blocks right below this above code that have no problem injecting the html into the base.html. Any idea as to why this is happening? :( Thanks, Dev PS - I came to this thread first and tried implementing javascript and basically came to the same issue the guy asking the question. I essentially tried both ways to no avail, and a lot of other things to boot. -
CharField not saving
I'm a relative django newbie, but I haven't been able to find that this is somewhere else. I setup django in accordance with the djangogirls tutorial and created a model that looks something like this: class Grimmage(models.Model): gStart = models.CharField(max_length=100, default='Not set'), gStartLat = models.FloatField(default=0.0) gStartLong = models.FloatField(default=0.0) # [...] gUpdateDate = models.DateField(default=timezone.now) gUser = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) I've done the database migration thing, and I try creating objects with Grimmage.objects.create(gUser=request.user). (I've tried other methods of creating objects with the same results.) This is what I have in the respective view now (Why I'm not manually setting the default values again will be clear in a moment): grim = Grimmage.objects.create(gUser=user) grim.gStart = 'Not set' grim.gFinish = 'Not set' grim.save() Ultimately, the views I'm making should check if the values have been changed from 'Not set' to move through getting values from the user. So, the object also has a method called 'whatsNext()' to return which value needs to be filled in next: def whatsNext(self): ''' Returns a sting to indicate what value is needed next ''' # Assumes the Grimmage has been checked for completeness and failed if self.gStart == 'Not set': return 'gStart' elif self.gFinish == 'Not set': return 'gFinish' … -
Django and Ajax, get the Foreign Key values oreturned by Json serializer
so here's my problem. I have a search bar and when i click the search button i send an ajax request to retrieve all the items that contains the word in the search input. The problem is that when i append the retrieved items to the Table,two of my fields are represented as an id, not with a name (because they have ForeignKeys) Models.py class Inventory(models.Model): code = models.IntegerField(primary_key=True) category = models.ForeignKey(Categoria, on_delete=models.CASCADE) description = models.TextField() value = models.DecimalField(max_digits=8, decimal_places=2) user = models.ForeignKey( User, on_delete=models.SET_NULL, null=True, limit_choices_to={'is_superuser': True},) brand = models.CharField(max_length=20) model = models.CharField(max_length=25) serial = models.CharField(max_length=30) status = models.BooleanField(default=True) image = CloudinaryFieldFix('image', null=True, blank = True) def __str__(self): return '{0} {1}'.format(self.code, self.description) Inventory.js $(document).ready(function(){ $("#btnSearch").click(function(){ description = $("#search").val(); $.ajax({ url: '/inventary/list/searched_equipment', data: { 'description' : description }, dataType : 'json', success: function(data){ var equipment = data; if (equipment.length==0){ $("#tblEquip").empty(); alert("No items"); } else{ for (var i=0;i<equipo.length;i++){ $("#tblEquip").empty(); alert(equipo[i]["fields"]["category"]); } } } }); }); Views.py def searched_equipment(request): description = request.GET.get('description') items = Inventory.objects.filter(description__icontains=description) html = seralizers.serialize('json',items) return HttpResponser(html) Also, i tried to use the Wadofstuff Full Serializer to get the full data of that other model object, not only the id, but i cant make it work. print(serializers.serialize('json',Inventory.objects.all(),indent=4,relations = ('category','user',))) … -
Django: a model instance for every possible combination of 2 other model instances
I have a user model with a Foreignkey indicating to which group a user belongs. A user can order a service. The price of the service depends on which service it is and to which group the user belongs. The number of services and groups can be changed, but at all times I need a price for each possible service-group combination. class User(models.Model): name = models.CharField() group = models.Foreignkey(Group) class Group(models.Model): group_name = models.CharField() class Order(models.Model): user = models.Foreignkey(User) type = models.Foreignkey(Service) class Service(models.Model): type = models.CharField() Seems like I can't simply add a price field to the Service model because there are as many prices for the same service as there are groups. Question 1: In what kind of model should I store the prices? I was thinking of the following: class Price(models.Model): service = models.Foreignkey(Service) group = models.Foreignkey(Group) price = models.DecimalField() Would that be a sensible strategy? Question 2: Only an Admin will create a new group or service, but when that happens I need to ensure that somehow in Django's admin interface when for example a new service is created, the form also asks for different prices for each group and vice versa if a new group … -
Using Zurb Foundation 6 javascript in a Django project
I have an existing Django project that I would like to use Zurb Foundation in (version 6.4.2 to be exact). I figured from the documentation that you can just reference the CDN or download the relevant files to your static folder and reference them from there. I have done the latter via <link rel='stylesheet' href="{% static 'foundation/css/foundation.min.css' %}" type='text/css' /> <script src="{% static 'foundation/js/vendor/jquery.js' %}"></script> <script src="{% static 'foundation/js/vendor/what-input.js' %}"></script> <script src="{% static 'foundation/js/vendor/foundation.min.js' %}"></script> <script> $(document).foundation(); </script> The css seems to be working as expected, however the javascript does not seem to work at all. When I paste a snippet from say enter link description here , say <p><a data-toggle="menuBar" aria-expanded="false" aria-controls="menuBar">Expand!</a></p> <ul class="menu" id="menuBar" data-toggler=".expanded"> <li><a href="#">One</a></li> <li><a href="#">Two</a></li> <li><a href="#">Three</a></li> <li><a href="#">Four</a></li> </ul> nothing happens. The menu loads but the menu does not expand as it does in the linked documentation page. Am I not referencing the correct files or do I need to install or load anything I haven' t mentioned? Or is this a Django problem and if so is there a work around? -
ERROR - ws_protocol - [Failure instance: Traceback: <class 'TypeError'>: missing arguments
Hello Awesome People! I don't really know how to have a correct title for my question, so I just copy/paste a part of the traceback. Recently facing an issue with Django channels. That's the first time that I use channels. Firefox Firefox can’t establish a connection to the server at ws://127.0.0.1:8000/atlantis-global-vision/room/14/WtOtXrOcpwwHzNi/. Chrome WebSocket connection to 'ws://127.0.0.1:8000/gerrard-jena/messenger/room/14/WtOtXrOcpwwHzNi/' failed: Error in connection establishment: net::ERR_CONNECTION_REFUSED Here is my root URLs patterns: url(r'^(?P<slug>[-\w.\d]{4,})/room/',include('messenger.urls')), This is my messenger.urls url(r'^(?P<id>\d+)/(?P<code>\w.+)/$', views.chatRoomView,name="chatRoomView"), I think everything works with that, the issue is in my routing.py from messenger.views import chatRoomView application = ProtocolTypeRouter({ 'websocket':AllowedHostsOriginValidator( AuthMiddlewareStack( URLRouter( [ url(r'^(?P<slug>[-\w.\d]{4,})/room/(?P<id>\d+)/(?P<code>\w.+)/$', chatRoomView), ] ) ) ) }) And my consumer is: class ChatConsumer(AsyncConsumer): async def websocket_connect(self,event): print("Connected",event) await self.send({ 'type':'websocket.accept' }) async def websocket_receive(self,event): print("receive",event) async def websocket_disconnect(self,event): print("diconnected",event) From my console I get the following traceback 2018-08-18 09:00:58,014 - ERROR - ws_protocol - [Failure instance: Traceback: : chatRoomView() missing 3 required positional arguments: 'slug', 'id', and 'code' ''' multiple lines ''' [2018/08/18 09:01:02] WebSocket DISCONNECT /atlantis-global-vision/room/14/WtOtXrOcpwwHzNi/ [127.0.0.1:58022] This is my view: def chatRoomView(request,slug,id,code): ''' stuff ''' -
Django - fully override validation for a model field
I have a model that takes a datetime via a form, converts it to unix time, and saves it as a decimal. This is achieved in the clean method of the model. The problem is that the clean method seems to provide additional validation, rather than overriding the basic validation ('is it actually a decimal?', in this case). I have an if statement with two branches. If the model receives no value for this field, it saves the current timestamp. This works correctly. The second branch should, if the field is not none, convert the datetime to a timestamp and save it. The problem is that by the time it reaches the clean method, it has already thrown a validation error, because some other validation method has noticed that the input is a datetime, and not a decimal. The model: class CompanyAnnouncement(models.Model): class Meta: ordering = ['publish_datetime'] verbose_name = 'Company Announcement' verbose_name_plural = 'Company Announcements' company = models.ForeignKey(Company, on_delete=models.CASCADE) publish_datetime = models.DecimalField(decimal_places=6, max_digits=18, help_text='Leave blank to publish immediately') title = models.CharField(max_length=100) document = models.FileField(upload_to='company_announcements', help_text='', null=True, blank=True) def clean(self): if self.publish_datetime: try: self.publish_datetime = self.publish_datetime.timestamp() except: raise ValidationError(_("Invalid datetime.")) else: self.publish_datetime = dt.now().timestamp() -
Where Are Media Files Stored In Browser on GET request
I am building a web application in Django in which I will try to access audio files in the Media directory of my project. For example: <audio src="/path/to/media/file"></audio> I am able to do that and access the file, but my question is where does that file get stored after it is requested. Is it temporarily saved on the browser? If so, for how long? Can I reduce the amount of time? -
In pipenv shell right after installing django: calling django-admin.py and getting "No module named 'django'"
I'm following this tutorial and ran into some trouble. This is the situation: Python 3.6.6 Running Windows 10 I installed pipenv Created a new virtual environment and entered it with "pipenv shell" I installed django with "pip install django" and it shows up when typing "pip freeze" When I start typing "django-admin.py," tabbing won't result in auto-completion. But despite that, if I run "django-admin.py startproject nameofproject," the correct file is called. Also, if I run python and check the contents of sys.path, it includes path\of\user.virtualenvs\nameofproject\Scripts, which is where django-admin.py is located. Though the correct file is called, I get the following error: ModuleNotFoundError: No module named 'django' Would appreciate any help :) -
ReverseManyToOneDescriptor object has no attribute order_by django 2.1
im learning from the book the python crash course and i'm trying to create ids for topic here's the code: def topic(request, topic_id): """show a single topic and all its entries.""" topic = Topic.objects.get(id=topic_id) entries = Topic.entry_set.order_by('-date_added') context = {'topic': topic, 'entries': entries} return render(request, 'learning_logs/topic.html', context) django raises an error when i go to http://localhost:8000/topics/1/ -
Django - use template tags in if statement
I saw similar questions but none of them solved my problem . I have a simple template tag like this : @register.simple_tag def liked_by_user(post_id, user): try: PostModel.objects.get(pk=post_id).like_set.get(user=user) return True except: return False and i want to use this in an if statement like this : {% if liked_by_user post.pk request.user %} doing somethin... {% else %} doing somethin... {% endif %} what can i do ? -
How to get an object with a similar tag using django
I have an object (a blogpost) which can have multiple tags in django. I'm trying to get related objects with one or more of these same tags. For example: You have a blogpost with a few tags, like 'food', 'drinks' and 'restaurants'. When you open this blogpost, there are displayed some 'related' blogposts (meaning they share one or more tags). An example of such a related blogpost would have the tags: 'soda', 'lemonade' and 'drinks'. Here is my view: instance = get_object_or_404(Blog, id=id) tags = instance.tags.values() related = [] for x in tags: #to put all the tags in an array related.append(x['name']) for a in Blog.objects.raw('SELECT * FROM "blog_table" WHERE related in "blog_table"."tags"'): print (a.name) #this should display the name of all the related blogposts (probably including itself) Here are my models: class Tag(models.Model): name = models.CharField(max_length=500) number = models.IntegerField(null=True, blank=True) def __str__(self): return str(self.number) + ' ' + self.name class Blog(models.Model): name = models.CharField(null=False, max_length=500, verbose_name='title of blogpost', unique=True) body = models.TextField(null=False, verbose_name='body of the blogpost') tags = models.ManyToManyField(Tag, blank=True, null=True) def __str__(self): return self.name -
ManyToManyField in Django with addinational information
I'm trying to figure out how to add additional information with a ManyToManyField in Django. For example this code: class Animal(models.Model): # ... pass class Log(models.Model): animal = models.ManyToManyField(Animal) If I would like to create a Log object and select the Animal object to it. Then I want to include more information in my Log like color of hair, colors of eyes with the Animal object there (I can't add those inside the Animal object itself). And then I want to add another exactly the same object again to the Log object. For example a fox. So I want to add the Animal object twice for two different foxes to the log. The characteristics are the same but the only thing is some slight change in the hair color. How could this be accomplished? -
Django : Navigation rerouting to wrong page
I have been following this link https://www.youtube.com/watch?v=p_n7g6tVloU&list=PLw02n0FEB3E3VSHjyYMcFadtQORvl1Ssj&index=8 I am facing a issue with my code the code is supposed to direct me to login.html but it is navigating me back to home.html The codes that i have been working are accounts/urls.py urlpatterns= [ url('',views.home), url(r'^login/$', login, {'template_name' : 'accounts/login.html'}), ] the root tutorials path = tutorials/urls.py urlpatterns = [ path(r'^admin/', admin.site.urls), re_path(r'^account/', include('accounts.urls')) ] views.py def home(request): numbers = [1,2,3,4,5] name = "Rajiv Pai" args = {'myName' : name, 'numbers' : numbers} return render(request,'accounts/home.html', args) accounts/home.html {% extends 'base.html' %} <h1> Home Page</h1> <!DOCTYPE html> <html> <head> {% block head %} <title> This is Home Page</title> {% endblock %} </head> <body> {% block body%} <h1> Hello World</h1> {% endblock %} </body> </html> login.html <!DOCTYPE html> <html> <head> {% load static %} <link rel="stylesheet" type="text/css" href="{% static 'accounts/style.css' %}"> <title>Login</title> </head> <body> <div class = "container"> <h1>Welcome</h1> You can login here!!! <button class = "btn btn-danger outline" type = "button" name = "button">Click Here</button> <h1>Hello, {{myName}} </h1> <br/> <ul> {% for number in numbers %} <li>{{ number }}</li> {% endfor %} </ul> </div> </body> </html> -
how to perform calculations like running total, aggregation in a django model that uses data from another model's multiple fields?
class journal(models.Model): Particulars =models.ForeignKey('transaction.ledger1',on_delete=models.CASCADE) Pa_Cr=models.ForeignKey('transaction.ledger1',on_delete=models.CASCADE,related _name='Creditledgers') Debit = models.DecimalField(max_digits=10,decimal_places=2) Credit = models.DecimalField(max_digits=10,decimal_places=2) in another model: class ledger1(models.Model): by_transactions_name =models.CharField(journal.journal,max_length=30,blank=False) by_transaction_amt = models.DecimalField(journal.journal,max_digits=19,decimal_places=4) to_transactions_name =models.CharField(journal.journal,max_length=30,blank=False) to_transaction_amt = models.DecimalField(journal.journal,max_digits=19,decimal_places=4) Closing_Balance = models.FloatField(blank=True, default=0.0) i am trying to create a double entry system that can map entries , but am unable to auto-populate the running total in closing balance from journal transactions. -
Channel error on connection rabbitmq, celery and django
=ERROR REPORT==== 18-Aug-2018::11:38:19 === Channel error on connection <0.17949.0> (IP:50872 -> IP:5672, vhost: 'myhost', user: 'myuser'), channel 1: {amqp_error,access_refused, "access to exchange 'celeryev' in vhost 'myhost' refused for user 'user'", 'exchange.declare'} Following above is the error i am facing right now. I had already running AWS instance, took a snapshot and put new django code over it. Run the celery task over it and facing this error in the rabbitmq server logs. When check the snapshot there was no user and vhost. So i added the exact same name and password user and vhost. and set the permissions as administrator. And still keep facing this issue. Any help in this regard would be much appreciated. -
Overriding Sign Up functionality of django-rest-auth or django-allauth
I want to override how django-rest-auth signs up a user. By default following info is needed to sign up a user : { "username" : "someusername", "password1" : "somepassword", "password2" : "somepassword", "email" : "someemail" } I want to customise it to be : { "username" : "someusername", "HOD_email" : "somepassword", "phone_number" : "somepassword", "email" : "someemail", "emp_id" : "some_emp_id" } Also I want to create a random dummy password for every new user on sign up. Here is my current code : # serializers.py 5class RegistrationSerializer(serializers.ModelSerializer): 6 7 class Meta: 8 model = User 9 fields = ('username', 'email', 'phone_number', 'emp_id', 'HOD_email') 10 11 12 def save(self, request): 13 """ 14 Create and return a Token 15 """ 16 print("My create is getting called------") 17 user = User(**validated_data) 18 try: 19 user.save() 20 except Exception as e: 21 print("error creating user", e) 22 return user # settings.py 36# REST AUTH SETTINGS 237REST_AUTH_SERIALIZERS = { 238 'REGISTER_SERIALIZER' : 'home.detectSoftware.detect.projects.GUMPS_BE_DEV_V2.1.Server.UserAuth.s\ erializers.RegistrationSerializer' 239} However, it continues to use the existing functionality. -
Django-CMS: PlaceholderField in django admin
I'm trying to use PlaceholderField instead of HTMLField in django admin. I read this docs but got nothing so my models.py from django.db import models from cms.models.fields import PlaceholderField class Blog(models.Model): name = models.CharField(max_length=100) field = PlaceholderField('content') Then I added some code to admin.py from django.contrib import admin from example.models import Blog from cms.admin.placeholderadmin import PlaceholderAdminMixin class MyModelAdmin(PlaceholderAdminMixin, admin.ModelAdmin): pass admin.site.register(Blog, MyModelAdmin) But when I try to add new model in django admin I see only name field Is this some steps that I lost?