Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Create database from model in django 1.10 with Postgres
I have multiple models that I'd like to create tables for. So far I've been running sql code to create them and then i can make use of them. This seems tedious and I'm pretty sure django can do it for me. After all it creates databases with makemigrations and migrate. But this does not seem to work with my models. Thanks in advance! -
how to record visited urls in django?
I want to records user visited links for my site realtymarker.com. Does any one have a better approach? A javascript method that sends a request on every page load is what we have. Let me know. Thank you! -
Django request array or not
How can I find out that incoming request is a array or not? For now I'm doing this approach def create(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) if isinstance(request.data, list): serializer = self.get_serializer(many=True, data=request.data) What could be the best way? -
Django multiple image uploads in admin without 3rd party apps
I need your help once again and I really hope that someone could offer a step by step guide easy to follow because I am a beginner. I am trying to create a photography portofolio and I do not have any idea on how to go about multiple imagefield uploads in admin. What I want to end up with is a Photography app that will enable me to upload multiple images at once under one category (e.g. "Landscape"). It would be nice if I could also resize them using Django in the process of uploading, so that I would have to resize them in Photoshop. Then I want to be able to use masonry to display all my images and filter them by category using isotope. I am looking for a solution without having to install 3rd party solutions like django-admin-multiupload or jQuery File Upload. Could you please help me start out? Thank you so much -
Django Q Filtered Results in Separate DIV
I have a simple Django model and Q lookup and everything works as expected, but I'd like the filtered results to display in a separate DIV while keeping the original query list unfiltered as annotated in the attached image. Below is my code, an annotated screenshot and a link to the page on a dev server. Any instruction would be great. Thank you. View def plaque_list(request): today = timezone.now().date() queryset_list = Plaque.objects.active().order_by("first_name") if request.user.is_staff or request.user.is_superuser: queryset_list = Plaque.objects.all().order_by("first_name") query = request.GET.get("q") if query: queryset_list = queryset_list.filter( Q(first_name__contains=query) | Q(last_name__icontains=query) ).distinct() paginator = Paginator(queryset_list, 8) # Show 25 contacts per page page_request_var = "page" page = request.GET.get(page_request_var) try: queryset = paginator.page(page) except PageNotAnInteger: # If page is not an integer, deliver first page. queryset = paginator.page(1) except EmptyPage: # If page is out of range (e.g. 9999), deliver last page of results. queryset = paginator.page(paginator.num_pages) context = { "object_list": queryset, "queryset_list": queryset_list, "title": "Locate a Veteran", "page_request_var": page_request_var, "today": today, } return render(request, "plaques/plaque_list.html", context) Template ... {% for obj in object_list %} <tr> <th><a href="{{ obj.get_absolute_url }}">{{ obj.first_name }}</a></th> <th><a href="{{ obj.get_absolute_url }}">{{ obj.last_name }}</a></th> <th>{{ obj.branch }}</th> <th>{{ obj.rank }}</th> <th>{{ obj.wall|upper }}</th> <th>{{ obj.direction|title }}</th> <th>{{ obj.row … -
Scrapy Closed early without error message
I have a simple pagination spider like so import scrapy class AuthorSpider(scrapy.Spider): name = 'author' start_urls = ['http://quotes.toscrape.com/'] pending_authors = {} def parse(self, response): # process pagination links next_page = response.css('li.next a::attr(href)').extract_first() next_page_request = None if next_page is not None: next_page = response.urljoin(next_page) # Create the Request object, but does not yield it now next_page_request = scrapy.Request(next_page, callback=self.parse, dont_filter=True) # Requests scrapping of authors, and pass reference to the Request for next page for href in response.css('.author+a::attr(href)').extract(): self.pending_authors[href] = False # Marks this author as 'not processed' yield scrapy.Request(response.urljoin(href), callback=self.parse_author, meta={'next_page_request': next_page_request}, dont_filter=True) def parse_author(self, response): def extract_with_css(query): return response.css(query).extract_first().strip() item = { 'name': extract_with_css('h3.author-title::text'), 'birthdate': extract_with_css('.author-born-date::text'), 'bio': extract_with_css('.author-description::text'), } # marks this author as 'processed' self.pending_authors[response.url] = True # checks if finished processing of all authors if len([value for key, value in self.pending_authors.iteritems() if value == False]) == 0: yield item next_page_request = response.meta['next_page_request'] # Requests next page, after finishing all authors self.pending_authors = {} yield next_page_request else: yield item I store all of my items into a Django DB. I also have a middleware that will raise an IgnoreRequest if the requestURL is in the DB. Randomly, the crawler will stop with a regular finish message. It also … -
Django 2.7 Rest API Validation Request
I use Django 2.7 to build Rest API application, and having problem to validate/clean the request data from client for get detail transaction (Not Save/update). for example the request data trx_no cannot less than 5 char length. where's the validation class i should create? should I validate on Model.py or using forms, or in serializer? Here's my models.py: class mst_trx(models.Model): trx_no = models.CharField(max_length=20,primary_key=True) Here's my views.py: class views_index(APIView): def post(self,request): action = request.POST['action'] if action == 'detail' : resp = detail.as_view()(request) class detail(APIView): def dispatch(self,request): ##I want to validate first before get data try: detail = mst_trx.objects.select_related().get(pk=request.POST['trx_no']) except mst_trx.DoesNotExist: raise Http404("Transaction does not exist") else: serializer = TrxDetailSerializer(detail) return serializer.data And Here's my serializer.py : class TrxDetailSerializer(serializers.ModelSerializer): class Meta: model = mst_trx fields = ('trx_no') -
Iterating over a model in Django template not rendering anything
Problem: I am trying to simply iterate over my Category model and display a list of categories. I've successfully done so with posts, but for some reason I can't get it to work with my categories model (It doesn't even make it passed the {% if categories %} statement). Thus, the <h2>Categories:</h2> and below is not rendered at all. I currently have two categories in my database ('Fitness' and 'Nutrition'). They are in my admin, and they also show up when I query through the command line. I can also successfully link to them from my 'post_detail' page (and display all posts within a category). However, I can't seem to iterate over the model to display all categories as a list... Code: post_list.html <div class="container"> <h2>Categories:</h2> {% if categories %} <h2>Categories</h2> <ul> {% for category in categories %} <li>{{ category.name }}</li> {% endfor %} </ul> {% endif %} </div> models.py from django.db import models from django.utils import timezone from django.template.defaultfilters import slugify class Category(models.Model): name = models.CharField(max_length=255, blank=False, default='') slug = models.SlugField(max_length=100, default='', unique=True) class Meta: verbose_name = "Category" verbose_name_plural = "Categories" ordering = ['name'] def __str__(self): return self.name def __unicode__(self): return self.name views.py from .models import Post, Category from … -
Can I use class method in views.py?
Now my code is like: def use_item(request): itemname = request.get('value') if itemname == 'item1': #do something if itemname == 'item2': #do something else Can I do it in the following way? views.py class use_item(self): def use_item(request): itemname = request.get('value') use = getattr(self,itemname) # say itemname is 'item1' use() def item1(request): #do something def item2(request): #do something else I've tried the second method but it seems that I was not doing it right. -
Django Save Override Not Updating Model Instance
I am trying to update a model instance of my Game model every time my Bet model saves. Every time I bet saves, I'd like to add 1 to the picks field on the game model. If I print out the picks mid save override on game, it looks like it accesses and updates the number, but it doesn't save it to the database. My hypothesis is that it's because I'm also overriding save on the game method, but when I comment this out, it still does not work. The override of save on the game model is very long, so please let me know if you see something wrong there too. Please let me know if you have suggestions! Bet model: class Bet(BaseModel): """" Bets on team games """ size = models.IntegerField() player = models.ForeignKey('bets.PlayerProfile', null=True, blank=True, related_name='bets') team_game = models.ForeignKey('betting.TeamGame') spread_at_time = models.ForeignKey('betting.Spread', related_name="spread_bets", blank=True, null=True) moneyline_at_time = models.ForeignKey('betting.Moneyline', blank=True, null=True, related_name="moneyline_bets") winner = models.BooleanField(default=False) tag = models.CharField(blank=True, null=True, max_length=128) # using char field to capture push outcome = models.CharField(blank=True, null=True, max_length=128) pro = models.BooleanField(default=False) cost = models.IntegerField(default=0) #for pro description description = models.CharField(max_length=500, null=True, blank=True) def save(self, *args, **kwargs): super(Bet, self).save(*args, **kwargs) # Update the number of … -
Django - Many to One - Cannot Assign Must Be Instance Of
I apologize if this is a duplicate post. I have spent days researching and trying to figure this out...but i'm at a dead end. I have a model (Header) that contains all of my order headers, and i need to link that to the (MarketPlace model) market place where they came from. There will only be 2 or 3 lines in the MarketPlace table but every line in Header should be related to one of those lines. Here is how i am attempting to create a record in the shell: (i may also be doing this wrong): h = Header.objects.filter(retailOrderNum = '185680144') a = Marketplace(id = None, contactName = 'MP Name',address1='555',address2='666',city = 'Salt Lake City' ,state = 'UT',zipCode='84104',country = 'US',phone='555-555-5555') I get this error: Cannot assign "]>": "MarketPlace.channel" must be a "Header" instance. Here are my models: class Header(models.Model): retailOrderNum = models.CharField(max_length=50,primary_key = True) orderNum = models.CharField(max_length=50) channel = models.CharField(max_length=50) orderDate = models.DateTimeField(null=True) contactName = models.CharField(max_length=500) address1 = models.CharField(max_length=1500) address2 = models.CharField(max_length=1500, null=True) city = models.CharField(max_length =100) state =models.CharField(max_length =100) zipCode =models.CharField(max_length=100,null=True) country = models.CharField(max_length =100) phone = models.CharField(max_length =100,null=True) #shippingSpecifications =models.CharField(max_length =100) shippingCode = models.CharField(max_length =100) orderShippedDate = models.DateTimeField(null=True) def __str__(self): return self.retailOrderNum class Line(models.Model): retailOrderNum =models.ForeignKey(Header, on_delete=models.CASCADE,db_column='retailOrderNum') item … -
Why should I use generic views?
I was going through the Django 1.10 tutorial when I came upon this section: Generic views abstract common patterns to the point where you don’t even need to write Python code to write an app. It talks about how you can simplify your code to make writing your views easier by using generic views. My question is, why should I use generic views? I feel like a lot of the examples shown are very implicit views which I dislike in comparison to writing out the views "manually". -
Django - not showing properly one of my tables in template
I'm having a problem here and I hope you could help me. here's what I have: Models.py class Personinfo(models.Model): name = models.CharField(max_length=128) def __str__(self): return self.name class Personage(models.Model): AGES = ( ('0', '0'), ('1', '1'), ('2', '2'), ) age = models.CharField(max_length=128,choices=AGES, default=True) def __str__(self): return self.age class Person(models.Model): person = models.ForeignKey(Personinfo, null=True) personage = models.ForeignKey(Personage, null=True) address = models.TextField() phone_number = models.CharField(max_length=128) hobbies =models.CharField(max_length=128) def __str__(self): return self.address Views.py def index(request): qs = Person.objects.all() form = personform(request.POST or None) form2 = personinfoform(request.POST or None) form3 = personageform(request.POST or None) context = { "qs": qs, "form2":form2, "form":form, "form3":form3, } form2_valid = form2.is_valid() form_valid = form.is_valid() form3_valid = form3.is_valid() if form2_valid and form_valid and form3_valid: a = form2.save() b= form.save(commit=False) b.person = a b.save() c = form3.save(commit=False) c.personage = a c.save() return render(request, "index.html", context) forms.py class personinfoform(forms.ModelForm): name = forms.CharField(label= 'Nombre') class Meta: model = Personinfo fields = ["name"] class personform(forms.ModelForm): address = forms.CharField(label='Direccion') phone_number = forms.CharField(label='Telefono') hobbies = forms.CharField(label='Hobbies') class Meta: model = Person exclude = ('person','personage',) fields = ["address","phone_number","hobbies"] class personageform(forms.ModelForm): class Meta: model = Personage fields =["age"] index.html <form method="POST" action="">{% csrf_token %} {{form2.as_p}} {{form3.as_p}} {{form.as_p}} <input type="submit" value="Save!" /> </form> <table > <tr> <th>Name</th> <th>Age</th> <th>Address</th> <th>Telefono</th> … -
How to wall off a Django view based on the result of another view
I'm writing a change password feature for a Django app of mine, allowing users to change their passwords at will. One requirement is that users must resubmit the original password before proceeding to change it. Views responsible for reauth of original password and enter new password are mapped to two separate urls. Currently the way it's set up, one can directly get to the enter new password part of the functionality simply by hitting the right url. I need to make reauth of original password compulsory, thus the current funtionality is unacceptable. What's the best strategy to redesign this feature such that reset password is walled off behind the reauth requirement? One thing coming to my mind is setting a flag as a session variable upon successful reauth, and allowing password reset only if the said flag is correctly set. But I'm hoping there could be a more robust way? My current code is: def reset_password(request,*args,**kwargs): if request.method == 'POST': form = ResetPasswordForm(data=request.POST,request=request) if form.is_valid(): #save new password hash else: context={'form':form} return render(request,'reset_password.html',context) else: form = ResetPasswordForm() context={'form':form} return render(request,'reset_password.html',context) def reauth(request, *args, **kwargs): if request.method == 'POST': form = ReauthForm(data=request.POST,request=request) if form.is_valid(): return redirect("reset_password") else: context={'form':form} return render(request, 'reauth.html', … -
Retrieve one-to-many QuerySet in Django
I have the following models: class RecipientList(models.Model): name = models.CharField(max_length=255) list_type = models.CharField(max_length=255) status = models.CharField(max_length=255) class RecipientListEmail(models.Model): email = models.CharField(max_length=255) recipient_list = models.ForeignKey(RecipientList, on_delete=models.DO_NOTHING) What I'm trying to do is retrieve all RecipientLists and for each recipient list I'd like to get a set of RecipientListEmails associated with it. In other words, it is a simple one-to-many (1 RecipientList to many RecipientListEmails) relationship and I'd like to grab all this information in one result set. Is it possible to do in Django without iterating over the RecipientList and querying RecipientListEmails individually or writing my own SQL join? -
Django + Jinja2 about generated HTML
The HTML code generated by Jinja2 sometimes is not well indented (checking view source in my web browser). So I was asking should I care about this? Also, is there any style guide when working with Jinja templates? for example indenting source code, which style is prefered? <ul> {% for i in seq %} <li>{{ i }}</li> {% endfor %} </ul> or <ul> {% for i in seq %} <li>{{ i }}</li> {% endfor} </ul> -
Ajax not executing on get in Django
I'm getting the "refreshing now" but not the "made it to views.py" or "request". What am I doing wrong? Thanks a mil for your help! Here's my code: Views.py def coordinates(request): print "Request: ", request if request.method == 'GET': print "made it to views.py" return HttpResponse('check') Map.js function refreshData() { x = 1; setTimeout(refreshData, x*1000); console.log("refreshing now"); $.ajax({ url: '127.0.0.1:8000/coordinates', type: 'get', success: function(data){ console.log('made it here'); }, failure: function(data){ alert('Got an error dude'); } }) (probably not necessary but) Index.html <script src={% static "map.js" %}></script> <!-- Get the map from Google --> <!-- Pass the initMap function from the above script as a callback to Google Maps --> <script src="https://maps.googleapis.com/maps/api/js?key={{GOOGLE_API_KEY}}&callback=initMap" async defer></script> <!-- include jQuery --> <script src={% static "jquery.js" %}></script> (Probably not necessary but) urls.py urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^go', views.go, name='go'), url(r'^rtl', views.rtl, name='rtl'), url(r'^coordinates',views.coordinates, name='coordinates') ] -
Django CRUD Update model that has foreign keys
Question 1: Adding into Klassen... this works but in the html the richting and the leraar is a list where you can pick one but it show the full description like naam and omschrijving. I only want that it shows the naam. image add klas Question 2: When I try to edit, it gives me an input of klas.richting.naam. But When I try to update it it gives ma an error: image edit error Even when I doesn't change anything. models.py class Richtingen(models.Model): naam = models.CharField(max_length=100) omschrijving = models.TextField(max_length=2000) def __unicode__(self): return u'%s %s' % (self.naam, self.omschrijving) class Leraren(models.Model): naam = models.CharField(max_length=100) voornaam = models.CharField(max_length=100) foto = models.ImageField(upload_to = 'leerkrachten', default='leerkrachten/anoniem.png') email = models.EmailField() def __unicode__(self): return u'%s %s %s %s' % (self.naam, self.voornaam, self.foto, self.email) class Klassen(models.Model): naam = models.CharField(max_length=100) numeriekeCode = models.CharField(max_length=100) richting = models.ForeignKey(Richtingen, on_delete=models.CASCADE) leraar = models.ForeignKey(Leraren, on_delete=models.CASCADE) def __unicode__(self): return u'%s %s %s %s' % (self.naam, self.numeriekeCode, self.richting, self.leraar) forms.py class RichtingForm(ModelForm): class Meta: model = Richtingen fields = ['naam', 'omschrijving'] class LeraarForm(ModelForm): class Meta: model = Leraren fields = ['naam', 'voornaam', 'foto', 'email'] class KlasForm(ModelForm): class Meta: model = Klassen fields = ['naam', 'numeriekeCode', 'richting', 'leraar'] views.py def edit_klassen(request, id): klas = Klassen.objects.get(id=id) edit … -
Accessing django models and functions from within python script hosted on separate heroku app
I'm looking for a way to access the models and functions in my django app hosted on heroku from a python script on a different heroku app. I understand that the following works if the script that you have is located in the same folder as your django app: import os import django os.environ.setdefault("DJANGO_SETTINGS_MODULE", "app.settings") django.setup() from manual_tasks.tasks import * but I'm looking to run the script on a different heroku app entirely. Is this possible? In this case, I wouldn't have the path/to/django-app because my script would be hosted on a separate heroku app. Any help is appreciated! -
How to revert changes, specifically deletions, with django-simple-history
We have django-simple-history set up for our models. Recently a whole bunch of models were mysteriously deleted. This was noticed a few days after the fact, so it would be nice to avoid a full DB backup restore since that would wipe manual changes that happened after the fact. I cannot find any way to easily restore an model instance, specifically a deleted one. I can query the Historical version of the model and find everything that was deleted. With that I can also observe that all of them had deletions as their last change. I can use the instance property on history - 1 to get the state before deletion but if I try to save that it errors since the model instance was deleted and doesn't exist anymore. So basically, what is the cleanest way to restore a deleted model instance if I have the Historical record of it with django-simple-history? I would like to retain the history if possible, so I am looking into any solution before totally recreating the objects. -
Django GenericRelated field conditional Query raising 'GenericRelation' object has no attribute 'field'
I have a an event object, there are other object besides notes that has generic relation to events, and doesn't have active field. Now I want to be able to write a query which excludes all events where the notes active field is False. So I tried doing the following. queryset = Event.objects.all() filters = ( Q(content_type__model='notes') & Q(note__active=False) ) queryset = queryset.exclude(filters) this didn't work because it running the query separately and when it try to execute for items for which there are no content_object or are not of type Notes, it fails and gives the following error: AttributeError 'GenericRelation' object has no attribute 'field'. class Event(models.Model): content_type = models.ForeignKey(ContentType, null=True, blank=True) object_id = models.PositiveIntegerField(null=True, blank=True) content_object = GenericForeignKey('content_type', 'object_id') class Notes(models.Model): active = models.BooleanField(default=True) event_log = GenericRelation( 'Event', related_query_name='note' ) -
Python. Django iterating a ridiculous amount more times over queryset. Very extrange
Can someone explain me this: >>> from inicio.models import EventoSubasta >>> procesos_concluidos = EventoSubasta.objects.filter(concluido=True, eliminado=False).order_by("-fechasubasta__fecha") >>> procesos_concluidos.count() 7 >>> for proceso in procesos_concluidos: ... print "proceso.codigo_proceso: %s - proceso.id: %s " % (proceso.codigo_proceso, proceso.id) ... proceso.codigo_proceso: SP010-2016 - proceso.id: 15 proceso.codigo_proceso: SP010-2016 - proceso.id: 15 proceso.codigo_proceso: SP010-2016 - proceso.id: 15 proceso.codigo_proceso: SP010-2016 - proceso.id: 15 proceso.codigo_proceso: SP010-2016 - proceso.id: 15 proceso.codigo_proceso: SP010-2016 - proceso.id: 15 proceso.codigo_proceso: SP010-2016 - proceso.id: 15 proceso.codigo_proceso: SP006-2016 - proceso.id: 13 proceso.codigo_proceso: SP005-2016 - proceso.id: 8 proceso.codigo_proceso: SP003-2016 - proceso.id: 5 proceso.codigo_proceso: SP004-2016 - proceso.id: 9 proceso.codigo_proceso: SP002-2016 - proceso.id: 4 proceso.codigo_proceso: SP001-2016 - proceso.id: 3 >>> Isn't it supposed to iterate once over each object in the queryset? why is it repeating the object with id 15 seven times. I don't understand. The project is in production. Please help. -
Django DetailView filter only active objects
I'm trying to filter my object shown on DetailView view. I can't show objects that has active=False property set, how cant i do that? -
Filter queryset with one of two criteria that match with the user. Django Rest Framework
I have this model: class MessageViewSet(viewsets.ModelViewSet): queryset = Message.objects.all() serializer_class = MessageSerializer and of course, it returns every message. A Message is so in the model: class Message(models.Model): created = models.DateTimeField(auto_now_add=True) type = models.CharField(_('type'), choices=MESSAGE_TYPE, default='Invitation', max_length=100) content = models.TextField(_('content'), blank=False) sender = models.ForeignKey(User, related_name='sender_message', verbose_name=_("Sender"), ) recipient = models.ForeignKey(User, related_name='receiver_message', null=True, blank=True, verbose_name=_("Recipient")) url_profile_image = models.URLField(_('url_profile_image'), max_length=500, blank=True, default='') class Meta: ordering = ('created',) and the serializer is so: class MessageSerializer(serializers.ModelSerializer): sender = serializers.ReadOnlyField(source='sender.uuid') recipient = serializers.ReadOnlyField(source='recipient.uuid') class Meta: model = Message fields = ('url', 'id', 'type', 'content', 'sender', 'recipient', 'url_profile_image') I just want that the queryset returns a message if the user is the sender or the recipient. I was trying with this: filter_backends = filters.DjangoFilterBackend filter_fields = ('recipient', 'sender') But it doesn't work, perhaps, because I don't know where to compare. -
How to get members of groups in autocomplete light field in django
I'm using version 2.2.10 I want to display users of a group in autocomplete field. I am able to display all users in autocomplete field when I'm creating group. But in a different scenario I need to list users of that group only when creating rosters within group users. Existing autocomplete model: ``` class UserAutocomplete( autocomplete_light.AutocompleteModelBase ): search_fields = [ 'username', 'last_name', 'first_name',] choices = [] def __init__(self, *args, **kwargs): super(UserAutocomplete, self).__init__(*args, **kwargs) self.choices = User.objects.all() def choices_for_request(self): print "coming in choices_for_request" self.choices = User.objects.all() return super(UserAutocomplete, self).choices_for_request() ``` In my form I have `users = autocomplete_light.MultipleChoiceField('UserAutocomplete', label='Users', required=False)` Now for my new form how to pass group information to UserAutocomplete so that I can modify the queryset. I can do following without using autocomplete: ``` self.fields['users'] = ModelMultipleChoiceField( required=True, queryset=group.users.all(), widget=CheckboxSelectMultiple) ``` But I want to use autocomplete light field. Let me know how to go about doing it.