Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Display the object related set objects in the admin
I have three models for Movie, NowShowing and UpComingMovie. NowShowing and UpComingMovie has foreignkey relationship with the Movie. class Movie(models.Model): name = models.CharField(max_length=254, unique=True) synopsis = models.TextField() release_date = models.DateField() director = models.ManyToManyField(MovieDirector) writer = models.ManyToManyField(MovieWriter) actor = models.ManyToManyField(MovieActor) censor_rating = models.PositiveIntegerField(choices=CENSOR_TYPE) @property def is_screening(self): if self.nowshowing_set.all().count() > 0: return True else: return False class NowShowing(models.Model): movie = models.ForeignKey(Movie) show_time = models.DateTimeField() class UpComingMovie(models.Model): movie = models.ForeignKey(Movie) Each three of the models can be accesed in the admin: class MovieAdmin(admin.ModelAdmin): list_display = ('name', 'release_date', 'censor_rating', 'is_screening') class Meta: model = Movie admin.site.register(Movie, MovieAdmin) admin.site.register(NowShowing) admin.site.register(UpComingMovie) The problem is that I have to go to NowShowing or UpComingMovie admin page to create/change object. Is it possible to display each movies related set fields (NowShowing or UpComingMovie) to display in the Movie object detail admin page itself, so that its related field can be created/changed from the Movie obj directly without going to NowShowing or Upcoming admin page? -
CSS functions in Django app, but cannot edit it anymore
I'm having quite the weird issue. My Django (1.10) app is functioning just fine. I initially set it up using bootstrap with my own style.css file to customize the rest of it. However, since then I've had some issues and lost my git commits, so I can only go back to about 10 days ago when it was stable in production. I thought all was well until I tried to style some new pages and change some existing css, and then I found I couldn't. My app seems to have style.css files all over the place. There seems to be 4 total, and none of them do anything. I've tried deleting everything from each one individually, and then deleting everything from all of them at once, but no matter what my site stays with its styling. I've cleared the cache from my browser, used a different browser, used incognito mode, etc. No matter what, the styles persist. I initially used collectstatic. Now, I've tried to do it again, and I've also tried collectstatic --clear, but both have the same effect: my root static folder gets an entire copy of my app put in it and I have to delete the … -
django votes how to create a button
I am using django and want to use the votes app to create like / dislike functionality. I want to use it with the saleor e-commerce platform so that users can vote products. I installed the votes app and then added it to the Product class of saleor as described in the readme. Then I added the following to the template hoping it will create a upvoting button but I end up with NoReverseMatch error: <form id=”upvote-form” role=”form” method=”get” action=”{% url ‘/votes/up/’ model=’Product’ id=product.pk vote=’true’ %}” novalidate> <button class=”btn primary”> {% trans “^” context “UP Vote” %} </button> </form> Any help appreciated. I am a complete newbie to django so please excuse my ignorance. -
Retrieving data from an array of check boxes in a Django template
In a Django template, I'm displaying some usernames (or unames) along with check boxes like so: <form method="POST" action="{% url 'process_unames' %}"> {% csrf_token %} {% for name in unames %} <input type="checkbox" name="target{{ forloop.counter0 }}" value="{{ unames|index:forloop.counter0 }}" checked>{{ name }}<br> {% endfor %} <button name="duration" value="{{ value }}" type="submit">Submit</button> </form> And then in the function process_unames, I'm trying to retrieve all checked unames via: def process_unames(request, *args, **kwargs): uname_list = request.POST.getlist('unames') This is consistently yielding an empty list, regardless of which uname I check or uncheck. How do I fix this? An illustrative example would be great. In case it matters, I haven't declared any form in forms.py with this Django template. Moreover, note that index is a custom template tag which does the following (and I can vouch it's correctly working): from django.template.defaulttags import register @register.filter(name='index') def index(List, i): return List[int(i)] -
converted local language using google input tool not getting displayed
I am using the following js code to convert local language from English in a django app. It is working locally, but on aws, display is not working, what i can see is only symbols of question mark. // Load the Google Transliteration API google.load("elements", "1", { packages: "transliteration" }); function onLoad() { var options = { sourceLanguage: 'en', destinationLanguage: ['ml'], shortcutKey: 'ctrl+m', transliterationEnabled: true }; // Create an instance on TransliterationControl with the required // options. var control = new google.elements.transliteration.TransliterationControl(options); // Enable transliteration in the textfields with the given ids. var ids = [ "lang", "langu", "language" ]; control.makeTransliteratable(ids); // Show the transliteration control which can be used to toggle between // English and Hindi and also choose other destination language. // control.showControl('translControl'); } google.setOnLoadCallback(onLoad); The error on console is A Parser-blocking, cross-origin script, https://www.google.com/uds/?file=elements&v=1&packages=transliteration, is invoked via document.write. This may be blocked by the browser if the device has poor network connectivity. See https://www.chromestatus.com/feature/5718547946799104 for more details. Thanks in advance for your help. -
How to build my python code and add to server where the end user can use it?
I am new to python. I want to use my code through URL? How it is possible -
Django, setting roles of users' models in admin
I really didn't want to ask this question, but amount of information in different tutorials and docs about this are overwhelming to me. I have three types of users: Admin, Guide, User: Admin can do anything in admin page. Admin can change simple Users to Guides Guide can only create GuideTour model objects and manage only his own tours. User can't login to admin page. How I can set these users in my model definition, in order to gain that kind of roles in my admin page? Is it single-table-inheritance mode? -
Django multiple duplications
I'm using django notifications, but when unread notifications increasing, loading time and duplication times are also increasing. How can I optimize this code ? {% for notification in request.user.notifications.unread %} <li><div class="media"> <div class="media-left"> <div class="media-object"> <img data-src="holder.js/50x50?bg=cccccc" class="img-circle" alt="50x50" style="width: 50px; height: 50px;" src="{{ BASE_DIR}}/media/profile_pictures/{{notification|getNotifUser}}/profile.jpg" data-holder-rendered="true"> </div> </div> <div class="media-body"> <strong class="notification-title"> <a id="{{ notification.target_object_id }}" class="{{ notification.pk }}"> {{ notification.actor_object_id|get_username}}&nbsp;{{notification.verb}} - request {{notification.target_object_id}}</a></strong> <div class="notification-meta"> <small class="timestamp">{{ notification.timesince | getLocalTimeDifference}} əvvəl</small> </div> </div> </div> </li> {% endfor %} -
how to add dynamic pagination in django using select option method?
I am making a dynamic pagination where I allow the user to enter the value and on that basis the templates show the values.I am using select option value of html to fetch the value. -
Redirect to reload current page view after form POST
In a simple blog application, when a user comments on a post, what's the recommended way to redirect to that same variable route or permalink to display the new comment (in django)? urlpatterns = [ ... url(r'^comments/(?P<post_id>[0-9]+)$', views.comments, name="thread"), url(r'^post/comment/$', views.post_comment, name="post_comment"), ] In the view, I can get the url with request.get_full_path(), but I assume rather than stripping off post_id there's a better way to pass it to the redirect. Example view (but not right): def post_comment(request): this_post = get_object_or_404(Post, id=post_id) author = User.objects.get(user=request.user) new_comment = request.POST.get('commentContent', None) parent_object = None comment = Comment.create(author=author, new_comment=new_comment, parent=parent_object) comment.save() return redirect('/comments/{}'.format(this_post.id)) thanks -
Is it possible to open a modal in Django to edit a form but while passing parameters to it?
I currently am building a template that allows the user to edit user and family information. I currently have it expanding down but would like to add the ability to use a modal. This is my current tag: Click to Edit If there is a way that I can do this, please, any advice would help. -
Django TestCase Warning: Converting column 'options' from VARCHAR to TEXT
I am new to Django testcase. And I am using the django with mysql for backend. While I am trying to run django testcase for the particular app. I got the warning like below. "Warning: Converting column 'options' from VARCHAR to TEXT" But this warning is stopping my testcase. Also not getting the result of testcases. At this time it created the test_db. Let me clear what happening at the time of testcase running and the details of this error. Thanks -
Django - subprocess call not working properly
I have these following views: class MiniView(generic.DetailView): model = Automata template_name = 'convert/mini.html' context_object_name = 'automata' command = "python MiniDFA.py" subprocess.call(command, shell=True) class DFAView(generic.DetailView): model = Automata template_name = 'convert/dfa.html' context_object_name = 'automata' command = "python NFAtoDFA.py" subprocess.call(command, shell=True) class TransitionCreate(UpdateView): model = Automata fields = [] [...] command = "python make_graph.py" subprocess.call(command, shell=True) [...] For I would like the commands to execute everytime I call the view, but for some reason only the last one seems to be working properly I'm not sure why.. the script by itself seems to be working fine. I also noticed that the scripts execute everytime the server runs, not sure why either.. -
Django React Nginx serving admin static files
I feel a bit awkward asking a question which has been answered before - however I feel there is a point of difference with regard to having node serve out the static files as opposed to django. The css bundled by webpack and served by node is working with no problems, where I'm having issues is serving up the admin css and another couple of other files using the get_static_prefix decorator. The file structure is as follows: root | public - templates - static | <-- collectstatic adding files here - vendor | server - app1 - app2 | settings.py /etc/nginx/sites-available/project server { listen xxx.xxx.xxx.xxx:8000; server_name xxx.xxx.xxx.xxx; location /static { alias /root/se/env/public/static/; } } and the setup in settings.py STATIC_URL = '/root/se/env/public/static/' MEDIA_URL = '/media/' STATIC_ONLY_URL = '/static_only/' if not DEBUG: MEDIA = '/media', STATIC_ROOT = '/root/se/env/public/static/' MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), 'public', 'media') STATICFILES_DIRS = '/root/se/env/public/vendor/static/', I've been going around in circles for a while now. I'm pretty new to Django and don't really get how this works. From what I can understand the the STATICFILES_DIRS are where collectstatic gathers the static files from and the STATIC_ROOT is where the static files are dumped after collectstatic is run. I think the … -
How to appropriately choose entries from database when using ManyToManyField?
I'm writing an application for a bike shop. I need to be able to assign many Repairs (i.e. a flat repair) to a Transaction. Each repair has a name, description, and price. Each transaction has a repairs field. For Transaction, I have repairs = models.ManyToManyField(Repair, blank=True) which makes logical sense. However, there will be some 40-odd different kinds of repairs. When I add repairs to a transaction, I don't want to have to create new instances of a Repair each time I create a new transaction and add repairs to it - I'd like to just have a pointer of sorts to that specific repair. In other words, Repair acts as a list of possible repairs, with prices and descriptions, and Transaction has a field that points to a list of these repairs. Additionally, my field in Transaction needs to be able to specify whether each repair has been completed. I need to do the same kind of thing for Item (i.e., a tube) being pointed to by a Transaction. I'm unsure how to do this in Django. I may be overthinking it, or my database design may be poor. -
Django Channels message life time
I have some (possibly huge) amount of JSON data I need to push into Django Channel. The data has very small required lifetime (2-3 seconds is enough). I use Redis as backend. What is default message lifetime? Is it possible to specify life time of the message? -
Django multiple many to many relationships not working
Are multiple many-to-many relationships possible in a single class? Here is my thinking: A policy can be translated into many Languages A Language can list many policies A country can list many policies (even in multiple languages) A policy can be discussed in many countries class Language(models.Model): iso_language = models.CharField(max_length = 2, primary_key=True) flag_image_filename = models.CharField(max_length = 10, default='en.png') nav_section_policy_list_title = models.CharField(max_length = 30, default='Policies') etc. class Country(models.Model): language_country_code = models.CharField(max_length = 5, primary_key=True, unique=True, default="en/ca") language_code = models.CharField(max_length = 2) # min_length=2 country_code = models.CharField(max_length = 2) # min_length=2 country_name = models.CharField(max_length = 50) class Policy(models.Model): image_filename = models.CharField(max_length = 30) start_date = models.DateField(default = None) languages = models.ManyToManyField(Language, through="Policy_Detail") countries = models.ManyToManyField(Country) class Policy_Detail(models.Model): policy = models.ForeignKey(Policy) language = models.ForeignKey(Language) needs_translation = models.BooleanField(default = True) name = models.CharField(max_length = 50) I'm having trouble implementing this code. Thanks for your help. -
Navigating Multiple Join Paths Django Model
class UOM(models.Model): name = models.CharField() description = models.TextField(max_length=45) class UOMConversion(models.Model) uom_origin = models.ForeignKey(UOM, related_name="from_uom") uom_dest = models.ForeignKey(UOM, related_name="to_uom") factor = models.DecimalField() I need to convert different types of UOM but can't figure out how to query using multiple relations to the same model. How can i retrieve and get name of the uom and the conversion factor? -
FileNotFoundError when generating LaTeX PDF with Django
Working from the example given here, I'm trying to get a Django app to generate a PDF from a template written in LaTeX. Note that I have not gotten to the stage of populating the LaTeX template file with values from the database. It currently has 'hard-coded' content, I'm just trying to get the PDF generation working first. views.py from django.shortcuts import render from django.http import HttpResponse from django.template import Context from django.template.loader import get_template from subprocess import Popen, PIPE import tempfile def pdf(request): context = Context({}) template = get_template('cv.tex') rendered_tpl = template.render(context).encode('utf-8') with tempfile.TemporaryDirectory() as tempdir: # Create subprocess, supress output with PIPE and # run latex twice to generate the TOC properly. # Finally read the generated pdf. for i in range(2): process = Popen( ['pdflatex', '-output-directory', tempdir], stdin=PIPE, stdout=PIPE, ) process.communicate(rendered_tpl) with open(os.path.join(tempdir, 'texput.pdf'), 'rb') as f: pdf = f.read() r = HttpResponse(content_type='application/pdf') r.write(pdf) return r But when I go to the URL I've pointed at the view, I get the following error. [WinError 2] The system cannot find the file specified: 'C:\\Users\\LTHORB~1\\AppData\\Local\\Temp\\tmp1sf9cual.log' I'm not very familiar with handling temporary files. What do I need to do? -
how to use single site for www and root in django sites framework
I currently have a single site, but I want to expand to several sites for use in django. I currently must have two entries in my django_sites table for my single site: 1 mysite.com My Site 2 www.mysite.com My Site Now that I want to have multiple sites, having multiple entries per subdomain is not feasible anymore since I want to create many to many relationships with objects associated with the sites. How can I use a single www and root domain per site instead of the two? -
Django website - make button link to a different app
I am trying to make a button that links to another app when you click it. For some reason, this works: <a href="{% url 'ridesharing:ride-list' %}" target="blank">Find a ride</a> But this does not: <button type="button" class="btn btn-xl" style=" border-color: rgb(2,132,69); background-color: rgb(2,132,69); color: rgb(246,246,247); font-family: Verdana;font-size: large" href="{% url 'ridesharing:ride-list' %}">Find a ride</button> I am using a button because I like how I can customize how it looks. How do I get the button to link to the right app. -
adding colour in a django models.TextField
I have a model in django: introduction = models.TextField(null=False, blank=False) When writing in the text field I want the colour of the middle section to be different from the rest. Any ideas how I do this how to set colours in the textfield? -
Django - Use signals to refresh another model's fields
I have two models, one of which uses data from the other model to populate its own fields. The issue is that when the first model is updated, the second model does not also update its own fields. I have to go in and actually edit/save the 2nd model for its fields to update. Something like this: models.py: class ModelA(models.ModelForm) ... class ModelB(models.ModelForm) count_number_of_model_A = models.IntegerField def save(self) self.count_number_of_model_A = ModelA.objects.all().count() super(ModelB, self).save() (this is a simplified version of what I'm trying to do) Now I want the field "count_number_of_model_A" in ModelB to update every time ModelA is altered. Right now, it only refreshes if I actually modify+save ModelB. I think the answer is to use signals (maybe?). I'm trying to set up a signal so that ModelB updates whenever a new object is created in ModelA. I have the following: @receiver(post_save, sender=ModelA) def update_sends(sender, **kwargs): if kwargs.get('created', False): #some code here to refresh ModelB?? The signal is functioning properly, as if I put in something like ModelB.objects.filter(some filter).update(some field), those changes are reflected when I go in and create a new ModelA object. But the whole model itself does not update, and the field in question that I'm after … -
Calling Scrapy Spider from Django
I have a project with a django and scrapy folder in the same workspace: my_project/ django_project/ django_project/ settings.py app1/ app2/ manage.py ... scrapy_project/ scrapy_project/ settings.py scrapy.cfg ... I've already connected scrapy with my django app1 model so every time I run my spider, it stores the collected data in my postgresql db. This is how my scrapy project can access to the django model #in my_project/scrapy_project/scrapy_project/settings.py import sys import os import django sys.path.append('/../../django_project') os.environ['DJANGO_SETTINGS_MODULE'] = 'django_project.settings' django.setup() Everything works great when I call the spider from the command line, but when I wanted to call the spider as a script from a django view or a Celery task ind django, for example: from scrapy.crawler import CrawlerProcess from scrapy.utils.project import get_project_settings process = CrawlerProcess(get_project_settings()) process.crawl('spider_name') process.start() I get an Error: KeyError: 'Spider not found: spider_name' I think I'm suppose to tell Django the Scrapy's location (as I've done in scrapy settings), but I don't know how. To be honest, I'm not even sure that how I design my folder structure for this project is the correct one. -
Django model, refreshing values from logfile read
I have a simple Django model that references a logfile for one of its fields. This logfile simply contains a list of ten numbers. On creation of the first instance this model from the admin panel, it successfully reads the logfile and sets a choice dropdown field from that file, but it doesn't notice changes to that logfile when creating new instances of that model. class List(models.Model): f = open(os.path.join(BASE_DIR, 'logtest.txt'), 'r') myfile = File(f) lines = myfile.readlines() linesCleaned = [int(i) for i in lines] listChoices = [(index,item) for index, item in enumerate(linesCleaned)] list_choice = models.IntegerField(choices=listChoices) new_value = models.IntegerField(default=0) f.close() def update_tags(sender, instance, *args, **kwargs): call_command('listScript', write_at_bit=str(instance.list_choice + 1) + str(instance.new_value)) The admin user choses the list_choice they want to to change, and chooses the new_value they want to write to that spot. The write is handled by the listScript, which is required because I need to interact with proprietary third party hardware. The write is successful, and the logfile shows the updates. But when the admin user tries to add another List object, the changes to the logfile don't reflect in the list on the admin panel.