Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Giving positions name in django automatically
I'm building a bus booking website using Django. I have an attribute position in my table 'seat'. It is linked to bus(table) by ForeignKey. Whenever a bus is created, seat instances are created equal to the capacity of the bus(capacity is defined by the user in bus table). I want to name the positions like 1_1, 1_2, 1_4, 1_5, 2_1, 2_2, 2_4, 2_5 etc.. where the first digit before underscore represents row and digit after underscore represents a column. I'm not using 3 because it's the aisle. this is my models.py class Seat(models.Model): class Meta: verbose_name_plural = "Seat" id = models.AutoField(primary_key=True,) position = models.CharField(max_length=4) bus = models.ForeignKey(Bus) status = models.CharField(max_length=20, choices=(('available', 'available'), ('reserved', 'reserved'), ('unavailable', 'unavailable'),), default='Available') def __str__(self): return '{0}-{1}-{2}'.format((self.bus),(self.id),(self.status)) @receiver(post_save, sender=Bus) def create_seats(sender, instance, created, **kwargs): if created: for seat in range (0, int(instance.capacity)): instance.seat_set.create( ) This is how the naming of position is done as you can see it's empty in the middle so for that 3rd column is not used. My question is how can automatically name the positions (like I create seats whenever a bus object is created) according to the chart without having to go in individual seat object and name the position. I … -
How to use parents model fields in the model form?
I use django 1.9 and have some inheritance of models e.g.: class TimeStampedModel(models.Model): created = models.DateTimeField(auto_now_add=True) modified = models.DateTimeField(auto_now=True) class Meta: abstract = True After that I use this model to add created and modified into my models. But I can't use this fields into the forms. E.g.: class Customer(TimeStampedModel): first_name = models.CharField(max_length=250, blank=True, null=True, default=None) last_name = models.CharField(max_length=250, blank=True, null=True, default=None) And the form code: class CustomerForm(forms.ModelForm): class Meta: model = Customer fields = ('first_name', 'last_name', 'modified') readonly_fields = ('modified', ) And I get an error: django.core.exceptions.FieldError: Unknown field(s) (modified) specified for ... How can I add this field to the form? I have it in the DB schema but django form doesn't get it. -
Optimization for comparing every element of a list to every element in database using Django
I'm working on a project in Django 1.10, and one of my apps requires that I import a list of ~500 IP addresses, then compare those ~500 IP addresses to the ~25,000+ IP addresses stored in my SQLite3 database. Unfortunately, this takes quite some time, which is something I greatly need to reduce. My database comprises of a Host table with a field called ipv4_address. Here's the relevant model.py: class Host(models.Model): ipv4_address = models.GenericIPAddressField(protocol='ipv4', default='0.0.0.0', unique=True) And here's the relevant views.py: bad_ips = [] read_bad_ips = [ '500', 'ips', 'here', '...' ] for ip in read_bad_ips: if Host.objects.filter(ipv4_address=ip).exists(): bad_ips.append(Host.objects.get(ipv4_address=ip)) Where read_bad_ips is a list of IP addresses and bad_ips is a list of the IPs I want that exist in both the database and the read_bad_ips list. What would be the best way to optimize this snippet of code from views.py? Thanks! -
Adding Sass to Django
I want to use SASS in my Django Project. But where should I put all my Sass files ? Should I create a 'Sass' folder in my Project Folder or is it better to create for each App a 'Sass' folder. And which converter would you recommend to convert my sass files to css ? -
separate divs with same class name from each other
How to separate divs with same class name from each other? I have something like this: <form role="form" id="comment-form"> <textarea class="form-control" rows="1" placeholder="{% trans 'Write a comment...' %}" name="comment" id="comment"></textarea> </form> <form role="form" id="comment-form"> <textarea class="form-control" rows="1" placeholder="{% trans 'Write a comment...' %}" name="comment" id="comment"></textarea> </form> <form role="form" id="comment-form"> <textarea class="form-control" rows="1" placeholder="{% trans 'Write a comment...' %}" name="comment" id="comment"></textarea> </form> ... I want to add this: $("#comment").keydown(function (evt) { var keyCode = evt.which?evt.which:evt.keyCode; if (evt.ctrlKey && (keyCode == 10 || keyCode == 13)) { $.ajax({ url: '/articles/comment/', data: $("#comment-form").serialize(), cache: false, type: 'post', But on keydown only first textarea with id="comment" responds, as every element must have unice id. I tried changing them to classes, but then they would ALL respond. How could i separate this forms, from getting into each others way? -
Multiply time in Django TimeField by float
I'm trying to read a time currently represented as a string into a Django TimeField Model and scale it via a float at the same time. For example: 00:31:14 / 1.0617 = 00:29:20 I've successfully read in the time and stored into the model but can't scale the time in a "nice" way (currently I read the time object back out of the database and update it). I would like to use the python datatime object that the TimeField is based on to do this calculation before saving to the database. Relevant code: class Time(models.Model): time = models.TimeField() date = models.DateField() date = "12/6/2009" time = "00:31:14" date = datetime.strptime(date, "%d/%m/%Y").strftime("%Y-%m-%d") time = models.Time(date=date, time=time) time.save() db_instance = models.Time.objects.all().filter(id=time.id)[0] db_instance.time = db_instance.time.replace( minute=int((db_instance.time.minute * 60 + db_instance.time.second) / 1.0617) / 60, second=int((db_instance.time.minute * 60 + db_instance.time.second) / 1.0617) % 60) -
Django M2M with addititional data with through
My problem is as follows. I am saving data for patients from a form on a webpage. The form is generated from model definitions in models.py. The information that I save is name, surname amongst others. I have a field for diagnosis which is selected using a multichoiceField and I save it using manytomany. When the data is saved, a separate table is created for the diagnosis assigned to each patient as expected. The table contains a diagnosis and the ID of the patient it applies to. Each diagnosis is saved as a separate record. In addition to selecting the diagnosis, I also save the date that the diagnosis is made. You will see what I mean in the models.py and form.py code below. I would like to have the date for which the diagnosis was made also saved in the table but I can't figure out how to do this. I have tried following the docs: https://docs.djangoproject.com/en/dev/topics/db/models/#intermediary-manytomany as well as some other posts on SO, but cannot figure out how to do it. I can't figure out how the views, forms and models need to be set up in order to achieve. Is it possible to do this and … -
How to fill Django database on view buttonclick
I'm just learning Django, so my question might seem not worth attention, but i spent some time googling and havnt found an answer. I have two models and a function to fill it def grabdata(): url = "https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/4.5_day.geojson" weburl = urllib.request.urlopen(url) if (weburl.getcode() == 200): data = json.laods(weburl.read()) EarthQuakes.objects.all().delete() LastGetSession.objects.all().delete() lastsession = LastGetSession(hand=data["metadata"]["title"]) lastsession.save() for i in data["features"]: earthquake = EarthQuakes(place=i["properties"]["place"], time=i["properties"]["time"], mag=i["properties"]["mag"], rept=i["properties"]["felt"], longitude=i["geometry"]["coordinates"][0], latitude=["geometry"]["coordinates"][1]) earthquake.save() But i didn't get how to execute it from a view. Or it better be a way to call a conroller function that calls the model function or something like that -
Using Django static() to generate audio files' URLs in production
I'm trying to get my Django app to play audio files (supposedly) uploaded by users via a form. Said files are tied to a model : # models.py class Doc(models.Model): # ... tape = models.FileField() The uploading and saving parts are working fine, and the files are stored where they should be : - djangoproject | - docapp | - media <- here So, in order to get where I want, I added these two lines to the settings.py file MEDIA_ROOT = os.path.join(BASE_DIR, 'docapp/media/') and MEDIA_URL = 'docapp/media/'. I hoped to be able to link to the audio files thus: # templates/docapp/index.html ... <audio src='{{ doc.tap.url }}' controls></audio> Unfortunately, this wasn't working because the link generated by doc.tap.url (http://localhost/docapp/media/filename.aac) was returning a 404 error. After a lot of googling I found this answer, which I happily copy-pasted into my app ... and it worked. The problem is that I'm not comfortable with inserting code in my apps that I don't understand. I did some research about the static() function and all I could get is this : Helper function to return a URL pattern for serving files in debug mode Does this mean that the static function should not be … -
Get the progress of an upload request in Python
I am trying to let user upload an image from a webpage, and while doing it, I want to show a progress bar displaying how much of the act is complete. In the background, Django simply takes the file, uploads it to B2 (B2, scroll to the end of the page and choose Python). This is a sample code (assuming that the Ajax request had uploaded the photo in some local folder in the server, as given by pathToFile): def uploadImage(pathToFile): fileName = os.path.basename(pathToFile) sha1OfFileData = hashlib.sha1(open(pathToFile, 'rb').read()).hexdigest() uploadURL, uploadAuthToken = getPreFileUploadData() headers = { 'Authorization': uploadAuthToken, 'X-Bz-File-Name': fileName, 'Content-Type': "b2/x-auto", 'X-Bz-Content-Sha1': sha1OfFileData } print "About to make a request object" request = urllib2.Request(str(uploadURL), open(pathToFile, 'rb').read(), headers) try: response = urllib2.urlopen(request) responseData = json.loads(response.read()) response.close() return responseData["fileId"] except Exception, e: print "Messed up: " + str(e) return "" However, the problem here is that urlopen is a blocking call, and I cannot glean any information regarding its progress. This answer seems to be doing what I want (the reporthook function), but it uses urlretrieve function to download. Can anyone guide me on how to use the same urlretrieve function to do my upload? I will update a token (sent by … -
Accessing 'Request' in Django Rest Framework custom method field
Using a custom method field in Django Rest Framework, I'm required to pass/access the 'Request Object' in the method called get_tag_group_url. However, 'Request Object' does not appear to be available in the TagSerializer class and is 'None'. Why, and how to pass? Example: class ProjectSerializer(serializers.ModelSerializer): tags = serializers.SerializerMethodField() def get_tags(self, obj): request = self.context.get('request', None). <--- exists here # code removed or brevity. return TagSerializer(obj.tags.all(), many=True).data class TagSerializer(serializers.ModelSerializer): tag_group_url = serializers.SerializerMethodField() def get_tag_group_url(self, obj): # I need access to the request here but it is not passed. request = self.context.get('request', None) <--- No request 'None' -
java memcache db connect to to django
I have to program , first with Java , Memcache database second with Django Memcache database Memcache is share between to program i wrote java program by Memcache(127.0.01:11211) db , this is ok and good connect and no problem, and connect Django "pylibmc" to Memcache(127.0.01:11211) and no problem but the db Django is not same Django database of java program .................... how can connect to same database woth Django and Java ??? tanks alot. -
How do i control when to stop the audio input?
I am using the SpeechRecognition Python package to get the audio from the user. import speech_recognition as sr # obtain audio from the microphone r = sr.Recognizer() with sr.Microphone() as source: print("Say something!") audio = r.listen(source) This piece of code when executed starts listening for the audio input from the user. If the user does not speak for a while it automatically stops. I want to know how can we get to know that it has stopped listening to audio? How can I manually disable it ? I mean if i want to listen audio for 50 seconds and then stop listening to any further audio? -
Saving Many-to-Many relations with TabularInline generates error when main table has not been saved yet
For a situation with tables joined by a map table to create a many-to-many I use a TabularInline which allows editing the parts of a Machine in the Machine form. So the objects are: class Machine (models.Model): name = models.CharField(max_length=45) parts = models.ManyToManyField(Part, through='Machine2PartMap') class Part (models.Model): name = models.CharField(max_length=45) class Machine2PartMap (models.Model): machine = models.ForeignKey(Machine) part = models.ForeignKey(Part) The admin is: class M2PMapInline(admin.TabularInline): model = Machine2PartMap extra = 1 unique_together = (("machine", "part"),) class MachineAdmin(admin.ModelAdmin): inlines = [M2PMapInline] def get_readonly_fields(self, request, obj=None): return self.readonly_fields + ('id',) admin.site.register(Machine, MachineAdmin) The TabularInline in the admin form for the machine creates a section that allows me to add/edit the machine's parts in that form. The operations that create the error are: Click on the Add (+) to bring up a new Machine form. Type data into the fields of the Machine form (do not save) Click on the + to add a new part (in the TabularInline section Machine form) In the pop-up Part form, fill the fields of the Part and save. In the Machine form, click the save button. Error: save() prohibited to prevent data loss due to unsaved related object 'machine'. If I follow all the steps above and … -
Insert using bulk_create fails with an ValueError of a field name
this is my model in which i am doing bulk insert class Seats(models.Model): seat_no = models.ManyToManyField(Snumber) movie_name = models.ForeignKey(Movies) multiplex_name = models.ForeignKey(Multiplex) date = models.ForeignKey(Date) time = models.ForeignKey(Time) def __str__(self): b = str(self.date) c = str(self.time) d = str(self.multiplex_name) return d+" "+b+" "+c class Meta: unique_together = ('movie_name', 'multiplex_name', 'date', 'time') verbose_name_plural="Seats" I have the single object of Movies in mov , Multiplex in mul And have multiple objects of Date in dt, Time in tm and Snumber in st I want to add all objects of st in each time in tm on each date in dt with multiplex in mul and movie in mov This is my Failed attempt to do so Seats.objects.bulk_create([ Seats(movie_name = mov, multiplex_name = mul, seat_no = set, date = dat, time = tim )for dat in dt for tim in tm for set in st]) It is showing ValueError Traceback (most recent call last): File "<console>", line 2, in <module> File "<console>", line 2, in <listcomp> File "/usr/local/lib/python3.5/dist-packages/django/db/models/base.py", line 550, in __init__ setattr(self, prop, kwargs[prop]) File "/usr/local/lib/python3.5/dist-packages/django/db/models/fields/related_descriptors.py", line 499, in __set__ manager = self.__get__(instance) File "/usr/local/lib/python3.5/dist-packages/django/db/models/fields/related_descriptors.py", line 476, in __get__ return self.related_manager_cls(instance) File "/usr/local/lib/python3.5/dist-packages/django/db/models/fields/related_descriptors.py", line 783, in __init__ (instance, self.source_field_name)) ValueError: "<Seats: Badrinath … -
How should I generate cache keys
I want to cache shortened links, but how should I name the keys. Is something like this sufficient? What is good practise? cache.set('shortened' + question.id, shortened, 5 * 60) -
show first_name, last_name and email in profile serializer
I have a Profile model which after user signs up has to update their profile. For that i have designed two serializer, one UserSerializer to show the list of users and another ProfileSerializer which has lots of fields for user to add in their profile. The user not only gets to update their profile like height, weight, age, location, body_type etc but also should get to update first_name, last_name, email from the profile. Here is my UserSerializer and ProfileSerializer class ProfileSerializer(serializers.ModelSerializer): # url = serializers.HyperlinkedRelatedField(source="user", view_name="user_profile") user = serializers.PrimaryKeyRelatedField(read_only=True) token = serializers.PrimaryKeyRelatedField(read_only=True) class Meta: model = Profile fields = ('token', 'user', 'current_location', 'permanent_location', 'dob', 'about_me', 'gender_status', 'create_profile_for', 'marital_status', 'height', 'weight', 'body_type', 'complexion',) def update(self, instance, validated_data): first_name = validated_data.pop('first_name', None) last_name = validated_data.pop('last_name', None) user_inst_fields = {} if first_name: user_inst_fields['first_name'] = first_name if last_name: user_inst_fields['last_name'] = last_name if user_inst_fields: User.objects.update_or_create(id=instance.user.id, defaults=user_inst_fields) profile, created = Profile.objects.update_or_create(token=instance.token, defaults=validated_data) print('profile', profile, created) return profile class UserSerializer(serializers.ModelSerializer): profile = ProfileSerializer(required=True) class Meta: model = User fields = ('id', 'profile', 'username', 'email', 'first_name', 'last_name',) I could not show the fields of first_name, last_name and username for user to update them along with their profile. You can see the screenshot, no first_name, last_name and username is … -
Display profile pic from model in template in django
I want to insert the user's image in the img src field.But I'm not able to do it. My code: models.py class allusers(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) avatar = models.ImageField(upload_to='retest/static/images/') views.py u = User.objects.get(username=username) tempate <img src={{ u.allusers.avatar }} -
How to insert python value into a Django HTML template?
In Django, I have an HTML template where I would like to insert values for some javascript variable. <html> var jsvar= {{ Python_Django_String_VAR}} </html> In Django View: return render(request, pageurl, context) -
How to use django and node.js together?
I mean can you illustrate by a simple web app in django with node.js for real time communication.i tried a lot but couldn't found anything on Google. -
Declare another template path for CreateView
I have 2 Apps in my django project , 1. HotelApp , 2. ManageHotels The hotel details are shown to the user using the model in the HotelApp. However I have set up a CreateView form in the ManageHotels app for owners to add Hotels. The problem is , CreateView attempts to find the form template inside HotelApp/templates/HotelApp/hotels_forms.html I would rather put hotels_forms.html in the ManageHotels/templates/ManageHotels/hotels_forms.html How do I change the template path ? Thanks! -
django, init inherited model from super model
I want to save the history of what happens to objects stored in a particular model in my Django application. To that end I want to create a model that inherits from my "observed" model and adds two additional fields, history_id to override what is the primary key of the initial model, and when to save the time when a particular modification happened. Then I want to use the @receiver(pre_save, MyModel) to save that new model to DB. However, the difficulty I ran into is that I cannot easily instantiate the inherited model from the super model, for example, like this: inherited = InheritedModel(super_model_instance). For now it seems that I will have to write a serialiser to serialise the super model and to init the inherited model from it, but is there an easier way to do it? -
Django Select Widgets has string options values instead of integer
I have used a modelForm with a limited integer choice field: n = models.IntegerField(choices=[(1,1), (2,2), (3,3)]) The corresponding widget is naturally a Select Widget. The problem is the corresponding value to each option is formatted has a string instead of an integer. <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> When I post the selected value and clean my form, I get the following error: n must be an integer. FYI: I am working with Django 1.10. -
Django app generator
I made generator for django web application. I made my generator project in one file, and when I start generator, it makes django web app in new file. But I have one issue, I don't know hot to integrate generated code with hand written code. I make changes in generated django web app, but when I start my generator again, it override all hand written code. Can anyone help me with this problem? -
Decorator to cache expensive non-field django model attributes
I have some models, lets say it's something like this: class book(models.Model): name = models.CharField(max_length=256) ... class vote(models.Model): book = models.ForeignKey( book ) is_up = models.BooleanField( default = False ) ... class comment(models.Model): ... And I would like to have a decorator, ModelCacheAttr so that I can cache some expensive methods the first time they're used or calculated elsewhere. Like the total number of upvotes, downvotes and the overall percentage. Also, It's important to note that models should be cached based on their model_id rather than their python object id. And, It should be possible to removed a cache, in-case it has been expired, likely in a related vote's post_save signal. So lets extend the book class so that it covers all that I said: class book(models.Model): name = models.CharField(max_length=256) ... def _update_votes(self): U,D = 0,0 for v in vote.objects.filter( book_id = self.id ): if v.is_up: U+=1 else: V+=1 self.percentage.set_cache( U / (U + D) if U + D > 0 else 50 ) self.up_votes.set_cache( U ) self.down_votes.set_cache( D ) @ModelCacheAttr def percentage(self): self._update_votes() return self.percentage() @ModelCacheAttr def up_votes(self): self._update_votes() return self.up_votes() @ModelCacheAttr def down_votes(self): self._update_votes() return self.down_votes() @ModelCacheAttr def total_comments(self): return comments.objects.filter( book_id = self.id ).count() So far, this …