Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: `Related Field got invalid lookup: icontains`
I am creating an image sharing website.... PROBLEM 1: here is a screen shot of the search page of images enter image description here The problem here is, when I search by tag, there is an error message: Related Field got invalid lookup: icontains PROBLEM 2: here is a screen shot of the upload page of an image enter image description here The problem is, I can only pick tags but not input new tag here. I want it to be able to let uploader of image to input at most 10 tags.... Here are my codes: models.py class Tag(models.Model): tag_name = models.CharField(max_length=50) def __str__(self): return self.tag_name class Image(models.Model): category = models.ForeignKey(Category, blank=True, null=True, on_delete=models.DO_NOTHING) in_gallery = models.ManyToManyField(Gallery, blank=True) tag = models.ManyToManyField(Tag, blank=True) title = models.CharField(max_length=100) photo = models.FileField() description = models.CharField(max_length=1000) def __str__(self): return self.title + '-' + self.description def regions_changed(sender, **kwargs): if kwargs['instance'].tag.count() > 1: raise ValidationError("You can't assign more than three regions") class ImageTag (models.Model): image = models.ForeignKey(Image, blank=True, null=True, on_delete=models.DO_NOTHING) tag = models.ForeignKey(Tag, blank=True, null=True, on_delete=models.DO_NOTHING) filters.py class ImageFilter(django_filters.FilterSet): title = django_filters.CharFilter(lookup_expr='icontains') description = django_filters.CharFilter(lookup_expr='icontains') tag = django_filters.CharFilter(lookup_expr='icontains') class Meta: model = Image fields = ['title', 'description', 'category', 'tag'] class NullFilter(django_filters.FilterSet): class Meta: model = Image … -
How to pass request to Celery task parameter in Django project?
I am using wkhtmltopdf with Django to generate a PDF file and email it to someone. Here is my view: class ChallanEmail(AtomicMixin, View, LoginRequiredMixin): template = "europarts/challan/email_template.html" def get(self, request, **kwargs): challan = Challan.objects.get(pk=kwargs['pk']) ref_no = challan.ref_no date = challan.created recipient = challan.recipient address = challan.recipient_address challan_rows = ChallanRow.objects.filter(challan=challan) context = { "ref_no": ref_no, "date": date, "recipient": recipient, "address": address, "challan_rows": challan_rows, } response = PDFTemplateResponse( request=request, template=self.template, filename='challan_email.pdf', context=context, show_content_in_browser=True, cmd_options={'margin-top': 10, 'zoom': 1, 'viewport-size': '1366 x 513', 'javascript-delay': 1000, 'no-stop-slow-scripts': True}, ) file_path = os.path.join(settings.BASE_DIR, settings.MEDIA_ROOT, 'challan_email.pdf') with open(file_path, 'wb') as f: f.write(response.rendered_content) subject = 'From Design Ace Limited' body = self.request.GET.get('email_body', '') from_email = 'Sorower Hossain <sorower@europartsbd.com>' to = ['{}'.format(self.request.GET.get('to_address'))] attachment = os.path.join(settings.MEDIA_ROOT, 'challan_email.pdf') send_email(subject, body, from_email, to, attachment) return HttpResponseRedirect(reverse('europarts:challan_details', args=(kwargs['pk'],))) As you can see towards the end I am sending the email with a task (send_email) using celery. However, the most time consuming process is the PDF creation process. Here is the portion of code that does that: response = PDFTemplateResponse( request=request, template=self.template, filename='challan_email.pdf', context=context, show_content_in_browser=True, cmd_options={'margin-top': 10, 'zoom': 1, 'viewport-size': '1366 x 513', 'javascript-delay': 1000, 'no-stop-slow-scripts': True}, ) The problem I am facing is whenever I am trying to transfer all the parameters to … -
When using the patch method, I get an error: "PATCH" not allowed
I study Rest framework and faced with a problem: detail": "Method "PATCH" not allowed. I do everything according to the documentation. I want update only fields: first_name and password. views class UpdateUserSet(viewsets.ModelViewSet): permission_classes = (IsAuthenticated,) serializer_class = UserSerialize def partial_update(self, request, pk=None): return Response(status=status.HTTP_201_CREATED) serialize class UserSerialize(serializers.ModelSerializer): first_name = serializers.CharField(max_length=30) password = serializers.CharField(write_only=True) class Meta: model = User fields = ('first_name', 'password',) What I doing wrong? -
Django display different datetime from database to template?
I have the table that showing date as follows: RegDate 2018-04-12 13:43:55.023 2018-04-18 12:49:39.670 2018-04-18 18:56:12.587 It successfully displayed in page, however there is a time diference (9 hours faster in template) Anybody knows why a difference time happened? file.html <td class="text-center">{{ item.regDate|date:"Y.m.d H:m:s" }}</td> forms.py RegDate = forms.DateTimeField(required=False, widget=forms.DateTimeInput(attrs={'id': 'RegDate', 'class': 'form-control', 'name': 'RegDate', 'valtype':'datetime', 'data-isdate': 'True'}), input_formats=[DEFAULT_DATEFORMAT]) -
Resource not found in Kubectl
I am geeting some issue while running the following command. kubectl get service -l component=gateway --namespace openfaas No resources found. helm version Client: &version.Version{SemVer:"v2.9.0-rc4", GitCommit:"030d2c066bcf5a37931e0169b7921f3758d97095", GitTreeState:"clean"} Error: cannot connect to Tiller Even though helm init is working properly I have upgraded the helm as well. please help me to find the solution for above problem -
Editing image field using Django forms
I am currently creating an application that allows users to view and edit their own personal profile. I've recently added in the ability for a user to add a profile picture to their profile. I can add a profile in the admin page and it will show up on the selected users profile no problem. The problem is when the user tries to update their picture I am getting an ValueError telling me that the image attribute has no file associated. Below is how I have tried to implement the functionality. Models class UserProfileModel(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) age = models.PositiveIntegerField(blank=True, null=True) email = models.EmailField(max_length=254, null=True, blank=True, unique=True) height = models.PositiveIntegerField(blank=True, null=True) weight = models.PositiveIntegerField(blank=True, null=True) bio = models.CharField(max_length=100, blank=True, default='') image = models.ImageField(upload_to='profile_image', blank=True) forms class UpdateProfile(forms.ModelForm): class Meta: model = UserProfileModel fields = ('email', 'age', 'height', 'weight', 'bio', 'image') views def update_profile(request): args = {} if request.method == 'POST': form = UpdateProfile(request.POST, instance=request.user.userprofilemodel) if form.is_valid(): form.save() return HttpResponseRedirect(reverse('account:profile')) # return render(request, 'account/profile.html') else: form = UpdateProfile() if request.user.is_authenticated(): form = UpdateProfile(instance=request.user.userprofilemodel) args['form'] = form return render(request, 'account/edit_profile.html', args) HTML <!DOCTYPE html> <html> <body> {#<h2 style="text-align:center">User Profile Card</h2>#} <div class="container"> <h1>{{ user }}s Profile </h1> <div style="margin: 24px 0;"> … -
How to render HTML template?
I am looking at this method(from the book written by Antonio Mele) def post_list(request): posts = Post.published.all() return render(request,'blog/post/list.html',{'posts': posts}) The OP said that we will create HTML templates to render the data generated by the views.I do not understand this.This is the blog folder ls output ~/mysite/blog$ ls admin.py apps.py __init__.py migrations models.py __pycache__ tests.py views.py This is what views looks like cat views.py from django.shortcuts import render I can not grasp link between the post and views.py in this example. -
No such file or directory in django
Whenever I am calling the uploaded_file_url in django,it shows No such file or directory error But I checked manually.The directory and file are exist Here is my code uploaded_file_url=None uploaded_file_url2=None def upload(request): if request.method == 'POST': #request.FILES['myfile'] and request.FILES["myfile1"]: myfile=request.FILES['myfile'] myfile2=request.FILES["myfile2"] fs = FileSystemStorage() filename = fs.save(myfile.name, myfile) filename2=fs.save(myfile2.name, myfile2) global uploaded_file_url uploaded_file_url = fs.url(filename) global uploaded_file_url2 uploaded_file_url2 = fs.url(filename2) return HttpResponseRedirect('/home/') #upload_file = request.FILES['upload_file'] #data = [row for row in csv.reader(upload_file.read().splitlines())] return render(request, 'myapp/upload.html') def home(request): data= open(os.path.join(settings.MEDIA_ROOT, str(uploaded_file_url)),'rb').read() //some code here return render(request,'myapp/home.html',{"a":a}) Here I want to open the uploaded_file . Any suggestions here.Thanks in advance -
No module named 'sage.all'
Im going to use sage module in my Django web application so in my python virtualenv v3.6 I installed sage using pip. when I run my script to use sage I get the following error: Exception Value: No module named 'sage.all' I read some posts that sage has its own python. does it mean that I can not use sage in my python virtualenv? -
python,django, solr, haystack: django templates context error when editing solr_build_schema BaseCommand.add_argument()
Please help....i am trying use solr, pysolr and haystack on my django site search. I have edited the haystack build_solr_schema script to use BaseCommand.add_argument(), removing the default options_list. Below are my versions used; Python 3.5.2 Django 1.11.11 solr-7.3.0 django-haystack 2.4.0 pysolr 3.7.0 # encoding: utf-8 from __future__ import absolute_import, division, print_function, unicode_literals import sys from optparse import make_option from django.core.exceptions import ImproperlyConfigured from django.core.management.base import BaseCommand from django.template import Context, loader from haystack import constants from haystack.backends.solr_backend import SolrSearchBackend class Command(BaseCommand): help = "Generates a Solr schema that reflects the indexes." def add_arguments(self, parser): # positional arguments parser.add_argument("-f", "--filename", action="store", type="string", dest="filename", help='If provided, directs output to a file instead of stdout.',), # optional positional arguments parser.add_argument("-u", "--using", action="store", type="string", dest="using", default=constants.DEFAULT_ALIAS, help='If provided, chooses a connection to work with.') """ base_options = ( make_option("-f", "--filename", action="store", type=str, dest="filename", help='If provided, directs output to a file instead of stdout.'), make_option("-u", "--using", action="store", type=str, dest="using", default=constants.DEFAULT_ALIAS, help='If provided, chooses a connection to work with.'), ) option_list = BaseCommand.option_list + base_options """ def handle(self, **options): """Generates a Solr schema that reflects the indexes.""" using = options.get('using') schema_xml = self.build_template(using=using) if options.get('filename'): self.write_file(options.get('filename'), schema_xml) else: self.print_stdout(schema_xml) def build_context(self, using): from haystack import connections, … -
Django tutorial recommendation
I have to make a simple web site to insert and retrieve data in few tables. The choice of database is PostgreSQL. To start with simple manual insertion, later I will need to update it to add a script that can insert values periodically reading values from some sensors through RaspberryPi. I find Django framework is a good choice for database-driven websites development. I find this tutorial seems nicely written and since I need to work on forms for insertion/update data, has section django working with froms. https://developer.mozilla.org/en-US/docs/Learn/Server-side/Django Can someone please see whether this is good tutorial to follow for beginners for kind of work I described. Recommendation of other tutorials will also be very helpful. Thank you very much in advance ! -
How to load an image file into a Django File object, then save into a FileField of my model
So I've spent more than 24 hours trying to figure out how to store an image into my model. class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) avatar = models.FileField(null=True, upload_to='www-avatar/') My Profile Model has an attribute avatar which stands for the profile picture. What I want to do is after the User has finished the sign-up process, the Profile Model would then be assigned a default image from my static folder. Here is my Settings.py for static STATIC_ROOT = '/srv/foo/' STATIC_URL = '/static/' STATICFILES_DIRS = (os.path.join(BASE_DIR, "bar/resource/"), ) And the image that I want to load and store into the model is in bar/resource/profile_light.png So far, the solution I've come up is with this file = File() url = static("bar/resource/profile_light.png") file = urllib.request.urlopen(url).read() r = File(file) authbox.profile.avatar = File(file) authbox.profile.save() To no avail. I am new to Django and I would very much appreciate any form of help. EDIT: I may have worded my question poorly, but I need to add a default image on the profiles that are created. The snippet i gave above of the saving of the avatar is located after the sign up process. So basically I want to access the image every time someone signs … -
Fetch Django view data with AJAX
Currently I am building an app which update the main page's data via AJAX. Based on this question I used (see code/1/ below) ajax to refresh my page. My other aim is to catch just certain variable from the view and use as a JS variable. If I use only Django template variable in the AJAX request my variable not refreshig. First attempt: Django view: def fetch_data (request): query_1=Objects.all() query_2=Objects.all() #From these queries I colect data and push them to lists. context= { 'variable_1': variable_1, 'variable_2': variable_2, 'time_variable': time_variable #changing in every minute } return render(request, 'app/index.html', context) AJAX: Here I use the AJAX request. I run it in every minute to realod my page my page. My problem is that I want to load just let's say the time_variable to use it again within AJAX. If I use it like a single template variable ({{time_variale|safe}}) when the AJAX reloading I get the same variable again and again and not a new one because of the refreshing. How gen I catch the Django variable? setInterval(function(){ if(new Date().getSeconds() === 0) { $.ajax({ url:'{% url 'fetch_data' %}', success: function (data){ $('body').html(data); #This working, the data refreshing var="{{time_variable|safe}}"; #Here I always get the … -
django form validation -validation error custom message not work
This is a Django rest project I'm creating a user registration form .. I wrote a validation for username like below but my custom validation error is not showing and it shows a default message like below... how can I fix this? My other question is: Whats the difference between def validate_username and def clean_username Thank You This is the default Django message: "{ "username": [ "A user with that username already exists." ] } " This is my view: class UserRegisterApiView(CreateAPIView): permission_classes = [AllowAny] serializer_class = UserRegisterSerializer queryset = User.objects.all() This is my serilizer: class UserRegisterSerializer(ModelSerializer): #email2 = EmailField(label='confirm email') email = EmailField(label='email', ) class Meta: model = User fields = [ 'username', 'first_name', 'email', 'password', ] extra_kwargs = { "password": { "write_only": True } } # check if the user name is taken def validate_username(self, value): username = value qs = User.objects.filter(username=username) if qs.exists(): raise ValidationError("این نام کاربری آزاد نمیباشد") return value -
angular, Subsequent errors won't be logged
How to fix this bug on angular -
How to display polish characters in python
I have in my database varchar column containing text with polish characters. I already changed format in DB to utf8 Now I am pulling data from DB using Django raw SQL creator and receiving an error: UnicodeDecodeError: 'utf8' codec can't decode byte 0xd3 in position 9: invalid continuation byte I have no idea how to repair it. There is # -- coding: utf-8 -- at the beginning of view file. Will be thankful for each support, Thanks in advance, -
Push to Heroku my local database - django and Windows
I'm trying o push the database from local to Heroku. Is a Django Database and I'm on windows 7. If I do heroku pg:info I get no database name, for : === DATABASE_URL Plan: Hobby-dev Status: Available Connections: 1/20 PG Version: 10.3 Data Size: 10.6 MB Tables: 37 Rows: 97/10000 (In compliance) Fork/Follow: Unsupported Rollback: Unsupported Continuous Protection: Off Add-on: postgresql-rugged-89466 If I try: pg:psql I get The local psql command could not be located. I have PostgreSQL installed locally with EnterpriseDB installer(from their website) I tried set DATABASE_URL=postgres://$(whoami) using by db name instead of $(whoami) doesn't do anything Because of this I don't know how to do the pg:push -
Django: make user is_active = False
I have a user model and a template with list of user with buttons DISABLE user, by clicking on which profile becomes inactive. models.py class User(AbstractUser): some user fields def block_profile(self,*args,**kwargs): user = self.user user.is_active = False user.save() messages.success(request, 'Profile successfully disabled.') return redirect('index') views.py def user_list(request): profiles = Profile.objects.all() return render(request, "vstories/vstories.html", {'profiles':profiles}) vstories.html {% for profile in profiles %} {{ profile.nickname }} <button> ??BLOCK_USER?? </button> {% endfor %} Did I write the function correctly in the model and how do I insert it in the template to output the button? -
Why form.is_valid() always return field is required?
I don't know why my form after submitting it always returns that the phone is required, i am stuck with this problem about one hour :(, i've seen lots of articles and questions that has been asked but without avail . views.py: def register(request): if request.method == 'POST': form = SignUpForm(request.POST or None) if form.is_valid(): user = form.save(commit=False) telephone = number_prettify(form.cleaned_data.get('telephone')) user.phone = telephone raw_password = form.cleaned_data.get('password1') user.save() user = authenticate(phone=user.phone, password=raw_password) auth_login(request, user) return redirect('/') else: form = SignUpForm() return render(request, 'register.html', {'form': form}) here is my forms.py: from django import forms from django.contrib.auth import get_user_model from django.contrib.auth.forms import UserCreationForm # from .models import Client User = get_user_model() class SignUpForm(UserCreationForm): telephone = forms.CharField(label='Номер телефона', help_text='Required. Inform a valid phone number.', widget=forms.TextInput(attrs={'placeholder': '___-__-__-__','class':"uk-input phone_us"})) password1 = forms.CharField(label='Пароль',widget=forms.PasswordInput()) password2 = forms.CharField(label='Повторите пароль',widget=forms.PasswordInput()) agree_1 = forms.BooleanField() agree_2 = forms.BooleanField() def clean(self): if not self.cleaned_data['agree_1']: raise forms.ValidateError('You have to agree to out privacy') class Meta: model = User fields = ('phone',) here is also the models.py: class Client(AbstractBaseUser, PermissionsMixin): email = models.EmailField(null=True, blank=True, unique=True) phone = models.CharField(max_length=18,unique=True) joined = models.DateTimeField(auto_now_add=True) password = models.CharField(default='', null=False, max_length=255) USERNAME_FIELD = 'phone' class Meta: db_table = 'client' unique_together = ('phone',) my register.html template: <div class="uk-margin"> <label> <div … -
Django wrong url pattern for subpath
I don't really know how to explain well my issue. What I'm trying to do is the following. My admins linked my django server address 192.168.2.1:8001 to a web address: devel.genesilico.pl/modomics to make public the website that otherwise would be visible only on our local network. If I visit that address I see the main page of my site without the static files, and if I try to visit another page the address changes to: devel.genesilico.pl/modifications So the modomics prefix path is removed and it cannot find the page. I though that changing my urls.py adding modomics in front of all of them would resolve this issue, but no. At this point the DEBUG of Django shows me this (photo attached).And also in this case the prefix "modomics" is removed. I don't know what to do. I don't know if this problem is given by django or by the setup of the web address that my admins gave me. -
Can I have different root URLs in the same app?
In my DRF project, I have 2 apps, Users and Prodcuts. Prodcuts has 2 models: Category and Product. My root URL conf looks like this api_urls = [ path('users/', include('users.urls')), path('products/', include('prodcuts.urls')) ] urlpatterns = [ path('admin/', admin.site.urls), path('api/', include(api_urls)) ] and the products.urls urlpatterns = [ path('', views.ProductListCreateAPIView.as_view()) ] I want my API scheme to be something like /api/users/ /api/products/ /api/categories/ Right now, this works fine for the first 2, but obviously doesn't cover the 3rd setting, i.e. if I was to add path('categories', views.CategoriesListCreateAPIView.as_view()) to my products.urls, the URL scheme would be /api/products/categories/ My question is, is there someway to achieve the /api/categories/ objective without splitting off Category into its own app? I feel as if it's too insignificant to warrant having its own app and should be in the same app. Obviously, I guess I could just import the views directly in the root URL conf but that doesn't feel like a 'clean' solution. -
ArrayField with JSONField as base_field in Django
I have a GooglePlace model with a field to store the address_components being returned by Google Places API. This is the field in model address_components = ArrayField(JSONField(), null=True, blank=True) I am trying to store the data like this address_components = [component for component in google_place_details.get("address_components")] But I am getting this error : column "address_components" is of type jsonb[] but expression is of type text[] LINE 1: ... '2018-04-26T07:49:02.101395+00:00'::timestamptz, ARRAY['{"l... ^ HINT: You will need to rewrite or cast the expression. I tried json.dumps each component, encode. But I think I am missing something silly. Any help will be much appreciated This is sample response : "address_components":[ { "long_name":"Chennai", "short_name":"Chennai", "types":[ "locality", "political" ] }, { "long_name":"Ramagiri Nagar", "short_name":"Ramagiri Nagar", "types":[ "sublocality_level_2", "sublocality", "political" ] }, { "long_name":"Velachery", "short_name":"Velachery", "types":[ "sublocality_level_1", "sublocality", "political" ] }, { "long_name":"Chennai", "short_name":"Chennai", "types":[ "administrative_area_level_2", "political" ] }, { "long_name":"Tamil Nadu", "short_name":"TN", "types":[ "administrative_area_level_1", "political" ] }, { "long_name":"India", "short_name":"IN", "types":[ "country", "political" ] }, { "long_name":"600042", "short_name":"600042", "types":[ "postal_code" ] } ], -
getting error while submitting a form using post method
Error : CSRF token missing or incorrect. Want to pass token to submit a form which is not on a django-template. views.py .... def post(self, request): form = self.form_class(request.POST or None, request.FILES or None) if form.is_valid(): email = form.cleaned_data.get('email') user = authenticate(email=email) if user is None: form.save() message = 'Saved Successfully' return HttpResponse(message) else: message = 'User Exists' return HttpResponse(message) else: message = 'Invalid form data' return HttpResponse(message) .... form.html .... <h1>Register</h1> <form class="newform" action="/api/register/" method='POST'enctype="multipart/form-data"> <input type='hidden' name='csrfmiddlewaretoken' value="some token value" /> .... </form> .... -
path('accounts/', include(accounts.urls)), NameError: name 'accounts' is not defined
I was just making a clone of ProductHunt.com website and while addressing the urls i am getting error as name error! when i type 'localhost:8000/accounts/signup' it should take me to a html page which i did for testing! the main urls.py looks like: from django.contrib import admin from django.urls import path, include from products import views urlpatterns = [ path('admin/', admin.site.urls), path('', views.home, name="home"), path('accounts/', include(accounts.urls)), ] So by this it goes to the accounts folders urls.py which looks like: from django.urls import path, include from .import views urlpatterns = [ path('signup', views.signup, name="signup"), path('login', views.login, name="login"), path('logout', views.logout, name="logout"), ] Then this goes to the views.py which looks like: from django.shortcuts import render def signup(request): return render(request, 'accounts/signup.html') def login(request): return render(request, 'accounts/login.html') def logout(request): return render(request, 'accounts/signup.html') Atlast my html is: {% extends 'base.html %} {% block content %} signup! {% endblock %} Why am i getting a name error: File "C:\Users\Kiran\Desktop\producthunt-project\producthunt\urls.py", line 8, in <module> path('accounts/', include(accounts.urls)), NameError: name 'accounts' is not defined Help Me, THANKS, -
InconsistentMigrationHistory - Migration .. is applied before its dependency
I have 2 models which are interdependent one of another: class Account(models.Model): created_by = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True, null=True,related_name='%(app_label)s_% (class)s_created_by', on_delete=models.CASCADE) updated_by = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True, null=True, related_name='%(app_label)s_%(class)s_updated_by', on_delete=models.CASCADE) class User(AbstractBaseUser, MetaData, PermissionsMixin): account = models.ForeignKey(Account, blank=True, null=True, related_name='owner', on_delete=models.CASCADE) I have issues: InconsistentMigrationHistory: Migration admin.0001_initial is applied before its dependency users.0001_initial on database 'default'. I tried to remove from the User the account foreign key, migrate User, than migrate accounts, account FK fails, same error. I tried to do it starting from the Account it fails, removing FK to users. I'm interesting on do it on a new datbase(server) and reset on an old database local.