Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Unresolved attribute reference 'objects'
In models.py I have class Memo: class Memo(models.Model): MonthName = models.ForeignKey(Months, on_delete=models.CASCADE) ProjectName = models.ForeignKey(Project, on_delete=models.CASCADE) Hours = models.IntegerField(blank=True, null=True) # ProjectManager = models.ForeignKey(ItEmployee, on_delete=models.CASCADE) def __str__(self): return str(self.MonthName) + ' - ' + str(self.ProjectName) In views.py I am getting warning Unresolved attribute reference 'objects' for class Memo: from django.http import HttpResponse from History.models import Memo def memos(request): all_memos = Memo.objects.all() html = '' for memo in all_memos: url = '/memo/' + str(Memo.MonthName) + '/' html += '<a href="' + url + '">' + Memo.ProjectName + '</a><br>' return HttpResponse(html) -
Django: FieldError: Invalid field name(s) for model
When i'm trying to use update or create query it's gives error FieldError: Invalid field name(s) for model Here it is my models.py class Mymodel(Base): name = models.CharField(max_length=50) query = models.TextField() args = models.TextField() server_details = models.TextField() Now I want to update or create query of Mymodel Here it is my data dict kwargs={ "name": "PQR", "query": "ABC", "args": "{}", "server_details": "XYZ" } Here I'm trying to do obj, created = Mymodel.objects.update_or_create( id=params.get('id'), defaults=kwargs ) When I'm trying to update_or_create its gives following error FieldError: Invalid field name(s) Mympdel: 'name', 'query' -
Update View showing blank forms when I try to edit in my Django website
So I'm creating a django website and I have a button of edit. After the edit is clicked there is pop up with a few forms to edit. The problem is that the forms to edit are blank! instead of having the previous data. for example- ServerName="Yossi" When I click edit instead of having "Yossi" in the form I have nothing. models.py - from django.db import models # Create your models here. class serverlist(models.Model): ServerName = models.CharField(max_length = 30) Owner = models.CharField(max_length = 50) Project = models.CharField(max_length = 30) Description = models.CharField(max_length = 255) IP = models.CharField(max_length = 30) ILO = models.CharField(max_length = 30) Rack = models.CharField(max_length = 30) Status = models.CharField(max_length = 30) #date = models.DateTimeField(auto_now=True) views.py - # Create your views here. from django.shortcuts import render_to_response from django.shortcuts import render, redirect from django.template import RequestContext from django.views.generic import TemplateView, UpdateView, DeleteView, CreateView from DevOpsWeb.forms import HomeForm from DevOpsWeb.models import serverlist from django.core.urlresolvers import reverse_lazy from simple_search import search_filter from django.db.models import Q class HomeView(TemplateView): template_name = 'serverlist.html' def get(self, request): form = HomeForm() query = request.GET.get("q") posts = serverlist.objects.all() if query: posts = serverlist.objects.filter(Q(ServerName__icontains=query) | Q(Owner__icontains=query) | Q(Project__icontains=query) | Q(Description__icontains=query) | Q(IP__icontains=query) | Q(ILO__icontains=query) | Q(Rack__icontains=query)) else: posts … -
Ajax making a get after a post in Django
I am trying to update a product list using Ajax once a user submits a new product. I have an Ajax get once the page loads (to initially load all the products and populate a <li> with them) and require this function once again when a user adds a product, so it is displayed instantly without refresh. Currently upon success of ajax post (form completion and submission) in the success: function() I call the following (get/ being a URL where I return a JsonResponse) $.ajax({ type: 'POST', url: 'new/', data: product_data, success: function () { $.get("get/", function(data) { $.each(data, function(i, product) { console.log("i:" + i, "product: " + product) }); }); } }); This returns me the objects I require however I only want to append the last object to the <li> in my HTML or I'd be adding another list of duplicates. How could I do this effectively? -
Django Admin: How to enable the use of the CustomManager() of the related to the inline model?
class MainModel(models.Model): pass class ThirdModel(models.Model): objects = CustomManager() def __str__(): # Here I use the to_attr defined in the CustomManager() class ChildModel(models.Model): main_key = models.OneToOneField(MainModel) content = models.ManyToMany(ThirdModel) ChildModelInline(admin.TabularInline): model = ChildModel MainModelAdmin(admin.ModelAdmin): model = MainModel inlines = (ChildModelInline, ) In the admin page, when I add a new ThirdModel using the default SelectMultiple widget of the ChildModelInline in the MainModelAdmin instance, apparently, the CustomManager() of the ThirdModelis not used. Details of the ThirdModel: The CustomManager has a Prefetch() with to_attr attribute. The calls to this attribute in the __str__() method raise an AttributeError. The above happen only when I save the added new entry. Otherwise, the names of the available instances appear without errors in the widget. -
Django Get and Filter
I have a design question on django. Can someone explain to me why the Django ORM 'get' doesn't return a queryset? To the best of my understanding, a queryset should/is the result of a db query. With that logic, isn't a get query a queryset? Also, from my research towards this question, I found out the get query calls the model manager while the queryset doesn't. Is there a reasoning behind all of this? -
Django Middleware breaking form submission?
When I add middleware, the forms on the page with templateresponse stop working: submission causes loading for several minutes, and then results in a load-balancer error. The form, process_img method, and bot view all work exactly as expected when the middleware isn't defined in settings.py. The code: In settings.py: 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' 'polls.views.ExampleMiddleware' ] MIDDLEWARE_CLASSES = [ 'polls.views.ExampleMiddleware' ] Middleware definition in views.py: class ExampleMiddleware(MiddlewareMixin): def __init__(self, get_response): self.get_response = get_response def __call__(self, request): response = self.get_response(request) return response def process_template_response(self, request, response): if 'right' in request.POST: response.context_data['response'] = 'Sweet, thanks!' elif 'wrong' in request.POST: response.context_data['response'] = 'Awww, sorry' return response Relevant view in views.py: def bot(request): img_form = ImageUploadForm() context = {'img_form':img_form} if request.method=='POST': img_form = ImageUploadForm(request.POST, request.FILES) if img_form.is_valid(): myfile = request.FILES['image'] context = process_img(myfile) return TemplateResponse(request, 'polls/bot.html',context) return TemplateResponse(request, 'polls/bot.html',context) Details: Python 3.5, Django 1.11, hosting on Python anywhere. What's breaking the form submission and how do I fix it? -
Django Pyrebase
I am trying to connect my Django website with firebase. There is not enough material for that,luckily I got this https://github.com/thisbejim/Pyrebase but I am not able to understand where to write this code .I am newbie to Django. I have written this code in pyrebase.py file: import pyrebase config = { apiKey: "AIzaSyD0kwTsifJAL3C7mTj6Hil6Lfutes0jdEo", authDomain: "minor1-5e62c.firebaseapp.com", databaseURL: "https://minor1-5e62c.firebaseio.com", projectId: "minor1-5e62c", storageBucket: "minor1-5e62c.appspot.com", messagingSenderId: "69802125895" }; firebase=firebase.initializeApp(config); and when I am running it on python terminal,I am getting this error: Traceback (most recent call last): File "D:\Django2\mysite1\personal\dd.py", line 4, in apiKey: "AIzaSyD0kwTsifJAL3C7mTj6Hil6Lfutes0jdEo", NameError: name 'apiKey' is not defined I have my project evaluation on 13th November . Someone please help me. -
Return all foreign keys used in this queryset
I'm struggling to explain what I want to do (hence I am unable to actually find a post about this) so hopefully someone can help me out. I have couple models and all are tied to the Product model class Product(models.Model): category = models.ManyToManyField(Category) collection = models.ForeignKey(Collection) item_type = models.ForeignKey(ItemType) colour = models.ManyToManyField(Colour) product_name = models.CharField(max_length = 250, default='') product_name_pl = models.CharField(max_length = 250, default='') last_updated = models.DateTimeField(auto_now_add=False, auto_now=True) active = models.BooleanField(default=True) product_comment = models.CharField(max_length = 300, default='', blank=True) product_comment_pl = models.CharField(max_length = 300, default='', blank=True) display_order = models.PositiveIntegerField(blank=True) def __str__(self): return self.product_name e.g. class Collection(models.Model): collection_name = models.CharField(max_length = 250) slug = models.SlugField(unique=True, default='m') description = models.TextField(blank=True) image = models.FileField(upload_to='images/collections/', blank=True) collection_type = models.ManyToManyField(CollectionType) display_order = models.PositiveIntegerField(default=999) def __str__(self): return self.collection_name or class Colour(models.Model): colour_name = models.CharField(max_length = 250) slug = models.SlugField(unique=True, default='m') description = models.TextField(blank=True) image = models.FileField(upload_to='images/types/', blank=True) def __str__(self): return self.colour_name The idea is when I retrieve a set of products by using the Collection, I want to have a list of available colours in the current selection and maybe a count of how many of each product each colour has. What I'm mostly looking for is a point towards a correct direction in the queryset … -
how to set a method in Django rest framework's veiwSet not require authentication
I have viewset like below : from rest_framework import viewsets from paas.serializers import UserSerializer import logging logger= logging.getLogger(__name__) class UserViewSet(viewsets.ViewSet): def list(self,request): pass def create(self,request): logger.info(request.data) current_user = UserSerializer.create() also, I use the DRF Token based authentication in my code. how can I simply say that this create method don't require authentications? as you know after implementing authentication with the token, all request's should have Token in header's, and any request dosn't have will get 403 error. -
How to set password in user table when user is signup using google or facebook django allauth
By overriding the SocialAccountManager def save_user(self, request, sociallogin, form=None): """ Saves a newly signed up social login. In case of auto-signup, the signup form is not available. """ u = sociallogin.user u.set_unusable_password() if form: get_account_adapter().save_user(request, u, form) else: get_account_adapter().populate_username(request, u) sociallogin.save(request) return u how to get the password from social account signup -
Django - Statit files don't serve in production
My site works well in local but when I put it on my server, it can't load the static files. Here's my files. settings.py DEBUG=False STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' All my static are in /myproject/mymainapp/static I've got another directory "static" of the root of my project by doing manage collectstatic in production. Here's my nginx conf file : [...] root /home/user/site/mymainapp/; [...] location /static { alias /home/user/site/mymainapp/static; } I've tried to set the path to my static directory in my root directory project but it don't make anything better. My URLs patterns : urlpatterns = [ [...] nothing relative to static files ] Maybe I should add something in my URLs patterns ? Thanks for your help :) -
passing empty queryset to form results in form_invalid
I have a model form that contains among other things a dropdown list of pupils (ModelMultipleChoiceField), which is initially empty but when a user selects a teacher, I get the list of pupils registered for this teacher via ajax request. self.fields['pupil'] = forms.ModelMultipleChoiceField(queryset=Pupil.objects.none(),) Everything works till the validation. Since initially queryset points to none, when a form is submitted it is returned with an error "It is invalid choice". I can pass the entire set of pupils to the pupil field and then make it empty via jQuery but that looks ugly. What is the right way of doing it? -
Django __str__ returned non-string (type NoneType)
I am getting __str__ returned non-string (type NoneType) error at edit Product Model object Product Model class Product(models.Model): ProductName = models.CharField(blank=True, max_length=250) Price = models.FloatField(blank=True, default=9.99) Tax = models.FloatField(blank=True, null=True, default=0.0) StoreId = models.IntegerField(blank=True, null=True) RelatedStore = models.ForeignKey(Store, blank=True, null=True) Category = models.CharField(max_length=200, blank=True, null=True, default='No Specific Category') ProductImage = models.CharField(max_length=400, null=True, blank=True) Features = models.TextField(blank=True, null=True) ProductSize = models.IntegerField(blank=True, null=True, default=3) FavoriteField = models.BooleanField(blank=True, default=False) Active = models.BooleanField(blank=True, default=True) def __unicode__(self): return self.ProductName def __str__(self): return self.ProductName Any helpful answer will be appreciated. -
request.user.is_authenticated always return false in python/django
its been 5 days strugling with this.It was working well at first but suddenly it started giving me some erros that i couldn't understand so i started modifying my code from MyCustomUser model and custom authentication backend but still i cant figure this problem. What surprise me is that when i register users with sign_up function, the line " if user is not None and request.user.is_authenticated:" return false and it doesn't log in the user after sign up, but when i open django shell and test if user.is_authenticated it return True and user.is_anonymous return False. Can please anyone help me identify what is the problem here. Please fellow django developers. bellow is my sign_up view: def sign_up(request): if request.method == 'POST': form = SignUpForm(request.POST) if form.is_valid(): new_user = form.save(commit=False) #create string of first_name an last_name full_name = '{0} {1}' .format(new_user.first_name, new_user.last_name) #Slugify full name new_user.slug = slugify(full_name) new_user.save() email = request.POST.get('email') raw_password = request.POST.get('password1') #Authenticate the user user = authenticate(email=email, password=raw_password) if user is not None and request.user.is_authenticated: login(request, user) #Redirect to success url after user has successfully is logged in. return HttpResponseRedirect(reverse_lazy('jogos:question-list')) else: form = SignUpForm() return render(request, 'jogos/sign_up.html', {'form':form}) from jogos.models import MyCustomUser from django.contrib.auth import get_user_model And … -
Current user as a comment's autor (DJANGO)
I have create a model called 'Comentario' where the logged user can create his own comment. How can I do to automatically save as the author of the comment the logged user. Here I show my schema: models.py class Comentario (models.Model): titulo = models.CharField(max_length=50) texto = models.CharField(max_length=200) autor = models.ForeignKey (Perfil, editable=False, blank=True) fecha_publicacion = models.DateTimeField(auto_now_add=True) tag = models.ManyToManyField(Tags, blank=True) def __str__(self): return (self.titulo) views.py class ComentarioCreate (LoginRequiredMixin,CreateView): model = Comentario form_class = ComentarioForm template_name = 'home/comentario_form.html' success_url = reverse_lazy ('home:listar') def save(self): autor=self.request.user.username user.save() forms.py class ComentarioForm(forms.ModelForm): class Meta: model = Comentario fields = [ 'titulo', 'texto', 'tag', ] labels = { 'titulo': 'Titulo', 'texto' : 'Descripcion', 'tag' : 'Etiquetas', } widgets = { 'titulo':forms.TextInput(attrs={'class':'form-control'}), 'texto':forms.TextInput(attrs={'class':'form-control'}), 'tag':forms.CheckboxSelectMultiple(), } Perfil is a model which inherits form AbstractUser. models.py class Perfil(AbstractUser): nom_puesto = models.ForeignKey(Puesto, blank = True) def __str__(self): return '{}'.format(self.username) How can I do to have in the field 'autor' the username of the logged user? thank you for your answer! -
django - load currently logged in user information in the form
django noob here. The question i am going to ask has been asked several times, however, i couldn't find the answers which can help my case. the query is: I have a Form having a choice field which loads its choices information from the database. Basically, I have designed my models in such a way that, the choices displayed is individual to the users. for example: for user1, the choice field shows a,b,c,d. where as for user 2, the choice field shows v,w,d. The problem i am facing is referencing the logged in user and getting the username. then pass the username as the filter to the database. I have come across numerous init functions trying to do this, somehow it is not helping my case. forms.py class class_model(forms.Form): class_name = forms.ChoiceField( required=False, widget=forms.Select, ) def __init__(self, user, *args, **kwargs): self.user = user super (class_model, self).__init__(*args, **kwargs) current_user = self.user name = current_user.username k = User.objects.get(username=name) y = UserProfile.objects.get(user=k) schoolid = y.schoolid primary_filter = Class1.objects.filter (school_id=schoolid) ax = [("Choose Class", "Choose Class")] + list (primary_filter.objects.values_list ('class_name', 'class_name').distinct()) self.fields['class_name'].choices = ax The error i receive: 'QueryDict' object has no attribute 'username' -
Django: ManyToMany relationship and database duplicity
So I have models GeneralUser, Business, Brand, Bottle. class Business(models.Model): name = models.CharField(max_length=100, blank=False) owner = models.ForeignKey(GeneralUser, on_delete=models.CASCADE, blank=False, related_name="businesses") class Brand(models.Model): name = models.CharField(max_length=150, blank=False, unique=True) businesses = models.ManyToManyField(Business, related_name="brands", blank=False) class Bottle(models.Model): name = models.CharField(max_length=150, blank=False) slug = models.SlugField(max_length=550, default="", null=False, blank=False) brand = models.ForeignKey(Brand, on_delete=models.CASCADE, blank=False, related_name="bottles") Each Brand can belong to many businesses, and each Business can hold many brands. My goal is to not have Brand objects created if they already exist in the database. I've built a Bottle ModelForm which also allows the user to choose and create a new Brand in the process. But the problem I'm facing now is this: Users only see brands associated with the Business. User 1 created Brand X → OK User 2 tries to create Brand X → IntegrityError unique constraint failed. Which I totally understand and not surprised by. My question is what's the best solution in this case? -
How to get specific field from serializer of Django rest framework
Inside Views.py, I have these code: class ServerViewSet(viewsets.ViewSet): def list(self, request): servers = Server.objects.all() serializer = ServerSerializer(servers, many=True) return Response(serializer.data) # In here, I want to get the server name only def retrieve(self, request, pk=None): servers = get_object_or_404(Server, pk=pk) serializer = ServerSerializer(servers) return Response(serializer.data) # In here, I want to get the server name and ip address Inside serializers.py, I have these code: class ServerSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Server # fields = '__all__' fields = ('id', 'name', 'desc', 'ip_address') Is there an official method to filter out the specific field from serializers.data -
Сelery hangs on startup
I'm trying to use real-time processing with a Django app that is configured as specified in the documentation. Without my_monitor() functions from the example, celery works fine, but as soon as I add this function it doesn't run. Project struct: - proj/ - firstapp/ - manage.py - proj/ - __init__.py - celery_config/ - __init__.py - main.py - ... - celery.py - settings.py - urls.py - ... - ... In celery.py file I have the following code that works: from __future__ import absolute_import import os from celery import Celery from . import celery_config as config os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'proj.settings') celery_app = Celery('proj') celery_app.config_from_object(config) celery_config stored broker_url, queues, routers, shedule and etc. Run celery: $ celery -A proj ... and in this form it works fine then I add the function in celery.py: def celery_logger(app): state = app.events.State() def logging_task_received(event): state.event(event) task = state.tasks.get(event['uuid']) # here I want to add your own log entry in db with app.connection() as connection: recv = app.events.Receiver(channel=connection, handlers={ 'task-received': logging_task_received, }) recv.capture(limit=None, timeout=None, wakeup=True) celery_logger(celery_app) and now, it hangs when you call celery -A proj ... -
Django ManytoManyField and widgets
I have two models, Product and Category and ManytoMany field in Product. The Category appear as key on ProductCreate View. I need to customize the widget and field for Categories. I checked in Django source Fields and Widgets but I don't see a reference(class) for ManyToMany. To what type of Field and Widget ManyToMany relationship corresponds(I presume is Charfield as save or SelectField)? Where I can find the code ? (an example to customize field/widget in this case) -
Django: Cannot display object image in DetailView
As you see in shot-screens the object image is shown in ListVIew. but I don't have access to this image in DetailView with same url. List View: {% for team in teams %} <tr> <td>{{ forloop.counter }}</td> <td><img src="{% thumbnail team.logo 30x30 %}" alt=""> {{ team.name }}</td> .... Detail View: ... <h3 class="page-header"><img src="{% thumbnail team.logo 30x30 %}">{{ team.name }}</h3> ... -
Get data from 2 Model in Django python
class Product(models.Model): name = models.CharField(max_length=200) price = models.FloatField() avgrating = models.FloatField() def __str__(self): return self.name class Rating(models.Model): Product_id = models.ForeignKey('Product', related_name='Product_id') User_id = models.ForeignKey('User', related_name='User_id') rate = models.IntegerField() I want like - name of the product - price of the product - avgrating (AVG rating) - depend on User_id and Product_id and SQL query like: select p.name,p.price,p.avgrating,r.rate from Product p, Rating r where User_id=1; out Like: in json formate { "name":"Iphone 8", "Price":80000, "avgrating":3.5, "rate":5 } -
I want to use wpadmin in django but having an issue
Hello everyone I want to integrate wpadmin by barszczmm into my django project but in his documentation he has written Add django.core.context_processors.request to TEMPLATE_CONTEXT_PROCESSORS setting. Icannot exactly understand what this means . I tried by adding this line django.core.context_processors.request in setting.py under templates -> 'context_processors' but nothing happened and server gives the exception InvalidTemplateLibrary at /admin/ .please tell me exactly what to do -
Django passing variables into string
I'm trying to pass: img src="{% static '/static_dirs/images/itcg/01_{{ card_id }}.jpg' %}" alt="{{ card_id }}"> to load image with file name 01_xx.jpg, but the result is just xx without image. Basically what happens is that {{ card_id }} works in alt but I can't load the image. I have tried to change 01_{{ card_id }}.jpg into 01_01.jpg and it works, so the static files can load properly but apparently 01_{{ card_id }}.jpg is not working as intended. I also tried to changing one of my image name from 01_01.jpg into 01.jpg and do the following: img src="{% static '/static_dirs/images/itcg/{{card_id}}.jpg' %}" alt="{{ card_id }}"> The image still not loading, so I guess the problem is not in "01_" part either. Can someone help?