Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django output Fixtures from UserTeams
I am trying to print a list of fixtures for the logged in player, where the fixtures they can view are only those for the teams they are a member of. Basically I want to output the fixtures where the hometeamID/awayteamID = each teamID in UserTeams where the userID = request.user. Fixtures model: class Fixtures(models.Model): fixture = models.CharField(max_length=100) hometeamID = models.ForeignKey(Team,related_name='team1',on_delete=models.CASCADE) awayteamID = models.ForeignKey(Team,related_name='team2',on_delete=models.CASCADE) datetime = models.DateTimeField() homegoals = models.PositiveSmallIntegerField() awaygoals = models.PositiveSmallIntegerField() played = models.NullBooleanField() UserTeams model: class UserTeams(models.Model): userID = models.ForeignKey(User,on_delete=models.CASCADE) teamID = models.ForeignKey(Team,on_delete=models.CASCADE) Fixtures View: def fixturesview(request): query = Fixtures.objects.all() return render(request, 'teammanager/fixtures.html', { "fixtures": query }) HTML: <p>Fixtures</p> {%for team in teams%} <h3>{{fixtures.fixture}}</h3> {%endfor%} -
wkhtmltopdf with pdfkit not working on VPS server
I've installed wkhtmltopdf and xvfb. It's working fine in server with command line as well as in django/python shell but with uwsgi+nginx it throwing the below error wkhtmltopdf exited with non-zero code 127. error: /usr/bin/xvfb-run: 25: /usr/bin/xvfb-run: awk: not found /usr/bin/xvfb-run: 97: /usr/bin/xvfb-run: getopt: not found Django Version: 1.11.6 Exception Type: OSError Exception Value: wkhtmltopdf exited with non-zero code 127. error: /usr/bin/xvfb-run: 25: /usr/bin/xvfb-run: awk: not found /usr/bin/xvfb-run: 97: /usr/bin/xvfb-run: getopt: not found Exception Location: /home/dev/env3/lib/python3.5/site-packages/pdfkit/pdfkit.py in to_pdf, line 159 Python Executable: /usr/bin/uwsgi-core Python Version: 3.5.2 Thanks. -
Receive thumbnail of uploaded video in javascript
I have an upload box which changes its background to the uploaded image via the following code: $('input#id_image').on('change', function(e) { var imagePath = URL.createObjectURL(e.target.files[0]); $('.add_file_label').css('background', 'url(' + imagePath + ') scroll no-repeat center/cover'); }); however I want to be able to change the background when a video is uploaded, using a randomly generated thumbnail. I can already acquire that thumbnail in my Django backend via the following code using Moviepy (instance is the uploaded FileField: def generate_thumbnail(instance): filename = instance.image.path thumbnail = VideoFileClip(filename) name = random_string() + '.png' time = random.randrange(60) thumbnail.save_frame('media/' + name, t=time, withmask=True) instance.thumbnail = name and this thumbnail is used as the thumbnail after the form is submitted. However I need to obtain the thumbnail before the form is submitted as I want the upload box to change its background to the thumbnail as soon as the user selects their uploaded video (similar to how it changes when someone uploads an image). So is there any way to obtain the thumbnail generated from my Django backend? The thumbnail saves in my media folder but that's only after the form has been submitted so it isn't accessible via AJAX. Or could generating the thumbnail in the front-end … -
Customize Python package - django-paypal
I'm working on a project in which I need to make some changes in django-paypal package. I have cloned the package's GitHub repo and make a very simple change (Just change a form submit type=image source) and then install it via python setup.py install but now I couldn't find any path to import this package. For example when I install it by using pip install django-paypal i was able to import it like from paypal.standard.forms import PayPalPaymentsForm but after installing it via python setup.py install from my local changed source then it couldn't find any paypal package. How can i fix this issue? Help me, please! Thanks in advance! -
django data migration type not mach error
I have the following model class Region(models.Model): polygon = models.PolygonField(_("polygon")) name = models.CharField(_("name"), max_length=100) Now I am going to convert PolygonField to MultiPolygonField and for sure I have to convert the current data type from Polygon to MultiPolygon. The migration I have written: def convert_polygon_to_multipolygon(): migrations.RunSQL(""" UPDATE locations.region set polygon_tmp = (Select ST_Multi(polygon) from locations_region) """) class Migration(migrations.Migration): operations = [ migrations.AlterField( model_name='region', name='polygon', field=django.contrib.gis.db.models.fields.MultiPolygonField(srid=4326, verbose_name='polygon'), ), migrations.RunPython(convert_polygon_to_multipolygon), ] In which I change column type and then convert data, but I am facing this error: django.db.utils.DataError: Geometry type (Polygon) does not match column type (MultiPolygon) The other way I tried was to first create a new column with MultiPolygon type, then copy and convert Polygon column data to MultiPolygon in this new column, then remove the old Polygon column and rename the new column to Polygon again, which encounters the same error again. My migraion: def convert_polygon_to_multipolygon(): migrations.RunSQL(""" UPDATE locations.region set polygon_tmp = (Select ST_Multi(polygon) from locations_region) """) class Migration(migrations.Migration): operations = [ migrations.AddField( model_name='region', name='polygon_tmp', field=django.contrib.gis.db.models.fields.MultiPolygonField(srid=4326, verbose_name='polygon', null=True), ), migrations.AlterField( model_name='region', name='polygon', field=django.contrib.gis.db.models.fields.MultiPolygonField(srid=4326, verbose_name='polygon'), ), migrations.RunPython(convert_polygon_to_multipolygon), migrations.RemoveField( model_name='region', name='polygon', ), migrations.RenameField( model_name='region', old_name='polygon_tmp', new_name='polygon', ), ] where is the problem? tnx -
how to give a user to a model field to choose from during signup?
how to make a user registration form including a model field in it as a required field? like i want college field to show up on registration page as a drop-down menu my models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) college = models.ForeignKey(College, on_delete=models.CASCADE) @receiver(post_save, sender=User) def update_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) instance.profile.save() class College(models.Model): col = models.CharField(max_length=100) def __str__(self): return self.col my forms.py class SignUpForm(UserCreationForm): college = forms.CharField() class Meta: model = User fields = ('username', 'college', 'password1', 'password2', ) and the views.py includes this: def signup(request): if request.method == 'POST': form = SignUpForm(request.POST) if form.is_valid(): user = form.save() user.refresh_from_db() user.save() raw_password = form.cleaned_data.get('password1') user = authenticate(username=user.username, password=raw_password) login(request, user) return redirect('home') else: form = SignUpForm() return render(request, 'registration_form.html', {'form': form}) -
django - Importing dictionary data into model data with Foreign Key
I get the below model.py from django.db import models class User(models.Model): user_name = models.CharField(max_length = 50) def __str__(self): return self.user_name class Profile(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE,) hobby = models.CharField(max_length = 50, unique = True) job = models.CharField(max_length = 60) I created a user object instance named 'Elvin'. I get the below views.py from django.shortcuts import render from django.db import IntegrityError from .models import User, Profile item = { 'user': 'Elvin', 'hobby': 'horse riding', 'job': 'banker'} def create(request): try: profile = Profile.objects.create(**item) profile.save() except IntegrityError: pass template = 'index.html' thing = Profile.objects.order_by('-hobby') context = {'thing':thing} return render(request, template, context) However, it returns a ValueError. Cannot assign "'Elvin'": "Profile.user" must be a "User" instance. I wonder how i can import my dictionary data into a ForeignKey data in model data? Thanks. -
myslq-python install error: Cannot open include file: 'config-win.h
Hi, Im trying to 'pip install mysql-python' and I keep getting an error. I was wondering if anyone knows what I need to do get this working? I'm using Windows 10, python 3.6 and mysql 5.7. I'm new to coding so if there is something I missed please let me know. Thanks This is the error I keep getting: _mysql.c(42): fatal error C1083: Cannot open include file: 'config-win.h': No such file or directory error: command 'C:\\Program Files (x86)\\Microsoft Visual Studio\\2017\\Community\\VC\\Tools\\MSVC\\14.13.26128\\bin\\HostX86\\x64\\cl .exe' failed with exit status 2 -
django.db.utils.DataError: invalid input syntax for integer: "user"
I made one change to my model, everything went fine during python manage.py makemigrations but then when I ran python manage.py migrate I got this error and traceback: django.db.utils.DataError: invalid input syntax for integer: "user" File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 356, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/usr/local/lib/python2.7/dist-packages/django/core/management/commands/migrate.py", line 204, in handle fake_initial=fake_initial, File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/executor.py", line 115, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/executor.py", line 145, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/executor.py", line 244, in apply_migration state = migration.apply(state, schema_editor) File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/migration.py", line 129, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/operations/fields.py", line 216, in database_forwards schema_editor.alter_field(from_model, from_field, to_field) File "/usr/local/lib/python2.7/dist-packages/django/db/backends/base/schema.py", line 515, in alter_field old_db_params, new_db_params, strict) File "/usr/local/lib/python2.7/dist-packages/django/db/backends/postgresql/schema.py", line 112, in _alter_field new_db_params, strict, File "/usr/local/lib/python2.7/dist-packages/django/db/backends/base/schema.py", line 684, in _alter_field params, File "/usr/local/lib/python2.7/dist-packages/django/db/backends/base/schema.py", line 120, in execute cursor.execute(sql, params) File "/usr/local/lib/python2.7/dist-packages/django/db/backends/utils.py", line 80, in execute return super(CursorDebugWrapper, self).execute(sql, params) File "/usr/local/lib/python2.7/dist-packages/django/db/backends/utils.py", line 65, in execute return self.cursor.execute(sql, params) File "/usr/local/lib/python2.7/dist-packages/django/db/utils.py", line 94, in __exit__ six.reraise(dj_exc_type, dj_exc_value, traceback) File "/usr/local/lib/python2.7/dist-packages/django/db/backends/utils.py", line 65, in … -
Does django accept Jinja loop together with condintion in one line?
There's a wonderful example in Jinja docs regarding how not to use break: {% for user in users if not user.hidden %} <li>{{ user.username|e }}</li> {% endfor %} However when trying to use similar approach in Django template it gives me error: TemplateSyntaxError at /childminder/task-list/ 'for' statements should use the format 'for x in y': for link in form.links if link.status == form.status Original code: {% for link in form.links if link.status == form.status %} {% url link.url id=application_id %} {% else %} {% for link in form.links if link.status == "Other" %} {% url link.url id=application_id %} {% endfor %} {% endfor %} Point is that I list of links in a list of forms (so those links belongs to specific form only), and there's status and url in that list of links. IF all link statuses didn't match form statuses THEN search for link status Other and print it's link. Can't come up with another approach. Just adding one more link_default object to a form doesn't sound too good for me. -
MoviePy error: the file /tmp/testvideo.mp4 could not be found ! Please check that you entered the correct path
I'm trying to generate a thumbnail from an uploaded video using Moviepy. Here's my function (instance is the uploaded FileField (video)): def generate_thumbnail(instance): filename = instance.image.path.split('/')[-1] print(filename) #successfully prints name of uploaded file: "testvideo.mp4" thumbnail = VideoFileClip('/tmp/%s' % filename) #this line sparks the error name = random_string() + '.png' time = random.randrange(60) thumbnail.save_frame('media/' + name, t=time, withmask=True) instance.thumbnail = name thumbnail = VideoFileClip('/tmp/%s' % filename) returns the error: OSError at /post/ MoviePy error: the file /tmp/testvideo.mp4 could not be found ! Please check that you entered the correct path. Full Traceback: Traceback: File "/Users/zorgan/Desktop/app/lib/python3.5/site-packages/django/core/handlers/exception.py" in inner 41. response = get_response(request) File "/Users/zorgan/Desktop/app/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "/Users/zorgan/Desktop/app/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/zorgan/Desktop/app/lib/python3.5/site-packages/django/contrib/auth/decorators.py" in _wrapped_view 23. return view_func(request, *args, **kwargs) File "/Users/zorgan/Desktop/project/site/post/views.py" in post 50. generate_thumbnail(instance) File "/Users/zorgan/Desktop/project/site/functions/helper_functions.py" in generate_thumbnail 45. thumbnail = VideoFileClip('/tmp/%s' % filename) File "/Users/zorgan/Desktop/app/lib/python3.5/site-packages/moviepy/video/io/VideoFileClip.py" in __init__ 81. fps_source=fps_source) File "/Users/zorgan/Desktop/app/lib/python3.5/site-packages/moviepy/video/io/ffmpeg_reader.py" in __init__ 32. fps_source) File "/Users/zorgan/Desktop/app/lib/python3.5/site-packages/moviepy/video/io/ffmpeg_reader.py" in ffmpeg_parse_infos 272. "path.")%filename) Exception Type: OSError at /post/ Exception Value: MoviePy error: the file /tmp/testvideo.mp4 could not be found ! Please check that you entered the correct path. Any idea what the problem is? -
Model object has no attribute HyperlinkedRelatedField
I've checked dozens of examples and I think I am doing it the right way, however I am getting this error message 'City' object has no attribute 'store', Please help, see my serializer enclosed. class CitySerializer(serializers.HyperlinkedModelSerializer): store = serializers.HyperlinkedRelatedField(view_name = 'store:listStoreByCity',read_only=True) class Meta: model = City read_only_fields = ['location'] fields = [ "city", "latitude", "longitude", "store", "state", "img", "location", ] -
Expecting None type value for PositiveSmallIntegerField
I have following model class class GroupstageTournamentModel(ClusterableModel): #Score of TEAM 1 team_1_first_halftime_score = models.PositiveSmallIntegerField(blank=True, default=None, verbose_name='Resultat 1. HZ') team_1_first_halftime_point = models.PositiveSmallIntegerField(blank=True, default=0, verbose_name='Punkte 1. HZ') team_1_second_halftime_score = models.PositiveSmallIntegerField(blank=True, default=None, verbose_name='Resultat 2. HZ') team_1_second_halftime_point = models.PositiveSmallIntegerField(blank=True, default=0, verbose_name='Punkte 2. HZ') team_1_shootout_score = models.PositiveSmallIntegerField(blank=True, default=None, verbose_name='Resultat Shootout') team_1_shootout_point = models.PositiveSmallIntegerField(blank=True, default=0, verbose_name='Schootout Punkte') team_1_total_score = models.PositiveSmallIntegerField(blank=True, default=0, verbose_name='Resultat Total') team_1_total_points = models.PositiveSmallIntegerField(blank=True, default=0, verbose_name='Punkte Total') #Score of TEAM 2 team_2_first_halftime_score = models.PositiveSmallIntegerField(blank=True, default=None, verbose_name='Resultat 1. HZ') team_2_first_halftime_point = models.PositiveSmallIntegerField(blank=True, default=0, verbose_name='Punkte 1. HZ') team_2_second_halftime_score = models.PositiveSmallIntegerField(blank=True, default=None, verbose_name='Resultat 2. HZ') team_2_second_halftime_point = models.PositiveSmallIntegerField(blank=True, default=0, verbose_name='Punkte 2. HZ') team_2_shootout_score = models.PositiveSmallIntegerField(blank=True, default=None, verbose_name='Resultat Shootout') team_2_shootout_point = models.PositiveSmallIntegerField(blank=True, default=0, verbose_name='Schootout Punkte') team_2_total_score = models.PositiveSmallIntegerField(blank=True, default=0, verbose_name='Resultat Total') team_2_total_points = models.PositiveSmallIntegerField(blank=True, default=0, verbose_name='Punkte Total') And as you can see some of my PositiveSmallIntegerField's are deafult=None. And if I save this model I get an Error django.db.utils.IntegrityError: NOT NULL constraint failed: tournament_groupstagetournamentmodel.team_1_first_halftime_score Can I somehow ignore this error and save this model? I deliberately made the default value None -
Django admin site gives error on Djangae
I have a Django app that works perfectly on google app engine, using the datastore via djangae. However, the admin site throws an error: NotSupportedError at /admin/auth/user/5629499534213120/change/ Cross-join where filters are not supported on the Datastore This error only occurs when trying to edit the default Django user model. Not sure why this is happening but I need help ASAP! -
Filtering django REST results by SerializerMethodField
How would I filter results based on a computed field from a Serializer? I tried treating it like any other field, but django doesn't like it. Serializer class ImageSerializer(serializers.ModelSerializer): is_annotated = serializers.SerializerMethodField('has_annotation') class Meta: model = Image fields = '__all__' @staticmethod def has_annotation(image): return image.annotation_set.count() > 0 View class ImageViewSet(viewsets.ModelViewSet): serializer_class = ImageSerializer lookup_field = 'id' permission_classes = [ Or(IsAdmin), IsAuthenticated ] def get_queryset(self): queryset = Image.objects is_annotated_filter = self.request.query_params.get('is_annotated', None) if is_annotated_filter is not None: queryset = queryset.filter(is_annotated=is_annotated_filter) queryset_order = get_queryset_order(self.request) return queryset.order_by(queryset_order).all() http://www.django-rest-framework.org/api-guide/filtering/#filtering-against-query-parameters http://www.django-rest-framework.org/api-guide/fields/#serializermethodfield -
How to set dynamic content in a javascript popover
I have a page showing a large number of words. For each word I can run a non-trivial database query (left joining a few tables, for example). I would like the result of that query to be shown in a popover when I click on the word. Running all the queries when the page is generated is not really an option as it would take a long time and be a bit wasteful. Ideally, I would have a setup where, when clicking on the word, I somehow send a query to the server which would respond with the query result. I would then display the query result in the popover. I am a beginner when it comes to webdev, but I imagine I am not the first person to have this use-case. What would be the easiest way of obtaining the effect I have described above? I am using popover.js (via Bootstrap 4). The server is written in Django, if it matters. -
download files with angular 4
I am doing a component in angular 4 and an api of django rest framework to upload documents and this part I already have it done, but I must already make the file that was uploaded to be downloaded, with the api genre a temporary route where the document will be and I return the route from this to angular, but I do not know how to proceed in angular to download the file of the route that I generate the api -
Filter JSON results - Django 1.8 - Github API v3
I'm trying to filter the result of an API query on template, I have this method: def profile(request): parsedData = [] if request.method == 'POST': username = request.POST.get('user') req = requests.get('https://api.github.com/users/' + username + '/repos') jsonList = [] jsonList=req.json() for data in jsonList: userData = {} userData['html_url'] = data['html_url'] userData['created_at'] = data['created_at'] userData['updated_at'] = data['updated_at'] userData['forks_count'] = data['forks_count'] repo_instance = Repo.objects.create(name=data['html_url'],created_at=data['created_at'],updated_at=data['updated_at'],forks_count=data['forks_count']) repos = Repo.objects.filter(updated_at__lt = timezone.now()).order_by('updated_at') parsedData.append(userData) return render(request, 'app/profile.html', {'data': parsedData}) This method, makes a query into an address like this one for example githubtraining Also stores every repository found into the db. Now, what I want, is to filter the results obtained from this query into the view of my app, this is what I have on my template: <div class="table-responsive"> <table class="table table-bordered table-hover table-striped tablesorter"> <thead> <tr> <th class="header"> Url <i class="icon-sort"></i></th> <th class="header"> Created at <i class="icon-sort"></i></th> <th class="header"> Updated at <i class="icon-sort"></i></th> <th class="header"> Forks count <i class="icon-sort"></i></th> </tr> </thead> <tbody> {% for key in data %} <tr> <td>{{ key.html_url }}</td> <td>{{ key.created_at }}</td> <td>{{ key.updated_at }}</td> <td>{{ key.forks_count }}</td> </tr> {% endfor %} </tbody> </table> </div> As You can see, the API returns the repo with some JSON data, one of these items … -
Django: Do I have to check if variable is not NULL in clean() method?
In my models.py I have a clean() method that should do some validation affecting multiple fields of a model. However, I noticed that I have to check for every field that I need in the clean() method if it's not null. Even if the fields have blank=False the clean() method is run although not all required fields have been filled. So here can you find my clean() method now: def clean(self): if self.fieldA and self.fieldB: if self.fieldA > self.fieldB: raise ValidationError("Some text") if self.fieldC and self.fieldA: if self.fieldC > self.fieldA: raise ValidationError("Some other text") if self.fieldD and self.fieldB: if self.fieldD < self.fieldB: raise ValidationError("Some other text") My question: Is that really the way to go, am I doing it the right way? Because in the docs I could not find all those checks if the fields are available. However, in my experience it showed they are. I'd like to have some input/explanation from experienced Django devs. -
error django auth.py registrations
File "C:\Python34\lib\importlib__init__.py" in import_module 104. return _bootstrap._gcd_import(name[level:], package, level) File "C:\Python34\lib\site-packages\registration\auth_urls.py" in 27. from django.urls import reverse_lazy Exception Type: ImportError at / Exception Value: No module named 'django.urls' -
django rest framework and react native user authentication with undefined response
I am very new to this and would like to know how to do this properly. My back end is a django rest framework and my front is under react native. my back end has users and my application requires token authentication to identify a user. After exploring react native further i know i will need to use fetch and post methods to access the api. successful authentication should get the user to navigate to the main page This is what i have so far: import React, { Component } from 'react'; import { StyleSheet, Text, View, TextInput, KeyboardAvoidingView, TouchableOpacity, AsyncStorage, } from 'react-native'; export default class Form extends Component<{}> { constructor(props){ super(props); this.state = { username: "", password: "", } } componentDidMount(){ this._loadInitialState().done(); } _loadInitialState= async() => { var value = await AsyncStorage.getItem('user'); if (value !== null){ this.props.navigation.navigate('Main') } } render(){ return( //<KeyboardAvoidingView style={styles.wrapper}> <View style={styles.container}> <TextInput style={styles.boxInput} underlineColorAndroid='rgba(0,0,0,0)' placeholder="Username" onChangeText={ (username) => this.setState({username}) } underlineColorAndroid='transparent' onSubmitEditing={()=> this.password.focus()}/> <TextInput style={styles.boxInput} underlineColorAndroid='rgba(0,0,0,0)' placeholder="Password" onChangeText={ (password) => this.setState({password}) } underlineColorAndroid='transparent' secureTextEntry={true} ref={(input) => this.password = input}/> <TouchableOpacity style={styles.button} onPress={this.login}> <Text style={styles.textButton}>{this.props.type}</Text> </TouchableOpacity> </View> //</KeyboardAvoidingView> ); } login = () => { //alert(this.state.username); fetch('http://.../token-auth/', { method: 'POST', headers : { 'Authorization': 'Token' … -
Django / PostgreSQL: auto-increment a row's field on update
I want to implement a row version number that increments whenever a table row is updated. I'm using PostgreSQL. Essentially I want this field to behave similarly to the following updated_at timestamp field: updated_at = models.DateTimeField(auto_now=True) Except instead of updating with the current time, I want to auto-increment the current field value of the row. So if the row had version=1 and I made an update on the row, it would autoincrement that row to version=2. I know I can implement this by overwriting the model save() method, but I was wondering if there was a way to implement this on the database level (and ideally through the Django ORM) so that it applies to any database accessing script/query. -
Django serialize POST & PUT request in a nested object
I'm using the Writable Nested Serializer to serialize my request. I had no problem serializing doing PUT/POST when the data is nested in 1 layer. (i.e. {name:'personA', project:{ name:'projA', client:'clientA'}}) However, I ran into a problem when it is nested in 2 layers - I couldn't figure out on how to modify the update() function. Please help! data sample { "id": 6106, "name": { "id": 213, "name": "personA" }, "project": { "id": 1663, "project": "ProjectA", "client": { "id": 72, "name": "ClientA" }, "project_manager": { "id": 32, "name": "personB" } }, "booking": 100, "date": "2017-12-01" } serializers.py class projectSerializer(serializers.ModelSerializer): client = clientSerializer() project_manager = userSerializer() class Meta: model = project fields = ('id', 'project', 'client', 'project_manager') class bookingListSerializer(serializers.ModelSerializer): project = projectSerializer() name = userSerializer() class Meta: model = bookingList fields = ('id', 'name', 'project', 'booking', 'date') def update(self, instance, validated_data): project_data = validated_data.pop('project') name_data = validated_data.pop('name') try: project_instance = project.objects.filter(**project_data)[0] name_instance = user.objects.filter(**name_data)[0] except IndexError: raise serializers.ValidationError # update the project if request is valid instance.project = project_instance instance.name = name_instance instance.save() return instance views.py # other viewsets... class bookingListViewSet(viewsets.ModelViewSet): queryset = bookingList.objects.all() serializer_class = bookingListSerializer -
Method for calculating the final score of fields with type of None
Help me please figure out how to correctly check the value of the fields and draw up a total score of goals. The problem is that the final estimate is calculated by the pre_save method. And model has first half time of match, second half time of match and shootout score. User can just update the first halftime score and save that model in this case pre_save will take this value, add it to total score and ignore second halftime and shootout. But after second halftime of match, User have to update the score of second halftime and then pre_save method will calculate this two values (first and second) and ignore shootout and so one. I hope you will understand what I will achieve. Here is my model: class GroupstageTournamentModel(ClusterableModel): #Score of TEAM 1 team_1_first_halftime_score = models.PositiveSmallIntegerField(blank=True, default=None, verbose_name='Resultat 1. HZ') team_1_first_halftime_point = models.PositiveSmallIntegerField(blank=True, default=0, verbose_name='Punkte 1. HZ') team_1_second_halftime_score = models.PositiveSmallIntegerField(blank=True, default=None, verbose_name='Resultat 2. HZ') team_1_second_halftime_point = models.PositiveSmallIntegerField(blank=True, default=0, verbose_name='Punkte 2. HZ') team_1_shootout_score = models.PositiveSmallIntegerField(blank=True, default=None, verbose_name='Resultat Shootout') team_1_shootout_point = models.PositiveSmallIntegerField(blank=True, default=0, verbose_name='Schootout Punkte') team_1_total_score = models.PositiveSmallIntegerField(blank=True, default=0, verbose_name='Resultat Total') team_1_total_points = models.PositiveSmallIntegerField(blank=True, default=0, verbose_name='Punkte Total') #Score of TEAM 2 team_2_first_halftime_score = models.PositiveSmallIntegerField(blank=True, default=None, verbose_name='Resultat 1. HZ') team_2_first_halftime_point = models.PositiveSmallIntegerField(blank=True, … -
Can anyone help me with search algorithem in django?
I am new to django, I am trying to make a search box in which you can add a name and it searches through the database and to find results having similar name. This is my views: def result(request): # Shows the matched result request.GET.get('q') incubators = Incubators.object.all() check = Incubators.objects.filters(incubator_name__icontains="q") return render(request, 'main/results.html', {'check': check}) My HTML file goes like: {%extends 'main/base.html'%} {%load staticfiles%} {%block title%} Incubators: Search and Apply through e-application {%endblock%} {%block content%} <link href="{%static "main/incubator/incubator.css"%}" rel="stylesheet" id="bootstrap-css"> <script src="//netdna.bootstrapcdn.com/bootstrap/3.1.0/js/bootstrap.min.js"></script> <script src="//code.jquery.com/jquery-1.11.1.min.js"></script> <!------ Include the above in your HEAD tag ----------> <div class="topnav"> <a class="active" href="#home">Top Incubators</a> <a href="#about">Nearest</a> <a href="#contact">Recomnded</a> <input type="text" class = "search-inc" name = "q" value = "{{query}}" placeholder="Search Incubator"> </div> {%for inc in incubators%} <div class = "inc_list"> <ul class="large-icon-list clearfix"> <li class="icon-list-sheets"> <div class="icon-list-image" ><img src = "../../static/main/incubators/logo/{{inc.logo}}"></div> <div class="icon-list-content"> <a href = 'main:details' class = "detail-link"><h4 class = "inc_title">{{inc.incubator_name}}</h4> </a> <h5 class = "inc_location">{{inc.city_location}}</h5> <p class = "inc_desc">{{inc.description}}</p> </div> </ul> </div> {%endfor%} {%endblock%} I am facing the following problems: 1) First my HTML search box is not showing response. 2) What should be my url pattern for the result.html and is there a way that I don't have to create …