Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django 'Model' object has no attribute '_meta' error
I'm working using Django to make a hardware web database. Here is my models.py from django.db import models class Desktop(models.Model): Model_Number = models.CharField(max_length=250) OS_Version = models.CharField(max_length=250) Hard_Drive_Size = models.CharField(max_length=250) RAM = models.CharField(max_length=250) Service_Tag = models.CharField(max_length=250) System_Image = models.CharField(max_length=250) Note = models.CharField(max_length=250) def __str__(self): return self.Model_Number + ' - ' + self.OS_Version + ' - ' + self.Note class Laptop(models.Model): Model_Number = models.CharField(max_length=250) OS_Version = models.CharField(max_length=250) Hard_Drive_Size = models.CharField(max_length=250) RAM = models.CharField(max_length=250) Service_Tag = models.CharField(max_length=250) System_Image = models.CharField(max_length=250) Note = models.CharField(max_length=250) def __str__(self): return self.Model_Number + ' - ' + self.OS_Version + ' - ' + self.Note class Monitor(models.Model): Size = models.CharField(max_length=250) Model = models.CharField(max_length=250) Supported_Interfaces = models.Model(max_length=250) Service_Tag = models.Model(max_length=250) def __str__(self): return self.Size + ' - ' + self.Model class Phone(models.Model): Model = models.CharField(max_length=250) def __str__(self): return self.Model class Dock(models.Model): Supported_Laptop = models.CharField(max_length=250) Model_Number = models.CharField(max_length=250) def __str__(self): return self.Model_Number + ' - ' + self.Supported_Laptop Here is the error code that I receive when I command python "manage.py makemigrations hardware Does anyone know why its throwing me that error? Thanks! -
Access ajax elements with django
i am using ajax to fetch django model and get results views.py def browse_jobs(request): keyword = request.GET.get('keyword', None) company = Company.objects.filter(title__icontains=keyword) data = serializers.serialize("json", company, fields=('title')) return JsonResponse({'data':data,}) ajax request $.ajax({ url: '/browse_jobs', data: { 'keyword': keyword, }, dataType: 'json', success: function (data) { if (data) { console.log(data.title); } } }); and i am getting this response from django {"data": "[{\"model\": \"app.company\", \"pk\": 1, \"fields\": {\"title\": \"Facebook\"}}, {\"model\": \"app.company\", \"pk\": 2, \"fields\": {\"title\": \"Fabook\"}}]"} my question is how i can access the title. -
How to enable django form fields based on check box input?
This is my django dynamic form which generates field based on the given csv file column. class SetFeatureForm(forms.Form): def __init__(self, project=None, *args, **kwargs): super(SetFeatureForm, self).__init__(*args, **kwargs) if project: choices = [(column,column) for column in pd.read_csv(project.file.path).columns] self.fields['feature'] = forms.MultipleChoiceField(choices=choices, required=True, ) self.fields['feature'].widget.attrs['size']=len(choices) for _,choice in choices: self.fields[choice] = forms.ChoiceField( choices=DATA_TYPE.items()) I have to enable all the fields based on the field 'feature' which is MultipleChoiceField. Based on the selection I have to enable the 'choice' field. How can I do that, Thanks in advance. -
python virtualenv env variable error windows 10
I am trying to set environment variables in my python 3 virtual environment, by setting them in the activate file. (I am setting them for my development environment in this case.) Having activated the virtualenv (env/scripts/activate), seeing "(venv)" at the beginning of my powershell lines, I run: python manage.py runserver In the manage.py file I have specified the settings file to use. And the content of that settings file I will show down below in this post. The variables are meant to be passed to my Django application, but I get the following error: django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty. Searching the internet, and mainly SO, I find different approaches to setting environment variables, but each gives the same error. So I wonder what I am doing wrong. What I have tried: It seems I have to set the environment variables in the 'activate.bat' file located at 'env/scripts/activate.bat'. I have tried different ways of doing this, and I have tried the same ways in this file: 'env/scripts/activate' (without the .bat extension), just to be sure. I have tried adding lines of the formats found below, to the end of the activate files: set "SECRET_KEY=^af*$gsdgaGJA4gg($g134FADGJ" set SECRET_KEY=^af*$gsdgaGJA4gg($g134FADGJ export SECRET_KEY="^af*$gsdgaGJA4gg($g134FADGJ" … -
Django auth module for custom login
I'm using django authentication module and creating custom login now I can able to login but after I login if I refresh that page the page showing the user as anonymous user. How to maintain the loggedin user session How to use cookie here? -
How to install django cms in Anaconda/Conda?
When I try to install Django cms in conda with conda install -c auto djangocms-installer I get the following error message: UnsatisfiableError: The following specifications were found to be in conflict: - anaconda==5.2.0=py36_3 - djangocms-installer How to install django cms in Anaconda/Conda? -
aiortc Django integration
I would like to integrate aiortc inside a django app to enable P2P video chat with screen sharing. Could someone point me in the right direction to get started? I looked at the docs, but it isn't that beginner friendly. -
Django time reformat
I have a pair of time field input in my Django forms. I wanted to create the form in a way that allows the user to enter the time in which ever format he would like and the program will reformat to the correct type. Not sure what is the best way to go. using Django validation but user do not get feedback about input. using html5 time input, sounds promising but it has poor support for IE, which users are expected to use. Javascript/jquery but the user can change the Javascript code to bypass client side validation. Any suggestions -
Django views load before calling url
My problem is that my Django view just loads one time at the start of the program. When I call the url the program doesn't load it anymore. Hope anyone can help me. -
Django Table view from pandas dataframes
I can't seem to find the best or easiest way to add a pandas dataframe to a django project without going through the full model specification. My project has plenty of one off computations which I would like to be able to visualise in a sortable/easy to use table view. -
Django ORM Issue: Same Query Set on 2 different views runs as drastically different speeds
Hopefully this is an easy answer: I have Two views--one part of the admin site, and the other a publicly accessible view. They both perform the same set of queries--literally copy and pasted code. masterQuery = myObject.objects.filter(is_public=True) newQuery = queriedForms.filter(ref_to_parent_form__record_reference__form_name__icontains=term['TVAL'], ref_to_parent_form__record_reference_type__pk=rtypePK) newQuery = newQuery.filter(flagged_for_deletion=False) term['count'] = newQuery.count() masterQuery = (newQuery & masterQuery) singleQueryStats['intersections'] = masterQuery.count() Each view has this exact same code--it's not the prettiest query--but regardless: On the admin view--this runs in less than like a 1/4 second. On the public Views.py view--it takes 8 minutes. I cannot figure out why. The queryset.query output is the same. The variables(admin submitted through POST/Public submitted through GET) also match. Please Haaaaaalp -
How does DRF turn off CSRF-token check for JWT-based authentication?
I'm using Django Rest Framework with JWT as authentication mechanism. As far as I've understood, using JWT authentication makes the CSRF-token check not necessary as long as the token is not stored in a cookie. However, checking the django-rest-framework-jwt code and the Django CsrfViewMiddleware I don't understand which part of the code turns off the CSRF-token check for JWT-based authentication. Does somebody know and can point to the relevant parts of the code? -
how can we search many to many field in django admin search field
Here, I have a many to many field define in Django model and I want to search that many to many field in my Django admin search field. As we cannot place many to many field in the 'search_fields=[]' of the customise djangomodelAdmin class.If anyone have the solution please give some suggestions. -
Django template tag to add GET parameters from current request to url in Python3+Django2
I'm trying to migrate my project from Python 2.7/Django 1.11 to Python 3.7/Django 2.1. In my project I've used 'add_get_parameter' template tag from the following django snippet: https://djangosnippets.org/snippets/2428/ add_get_parameter.py class AddGetParameter(Node): def __init__(self, values): self.values = values def render(self, context): #req = resolve_variable('request',context) #deprecated in modern Django req = template.Variable('request').resolve(context) params = req.GET.copy() for key, value in self.values.items(): params[key] = Variable(value).resolve(context) return '?%s' % params.urlencode() @register.tag def add_get_parameter(parser, token): from re import split contents = split(r'\s+', token.contents, 2)[1] pairs = split(r',', contents) values = {} for pair in pairs: s = split(r'=', pair, 2) values[s[0]] = s[1] return AddGetParameter(values) And in templates I've used it to make pagination urls like this: {% load add_get_parameter %} <div class="pagination"> <span class="step-links"> {% if device_tests.has_previous %} <a href="{% add_get_parameter page=device_tests.previous_page_number %}">Previous</a> {% endif %} {% for num in device_tests.paginator.page_range %} {% if num == device_tests.number %} <span class="current"><b>{{ num }}</b></span> {% else %} <a href="{% add_get_parameter page=num %}"> {{ num }}</a> {% endif %} {% endfor %} {% if device_tests.has_next %} <a href="{% add_get_parameter page=device_tests.next_page_number %}">Next</a> {% endif %} </span> </div> It all works in Python 2.7/Django 1.11 but it doesn't in Python 3.7/Django 2.1. Django complains: Exception Type: AttributeError Exception Value: 'int' … -
TypeError at /accounts/create/ 'odict_values' object does not support indexing
Hi i'm getting the above error when submitting the final form in a wizard to save to my models.py. Please see my code below. Any assistance to resolve this is highly appreciated. models.py class Item(models.Model): user=models.ForeignKey(User, on_delete=models.DO_NOTHING) price=models.DecimalField(max_digits=8,decimal_places=2) image=models.ImageField(upload_to="assets/",blank=True,storage=img) description=models.TextField(blank=True) def __unicode__(self): return '%s-%s' %(self.user.username, self.price) forms.py class FirstForm(forms.Form): id = forms.IntegerField(widget=forms.HiddenInput, required=False) price = forms.DecimalField(max_digits=8, decimal_places=2) #add all the fields that you want to include in the form class SecondForm(forms.Form): image = forms.ImageField(required=False) class ThirdForm(forms.Form): description = forms.CharField(widget=forms.Textarea) views.py class MyWizard(SessionWizardView): template_name = "registration/wizard_form.html" file_storage = models.img #if you are uploading files you need to set FileSystemStorage def done(self, form_list, **kwargs): for form in form_list: print(form.initial) if not self.request.user.is_authenticated: raise Http404 id = form_list[0].cleaned_data['id'] try: item = Item.objects.get(pk=id) ###################### SAVING ITEM ####################### item.save() print(item) instance = item except: item = None instance = None if item and item.user != self.request.user: print("about to raise 404") raise Http404 if not item: instance = Item() for form in form_list: for field, value in form.cleaned_data.iteritems(): setattr(instance, field, value) instance.user = self.request.user instance.save() return render_to_response('wizard-done.html',{ 'form_data': [form.cleaned_data for form in form_list], }) def edit_wizard(request, id): #get the object item = get_object_or_404(Item, pk=id) #make sure the item belongs to the user if item.user != request.user: … -
third party authentication with facebook
I am trying to use facebook login for my website but it gives me an error like this:"URL blocked: This redirect failed because the redirect URI is not white-listed in the app's client OAuth settings. Make sure that the client and web OAuth logins are on and add all your app domains as valid OAuth redirect URIs." -
Django memory leak with large queries
First things first; Debug = False in my settings file I am using iterator to go over rows in queryset Python 2.7, Django 1.11.12, Ubuntu 16.04, Database Postgresql, Nginx + Gunicorn I have an endpoint in my application where I run a large query on the database. When a request arrives, I run a query that returns a large number of rows from a large table, go over the results using iterator and construct a list out of the rows, and return the list. I track the memory usage of my Django processes and here is what happens: Initially, each process consumes around 40 MBs of memory When I run the query for the first time, memory usage goes up to around 700 Mbs Second time I run the query (assuming the request landed in the same process), memory usage goes up to around 1400 MBs. And it goes on like this until the server is out of memory. There seems to be a memory leak here but I couldn't find what is causing it. This is my my view does simply: results = Model.objects.filter(a=1, b=2).values('a', 'b', 'c').order_by('c') result_list = [] for row in results.iterator(): result_list.append(row) return Response({'body': result_list}) Any … -
Django - How to track if a user is online/offline in realtime?
I'm considering to use django-notifications and Web Sockets to send real-time notifications to iOS/Android and Web apps. So I'll probably use Django Channels. Can I may use Django Channels to track user online status in real-time? How I can achieve this without polling constantly the server? I'm looking for a best practice, but I wasn't able to find any proper solution. -
Django - TypeError after creating object
I have a Profile model which has a OneToOneField with the User model. This is the model: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) branch = models.CharField(max_length=10) section = models.CharField(max_length=10) optedCourses = models.ManyToManyField(Course, blank=True) Now, I am using this serializer to POST data: class ProfileSignupSerializer(serializers.ModelSerializer): user = UserSerializer(required=True) class Meta: model = Profile fields = '__all__' def create(self, validated_data): # import ipdb # ipdb.set_trace() user_data = validated_data.pop('user') user = User.objects.create_user(**user_data) optedCourses = validated_data.pop('optedCourses') profile = Profile.objects.create(**validated_data, user=user) if optedCourses: profile.optedCourses.set(optedCourses) return Profile The problem here is right after the objects are created, I am getting this error int() argument must be a string, a bytes-like object or a number, not 'DeferredAttribute' I am unsure of where I am getting this error from. This is the traceback: Traceback (most recent call last): File "C:\Users\Sreekar Mouli\Documents\Mini Project\Backend\venv\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\Sreekar Mouli\Documents\Mini Project\Backend\venv\lib\site-packages\django\core\handlers\base.py", line 126, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\Sreekar Mouli\Documents\Mini Project\Backend\venv\lib\site-packages\django\core\handlers\base.py", line 124, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Sreekar Mouli\Documents\Mini Project\Backend\venv\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "C:\Users\Sreekar Mouli\Documents\Mini Project\Backend\venv\lib\site-packages\django\views\generic\base.py", line 68, in view return self.dispatch(request, *args, **kwargs) File "C:\Users\Sreekar Mouli\Documents\Mini Project\Backend\venv\lib\site-packages\rest_framework\views.py", line 483, in dispatch response = self.handle_exception(exc) … -
Sqlite3 django error
Datatype mismatch i got this error with this query what's wrong with it please do correct me cursor.execute('''INSERT INTO aioapp_output SELECT username, meaning , NULL FROM aioapp_name N JOIN aioapp_meaning1 T ON N.userid = T.userid ''') -
Is need to change DB in unit test cases - python django
I am creating unit test cases now.. I create delete API.. Its working fine with Post Man. Its delete the the Record... But Its do not delete Report when I run this in test case.. Its wrong something or its normal behaviour in test cases. I am creating this test cases in python.. Thanks in Advance -
Python library for adding a digital signature to pdf doc given a private key file(.pem) and certificate file (.pem)
Is there any python library available by using that i can add digital signature to pdf(using certificate file and private key file). -
'<' not supported between instances of 'method' and 'method'
I'm trying to do Winerama Recommender Tutorial . I met a error which I can't solve. When I try to go to the tab 'recommendation list' the browser returned the following error. Error Environment: Request Method: GET Request URL: http://127.0.0.1:8000/recommendation/ Django Version: 2.0.7 Python Version: 3.7.0 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'bootstrap3', 'reviews', 'registration'] Installed 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'] Traceback: File "C:\Users\tymot\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\exception.py" in inner 35. response = get_response(request) File "C:\Users\tymot\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\base.py" in _get_response 128. response = self.process_exception_by_middleware(e, request) File "C:\Users\tymot\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\base.py" in _get_response 126. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\tymot\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\contrib\auth\decorators.py" in _wrapped_view 21. return view_func(request, *args, **kwargs) File "C:\Users\tymot\Desktop\Cd-12.50-20.08\env\my_app\winerama\reviews\views.py" in user_recommendation_list 89. reverse=True Exception Type: TypeError at /recommendation/ Exception Value: '<' not supported between instances of 'method' and 'method' I created everything according to the steps in the tutorial. File moodels.py class Cluster(models.Model): name = models.CharField(max_length=100) users = models.ManyToManyField(User) def get_members(self): return "\n".join([u.username for u in self.users.all()]) Next i added admin.py and create 3 klaster with users in '/admin'. from django.contrib import admin from .models import Wine, Review, Cluster class ReviewAdmin(admin.ModelAdmin): model = Review list_display = ('wine', 'rating', 'user_name', 'comment', 'pub_date') list_filter = ['pub_date', 'user_name'] search_fields = ['comment'] class ClusterAdmin(admin.ModelAdmin): model = Cluster list_display … -
django register user as superuser
I am using a OneToOne relationship to create a custom user like this: class Patient(models.Model): user = models.OneToOneField(Django_User, on_delete=models.CASCADE) models.PositiveSmallIntegerField(choices=USER_TYPE_CHOICES) birthday=models.DateField(auto_now=False, null=True, blank=True) USERNAME_FIELD='username' def __str__(self): return self.user.username def save(self, *args, **kwargs): super(Patient, self).save(*args, **kwargs) def set_birthday(self, birthday): birthday = self.birthday Now there have been some additions to my task and i need to give every user is_staff or is_superuser permissions. I created a form: class UserPermissionForm(forms.Form): permission = [(1, 'Patient'), (2, 'Lieferant'), (3, 'Andere'), (4, 'Mitarbeiter'), (5, 'Admin')] Zugriffsrechte = forms.ChoiceField(choices= permission, widget=forms.Select()) And tried setting the permissions in my view - genericform is just the usual django user creation form, form is the form where the birthday is set and permission is the form seen above: def register_user_view(request): title="Register User" genericform = GenericCreationForm(request.POST or None) form=UserRegisterForm(request.POST or None) permission = UserPermissionForm(request.POST or None) if form.is_valid() * genericform.is_valid() * permission.is_valid(): genericform.save() username = genericform.cleaned_data.get('username') raw_password = genericform.cleaned_data.get('password1') user_type = int(request.POST.get('Zugriffsrechte')) new_user = authenticate(username=username, password=raw_password) profile = form.save(commit=False) profile.user = new_user profile.save() is_superuser = False is_staff = False if user_type > 3: is_staff = True print('YOU SHALL BE STAFF') if user_type > 4: is_superuser = True print('YOU SHALL BE ADMIN') profile.user.is_staff = is_staff profile.user.is_superuser = is_superuser login(request,profile.user) return redirect("/register/done") context={ … -
Django 2.0: Get queries dynamically from search
I am new to django framework and as a practice project I am trying to build an ecommerce website using django. I have a class based view for my search page. I wrote the view to get the query for a particular query. views.py class SearchProductView(ListView): template_name = "products/product_list.html" queryset = Product.objects.filter(title__icontains='book') print(queryset) I would like to know how I can write a function to get the search queries dynamically. For eg: If i search 'book', then my queryset should contain all things book and if I search 'car', then I should get all things car. template.html {% extends "base.html" %} {% block content %} <div class='row'> {% for object in object_list %} <div class='col'> {{ forloop.counter }} {% include 'products/snippets/card.html' with instance=object %} </div> {% endfor %} </div> {% endblock %} urls.py from django.urls import path from . import views from .views import ( SearchProductView, ) app_name = 'search' urlpatterns = [ path('', SearchProductView.as_view(), name='search_page'), ]