Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django GenericForeignKey being deleted when it shouldn't
I'm having a problem where if I delete an object, another object is being deleted seemingly wrongly. models.py class Document(models.model): file = models.FileField(upload_to=document_path, null=True, max_length=256) ri_ct = models.ForeignKey( ContentType, null=True, editable=False, related_name='documents_related_item', on_delete=models.PROTECT ) ri_id = models.PositiveIntegerField(null=True, editable=False, db_index=True) related_item = GenericForeignKey('ri_ct', 'ri_id') class Invoice(models.model): documents = GenericRelation( Document, related_query_name='invoices', content_type_field='ri_ct', object_id_field='ri_id' ) class BalanceUpdate(models.model): related_item_ct = models.ForeignKey( ContentType, limit_choices_to=Q(app_label='main', model__in=('proformainvoice', 'invoice')), related_name='balance_updates', null=True, on_delete=models.PROTECT, ) related_item_id = models.PositiveIntegerField(null=True, blank=True, db_index=True) related_item = GenericForeignKey(ct_field='related_item_ct', fk_field='related_item_id') Now, if I do Invoice.objects.filter(query).delete() I'm getting a BalanceUpdate, which is related to Invoice, also deleted. After a fair amount of debugging I've found that when deleting the Invoice, the document is being deleted (correctly due to the defined GenericRelation). If I insert a print here, sub_objs has a BalanceUpdate as a related object. Surely this shouldn't be the case. Can someone explain how this is happening? Cheers. -
Static files won't load when out of debug in Django production
I have a problem, after deployment of the web application on the server I do not see images added to the database. Django no display my images in site. urls.py from django.conf import settings from django.conf.urls.static import static from django.contrib import admin from django.urls import path, include, re_path from shop import views urlpatterns = [ path('pvb-admin/', admin.site.urls), path('', include('pages.urls')), path('accounts/', include('django.contrib.auth.urls')), path('offer/', include('offers.urls')), path('shop/', include('shop.urls')), path('cart/', include('cart.urls')), ] if settings.DEBUG is False: urlpatterns += static(settings.STATIC_URL,document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT) if settings.DEBUG: import debug_toolbar urlpatterns = [ path('__debug__/', include(debug_toolbar.urls)), ] + urlpatterns settigns.py STATIC_URL = '/static/' STATICFILES_DIRS = [os.path.join(BASE_DIR, 'pvb/static')] STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATICFILES_FINDERS = [ "django.contrib.staticfiles.finders.FileSystemFinder", "django.contrib.staticfiles.finders.AppDirectoriesFinder", ] # Media Folder Settings MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') Static files are displayed. Only from the media folder not. -
Get the count of words in tinymce with Word Count plugin
I wanna get the count of words in the textarea and make changes to my users account based on the number of words for example: a person writes 1000 words and its credibility goes up in the account (I use Django) -
Django url tag not working when dinamically loading the page
This is my first time posting a question, so I will be as concise as possible. I am trying to dynamically populate the HTML of a page upon log in. For the front end application I use Django + HTML & CSS. I want to dynamically add a 'li' item to an existing 'ul'. The previous code, when the page was statically loaded was: <ul id="marketplace-list"> <li id="shoes-marketplace-dropdown" class="dropdown dropdown-toggle"> <a href="{% url 'shoes_marketplace' %}">Shoes</a> <ul class="dropdown-menu" role="menu"> <li><a href="{% url 'shoes_men' %}">Men</a></li> <li><a href="{% url 'shoes_women' %}">Women</a></li> </ul> </li> When clicking the "Men" href, my browser would redirect to the following URL : http://localhost:9000/marketplaces/shoes/men/ Now I have tried to assign the HTML value of the 'li' with the id: shoes-marketplace-dropdown to a variable in a .js script, and add the content the the 'ul' with the id: marketplace-list dynamically, in the $(document).ready( function {...}) My approach is: var shoes_market = " <li id=\"shoes-marketplace-dropdown\" class=\"dropdown dropdown-toggle\">" + " <a href=\"{% url \'shoes_marketplace\' %}\">Shoes</a>" + " <ul class=\"dropdown-menu\" role=\"menu\">" + " <li><a href=\"{% url \'shoes_men\' %}\">Men</a></li>" + " <li><a href=\"{% url \'shoes_women\' %}\">Women</a></li>" + " </ul>" + "</li>"; And in the $(document).ready() function I write: $("#marketplace-list").prepend(shoes_market) The HTML page builds correctly, … -
Django Tutorial: unexplained 404 error after completing 2nd page
I have finished https://docs.djangoproject.com/en/3.0/intro/tutorial01/ and https://docs.djangoproject.com/en/3.0/intro/tutorial02/ The 1st intended tutorial works when i execute, but now when am trying to view the admin site as the http://127.0.0.1:8000/admin/ is tying to load, i get a page not found and the terminal exits by itself. Someone to kindly assist i am a newbe enter image description here -
Idea for ManyToMany Field in django-admin
I have some items present in the Table 'ItemNames' class ItemNames(models.Model): """Name of the Items only""" name = models.CharField(max_length = 100) quantity = models.IntegerField() def __str__(self): return self.name I have one more table 'Inventory Issued' class InventoryIssued(models.Model): item_name = models.ManyToManyField(ItemNames) Now output am getting is like this but am I looking for output in which I can not only add items but also specify quantity required? Note: I have already gone with StackedInline Concept but it creates a new object in the ItemNames Table Rather than using the old object Thanks Pradyum -
How to filter images by using categories in django?
I'm trying to make a gallery page for my Django application and I want to display images of specific category on their respective pages but the issue I face is I'm unable to apply filter for that like I have several images related to food and some related to travel I want to display all food images on a food page and all travel images on its travel page I have created a drop-down list of my all pages to display that image please have a look on this screenshot https://prnt.sc/qnznml ! I tried def get_queryset(self): return Postgallery.objects.filter(postgallery_id=self.kwargs.get('slug')) but it does't work -
Can't render custom user model via forms
So I'm making a custom user model. This is what I'am following Here. I have been pretty much following the tutorial but still I cant make it done. here's my code. forms.py from django import forms from django.contrib.auth.forms import ReadOnlyPasswordHashField from .models import User class UserAdminCreationForm(forms.ModelForm): """ A form for creating new users. Includes all the required fields, plus a repeated password. """ password1 = forms.CharField(label='Password', widget=forms.PasswordInput) password2 = forms.CharField(label='Password confirmation', widget=forms.PasswordInput) class Meta: model = User fields = ('email',) def clean_password2(self): # Check that the two password entries match password1 = self.cleaned_data.get("password1") password2 = self.cleaned_data.get("password2") if password1 and password2 and password1 != password2: raise forms.ValidationError("Passwords don't match") return password2 def save(self, commit=True): # Save the provided password in hashed format user = super(UserAdminCreationForm, self).save(commit=False) user.set_password(self.cleaned_data["password1"]) if commit: user.save() return user class UserAdminChangeForm(forms.ModelForm): """A form for updating users. Includes all the fields on the user, but replaces the password field with admin's password hash display field. """ password = ReadOnlyPasswordHashField() class Meta: model = User fields = ('email', 'password', 'active', 'admin') def clean_password(self): # Regardless of what the user provides, return the initial value. # This is done here, rather than on the field, because the # field does not … -
CSRF protection for Django and Angular application
I have an application with Django in backend and Angular in frontend. I am serving the application through Django. I want to write an API in django to perform edit on Angular form. For now I have written the API using @csrf exempt decorator on top of the view. But now I want to remove @csrf exempt decorator and want to protect it from csrf. How to proceed for this. -
Django Template how to apply filter on the result returned by simple tag
I have a following simple_tag. @register.simple_tag def Test(arg1,arg2) return arg1+arg2 And in the template. <h6>{% Test val.arg1 val.arg2 %}</h6> And now I want to apply the filter on the above returned data from simple_tag Test, for example, I want to apply naturaltime filter on the returned data, how to do it along with the simple tag. <h6>{% Test val.arg1 val.arg2 | naturaltime %}</h6> -
how to subtract a date from today in django model
models.py import datetime as dt class Campaign(models.Model): enddate = models.DateField() def rest_of_the_day(self): now = dt.datetime.now().date() print('printing now value') print(now) print(self.campaign_enddate) return (self.campaign_enddate-now).days in views.py def landing_page(request): campaigns = Campaign.objects.all().order_by('-id') return render(request, 'core/landing_page.html',{'campaigns':campaigns}) in html template <span>{{campaign.rest_of_the_day}}</span> I'm trying to store an end date and show the days left to the end date in html file using rest_of_the_day function in models.py for example : if end date is 30-01-2010 and today is 15-01-2020, i want the rest_of_the_day to show 15 however, i get a TypeError at / unsupported operand type(s) for -: 'NoneType' and 'datetime.date' -
Django admin add template: combine fields for saving in DB
I'm new to Python and Django, and I need help from experienced pythonists. I have a model Unit like that: class Unit(models.Model): unit_type = models.CharField("Unit type", max_length=25) content = models.TextField() I want to be able to add some units with Admin panel. But in the content field I need to have a JSON-serialized object, containing a bunch of data, so I want to let users to add that data via ordinary fields, and combine them in JSON programmatically and save in the content. But when I try to register this model in Admon like that: class UnitAdmin(admin.ModelAdmin): fieldsets = [ (None, {'fields': ['unit_type', 'url', 'name']}), ] admin.site.register(Unit, UnitAdmin) I get an error: FieldError at /admin/cms/unit/add/ Unknown field(s) (name, url) specified for Unit. Check fields/fieldsets/exclude attributes of class UnitAdmin. Can I somehow collect more data in my admin panel than I need to save in a database? -
Many to many relationship, Remove value from intermediate table
I have two models (ClinicHospital and Doctor) and which are related to many-to-many to relation. class ClinicHospital(models.Model): name = models.CharField(max_length = 256) address = models.TextField() contact = models.CharField(max_length = 15) lat = models.FloatField() lon = models.FloatField() def get_absolute_url(self): return reverse("clinichospital_list") def __str__(self): return self.name class Doctor(models.Model): name = models.CharField(max_length = 256) speciality = models.CharField(max_length = 256) contact = models.CharField(max_length = 12) clinic_hospital = models.ManyToManyField(ClinicHospital) def __str__(self): return self.name and have CBV view which returns all clinic_hospital based on Doctor class DoctorDetailView(generic.DetailView): model = Doctor # slug = none def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['clinic_hospital_list'] = self.object.clinic_hospital.all() return context Now, I want to delete just value from intermediate table based on specific Doctor. In other word delete specific record form clinic_hospital_list in class base view -
JWT custom authentication Middleware Returning Anonymous user
As per of this discussion I am using solution of cancan101 for this https://github.com/jpadilla/django-rest-framework-jwt/issues/45 discussion. I created a middleware.py file in my app and in My app its code is like from rest_framework.request import Request from django.utils.functional import SimpleLazyObject from django.contrib.auth.middleware import get_user from rest_framework_jwt.authentication import JSONWebTokenAuthentication from django.utils.deprecation import MiddlewareMixin def get_user_jwt(request): user = get_user(request) if user: return user try: user_jwt = JSONWebTokenAuthentication().authenticate(Request(request)) if user_jwt is not None: return user_jwt[0] except: pass return user class AuthenticationMiddlewareJWT(MiddlewareMixin , object): def process_request(self, request): assert hasattr(request, 'session'), "The Django authentication middleware requires session middleware to be installed. Edit your MIDDLEWARE_CLASSES setting to insert 'django.contrib.sessions.middleware.SessionMiddleware'." request.user = SimpleLazyObject(lambda: get_user_jwt(request)) and my middleware settings are MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'CustomerWeb.middleware.AuthenticationMiddlewareJWT', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] Now when I debug in this middle ware I am getting user correctly but in my view.py its still anon user . What I am doing wrong here ? thanks in advance -
Image uploading in s3 bucket takes too long
I have to upload images in s3 bucket in my django project. I'm using boto3 to the do the same as follows: def handle_uploaded_file(file, filename): s3 = boto3.resource('s3', aws_access_key_id=ACCESS_KEY,aws_secret_access_key=SECRET_KEY) check = s3.Bucket(bucket).put_object(Key=filename, Body=file,ContentType='image/png',ACL='public-read') return check I'm calling this function in my API like this: if request.FILES and request.FILES.get('tagimage', None) is not None: tagimage = request.FILES['tagimage'] tagimage_name = tagimage.name number = number_genarator() tagimage_name = str(number) + tagimage_name tag_upload = handle_uploaded_file(tagimage,tagimage_name) res['tagimage']=tag_upload record.tagimage = tagimage_name But this process is taking too long as per me. To upload one image it's taking me three seconds barring the time needed for the other part of my API. Can someone suggest a faster way to upload images? -
How To Have Real Time in Django
Im Developing an Website and I Need to Send Realtime Notfications to Users Mobile; How Can I Perform WebSockets in Django ? -
Apps aren't loaded yet while doing the official Django tutorial
I'm facing an issue with the Django settings while doing the official Django tutorial . The PyDev console returns an error Apps aren't loaded yet when I execute the debug mode (F11) on the file models.py. It's a very simple project in which I only changed the project name to 'capital' and the application's name to 'marketsdata'. The workarounds proposed in this similar question do not solve my problem. Django 1.7 upgrade error: AppRegistryNotReady: Apps aren't loaded yet How is it possible the official tutorial returns such error with the basics settings.py and models.py files? what I'm doing wrong? models.py from django.db import models class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) settings.py INSTALLED_APPS = [ 'marketsdata.apps.MarketsdataConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] apps.py from django.apps import AppConfig class MarketsdataConfig(AppConfig): name = 'marketsdata' urls.py from django.contrib import admin from django.urls import include, path urlpatterns = [ path('marketsdata/', include('marketsdata.urls')), path('admin/', admin.site.urls), ] Debuger output: pydev debugger: starting (pid: 23504) Traceback (most recent call last): File "/home/abc/.eclipse/360744294_linux_gtk_x86_64/plugins/org.python.pydev.core_7.5.0.202001101138/pysrc/pydevd.py", line 3129, in <module> main() File "/home/abc/.eclipse/360744294_linux_gtk_x86_64/plugins/org.python.pydev.core_7.5.0.202001101138/pysrc/pydevd.py", line 3122, in main globals = debugger.run(setup['file'], None, None, is_module) File "/home/abc/.eclipse/360744294_linux_gtk_x86_64/plugins/org.python.pydev.core_7.5.0.202001101138/pysrc/pydevd.py", line 2195, … -
Granular page caching
My site's landing page was being cached for obvious reasons: url(r'^$', cache_page(7200)(vary_on_cookie(LandingPage.as_view())), name='landing_page') Now we introduced a new page we'd like that route to redirect to if certain conditions are met, essentially checking if the user has permission on a certain object: class LandingPage(TemplateView): def dispatch(self, request, *args, **kwargs): if has_permission(self.request.user, object): return redirect('new_page') return super(LandingPage, self).dispatch(request, *args, **kwargs) However, since the view is cached, the user won't be redirected if the original landing page was already cached. And viceversa. What I want is for the view to always run the permission check. If it passes, it should redirect to the new page which shouldn't be cached. If it doesn't, the landing page should be returned, and it should be cached. -
How to pass a queryset from a view function to another view function
I have a problem and don't know how to solve it. So, I have a function view called search, wich filter trought my database using user input from the HTML Template. def search(request): Here I get the input values with the request.GET.get() method from the "homepage/index.html" template and filter throught my databse by the user input (The filter looks like this: qsf = WhiskyContent.objects.all().filter(Q(products__icontains=input) & (Q(volume=volume[0]) | Q(volume=volume[1]) | Q(volume=volume[2]) | Q(volume=volume[3])) & Q(price__gt=von, price__lt=bis) & Q(concentration__range=(conc, conc_to))) content_order = qsf.order_by("price_with_shipping")) return render(request, "homepage/index.html", context) So far, anything worked fine but now I need the filtered Queryset (content_order) in another function, because I reperesent the filtered database items on another site. I filter on the page index.hmtl and I want the items get displayed on products.html So, I need the content_order queryset in the function "products" to pass the values to my html template "products.html" def products(request): return render(request, "homepage/products.html") If there is a way to do it, please tell me how :). Also if you have a completely different idea, tell me -
Error 401 when trying to register a new user. Works fine on localhost (Django rest api)
I have built a rest API using Django. I have tested the endpoints and everything seems to be working fine on localhost.However after deploying to digital ocean and trying to access the endpoint to register a new user. I get Error 401. What could be the problem? -
Как использовать Django 2.2 с legacy базой данных PostgreSQL 8.4? [closed]
Разрабатываю новое приложение на Django (DRF+Angular). На данный момент актуальная LTS версия Django 2.2. Необходимые данные хранятся в базе данных PostgreSQL 8.4. Но Django 2.2 поддерживает PostgreSQL 9.4 и выше. Как поступить в данной ситуации? Обновить PostgreSQL нет возможности. -
django template url tag with empty argument
I'm trying to make an article list view of my homepage which works in two ways. Here is a part of my app url.py: path('article_list/<slug:tag>', views.article_list, name='article_list'), I would like to make this one URL cover both all articles case and tag-specified article case, by making the view shows all articles if slug: tag is ''. Here is a part of my view.py: def article_list(request, tag): if tag == '': articles = get_list_or_404(Article) else: articles = get_list_or_404(Article, tags__name__in=[tag], publish=True) context = { 'tag': tag, 'articles': articles, } return render(request, 'blog/article-list.html', context) Every thing works just fine execpt rethriving all article URL on html with django template {% url %} tag. I want something like this: href="{% url 'article_list' '' %}" How can I make the URL with an empty argument(in this case, empty slug)? -
How display on an HTML a list of objects (ManyToMany) that is a class attribute
I am a Django beginner, so I hope my question makes sense. I am trying to understand the very basics of how a cart application works. No sessions involved. Also, I would like to display everything on the homepage, so that the order 'summary' will be always visible and updated on one page. As I said, I am just learning Django, so I have created two models, Item and Cart 'models.py' from django.db import models from django.contrib.auth.models import User # Create your models here. class Item(models.Model): name = models.CharField(max_length=25) price = models.DecimalField(max_digits=5, decimal_places=2) def __str__(self): return self.name class Cart(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) items = models.ManyToManyField(Item) total = models.DecimalField(max_digits=5, decimal_places=2) def __str__(self): return 'Order number: %s' % self.id a view for the homepage in 'views.py' from django.shortcuts import render from .models import Cart, Item # Create your views here. def home(request): items = Item.objects.all() carts = Cart.objects.all() length = len(Cart.objects.all()) cart = carts[length - 1] cart_items = cart.items return render(request, 'cart/home.html', {'cart': cart, 'items': items, 'cart_items': cart_items}) mapped in 'urls.py' (included in the main 'urls.py') from django.urls import path from . import views urlpatterns = [ path('', views.home, name='home') ] I have registered both the models in … -
Error converting YAML to JSON: yaml: line 3: did not find expected key
I have a docker application prepared. Now I would like to implement it on a server heroku, unfortunately an error is returned to me during the command execution. git push heroku master I receive this error message Enumerating objects: 466, done. Counting objects: 100% (466/466), done. Delta compression using up to 4 threads Compressing objects: 100% (442/442), done. Writing objects: 100% (466/466), 10.30 MiB | 1008.00 KiB/s, done. Total 466 (delta 83), reused 0 (delta 0) remote: Compressing source files... done. remote: Building source: remote: === Fetching app code remote: remote: =!= Build failed due to an error: remote: remote: =!= validate step: error converting YAML to JSON: yaml: line 3: did not find expected key remote: remote: If this persists, please contact us at https://help.heroku.com/. remote: Verifying deploy... remote: remote: ! Push rejected to powerful-cove-75131. remote: To https://git.heroku.com/powerful-cove-75131.git ! [remote rejected] master -> master (pre-receive hook declined) error: failed to push some refs to 'https://git.heroku.com/powerful-cove-75131.git' My heroku.yml file looks like this setup: addons: - plan: heroku-postgresql build: docker: web: Dockerfile release: image: web command: - python manage.py collectstatic --noinput run: web: gunicorn pvb.wsgi -
Integration of paytm gateway with Django app throws error in Paytm verify_checksum function
Payment works fine but after the payment is done, the response handler function throws an error in verify_checksum function saying "ord() expected string of length 1, but int found".