Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
python django models int() argument must be a string a bytes-like object or a number not a datetime
In Django models, I'm trying two create two tables jobs and images and I'm trying to relate the image table to the jobs table through the job_id but every time I migrate I get the following error: int() argument must be a string a bytes-like object or a number not a datetime my code below: from Django.db import models class Job(models.Model): job_id = models.IntegerField(default=1, primary_key=True) summary = models.CharField(max_length=200) upload = models.FileField(upload_to='uploads/') class Images(models.Model): image_id = models.IntegerField(default=1, primary_key=True) image = models.ImageField(upload_to='images/') job_id = models.ForeignKey(Job, on_delete=models.CASCADE) -
Running Django migrations on dockerized project
I have a Django project running in multiple Docker containers with help of docker-compose. The source code is attached from directory on my local machine. Here's the compose configuration file: version: '3' services: db: image: 'postgres' ports: - '5432:5432' core: build: context: . dockerfile: Dockerfile command: python3 manage.py runserver 0.0.0.0:8000 ports: - '8001:8000' volumes: - .:/code depends_on: - db Although the application starts as it should, I can't run migrations, because every time I do manage.py makemigrations ... I receive: django.db.utils.OperationalError: could not translate host name "db" to address: nodename nor servname provided, or not known Obviously I can open bash inside the core container and run makemigrations from there, but then the migration files are created inside the container which is very uncomfortable. In my project's settings the database is configured as: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'postgres', 'USER': 'postgres', 'HOST': 'db', 'PORT': '5432', } } As docker image containing database is accessible at localhost:5432 I tried changing database host in settings to: 'HOST': '0.0.0.0' But then when firing up the containers with docker-compose up I'm receiving: ... django.db.utils.OperationalError: could not connect to server: Connection refused Is the server running on host "0.0.0.0" and accepting TCP/IP … -
Django form post request without rendering
I have django form, then for each field I set initial value. How can I make POST request in my view.py (like after pressing submit button) without rendering the form. I just need to send these initial values as POST request to another url. -
How to search a dataframe word in a list using python
I have a dataframe as below variable value 0 ATM Cash withdrawal 8 Auto & Fuel fuel 16 Expense fees 17 Expense goods 18 Expense stationery 19 Expense purchase 20 Expense material 21 Expense telephone 24 Food/Restaurent food 25 Food/Restaurent catering 32 General others 40 Groceries big bazar 48 Income salary 49 Income deposit 50 Income rewards 56 Medical dr 57 Medical doctor 58 Medical dr. 59 Medical nursing 60 Medical pharmacist 61 Medical physician 62 Medical hospital 63 Medical medicine 64 Mobile recharge airtel 72 Payment tranfer 73 Payment payment 80 Shopping cloths 81 Shopping clothing 88 Travel travel and i have a list as listvalue=["POS 541919XXXXXX5316 PAYTM POS DEBIT","POS 541919XXXXXX5316 HASBRO CLOTHING POS DEBIT","POS 541919XXXXXX5316 RAKESH POS DEBIT","Salary for the month of April 2018"] I want to search each dataframe value with the each listvalue. If the value present in listvalue, it has to return dataframe variable I tried with below code json_data = open('C:/Users/nurture-user/Desktop/testingcat.json').read() jsonloaddata = json.loads(json_data) df = pd.DataFrame(dict([(k, pd.Series(v)) for k, v in jsonloaddata.items()])).melt().dropna() dfvaluelist=df.value.tolist() for singledesc in listvalue: for singlevalue in dfvaluelist: if singlevalue.lower() in singledesc.lower(): categorylist[singledesc] = singlevalue break if not singledesc in categorylist.keys(): categorylist[singledesc] = defaultValue for key, value in categorylist.items(): idx=df.value.str.contains(value) … -
django - makemessages command create an html.py file for each html file and give an UnicodeDecodeError
when i run this command : django-admin makemessages -l ar it's give this Traceback : Traceback (most recent call last): File "c:\users\ahmed\appdata\local\programs\python\python36-32\lib\site- packages\django\utils\encoding.py", line 65, in force_text s = str(s, encoding, errors) UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe9 in position 3107: invalid continuation byte During handling of the above exception, another exception occurred: Traceback (most recent call last): File "c:\users\ahmed\appdata\local\programs\python\python36-32\lib\runpy.py", line 193, in _run_module_as_main "__main__", mod_spec) File "c:\users\ahmed\appdata\local\programs\python\python36-32\lib\runpy.py", line 85, in _run_code exec(code, run_globals) File "C:\Users\Ahmed\AppData\Local\Programs\Python\Python36-32\Scripts\django-admin.exe\__main__.py", line 9, in <module> File "c:\users\ahmed\appdata\local\programs\python\python36-32\lib\site- packages\django\core\management\__init__.py", line 371, in execute_from_command_line utility.execute() File "c:\users\ahmed\appdata\local\programs\python\python36-32\lib\site-packages\django\core\management\__init__.py", line 365, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "c:\users\ahmed\appdata\local\programs\python\python36-32\lib\site- packages\django\core\management\base.py", line 288, in run_from_argv self.execute(*args, **cmd_options) File "c:\users\ahmed\appdata\local\programs\python\python36-32\lib\site-packages\django\core\management\base.py", line 335, in execute output = self.handle(*args, **options) File "c:\users\ahmed\appdata\local\programs\python\python36-32\lib\site-packages\django\core\management\commands\makemessages.py", line 384, in handle potfiles = self.build_potfiles() File "c:\users\ahmed\appdata\local\programs\python\python36-32\lib\site-packages\django\core\management\commands\makemessages.py", line 426, in build_potfiles self.process_files(file_list) File "c:\users\ahmed\appdata\local\programs\python\python36-32\lib\site-packages\django\core\management\commands\makemessages.py", line 522, in process_files self.process_locale_dir(locale_dir, files) File "c:\users\ahmed\appdata\local\programs\python\python36-32\lib\site-packages\django\core\management\commands\makemessages.py", line 590, in process_locale_dir msgs, errors, status = popen_wrapper(args) File "c:\users\ahmed\appdata\local\programs\python\python36-32\lib\site-packages\django\core\management\utils.py", line 23, in popen_wrapper force_text(output, stdout_encoding, strings_only=True, errors='strict'), File "c:\users\ahmed\appdata\local\programs\python\python36-32\lib\site-packages\django\utils\encoding.py", line 69, in force_text raise DjangoUnicodeDecodeError(s, *e.args) django.utils.encoding.DjangoUnicodeDecodeError: 'utf-8' codec can't decode byte 0xe9 in position 3107: invalid continuation byte. You passed in and create an html.py file for each html file for exemple : index.html create an … -
Django ignore mysql connection error
How do I "ignore" or "pass" on an MySQL connection error using Django? Right now when my app tries to connect to the Database and the Database is offline (for whatever reason (update etc)) the script just throws the error but I want the script to continue running even if there is no database connection. Is this possible? -
Django Rest Framework Custom Object Permission is not Called
So, i want to make endpoints where Anon or non-admin can only POST. The endpoints are: api/v1/keywords/ api/v1/keyword/$id I already made the custom permission and apply it into the class-based views. #permissions.py from rest_framework import permissions class AnonWriteOnly(permissions.BasePermission): """ Anon can only post """ def has_object_permission(self, request, view, obj): # Only allow post request allowed_methods = ('POST') if request.method in allowed_methods: print (True) #debugging purpose return True print(False) #debugging purpose return permissions.IsAuthenticated.has_permission(self, request, view) This is my views: # Anon can post. #Corresponds to the first endpoint class KeywordList(generics.ListCreateAPIView): """ List all keywords, or create a new keyword """ permission_classes = [AnonWriteOnly] queryset = Keyword.objects.all() serializer_class = KeywordSerializer #Corresponds to the second endpoint class KeywordDetail(generics.RetrieveDestroyAPIView): """ Retrieve, update, delete keyword """ permission_classes = [AnonWriteOnly] queryset = Keyword.objects.all() serializer_class = KeywordSerializer When I am not logged in and try to open the second endpoint, it works fine. It has 403 response, the output is also printed. False [27/May/2018 18:14:33] "GET /api/v1/keyword/1 HTTP/1.1" 403 10621 But, when I try to open the first endpoint it doesn't print anything, it is just run normally, without permission. [27/May/2018 18:28:02] "GET /api/v1/keywords/ HTTP/1.1" 200 13256 I have tried to change the permissions.IsAuthenticated to permissions.IsAdminUser but … -
How do I get the first page of results for multiple things in one query
The problem is a little hard to explain, but I'll do my best. I'm constructing a GraphQL server in Django (using Graphene), and part of this is the need to batch up database queries to avoid n+1 problems. Which means, when say fetching a set of Events, rather than making one query per Event ID, we make a single query with where id in (...). I'm trying to achieve the same with lists. My immediate use case is that every Event has a Venue, and I want to retrieve the next 5 (this is arbitrary) events for each Venue, in just one query. (Note: for a full justification behind this, I wrote an article a while ago) The PostgreSQL query I've come up with is this: SELECT * FROM ( SELECT *, ROW_NUMBER() OVER (PARTITION BY venue_id ORDER BY starts_at, ends_at, id) AS row_index FROM events_event WHERE starts_at >= '2018-05-20') x WHERE row_index <= 5 I don't think I'll have the need for case statements, because I don't think there's a realistic need to be able to batch up subsequent pages -- just the initial ones. So I have a few questions about this: Is there a better way of … -
Debug = False on heroku
I have a two question about Heroku and deploying application. Normally it works ok and everything fine, but there are two things that I don't understand with this. When I setup Debug = False the program crashes because it cannot find static files even if I run collectstatic before, as I saw when I comment "django_heroku.settings(locals())" than everything works fine. So my question is. Does heroku setup DEBUG = False automaticly after upload and I don't have to change this ?. Is this "django_heroku.settings(locals())" should be at the end of settigns.py. Does it mean that I cannot test production django environment locally and I need always put the source on the heroku platform? I added webpack_loader to the heroku apps, but every time I try to push the source to the heroku platform it says: " ModuleNotFoundError: No module named 'webpack_loader'", but I've installed this module. Does it mean that I need install this module on heroku and how to do this ? -
Django TemplateDoesNotExist at /
I am currently trying to build a tipping game app with Django. I'm new to Django and this is my first App. I found a already existing "template" on GitHub https://github.com/kdungs/tippspiel and want to adjust it for my purposes. I get the following if I run manage.py runserver: TemplateDoesNotExist at / {'player': <Player: Player object (1)>, 'top_players': <QuerySet [<Player: Player object (1)>]>, 'upcoming_matchdays': <filter object at 0x10d5b4c50>} Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 2.0.4 Exception Type: TemplateDoesNotExist Exception Value: {'player': <Player: Player object (1)>, 'top_players': <QuerySet [<Player: Player object (1)>]>, 'upcoming_matchdays': <filter object at 0x10d5b4c50>} Exception Location: /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/template/loader.py in get_template, line 19 Python Executable: /Library/Frameworks/Python.framework/Versions/3.6/bin/python3 Python Version: 3.6.5 Python Path: ['/Users/constantinkurz/Desktop/wm2018', '/Library/Frameworks/Python.framework/Versions/3.6/lib/python36.zip', '/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6', '/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/lib-dynload', '/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages'] Server time: So, 27 Mai 2018 13:01:14 +0200 Here is also my Settings.py: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'tippspiel', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'mysite.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'tippspiel/templates/tippspiel')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'mysite.wsgi.application' # Database # https://docs.djangoproject.com/en/2.0/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation … -
Django - model Validator doesn't work in CreateView nor UpdateView nor Admin
Not sure why but RangeMaxValueValidator doesn't work at all when trying to create or update an object. Even if I try to create or update through django admin it doesn't validate input. Instead, it raises exception from database. Exception Value: value "9223372036854775808" is out of range for type bigint LINE 1: ...imestamptz, 3, 'prenajom_kupa', NULL, NULL, NULL, '[92233720... I use BigIntegerRangeField and PostgreSQL. This is the model: from django.contrib.postgres.fields import BigIntegerRangeField, IntegerRangeField from django.contrib.postgres.validators import RangeMaxValueValidator class Dopyt(TimeStampedModel): .... cena = BigIntegerRangeField(null=True, blank=True, verbose_name='Cena [€]', validators=[RangeMaxValueValidator(9223372036854775807)]) .... I thought that django will automatically validate the RangeField so it won't even touch the database if there is an incorrect value posted but it raises: Exception Value: value "9223372036854775808" is out of range for type bigint LINE 1: ...imestamptz, 3, 'prenajom_kupa', NULL, NULL, NULL, '[92233720... So I decided to tell django explicitely the max value by adding validators=[RangeMaxValueValidator(9223372036854775807)], which is 9223372036854775807 for bigint in PostgreSQL but it raises the same error as before. As far as I know, the validators should work with ModelForms which I suppose I use implicitely if I use UpdateView, CreateView or editing the object from django admin. Note that: I haven't overriden clean method and haven't overriden … -
Django Success Url works in one app, but not another
I've been struggeling with a minor detail for a week now, and I've scoured Google for a suitable answer to my conundrum, alas with no luck. I am building https://vulpesvelox.pythonanywhere.com using https://github.com/vulpesveloxDesign/hubba as a base. In my project there is a 'blog' app, and also I've added a 'profiles' app. Both have models, forms, templates and local urlconfigs, which are somewhat alike and, I believe, fairly standard apps. The strange thing is that whereas success_url = '/blog/{slug}' (in the blog/views.py file) works just dandy with the urlconfig: path('', PostListView.as_view(), name='list'), path('create/', PostCreateView.as_view(), name='create'), path('<slug:slug>/', PostDetailView.as_view(), name='detail'), path('<slug:slug>/update/', PostUpdateView.as_view(), name='update'),, the same idea doesn't apply to the profile setup, which is set up thusly: success_url = '/profiles/{username}' path('<username>/', ProfileDetailView.as_view(), name='detail'), path('<username>/update/', ProfileCreateView.as_view(), name='update'), What I receive in stead of delicious user profile updates is a Key Error, but only on the local server...: KeyError at /profiles/admin/update/ 'username' Request Method: POST Request URL: http://localhost:8000/profiles/admin/update/ Django Version: 2.0.4 Exception Type: KeyError Exception Value: 'username' Exception Location: C:\Users\dfghjkljhghjk\Desktop\casa\env\lib\site-packages\django\views\generic\edit.py in get_success_url, line 113 Python Executable: C:\Users\dfghjkljhghjk\Desktop\casa\env\Scripts\python.exe Python Version: 3.6.3 Python Path: ['C:\Users\dfghjkljhghjk\Desktop\casa', 'C:\Users\dfghjkljhghjk\Desktop\casa\env\Scripts\python36.zip', 'C:\Users\dfghjkljhghjk\Desktop\casa\env\DLLs', 'C:\Users\dfghjkljhghjk\Desktop\casa\env\lib', 'C:\Users\dfghjkljhghjk\Desktop\casa\env\Scripts', 'c:\users\dfghjkljhghjk\appdata\local\programs\python\python36\Lib', 'c:\users\dfghjkljhghjk\appdata\local\programs\python\python36\DLLs', 'C:\Users\dfghjkljhghjk\Desktop\casa\env', 'C:\Users\dfghjkljhghjk\Desktop\casa\env\lib\site-packages'] Server time: Sat, 26 May 2018 12:48:34 +0200 ...whereas on pythonanywhere I get a different … -
I want to make sign in & up for my site with Django but it doesn't work
form.py class SignUpForm(forms.Form): name = forms.CharField(max_length=50, required=True) email = forms.EmailField(max_length=100, required=True) password = forms.CharField(max_length=20, required=True) class SignInForm(forms.Form): email = forms.EmailField() password = forms.CharField(max_length=20, min_length=8) view.py def Sign_Up(request): if request.method == 'POST': form = SignUpForm(request) if form.is_valid(): cd = form.cleaned_data name = cd['name'] email = cd['email'] password = cd['password'] us = User.objects.all() us = User(name=name, email=email, password=password) us.save() return HttpResponseRedirect('/') else: form = SignUpForm() return render(request,'User Login Page.html', {'form':form}) def Sign_In(request): if request.method =='POST' : form = SignInForm(request) if form.is_valid(): F = form.cleaned_data Eemail = F['email'] Epassword = F['password'] try: user = User.objects.filter(email=Eemail) except User.DoesNotExist: form = SignInForm() return render(request, "Admin Login Page.html", {'form': form}) if User.password == Epassword: return HttpResponseRedirect("/") form = SignInForm() return render(request,"Admin Login Page.html",{'form':form}) I'm new in Django I want to make sign in & up for my site with Django but it doesn't work! when i click on submit button my sign up directly go to address on HttpRsponseDirect even with empty parameters -
How to communicate with jQuery in Django?
I got this script in index.html <script> $(window).on("scroll", function() { if ((window.innerHeight + window.scrollY) >= document.body.offsetHeight) { alert("Bottom of page!"); } }); <script> and this in my views.py def entry(request, template='index.html', page_template='entry_list_page.html'): context = { 'entry_list': Entry.objects.filter()[:4], 'page_template': page_template, } if request.is_ajax(): template = page_template return render(request, template, context) How can I let Django know that jQuery has hit the bottom of the page so that I could display 4 more Entry objects? -
Django: DetailView and two slug fields
My database model has different organisers who can have several events. I now want to filter my DetailView down to organiser and then a specific event. My solution is that one here, but I still have in mind, that there shouldn't be two slug fields in the get_object method. Is there another approach to what I am trying to do? views.py class EventDetailView(DetailView): context_object_name = 'event' def get_object(self): organiser = self.kwargs.get('organiser') event = self.kwargs.get('event') queryset = Event.objects.filter(organiser__slug=organiser) return get_object_or_404(queryset, slug=event) urls.py urlpatterns = [ path('<slug:organiser>/<slug:event>/', EventDetailView.as_view(), name='event'), -
Update state of form with button django
Every row of the table has a button with the pk of the element. Using the button should fill the form with the states of the entry. I think I have a problem with the renderer, as it clears my form but I'm not sure how to fix this. I would like to achieve this without the use of AJAX if possible. html <form action="" method="POST"> {% csrf_token %} <input type="hidden" name="pk" value="{{ post.pk }}"> <input class="btn btn-default btn-danger" name="update" type="submit" value="Ändern"/> </form> views.py from django.shortcuts import render from django.utils import timezone from django.contrib.auth.decorators import login_required from django.http import HttpResponseRedirect from .forms import NameForm from .models import Eintrag @login_required() def get_name(request): # if this is a POST request we need to process the form data if request.method == 'POST' and 'add' in request.POST: # create a form instance and populate it with data from the request: form = NameForm(request.POST) # check whether it's valid: if form.is_valid(): #Eintrag.objects.filter(Name=request.user).delete() eintrag = form.save(commit=False) # process the data in form.cleaned_data as required # ... # redirect to a new URL: eintrag.Name = request.user # Set the user object here eintrag.pub_date = timezone.now() # Set the user object here eintrag.save() return HttpResponseRedirect(request.path) # generate an … -
Django - Requiring Optional Form Field
Somewhat new Django user here. I have a model and form that I intended to allow users to choose between uploading (posting, if using the model name) an image, text or both. Uploading is not allowed without an image despite the image attribute having blank=True and null=True. I then set the required=False on the image portion of the form, but this resulted in a MultiValueDictKeyError My model is: class Post(models.Model): image = models.ImageField(upload_to='uploaded_images', blank=True, null=True) text_post = models.CharField(max_length=1000) author = models.ForeignKey(User) My form is: class PostForm(forms.ModelForm): image = forms.FileField(required=False, label='Select an image file', help_text='Please select a photo to upload') text_post = forms.CharField(help_text="Please enter some text.") class Meta: model = Post fields = ('image', 'text_post',) exclude = ('author',) My view is: def posts(request, id=None): neighborhood = get_object_or_404(Neighborhood, id=id) form = PostForm() if request.method == 'POST': form = PostForm(request.POST, request.FILES) if form.is_valid(): post = Post(image = request.FILES['image']) post = form.save(commit=False) post.author = request.user post = post.save() next = request.POST.get('next', '/') return HttpResponseRedirect(next) else: form = PostForm() posts = Post.objects.all().order_by('-id') return render(request, 'posts.html', context = {'form':form, 'posts':posts, 'neighborhood':neighborhood}) and my form is: <form id="PostForm" method="post" action="/view/{{ neighborhood.id }}/posts/" enctype="multipart/form-data"> {% csrf_token %} {% for hidden in form.hidden_fields %} {{ hidden }} {% endfor … -
Django: Why is self. used here?
I was just looking into Dynamic Filtering on the official documentation: https://docs.djangoproject.com/en/2.0/topics/class-based-views/generic-display/#dynamic-filtering It says there def get_queryset(self): self.publisher = get_object_or_404(Publisher, name=self.kwargs['publisher']) return Book.objects.filter(publisher=self.publisher) Does anyone know, why for self.publisher = get_object_or_404, there was used self. at the beginning? I learned it so far that you don't add self. when defining the variable. Specifically what I am not sure about now is if I should either use that code here: def get_queryset(self): slug = self.kwargs.get('slug') return Event.objects.filter(organiser__slug=slug) Or that one: def get_queryset(self): self.slug = self.kwargs.get('slug') return Event.objects.filter(organiser__slug=self.slug) -
DJango how to write a view.py for signing in and registering as well as a log out
Hi I am new to Django I just want to know how to write the POST and GET so I can sign in and log out as well as register? thanks for your time. -
Ajax Call coming up empty in views.py (Django)
I am using Django and trying to call the following function in my .js file: $.ajax({ url : '/table', type : 'GET', data : { fields : 'fieldName' ,rows: 3 } }); Below is the code in my views.py file: def table(request): fields = request.GET["fields"] rows = request.GET["rows"] return render(request, 'nfl/table.html', {"rows": [[rows]], "finalFields": [fields]}) The error I am getting is MultiValueDictKeyError at /table. And when I use request.GET.get("fields") instead, the render function works but None is the value of my fields and rows. It seems like the data from my ajax call is not getting passed to my views.py file, why is this? -
How to add max_length to allauth username
I'm using Django allauth as my user account framework for my django site. The docs show there is an ACCOUNT_USERNAME_MIN_LENGTH however there is no ACCOUNT_USERNAME_MAX_LENGTH for some reason. Is there any way to create a max length for username? Here's my custom allauth signup form - maybe I can do something here?: class AllauthSignupForm(forms.Form): captcha = ReCaptchaField( public_key=config("RECAPTCHA_PUBLIC_KEY"), private_key=config("RECAPTCHA_PRIVATE_KEY"), ) class Meta: model = User def signup(self, request, user): """ Required, or else it throws deprecation warnings """ pass -
Anaconda prompt error conda not working
I tried installing Django using anaconda prompt and then it installed 10 or 11 packages, after that whenever I type something with "conda" on it in anaconda prompt it shows this: Traceback (most recent call last): File "C:\Users\root\Anaconda3\Scripts\conda-script.py", line 10, in <module> sys.exit(main()) File "C:\Users\root\Anaconda3\lib\site-packages\conda\cli\main.py", line 112, in main from ..exceptions import conda_exception_handler File "C:\Users\root\Anaconda3\lib\site-packages\conda\exceptions.py", line 18, in <module> from .common.io import timeout File "C:\Users\root\Anaconda3\lib\site-packages\conda\common\io.py", line 28, in <module> from .._vendor.tqdm import tqdm File "C:\Users\root\Anaconda3\lib\site-packages\conda\_vendor\tqdm\__init__.py", line 8, in <module> from ._tqdm import tqdm File "C:\Users\root\Anaconda3\lib\site-packages\conda\_vendor\tqdm\_tqdm.py", line 13, in <module> from ._utils import _supports_unicode, _environ_cols_wrapper, _range, _unich, \ ValueError: source code string cannot contain null bytes -
Best IDE/setup for Django, python, and SQL?
I am starting a little project that will involve a website with a database backend. I'm planning to use the Django framework and Postgres. I have experience programming but am a bit green when it comes to web development. Can anyone recommend an IDE (or other workflow related must-haves)? Here's what I'm looking for in the IDE: Must be Linux compatible HTML/CSS autocomplete, highlighting, etc. Python HTML/CSS autocomplete, highlighting, etc. Anything else that would be deemed necessary for Django FOSS is great but not a requirement Light(ish)-weight is also nice but not necessary -
Django encrypted-filefield
i currently try to figure out how to implement the Following: https://github.com/danielquinn/django-encrypted-filefield I only want to transparently encrypt my uploaded Data for later use on e.g. S3 First Problem is that i'm not able to get from django.contrib.auth.mixins import AuthMixin imported. I get the follwoing execpt from django.contrib.auth.mixins import AuthMixin ImportError: cannot import name 'AuthMixin' I'm simply not able to find it. At what package is it located? and second is that i have no idea how to implement the view if i only want encrypt and decrypt the file on the fly. Ans suggestions? my models.py from django.db import models from django.utils import timezone from smartfields import fields from smartfields.dependencies import FileDependency from smartfields.processors import ImageProcessor from django_encrypted_filefield.fields import EncryptedFileField #Post Model class Post(models.Model): author = models.ForeignKey('auth.User', on_delete=models.CASCADE) title = models.CharField(max_length=200) text = models.TextField(max_length=10000) tag = models.CharField(max_length=50, blank=True) postattachment = EncryptedFileField(upload_to='postattachment/%Y/%m/%d/', blank=True, null=True) postcover = fields.ImageField(upload_to='postcover/%Y/%m/%d/', blank=True, null=True, dependencies=[ FileDependency(processor=ImageProcessor( format='JPEG', scale={'max_width': 300, 'max_height': 300})) ]) created_date = models.DateTimeField(default=timezone.now) published_date = models.DateTimeField(blank=True, null=True) def publish(self): self.published_date = timezone.now() self.save() def __str__(self): return self.title ... Thank you :) -
<module> execute_from_command_line(sys.argv)
File "C:/Users/Zahidsf/Desktop/SSO_Project/manage.py", line 22, in execute_from_command_line(sys.argv) File "C:\Users\Zahidsf\Envs\myenv1\lib\site-packages\django\core\management__init__.py", line 371, in execute_from_command_line utility.execute() File "C:\Users\Zahidsf\Envs\myenv1\lib\site-packages\django\core\management__init__.py", line 347, in execute django.setup() File "C:\Users\Zahidsf\Envs\myenv1\lib\site-packages\django__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\Zahidsf\Envs\myenv1\lib\site-packages\django\apps\registry.py", line 89, in populate app_config = AppConfig.create(entry) File "C:\Users\Zahidsf\Envs\myenv1\lib\site-packages\django\apps\config.py", line 90, in create module = import_module(entry) File "C:\Users\Zahidsf\Envs\myenv1\lib\importlib__init__.py", line 126, in import_module