Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
What folder structure is required for a publishable Django app?
I have a Django app developed as part of my existing Django site that I'd like to separate out and publish on PyPI. What folder structure is required to make the app suitable for publishing to PyPI and importable via pip? Current folder structure (truncated): mysite/ - conf/ - mysite/ - __init__.py - settings.py - myapp/ - __init__.py - admin.py - models.py - manage.py -
Deploying django project with apache 2.4 doesn't work publicly
I am deploying a django project and I have configured the apache server with mod_wsgi as in many tutorials on the internet and the website was served successfully within the internal network using the server's IP and Port (80). After setting the ServerName, I still can access the website within the internal network using the IP but I can neither use the domain name I want internally nor publicly. I have made a special inbound rule in the firewall for my Port (80) to allow accessing the server. WSGIApplicationGroup %{GLOBAL} ServerName my.website.com:80 #ServerName localhost:80 <Directory /> AllowOverride none Require all granted </Directory> What else can I do to make my server publicly available using the domain? Thank you. -
Django 2.0.7 static files not found when DEBUG=False
The Django project is not rendering static files while I make DEBUG=False, the version of Django is 2.0.*. -
missing 1 required positional argument: 'request'
here is my view.py class categAdmin(admin.ModelAdmin): change_form_template = 'category_forms.html' list_display = ['title'] model = Category fields = ['status','title','category_post','body', 'photo', 'url','slider','Gallery','lists','pk_tree','video','maps'] # def render_change_form(self, request, context, **kwargs): # post = Post.objects.all() # context['eve'] = post # return super(categAdmin,self).render_change_form(request, context, **kwargs) def item_add(request, self, post_id): tree = post_id return self.add_view(request, extra_context={'tree': tree}) i am getting error item_add() missing 1 required positional argument: 'request' -
Django-tables2: Change attribute for multiple columns in __init__()
I can't figure out how to change attribute for multiple columns in one for loop. I want to set orderable=False to multiple columns. The only way which works is to explicitely define all these columns so I can add orderable=False to constructor. class PizzaTable(tables.Table): class Meta: template_name = 'django_tables2/bootstrap-responsive.html' model = Pizza fields = ['created', 'ham', 'olives', 'corn', 'price',] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) unorderable_columns = ['ham', 'olives', 'corn',] for column in unorderable_columns: self.columns.get(column).orderable = False This raises: 'BoundColumns' object has no attribute 'get' It has to be able to do it somehow, otherwise I would have to specify all of those columns: ham = tables.Column(accessor='ham',orderable=False) Do you have any ideas? -
If Statement To Check if a Table is contained in an Iframe
Sorry if this question seems basic, but I cannot find any simple explanations and I'm new to JavaScript, so please give any help/feedback you can. Basically I have an HTML iframe called iframe, and I would like a JavaScript if-statement to see if any <table> objects are in it. I don't know exactly how to reference that in the if-statement. Any help would be much appreciated. -
Celery in dockerized django project
I have a django project consisting of blog, article and comment applications. Comment model has a generic relation to Article model from article app and Entry from blog app. I want the two models (Entry and Article) to show the number of comments. In order to do this I have overridden save(), update() and delete() methods (the last is handled by a signal) which call a specific task that handles the update. Now to the code. comments/models.py: from django.db import models from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes.fields import GenericForeignKey from model_utils.models import TimeStampedModel from comments.tasks import update_comment_count_on_related_writing class CommentManager(models.query.QuerySet): def update(self, **kwargs): comments_for_previous_writings = dict() for comment in self.all().prefetch_related('writing_object'): comments_for_previous_writings[comment] = { 'writing_pk': comment.writing_id, 'writing_type_pk': comment.writing_type.pk } rows = super().update(**kwargs) for comment in self.all(): update_comment_count_on_related_writing.delay( comment.pk, comments_for_previous_writings[comment]['writing_pk'], comments_for_previous_writings[comment]['writing_type_pk'] ) return rows class Comment(TimeStampedModel): body = models.TextField() __writing_type_choices = ( models.Q(app_label='article', model='article') | models.Q(app_label='blog', model='entry')) writing_type = models.ForeignKey(ContentType, on_delete=models.CASCADE, limit_choices_to=__writing_type_choices) writing_id = models.PositiveIntegerField() writing_object = GenericForeignKey('writing_type', 'writing_id') objects = CommentManager.as_manager() def __str__(self): return '({}) {} - {}...'.format(self.writing_type, self.writing_object, self.body[:15]) def save(self, force_insert=False, force_update=False, using=None, update_fields=None): old_writing = None old_writing_pk = None old_writing_type_pk = None created = not self.id if not created: # Trick used to avoid changing old_writing* references after update … -
django annotate related fields at once with Count()
My Profile model have two m2m fields in one model - region and country. And as you know, country has there own region with foreignkey. I want to try counting profiles per region - not only include region but also in country__region. i.e.) If some have only has Africa region, and other has only Congo country (with the region Africa), I want to filter them at one. I try to solve it using annotate. I can find count of region individually like below profiles = Profile.objects.all() region_count = profiles.values('region').annotate(region_count=Count('region')) country_count = profiles.values('region').annotate(region_count=Count('country__region')) But how can I count queryset with specific region, filtering with region and region__country at once? Is there any possible method? Here's my profile / country model. The region model just has name field. class Profile(models.Model): region = models.ManyToManyField( Region, verbose_name="Region(s) of interest", blank=True, ) country = models.ManyToManyField( Country, related_name="country", verbose_name="Countries of interest", blank=True, ) ... clsas Country(models.Model): region = models.ForeignKey( Region, null=True, blank=True, ) ... Thanks for any help. Summary I want to count queryset with region and country__region at once with annotate. -
AttributeError: module in Django, Python
Getting the following error File "C:\Users\abc\Projects\ecom\src\ecom\urls.py", line 33, in <module> path('products/', views.ProductListView.as_view()), AttributeError: module 'ecom.views' has no attribute 'ProductListView' ecom/src/ecom/url.py from products.views import ProductListView, product_list_view from . import views urlpatterns = [ path('', views.home_page), path('login/', views.login_page), path('register/', views.register_page), path('products/', views.ProductListView.as_view()), path('products-fbv/', views.product_list_view), path('admin/', admin.site.urls), ] ecom/src/products/views.py from django.views.generic import ListView from django.shortcuts import render from .models import Product class ProductListView(ListView): queryset = Product.objects.all() template_name="products/list.html" def product_list_view(request): queryset=Product.objects.all() context={ 'qs':queryset } return render(request,"products/list.html", context) Its urgent, please help. Tried changing urlpatterns and products nothing worked. Please help! Thanks in advance -
Connnecting a HTML link to an API page
I have a working HTML view and a working detail API RUD view for some simple model objects. Within the HTML view, elements are listed that have their own API RUD view. I'd like to be able to link each list element in the HTML to it's own API RUD view. Below is my models.py: class Hints(models.Model): text = models.TextField(max_length=255) author = models.CharField(max_length=20) timestamp = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.text) def timestamp_pretty(self): return self.timestamp.strftime('%b %d %Y') def get_api_url(self, request=None): return api_reverse("api-hints1:hints-rud", kwargs={'pk': self.pk}, request=request) Below is my views.py: class HTMLAPIView(viewsets.ViewSet): renderer_classes = [TemplateHTMLRenderer] template_name = 'base.html' serializer_class = HTMLSerializer def list(self, request): queryset = Hints.objects.order_by('pk') paginator = Paginator(queryset, 5) # Show 5 items per page page = request.GET.get('page') queryset1 = paginator.get_page(page) return Response({'queryset1': queryset1}) class HintsListApiView(mixins.CreateModelMixin, generics.ListAPIView): lookup_field = 'pk' serializer_class = HintsSerializer def get_queryset(self): qs = Hints.objects.all() query = self.request.GET.get("q") if query is not None: qs = qs.filter( Q(text__icontains=query)| Q(author__icontains=query) ).distinct() return qs def post(self, request, *args, **kwargs): return self.create(request, *args, **kwargs) def get_serializer_context(self, *args, **kwargs): return {"request": self.request} class HintsRudView(generics.RetrieveUpdateDestroyAPIView): lookup_field = 'pk' serializer_class = HintsSerializer def get_queryset(self): return Hints.objects.all() def get_serializer_context(self, *args, **kwargs): return {"request": self.request} My urls.py: from .views import HintsRudView, HintsListApiView, HTMLAPIView from . import … -
Using Custom User Model for authentication in Django
I am using legacy my database in django. The user authentication method used by django needs to be changes in order to user legacy database data. There are two table in the database tab_users and tab_user_group Structure tab_user id | username | password | timestamp | user_group_id | status tab_user_group id | user_group_name | can_view | can_edit |can_delete | dashboard_access | app_access user_group_id in the tab_user is the id in the tab_user_group which details user_group of the user. id in both tables are primary keys Now the custom user authentication needs to be implemented using these field. Login and user creation -
call function in views.py from jquery
I have def main(request) in views.py Wanna to make endless scrolling. How can i call this func from jquery in my template: <script> $(window).scroll(function () { if ($(window).scrollTop() + $(window).height() == $(document).height()) { //call main } }); </script> -
Django Import Error at / No module named urls
I have changed the URLs in the website file, now, the page doesn't work. This is the error I get. I'm using Django 1.8.7 on Ubuntu 16.04, on a DigitalOcean Droplet and it is hosted on Gunicorn. This is my project url file: from django.conf import settings from django.conf.urls import include, url from django.conf.urls.static import static from django.contrib import admin urlpatterns = [ url(r'^', include('website.urls')), url(r'^admin/', include(admin.site.urls)), ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) This is website urls file: from django.conf import settings from django.conf.urls import url from django.conf.urls.static import static from . import views urlpatterns = [ url(r'^en/$', views.index_en, name='index_en'), url(r'^en/results/$', views.results_en, name="results_en"), url(r'^es/$', views.index_es, name='index_es'), url(r'^es/results/$', views.results_es, name="results_es"), ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) -
I want to show first 2 objects in my django template but it shows me this error
{% for post in object_list|slice : "2" %} <div class="w3-container w3-card w3-white w3-round w3-margin"><br> <img src="/w3images/avatar5.png" alt="Avatar" class="w3-left w3-circle w3-margin-right" style="width:60px"> <span class="w3-right w3-opacity">{{post.date}}</span> <h4>{{ post.author.username }}</h4><br> <hr class="w3-clear"> <p>{{post.text}}</p> </div> {% endfor %} The error shown is 'for' statements should use the format 'for x in y': for post in object_list|slice : "2" The code all my posts when I remove slice:2. Only when i add that in my code it shows me this error rest else all seems to be working well -
Bootstrap navbar dropdown populated with database entries in Django 2
I am trying to populate a navbar "dropdown-menu" with individual "dropdown-item"'s populated from data in the sqlite3 DB. I have something similar working on other pages but I cant get it to work in my navbar. I am creating a record label, and want the list of artists populated from entries in the DB. I have found one tutorial on doing something similar in php, but doesn't translate, and there doesn't seem to be anything either on youtube or here other than populating form data. Any help is greatly appreciated, as I have been trying to get it working for about a week now. I know it should be simple, but im missing something. the app is called "music" models.py class Artist(models.Model): artist_name = models.CharField(max_length=250, default='') artist_logo = models.FileField() artist_url = models.URLField(blank=True) def __str__(self): return self.artist_name class Release(models.Model): artist = models.ForeignKey(Artist, on_delete=models.CASCADE) release_title = models.CharField(max_length=500) release_cover = models.FileField() release_duration = models.IntegerField() def __str__(self): return self.release_title class Track(models.Model): release = models.ForeignKey(Release, default='', on_delete=models.CASCADE) artist = models.ForeignKey(Artist, default='', on_delete=models.CASCADE) track_title = models.CharField(max_length=200) track_version = models.CharField(max_length=200) track_genre = models.CharField(max_length=100) track_duration = models.IntegerField() track_number = models.SmallIntegerField() class Meta: ordering = ["track_number"] def __str__(self): return self.track_title views.py from django.contrib.auth import authenticate, login from django.views import … -
How to Embed multiple tweets of various users into HTML in django framework?
I am passing a data in the form of a dictionary from views.py to results.html in Django framework. The dictionary has the following format 'tweet': (tweet_analysis, tweet_id) now in results.html, called by the views.py, I am trying to Embed all the tweets that are passed to results.html, but the following code only displays one embedded tweet. dicPositive: This is the dictionary containing all the tweets data {% for tweet, tweet_feel in dicPositive.items %} <div id="tweet" tweetID="{{tweet_feel.1}}"></div> <script sync src="https://platform.twitter.com/widgets.js"></script> <script> window.onload = (function(){ var tweet = document.getElementById("tweet"); var id = tweet.getAttribute("tweetID"); twttr.widgets.createTweet( id, tweet, { conversation : 'none', // or all cards : 'hidden', // or visible linkColor : '#cc0000', // default is blue theme : 'light' // or dark }) .then (function (el) { el.contentDocument.querySelector(".footer").style.display = "none"; }); }); </script> <!-- <li>{{tweet}} &ndash;&gt; {{tweet_feel.0}} &ndash;&gt; {{tweet_feel.1}}</li> --> {% endfor %} -
Counting overlaping days in django
In my django project, I store user's vacation: class VacationRequest(BaseModel): requested_by = models.ForeignKey(User, related_name='vacation', verbose_name='User') start = models.DateField(__('Start')) end = models.DateField(__('End')) I need a feature to generate report. Reports are generated for selected range of days: class Report(BaseModel): company = models.ForeignKey(Company, related_name='reports') department = models.ForeignKey(Department, verbose_name=__('Department'), related_name='reports', null=True, blank=True) title = models.CharField(verbose_name=__('Title'), null=True, blank=False, max_length=32) start = models.DateField(__('Start')) end = models.DateField(__('End')) csv = models.FileField(__('CSV'), null=True, blank=True, upload_to=report_upload_path, max_length=256, storage=reports_storage) xls = models.FileField(__('XLS'), null=True, blank=True, upload_to=report_upload_path, max_length=256, storage=reports_storage) pdf = models.FileField(__('PDF'), null=True, blank=True, upload_to=report_upload_path, max_length=256, storage=reports_storage) def generate_files(self): headers = ['First name', 'Last name', 'Department', 'vacation days'] department_kwarg = {'userdata__department': self.department} if self.department else {} vacation_filter = models.Q(vacation__status=2, vacation__start__gte=self.start, vacation__end__lte=self.end) # what should I change here? users = User.objects.filter(company=self.company, **department_kwarg).annotate( days_used=models.Sum(models.Case(models.When( vacation_filter, then=models.F('vacation__archive_net_days') ), output_field=models.IntegerField(), default=0)) ).annotate( days_left=models.F('userdata__vacations_days_in_year') - models.F('userdata__used_vacations_days') ).values_list('first_name', 'last_name', 'userdata__department__title', 'days_used', 'days_left') self._generate_csv(users, headers) self._generate_pdf(users, headers) self._generate_xls(users, headers) it works almost fine, however, I want to calculate overlaping days also. For example, when user's vacation is between 10 July and 20 July and in my report I set start date to 11 July it will return 0 days but it should calculate days between. This is because vacation_filter = models.Q(vacation__status=2, vacation__start__gte=self.start, vacation__end__lte=self.end) -- it uses vacation__start__gte - which … -
Python-Django Multiple Database - TypeError: allow_migrate() missing 1 required positional argument: 'app_label' Error
So I'm working creating a multiple database assign in my django framework setup. And this documentation i'm following https://docs.djangoproject.com/en/2.0/topics/db/multi-db/ . But when i try run it i encounter some error in my database router. There error occurs in my AuthRouter.py Does anyone here also encounter this kind of problem? Thank you all for help. :) -
Django: Search many to many field while creating object
I've got a use case where I have multiple Ingredient that can be linked to a Recipe through the Django admin. Now I have around a hundred ingredients which makes it very difficult to select the ingredients in the following UI. Is there a way to add a search field or something similar to the django admin for easier selection? -
Need help in replacing Misaka by Mistune in the code below
from django.db import models from django.urls import reverse from django.utils.text import slugify import misaka class Group(models.Model): name = models.CharField(max_length=255,unique=True) slug = models.SlugField(allow_unicode=True,unique=True) description = models.TextField(blank=True,default='') description_html = models.TextField(editable=False,default='',blank=True) members = models.ManyToManyField(User,through='GroupMember') def __str__(self): return self.name def save(self,*args,**kwargs): self.slug = slugify(self.name) self.description_html = misaka.html(self.description) super().save(*args,**kwargs) In 2nd last line, since I'm getting some issues in downloading misaka due to windows visual C++ scenario,I want to replace misaka with mistune. Can someone help me understand what's the alternative of the line self.description_html = misaka.html(self.description) in mistune? -
Running the app dynamically in django
I am implementing a weather app in Django using openweathermap API. I have a form in my HTML and a action in it to trigger the method in my view. It works fine, but the problem is I have to trigger the action with a button in my form everytime I want the weather, but I want to get the weather dynamically in such a way that it generates the weather every 3 hrs. I thought of doing it with timmer but I don't know whether its the proper approach if any know of a good way to implement it please enlighten me. I want an app which generates weather dynamically without triggering any action. If my query is not understandable or want more information please do ask, I bad at put my query in words. -
Removing --------- from choices in dropdown
I believe that I may have implemented something that adds '-------' as a valid option in the drop downs that I have in my forms. Is there a setting in Django that I can change/remove/modify that will prevent '-------' from being an option that appears in one or all drop downs? Thanks! -
Django extended UserProfile model is not saving my extra informations
I have a UserProfile model extending contrib.auth.User, and when I try to save it, the extra information I added in the profile is not saved. Here is Models.py Models.py class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile') cellphone = models.CharField(max_length=20, blank=True, default='') def __str__(self): return self.user.username def create_user_profile(sender, instance, created, **kwargs): if created: profile, created = UserProfile.objects.get_or_create(user=instance) post_save.connect(create_user_profile, sender=User) And forms.py Forms.py class UserProfileForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput) email = forms.EmailField(required=True) cellphone = forms.CharField(max_length=20) class Meta: model = User # fields = ('cellphone', ) fields = ('username', 'cellphone', 'email', 'password', ) And finally my view.py def register(request): form = UserProfileForm(request.POST or None) if form.is_valid(): user = form.save() username = form.cleaned_data['username'] password = form.cleaned_data['password'] user.profile.cellphone = form.cleaned_data['cellphone'] user.set_password(password) user.save() user = authenticate(username=username, password=password) if user is not None: if user.is_active: auth_login(request, user) return render(request, 'user/index.html', {'user': user}) else: return render(request, 'user/register.html', {'form': form, }) I couldn't figure out why it is not saving the cellphone attribute. Please help me solve this issue, thank you -
TypeError: 'module' object is not callable in Django
I am trying to add wikipedia API in django and process the wikipedia throung HTML input in view.py. from django.contrib.auth.forms import UserCreationForm from django.shortcuts import render from django.http import HttpResponse import wikipediaapi from .forms import ContactForm, ColorfulContactForm def _form_view(request, template_name='basic.html', form_class=ContactForm): if request.method == 'POST': form = form_class(request.POST) mes = request.POST.get("message") search = mes.split(' ') query = search[2] #return HttpResponse(mes) mywiki(query) if form.is_valid(): pass # does nothing, just trigger the validation else: form = form_class() search_id = request.POST.get('message', None) # return render(request, template_name, {'form': form}) def mywiki(query): wiki_wiki = wikipediaapi.wikipedia('en') page_py = wiki.page(query) title = page_py.title return HttpResponse(title) #return HttpResponse(mes ) I get error which reports: TypeError: 'module' object is not callable Anyone help me Thanks -
Geodjango - Error when try to run server
I am trying to setup up Geodjango in my newly created project. I followed all steps given in django documentation. But when I try to run server following error occurs: After clicking OK the same window appears again and then after clicking OK following appears on console: self._handle = _dlopen(self._name, mode) OSError: [WinError 127] The specified procedure could not be found My SETTINGS.Py DATABASES = { 'default': { 'ENGINE': 'django.contrib.gis.db.backends.postgis', 'NAME': 'test', 'USER': 'postgres', 'PASSWORD': '*********', 'HOST': '127.0.0.1', 'PORT': '5432.', } } and my Models.py: from django.contrib.gis.db import models # Create your models here. class Shop(models.Model): name = models.CharField(max_length=100) location = models.PointField(blank=True, null=True) Any Idea?