Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django file upload with Bill Id
I'm new to Django and i'm working on uploading files. when uploading my files, the saving is working perfectly. but problem is i need to associate every aploaded file to a bill id, cause the uploaded file for me is a bill. something like billX_[45] 45 is the bill id in my database. billX is the uploaded file name. in some documentations i found that upload_to helps fo do so, but i still feel confused. my form.py is : class bills(forms.Form): numfacture=forms.CharField() myfile=forms.FileField() model.py class facture_ventes(models.Model): numfac=models.CharField(max_length=20) piece_joint=models.FileField(upload_to = 'FacturesVentes') in my view : if request.method == 'POST' and request.FILES['myfile']: myfile = request.FILES['myfile'] fs = FileSystemStorage() filename = fs.save(myfile.name, myfile) uploaded_file_url = fs.url(filename) return redirect('/veentes', { 'uploaded_file_url': uploaded_file_url }) The FacturesVentes is added to MEDIA_ROOT in the settings Any help please , Thank You So Much -
Is it possible to create two models for User in django
Is it possible to create two models for User in django without Extending User Model because I'm using postgres Replication and it is being used in my auth user and now I need to figure out how to add a type of user but not in the auth user that's the reason that I want to create another table that can have all the rights as auth user. thanks in advance. -
pass a list of object in django form
try: degree = get_list_or_404(Degree,education__user__username=username) except Http404: degree = Degree() degree will have multiple object which contains all the education details of a user. Now i want to send this degree object to form. I know how to pass a single instance of object. views.py def profile_edit(request,username): profile_edit = get_object_or_404(User,username=username) try: userprofile = get_object_or_404(UserProfile,user__username=username) except Http404: userprofile = UserProfile() # education = Education.objects.filter(user__username=username) try: # wanna send this in template degree = get_list_or_404(Degree,education__user__username=username) except Http404: degree = Degree() if request.user == profile_edit and request.user.is_authenticated: if request.method == "POST": form = EditForm(request.POST,instance=profile_edit) form1 = EditForm1(request.POST,instance=userprofile) form2 = EditForm2(request.POST,instance=degree) # how to pass degree ? if form.is_valid() and form1.is_valid() and form2.is_valid(): form.save() form1.save() form2.save() return redirect('profile_edit',username=username) else: form = EditForm(instance=profile_edit) form1 = EditForm1(instance=userprofile) form2 = EditForm2(instance=degree) context = {'form':form,'form1':form1,'form2':form2} return render(request,'userprofile/profile_edit.html', context) else: raise PermissionDenied Here is forms.py for degree :- class EditForm2(forms.ModelForm): class Meta: model = Degree fields = ('degree','major','passing_year','college',) -
Pass parameter to django as_view function
I have one url that passes a parameter through the as_view function: url( r'^$', ChangeListView.as_view( columns=('username', 'email') ), name="user-list" ), When i try to access the columns attribute in the view it returns None instead of the tuple that i have passed through the url class ChangeListView(generic.ListView): columns = None def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) print(self.columns) # Returns None instead of tuple return context -
get users goup name DRF
im trying to show user group name instead of it's id . i have this serilizer class for user class and i used this User = auth.get_user_model() for user Model but it give me error User' object has no attribute 'group' what is correct way to get all users group? class UserSerializer(ModelSerializer): groups = SerializerMethodField() def get_groups(self, obj): return obj.group.name class Meta: model = User fields = [ 'id', 'username', 'first_name', 'last_name', 'email', 'date_joined', 'last_login', 'is_staff', 'is_superuser', 'is_active', 'groups' ] -
Django order by count (@property) in many-to-many?
I have the following classes: class Site(models.Model): articles = models.ManyToManyField(Article, blank=True, null=True) products = models.ManyToManyField(Product, blank=True, null=True) class Product(models.Model): @property def sites_count(self): return self.site_set.count() In my admin I would like to the many to many relationships to be sorted by sites_count. class SiteAdmin(admin.ModelAdmin): def formfield_for_manytomany(self, db_field, request, **kwargs): if db_field.name == "articles": kwargs['queryset'] = Article.objects.order_by('sites_count') return super().formfield_for_manytomany(self, db_field, request, **kwargs) I get complaints that sites_count cannot be used because it's not a column in my db. What is an alternative approach to this? -
How to remove "Delete" checkbox on "extra" forms in Django inline formset
I'm using inline formsets in Django, and for each item showing one "extra" form, for adding another object. The forms for existing objects have "Delete" checkboxes, for removing that object, which makes sense. But also the "extra" forms have these "Delete" checkboxes... which makes no sense because there's nothing there to delete. Inline forms in the Django admin don't show these "Delete" checkboxes for "extra" forms. How can I remove these checkboxes on the "extra" inline forms? The inline formsets part of my template is something like this (simplified, full version here): {% for bookimage_form in form.forms %} {% for hidden_field in bookimage_form.hidden_fields %} {{ hidden_field.errors }} {% endfor %} {{ bookimage_form.as_table }} {% endfor %} And here's the "Delete" checkbox that seems superfluous: -
Where do I import the ExpiredSignatureError error from in django rest framework
I would love to handle that error within my custom authentication backend so, apparently, I have got to import it from somewhere. But I just cannot find where the right module. Any ideas? -
list_filter on auth.user in admin site
I am trying to add list_filter on User model in admin site. Following is the model: class Profile(models.Model): user = models.OneToOneField(User) is_admin = models.BooleanField(default=False) I want to filter the user's based on 'is_admin' flag from Profile model. How can I do this. -
django admin template. Set default value which will come from template
I have url that refers to django admin add, forms. This url for staff only when they click to the url in django admin i need set default value to admin forms which coming from template. For example in template in get request i have this url platforms/nodes/?type=backend&project=1 refers to '<a href='/admin/docs/platform/add/'></a>' when they enter the fields have long been filled field should be auto selected fields should be auto selected I can easly set forms values through get request get.GET.project and get.GET.platform, but how to set admin template forms? I please explain how to do this -
Cannot login at django homepage with Django CutterCookie Template.
I'm using django cookiecutter-django template and i have problem with login function: - createsuperuser is completed. - access http://localhost/accounts/login - perform sign function but django allways return the below image please help me show how to fixed this problem. I take 8 working hours to find out what is cause. -
Wagtail asynchronous call to Page model method from JS
I am trying to implement a lazy load of images in a Wagtail run website. My Page model: class Gallery(RoutablePageMixin, Page): #I have removed all the code for readability @route(r'^gallery/loadImages/') def lazy_load_images(self, request): I want to hit this method with the JS call. pass class Meta: verbose_name = "Gallery" My JS code: (function($) { $('#lazyLoadLink').on('click', function() { var link = $(this); var page = link.data('page'); $.ajax({ type: 'post', url: 'gallery/loadImages/)', data: { 'page': page, 'csrfmiddlewaretoken': window.CSRF_TOKEN // from index.html }, success: function(data) { debugger; }, error: function(xhr, status, error) { debugger; } }); }); }(jQuery)); If I want I can reach all urls in the page model with @route(r'^$') but cannot make it reach the method from the url in the AJAX method. Any idea how to do this? -
Is it possible to assign ticket to default queue on django-helpdesk?
When a ticket is submitted is it possible to assign ticket to default queue on django-helpdesk? -
django and python‘utf-8’ codec can't decode byte 0xb5 in position 5
enter image description here l am first to run django.I new a project without doing nothing and it still have some wrong questions.l found and found ,finally l am dismay. my django is 2.0.3 python is 3.6.4 ‘utf-8’ codec can't decode byte 0xb5 in position 5 -
Running "manage.py compilemessages" in Dockerfile gives "django.db.utils.OperationalError: could not connect to server: No such file or directory"
I have a repo with a django project and want to create a Docker image from it. I also don't want to store any compiled files in git so I try to automate creation of all the artifacts during the Docker image creation. If I insert: RUN python manage.py compilemessages -l en in my Dockerfile I get (note that all dependencies are installed on host machine): Traceback (most recent call last): File "manage.py", line 13, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 338, in execute_from_command_line utility.execute() File "/usr/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 312, in execute django.setup() File "/usr/local/lib/python2.7/site-packages/django/__init__.py", line 18, in setup apps.populate(settings.INSTALLED_APPS) File "/usr/local/lib/python2.7/site-packages/django/apps/registry.py", line 115, in populate app_config.ready() File "/src/playpilot/apps.py", line 21, in ready for ct in ContentType.objects.all(): File "/usr/local/lib/python2.7/site-packages/django/db/models/query.py", line 162, in __iter__ self._fetch_all() File "/usr/local/lib/python2.7/site-packages/django/db/models/query.py", line 965, in _fetch_all self._result_cache = list(self.iterator()) ... File "/usr/local/lib/python2.7/site-packages/psycopg2/__init__.py", line 164, in connect conn = _connect(dsn, connection_factory=connection_factory, async=async) django.db.utils.OperationalError: could not connect to server: No such file or directory Is the server running locally and accepting connections on Unix domain socket "/tmp/.s.PGSQL.5432"? I work this around with running docker-compose in a build script (with entire running environment) docker-compose up -d docker-compose exec web ./manage.py compilemessages -l en docker commit proj_web_1 image_name docker-compose down But … -
Django Model's DateTimeField is taking UTC even when TZ is Asia/Calcutta everywhere
I am using Django 1.11. My settings.py has following configured: TIME_ZONE = 'Asia/Calcutta' which is IST (Indian Standard Time). My system is set to IST. MySQL current_time returns IST, Django's server when running, shows timestamp in IST. Python's datetime.now() also gives IST. Now the problem is, my models.py has following fields: created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) and the database is MySQL. When I insert any record in it, the timestamps are in UTC. I was thinking of adding some middleware, as suggested by this answer, but that doesn't feel to be the recommended way. Why is it taking UTC even when everywhere IST has been configured? Am I missing some config that needs to be set separately for models? -
Create a "trending algorithm" using a model method
I have a Post model with an accompanying PostScore model: class Post(models.Model): ... date = models.DateTimeField(auto_now_add=True) class PostScore(models.Model): user = models.ForeignKey(User, blank=True, null=True) post = models.ForeignKey(Post, related_name='score') upvotes = models.IntegerField(default=0) downvotes = models.IntegerField(default=0) def hot(self): return self.upvotes - self.downvotes I want to create a trending algorithm based on upvotes and downvotes, similar to something like reddit where a Post's trending score decreases over time (date). At the moment I'm simply returning upvotes - downvotes because I don't know how to incorporate date. Can someone tell me how I can return a simply trending score which incorporates those 3 fields (upvotes, downvotes, date)? -
Django Sub query limit to one record not working
im new to sub queries and am not quite grasping the concept from the django documentation possibly from the complexity of my query. im my template I am using {{ item.circuit.devicecircuitsubnets_set.first.subnet }} Using first generates duplicate queries, when I try use .0 instead of .first I do not get a result in my template. so im looking to use a subquery instead. The circuit__devicecircuitsubnets_set should only return one record per parent record anyway but when there are multiple parent records I am getting duplicate queries my current error is: File "/usr/local/lib/python3.6/site-packages/django/db/models/fields/related_descriptors.py" in get_prefetch_queryset 612. instance = instances_dict[rel_obj_attr(rel_obj)] Exception Type: KeyError at /circuits/overview/90 Exception Value: (None,) my query: subquery = Subquery(DeviceCircuitSubnets.objects.values('circuit_id')[:1]) site_data = get_object_or_404(Site.objects \ .prefetch_related( Prefetch( 'sitecircuits_set', queryset=SiteCircuits.objects.filter(site_id=site_id) \ .exclude(circuit__decommissioned=True) \ .select_related('site') \ .select_related('circuit') \ .prefetch_related('circuit__circuit_type') \ .prefetch_related( Prefetch( 'circuit__devicecircuitsubnets_set', queryset=DeviceCircuitSubnets.objects.annotate(circuit_id=subquery) ) ) \ .prefetch_related('circuit__circuitfile') \ .prefetch_related('circuit__circuitnotes_set') \ .prefetch_related('circuit__service_provider') \ .prefetch_related('circuit__service_provider__provider') \ .prefetch_related('circuit__service_provider__contact_set') \ .prefetch_related('circuit__circuit_type') \ .prefetch_related('circuit__circuitmaintenance') ) ), id=site_id ) model layout -Sites -Circuits -Devices -Subnets --SiteCircuits (mapping table) --DeviceCircuitSubnets (mapping table) -
Django current url request.resolver_match
request.resolver_match.url_name is not working in template for django 1.11. Can anyone help me? -
Variable count doesn't get updated while counting number of similar lines in two files in python [on hold]
I have two database table named File1 and File2. File1 and File2 contain same program I wanted to access them from database, place it in another file(s) and count the number of same lines in two files. views.py import os os.environ['DJANGO_SETTINGS_MODULE']='websitepc.settings' import django django.setup() from plagiarism.models import File1,Result,File2 def getfile1(a): data=File1.objects.all() return data def getfile2(a): data1=File2.objects.all() return data1 def percent1(f): j = 1 g3 = set(line.strip() for line in open('examplefile1.py')) for line in g3: j = j + 1 #counts total number of lines in examplefile1.py g3 = set(line.strip() for line in open('examplefile2.py')) for line in g3: k = k + 1 #counts total number of lines in examplefile2.py f7 = open('examplefile1.py', 'r') f8 = open('examplefile2.py', 'r') global count1 count1=0 g1 = set(line.strip() for line in open('examplefile1.py')) g2 = set(line.strip() for line in open('examplefile2.py')) for line in g1 & g2: if line: count1 = count1 + 1 return count1 print(count1) def getresult(a): open("examplefile2.py", "w").close() open("examplefile1.py", "w").close() dbf1 = getfile1(2) #print(dbf1) exf1 = dbf1.get() data1 = str(exf1) #print(data1) file = open("examplefile1.py", "w") file.write(data1) dbf2= getfile2(2) exf2 = dbf2.get() data2 = str(exf2) #print(data2) file = open("examplefile2.py", "w") file.write(data2) data1=percent1(7) return data1 print(getresult(3)) The output I get is 15 0 the count1 value … -
Hide Model in Django Admin according to value in DB
I want to hide a model in the django admin interface according to a value in the database. My first solution was to add this to the ready() handler of the app: from foo.models import MyModel if MyModel.objects.filter(...).exists(): from foo.models import ModelToHide admin.site.unregister(ModelToHide) Above solutions works ... except: This fails in CI. If CI builds a new system from scratch, the database table of MyModel does not exist yet :-( Any hints how to solve this? -
Changing the default SQL column name transition rules in Django ORM
I am using MySQL and Django in my backend, and the big issue now is that I use underscores in MySQL, while I have to use camelCase in Django ORM.So the question is, can I somehow tell Django to insert underscores in those places where it encounters uppercase letter in the middle of the word, so that ownerAccount = models.ForeignKey(ownerAccount, models.CASCADE) becomes owner_account in MySQL. I know there is db_column solution, but it sounds like a hell to me and violation of DRY. I feel like there just should be a clean and quick solution for this -
i am getting folwlwing error while runing admin page in django 2.0AttributeError: 'WSGIRequest' object has no attribute 'user'
Internal Server Error: /admin/ Traceback (most recent call last): File "/home/uday/django-apps/env/lib/python3.5/site-packages/django/core/handlers/exception.py", line 35, in inner response = get_response(request) File "/home/uday/django-apps/env/lib/python3.5/site-packages/django/core/handlers/base.py", line 128, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/uday/django-apps/env/lib/python3.5/site-packages/django/core/handlers/base.py", line 126, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/uday/django-apps/env/lib/python3.5/site-packages/django/contrib/admin/sites.py", line 241, in wrapper return self.admin_view(view, cacheable)(*args, **kwargs) File "/home/uday/django-apps/env/lib/python3.5/site-packages/django/utils/decorators.py", line 142, in _wrapped_view response = view_func(request, *args, **kwargs) File "/home/uday/django-apps/env/lib/python3.5/site-packages/django/views/decorators/cache.py", line 44, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "/home/uday/django-apps/env/lib/python3.5/site-packages/django/contrib/admin/sites.py", line 212, in inner if not self.has_permission(request): File "/home/uday/django-apps/env/lib/python3.5/site-packages/django/contrib/admin/sites.py", line 186, in has_permission return request.user.is_active and request.user.is_staff AttributeError: 'WSGIRequest' object has no attribute 'user' [22/Mar/2018 07:51:30] "GET /admin/ HTTP/1.1" 500 80176 -
Django API i show 400 (Bad Request) error using angular4
i am using Django Rest API ang its callby Angular4 but i get error when i try to uplode image i still get bed request error home.component.ts hear i am using post method for uploading image with data. import { Component, OnInit } from '@angular/core'; import { Http, Response, Headers} from '@angular/http'; @Component({ selector: 'app-home', templateUrl: './home.component.html', styleUrls: ['./home.component.css'] }) export class HomeComponent implements OnInit { constructor(private http: Http) { } homeObj:object = {}; addSaveData = function(home){ this.homeObj = { "name" : home.name, "email": home.email, "subject": home.subject, "message": home.message, "image" : home.image, } let _url:string = 'http://127.0.0.1:8000/Home/Homemodel/'; this.http.post(_url, this.homeObj).subscribe(( res:Response) =>{ console.log(res); }) } ngOnInit() { } } This is my home.component.html it is angular4 code using as front-end for callig django API. <div id="headder" class="container"><h3>POST METHOD</h3></div> <form class="container" id="formNewPost" name="formNewPost" #postData = "ngForm" (ngSubmit) = "addSaveData(postData.value)"> <div class="row"> <div class="col-sm-4"> <div style="width:100%"><label>Name:</label></div> <input style="width:100%" type="text" name="name" id="name" placeholder="name" ngModel> </div> <div class="col-sm-4"> <div style="width:100%"><label>EMail:</label></div> <input style="width:100%" type="text" name="email" id="email" placeholder="email" ngModel> </div> <div class="col-sm-4"> <div style="width:100%"></div><label>Subject:</label> <input style="width:100%" type="text" name="subject" id="subject" placeholder="subject" ngModel> </div> <br> <br> <div class="col-sm-12"> <div style="width:100%"><label>Message:</label></div> <textarea style="width:100%" type="text" name="message" id="message" placeholder="message" ngModel></textarea> </div> <input type="file" > </div><br> <input class="btn btn-primary" style="float: right;margin-bottom:15px;" type="submit" value="POST"> … -
'ForeignRelatedObjectsDescriptor' object has no attribute 'filter'
I have a model called Metadata with GenericForeignKey, because I want it to be tied to multiple other model types, including Image and Video. class Video(models.Model): name = models.CharField(max_length=512) metadata = GenericRelation(Metadata, related_query_name='videos') class Image(models.Model): name = models.CharField(max_length=512) metadata = GenericRelation(Metadata, related_query_name='images') class Metadata(models.Model): content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') value = models.ForeignKey("Value", db_index=True) I need to be able to filter both ways, i.e. from Image/Video and from Metadata, like this: metas = Metadata.objects.filter(videos__name__contains='foo') values = metas.values_list('value') and videos = Video.objects.filter(name__contains='foo') values = videos.values_list('metadata__value') Now, the first query works fine. However on the second one I get the error: 'ForeignRelatedObjectsDescriptor' object has no attribute 'filter' Any suggestions as to what might be happening? Thanks!