Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Javascript add links to html a elements
I want to add href to an a html element from class of another element. It might also be good to know that i am using Django. Firstly i have this list: <ul> <li class="A" id="tablink">A</li> <li class="B" id="tablink">B</li> ... </ul> if list from the first ul is selected, i want the class of the list (example: A) to add to href element to all links in another ul: <ul> <a href="{% url id=id character= <!--here i want the character selected to be inserted--> %}">One</a> <a href="{% url id=id character= <!--here i want the character selected to be inserted--> %}">Two</a> ... </ul> As well i dont want the second url to be visible, when the character is not selected yet. Thank you! -
How to associate a bunch of boolean fields in a model to a single form?
Say I have a model with a few boolean fields and an already existing user foreign key. # models.py from django.db import models from django.conf import settings class MyModel(models.Model): existing_user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) bool1 = models.BooleanField(default=False) bool2 = models.BooleanField(default=False) bool3 = models.BooleanField(default=False) The default widget for BooleanField is a checkbox and if it was changed to RadioSelect it would expect a new set of radio buttons for each BooleanField in the model. # forms.py class MyModelForm(forms.ModelForm): class Meta: fields = ['bool1', 'bool2', 'bool3',] widgets = { 'bool1': forms.RadioSelect(), 'bool2': forms.RadioSelect(), 'bool3': forms.RadioSelect(), } I would like to create a form that presents the BooleanFields from models as a single radio select list that when selected updates the boolean for that model to true. -
Versioning a virtualenv for a django deployment - pip output of requirements
I'm currently writing a deployment script for a django app using fabric. It seems necessary / useful to me to have a system for versioning the virtualenv that the app uses, in case a rollback is needed. The most robust way I can think to do this is to create virtualenvs with the name equal to the md5 hash of the contents of the requirements file. this means that when the requirements change, the checksum will change and I can copy/update the virtualenv with a new hash and preserve the old hash virtualenv in case I need to rollback (then it's just a matter of switching a 'current' symlink). Trouble is I'm using nested requirements file syntax in e.g. my production.txt requirements file (-r base.text) so the md5 hash isn't going to take into account base requirements changes etc. Is there any output pip can provide to parse these files prior to installing them? I don't want to have to install them then pip freeze just to figure out if something has changed. -
Django crispy form with formset does not show delete checkbox
I have some code structure very similar to this example: https://gist.github.com/ibarovic/3092910 Everything is working pretty well, except that the delete checkbox after each Book element is not shown at all. If I change {% crispy formset formset.form.helper %} to {% crispy formset %} the delete checkboxes are shown, but the form does not work anymore (b/c the HTML form tags are used not only once). I suspect that those checkboxes are not known to the BookForm (b/c they somehow get added later by the inlineformset_factory), so they do not get added to the layout and are ignored. I have no idea how to circumvent that though. -
how do i fix the below given statement? it is about runserver. please help me to fix this
whenever I type this url - "127.0.0:8000/admin", it asks for username and password. As I am a beginner in Django , please bear with me to fix this? -
How do I have a functioning all button with a SimpleListFilter
I have a django admin that I am trying to change my default filter for. I have the filter displaying the data I want as default but my all button is not functioning correctly because I am returning a specific queryset when the value is None. Is there a way to have a functioning all button without changing the 'All' value? class EmailFilter(admin.SimpleListFilter): title = _('email category') parameter_name = 'email_category' def lookups(self, request, model_admin): return ( (10, _('Forwarded')), (8, _('Spam')), ) def queryset(self, request, queryset): if self.value() is not None: return queryset.filter(email_category=self.value()) return queryset class myAdmin(VersionAdmin): list_filter = (EmailFilter) -
how to use get_absolute_url
i am having trouble understanding code of website in tutorial. what i understood is that urls.py take a argument as product_slug which is used to get object in my show_product view and another argument is used in as template_name but what is argument 'catalog_product' doing it is defined in my model.when I remove 'catalog_product' I get error as: no reverse match at /category/guitar please explain how does this argument get_absolute_url work and how and where I can use it? model.py is: def get_absolute_url(self): return reverse('catalog_product', (), { 'product_slug': self.slug }) I am having uurls.py as: url(r'^product/(?P<product_slug>[-\w]+)/$',show_product, {'template_name':'catalog/product.html'}, 'catalog_product') and views.py: def show_product(request, product_slug, template_name="catalog/product.html"): p = get_object_or_404(Product, slug=product_slug) categories = p.categories.filter(is_active=True) page_title = p.name meta_keywords = p.meta_keywords meta_description = p.meta_description return render(request, template_name, locals()) template product.html :- % extends "catalog.html" %} {% block content %} <div class="product_image" > {% load static %} <img src="{% static 'images/products/main/{{ p.image}}' %}" alt="{{ p.name }}" /> </div> <h1>{{ p.name }}</h1> Brand: <em>{{ p.brand }}</em> <br /><br /> SKU: {{ p.sku }} <br /> In categor{{ categories.count|pluralize:"y,ies" }}: {% for c in categories %} <a href="{{ c.get_absolute_url }}">{{ c.name }}</a> {% if not forloop.last %}, {% endif %} {% endfor %} <br /><br /> {% … -
how to overcome the following url issue?
Hello I am beginner learning Django I am triying to follow this tutorial: https://docs.djangoproject.com/en/1.11/intro/tutorial01/ I created an app called Polls to test my site: Since I dont have idea where to put the file called urls.py I put this file at the following directories: Django/mysite/polls/urls.py Django/mysite/polls/migrations/urls.py This file contains: from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.index, name='index'), ] And finally I added the following lines: at this level: Django/mysite/mysite/urls.py this file contains: from django.conf.urls import include, url from django.contrib import admin from django.conf.urls import url from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^polls/', include('polls.urls')), ] I dont know where is the issue but when I run: Django/mysite$ python3 manage.py runserver Performing system checks... System check identified no issues (0 silenced). You have 13 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions. Run 'python manage.py migrate' to apply them. April 21, 2017 - 15:59:43 Django version 1.10.5, using settings 'mysite.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. I got in the page the following: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/ Using the URLconf defined in … -
Append .png image to a pdf using reportlab in Django framework
I'm using Django and reportlab to generate a PDF report I already can generate the pdf, but I Wanted to append a logo.png to it. these were the lines I added in views.py: from reportlab.platypus import Image logo = Image("/cdss/static/cdss/img/logo.png") exam.append(logo) But it isn't working, Am I exporting the Image() method wrong? Or is Path to the file wrong? Hope you can help me, thanks ;) -
reversed counting in django template with <ol>-tag
I want to write a template which is paginated (not all list items on the same page) is numbered with -tag because this is the most semantic way to order the list can be reversed or not the numbers are linked to the represented models (every li-tag contains an a-tag that is linked to a model.) That means the list not alway starts with 1. My model: class Mymodel(models.Model): number = positiveIntegerField() title = models.CharField(max_length=100) [...] number is unique, ordered and when you order the models with the number, there is no gap; number is 1-based What I have: (reverse is boolean variable which tells whether the list has to be reversed or not) {% if reverse %} <ol class="content" start="{{ article_list.0.number|add:article_list.count }}" reversed=true> {% for article in article_list reversed %} <li class="{% cycle '' '' '' '' 'seperate-bot border-gray' %}"><a href="{% url 'myapp:article' article.number %}">{{ article.title }}</a></li> {% endfor %} {% else %} <ol class="content" start="{{ article_list.0.number }}"> {% for article in article_list %} <li class="{% cycle '' '' '' '' 'seperate-bot border-gray' %}"><a href="{% url 'manifest:article' article.number %}">{{ article.alt_title }}</a></li> {% endfor %} {% endif %} </ol> Unfortunately counts the backward template part wrong: the last number is … -
css / javascript - Display image that follow the mouse when hover over text
I am struggling with this common question where there are many examples such as first1 but it is not exactly what I want to have and I have not been able to make modifications.Most of then are the contrary, display text when hover over a image... My website has a table within links or specifics key words and I would like, when a user has is mouse on them, it displays a popup close to the "link or keyword" within a static .svg. Basically what I want is like the "title" arg but rather than a text, an image should be displayed using javascript/CSS.Is it possible to have an example where it is possible to modify the image box distance, the design of this box ? I have not any code, any help would be more than appreciated. Thank you. -
How to ask for login to access to any url djanog
I have thies in views.py @login_required() def dadmin(request): I had not used @login_required() in dapost and dapage And in url.py url(r'^dadmin/$', dadmin, name='dadmin'), url(r'^dadmin/post/$', dapost, name='dapost'), url(r'^dadmin/page/$', dapage, name='dapage'), Now I want is everytime when users try to access domain.com/dadmin/any... it redirect to login page. how ca i Do that? without placing @login_required() in dapost and dapage? -
Django ImageField in forms not uploading, works from admin but not from form
So, I have a system where users can either choose from an already existing image gallery, or upload a new image to be processed and saved. First off, the model: class Post(models.Model): image = models.ForeignKey(Image, null=True, blank=True) title = models.CharField(max_length=200) slug = models.CharField(max_length=200, unique=True, blank=True) description = models.TextField(blank = True) text = models.TextField() def __str__(self): return self.title and our form class PostForm(BaseModelForm): new_image = forms.ImageField(required=False) def clean(self): return self.cleaned_data class Meta: model = Post fields = ('title','text', 'image', 'new_image', description') help_texts = { 'new_image': _('either upload a new image, or choose from the gallery') } so then our view where it gets processed def post_new(request): if request.method == "POST": form = PostForm(request.POST) if form.is_valid(): post = form.save(commit=False) post.author = request.user post.slug=slugify(post.title) if form.cleaned_data.get('new_image'): image = Image(title=post.title, description=post.description, image = form.cleaned_data.get('new_image')) image.save() post.image = image post.save() return redirect('post_detail', pk=post.pk) else: form = PostForm() return render(request, 'blog/post_edit.html', {'form': form}) Now what this should be doing is creating a new image object out of the form field, then saving it to the foreignkey constraint on the post model. But what it does is nothing, the post uploads fine with a blank image field, and the image never gets created. This makes me think … -
Django / Python POST API without Model/Serializer
I want to create a very simple API, with only one endpoint. I want to send to an API a json like : {"provider" : "com.facebook.orca", "code" : "1", "color" : "#FFFFF" } Then, I want to use a python library to control a device in my room(python-yeelight). I want to use this with a Auth token or a username/password authenticate. What I found on Django Rest Framework was way too complicated for what I need(which is accepting a POST and returning a "success" or "failure" message. Thank you! -
Django: redirecting URL from auto-generated "?search_bar="
So I am a new Django programmer and was wondering about how to pass a user-given value from a form into my URL address using Get method. So I have this search bar, and when the user presses enter, it automatically creates a url address of "?search_bar=user_input" But my urls.py, which is programmed to take the user_input variable, now fails to recognize my url address and my address is no longer matched to proceed to view.py. urls.py urlpatterns = [ url(r'^class/(?P<user_input>\w+)', views.newview), ] I understand that you cannot simply do the following because you shouldn't match query string with URL Dispatcher urlpatterns = [ url(r'^class/?search_bar=(?P<user_input>\w+)', views.newview), ] I should I solve this issue? How can I make the url.py recognize my new address and carry the user_input over to views.py? -
Missing Python Packages on Python Interpreter - Django
I've been working on a basic Django project and I deployed it to AWS Elastic Beanstalk. I'm not if that's causing this, but I'm just telling you this so that you know what I've been doing with my project. Then, my python project interpreter got kinda messy and when I try to run the application it started to give me some errors about missing packages. After that, I checked my project interpreter, ad it was like this: Then, I tried installing the required packages using PyCharm, however, it kept giving me the error below. I also tried to build some of those packages, like Django, on my own terminal but the error was same. Further, I was able to install packages on other python versions on my mac, which sorta tells I might have messed my default python interpreter somehow. I'd really appreciate any help here and please ask me if any extra detail is needed to answer this question before downvoting. -
Using remote MySQL database on Heroku running Django app
I've been struggling with the following problem: I have a MySQL database running on a remote web host. I connect to the MySQL database in my Django app (I use it as the main database). The Django app is running on a Heroku server but I get different data results compared to running it locally. Am I missing something, or are changes done on Heroku not committed to the database? -
Unexpected Circular Dependency in migration files
Error - django.db.migrations.exceptions.CircularDependencyError: accounts.0001_initial, songs.0001_initial accounts/models.py class AppUser(models.Model): user = models.OneToOneField(User) user_languages = models.ManyToManyField('songs.SongLang') user_genres = models.ManyToManyField('songs.SongGenre') def __str__(self): return self.user.username ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ songs/song_metadata_models.py class SongGenre(models.Model): short_name = models.CharField(max_length=10) full_name = models.CharField(max_length=100) def __str__(self): return self.full_name class SongLang(models.Model): short_name = models.CharField(max_length=10) full_name = models.CharField(max_length=100) def __str__(self): return self.full_name ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ songs/models.py class Song(models.Model): # Fields name = CharField(max_length=255) slug = AutoSlugField(populate_from='name', blank=True) created = DateTimeField(auto_now_add=True, editable=False) last_updated = DateTimeField(auto_now=True, editable=False) url = CharField(max_length=100) artist = CharField(max_length=50) album = CharField(max_length=50) like = BooleanField(default=False) dislike = BooleanField(default=False) # Relationship Fields requested_by = ForeignKey('accounts.AppUser', related_name='song_requested_by') dedicated_to = ManyToManyField('accounts.AppUser', null = True, blank = True,related_name='song_dedicated_to') recommended_to = ManyToManyField('accounts.AppUser', null = True, blank = True,related_name='song_recommended_to') How to solve this? -
Django Pagination from ?page= to /page/
I have this view: class PageView(ListView): # ... code ... paginate_by = 4 I'm using Bootstrap and in template I have something like: <div class="pagination"> <span class="page-links"> {% if page_obj.has_previous %} <a href="{{ request.path }}?page={{ page_obj.previous_page_number }}">previous</a> {% endif %} <span class="page-current"> Page {{ page_obj.number }} of {{ page_obj.paginator.num_pages }}. </span> {% if page_obj.has_next %} <a href="{{ request.path }}?page={{ page_obj.next_page_number }}">next</a> {% endif %} </span> </div> How can I transform GET variable ?page=number to look like /page/number/ in django? -
How to rename the columns of returned fields from Django model?
I have a Django model called Hormone: class Hormone: material = model.ForeignKey('Material',to_field='code') class Material: code = model.integer() type = model.text() I have a trouble to rename the intermediate result fields for the material meaning by using this syntax. Hormone.objects.extra(select={"content":"material__meaning"}).values("content").all() How do I correctly rename the key? Thanks -
'AnonymousUser' object is not iterable? Django
I'm creating a summary page of all the posts that user has created and returning those posts to the summary page. I get the error above? It's complaining about this line: uploaded_aircraft = Aircraft.objects.filter(user=request.user) View def aircraft_create(request): form = aircraft_form(request.POST or None) if form.is_valid(): instance = form.save(commit=False) instance.user = request.user instance.save() messages.success(request, "Your upload has been successfully added!") return HttpResponseRedirect(instance.get_absolute_url()) else: messages.error(request, "There seems to be something wrong. Have a look again..!") context = {"form":form,} return render(request,'aircraft/aircraft_form.html', context) Model class Aircraft(AircraftModelBase): user = models.ForeignKey(User) manufacturer = SortableForeignKey(Manufacturer) aircraft_type = SortableForeignKey(AircraftType) View def account_overview(request): fav_aircraft = FavoritedAircraft.objects.filter(user__id=request.user.id) fav_airline = FavoritedAirline.objects.filter(user__id=request.user.id) uploaded_aircraft = Aircraft.objects.filter(user=request.user) return render(request,'account/account_overview.html', {'favAircraft':fav_aircraft, 'favAirline':fav_airline, 'UploadedAircraft':uploaded_aircraft}) What seems to be actual problem here? -
Is there a good or safe way to handle user submitted rich text with django?
Basically exactly as said. I'm using CKEeditor to handle blog posts for some extra markup, but I'm worried about script attacks. -
How to validate data in django forms?
I have a feature on my website where a user can share content with another user registered on the site. They do this by entering in an email belonging to another user. This is then posted, setting the desired user to as a shared owner of content in the model. What is the best way to check that the email address belongs to a registered user of the site? Thanks! -
Getting model instance when using QuerySet.values()
Let's say I have two models, one referencing the other: class Shelf(models.Model): pass class Book(models.Model): shelf = models.ForeignKey(Shelf) I'd like to use values() on a QuerySet of Book instances: In [1]: Book.objects.create(shelf=Shelf.objects.create()) Out[1]: <Book: Book object> In [2]: Book.objects.values() Out[2]: [{'id': 1, 'shelf_id': 1}] The problem is that the returned dictionaries contain just the primary key of referenced model instances. Is there a way to get the actual models in a single query? The reason I'm using values() is so that I can merge two QuerySets for different models which I want to sort and render into a single table in a view. -
Django REST to SOAP Conversion
I want to convert my django app's REST API to SOAP API. But i do not want to change my server also i do not want to have another wsdl library.Is there some way to proceed with the above problem. I have tried ZSI and soaplib.