Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 … -
Django Timezone unaware DateTimeField Error
I have a simple Post model in my blog app as follows: class Post(CreateUpdateDateModel): # ... body = models.TextField() publish = models.DateTimeField() # ... def get_absolute_url(self): print(self.publish) return reverse( 'blog:post_detail', args=( self.publish.year, self.publish.month, self.publish.day, self.slug ) ) In my settings.py, I have: TIME_ZONE = 'Asia/Kolkata' USE_TZ = True I am using Django Admin to creat Post instances. Django Admin shows/displays correct time (local time, March 10). The printing the publish date in get_absolute_url method displays 2018-03-09 19:54:29+00:00. This leades to generation of incorrect url causing errors like: DoesNotExist at /blog/2018/3/9/third-blog-normal/ Please help or provide hints to resolve this issue. -
Updating A Profile Model Object in Django
I've searched and searched to try to figure out my issue or what I need to do here. I'm new to Django and havn't quite gotten the hang of allowing a user to change a model Object of a database through a form. What my code is doing is creating a default 'Profile' database whenever the user signs up with the following code: Models.py: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) state = models.CharField(max_length= 20, choices=STATE_CHOICES,default='N/A',) city = models.CharField(max_length=30,null=True, blank=True) birth_date = models.DateField(null=True, blank=True) Primary_Campaign_Interest = models.CharField(max_length=30, choices=Interest_choices, null='000') Secondary_Campaign_Interest = models.CharField(max_length=30, choices=Interest_choices, null='000') @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() This generates an empty table in my database that I would like the user to then be able to edit through a form. However, I would only like for the user to be able to edit the state and city fields along with some of the user fields, not the username. forms.py class ProfileForm(forms.ModelForm): class Meta: model = Profile fields = ('state','city') views.py @login_required @transaction.atomic def update_profile(request): if request.method == 'POST': user_form = SignUpForm(request.POST, instance=request.user) profile_form = ProfileForm(request.POST, instance=request.user.profile) if user_form.is_valid() and profile_form.is_valid(): user_form.save() profile_form.save() messages.success(request, _('Your profile was successfully … -
How to display the data of an Inline in a (ListView) that is in a class based on function? Django
I have an inLine in my create function which works very well, but to which I now want that inLine to pass it to my view based on class ArancelListView (ListView), the inline has code and description, that fields I want to pass to my listView, If someone has an idea of how to follow this, it would be of great help to me. Thank you. def ArancelCreateUpdate(request, pk=None): if pk: arancel = Arancel.objects.get(pk=pk) title_meta = u'Arancel: Actualización' title = u'Arancel' nav = ( ('Panel Mando', '/'), ('Arancel', reverse('arancel_list')), ('Actualización', '') ) else: arancel = Arancel() title_meta = u'Arancel: Registro' title = u'Arancel' nav = ( ('Panel Mando', '/'), ('Arancel', reverse('arancel_list')), ('Registro', '') ) # formset ArancelTipoIMDGFormset = inlineformset_factory(Arancel, ArancelTipoIMDG, extra=0, can_delete=True, fields=('arancel', 'tipo_imdg'), min_num=0, validate_min=True) if request.method == 'POST': next = request.GET.get('next') form = ArancelForm(request.POST, instance=arancel) arancelTipoIMDGFormset = ArancelTipoIMDGFormset(request.POST, instance=arancel) if form.is_valid() and arancelTipoIMDGFormset.is_valid(): resultado = ArancelTipoIMDG.validar_formset(arancelTipoIMDGFormset) if resultado['estado'] == 'OK': arancel = form.save() arancelTipoIMDGFormset.save() if next == 'new': return redirect(reverse('arancel_create')) if next == 'self': return redirect(arancel.get_update_arancel_url()) else: return redirect('arancel_list') else: errores = resultado['msg'] return render('administrador/arancel/arancel_form.html', locals(), context_instance=ctx(request)) else: form = ArancelForm(instance=arancel) arancelTipoIMDGFormset = ArancelTipoIMDGFormset(instance=arancel) return render('administrador/arancel/arancel_form.html', locals(), context_instance=ctx(request)) HTML: <form id="form" action="#" method="post" enctype="multipart/form-data" class="form-horizontal"> {% csrf_token %} … -
How to Add Attribute to Django QuerySet That Will Get Serialized?
I have two Django 1.8 models that represent lists and items in lists. I also have a view that uses the Django REST framework to act as a REST endpoint and a template containing an jQuery Ajax block that calls this endpoint. This view gets all the lists owned by a particular user and looks to see if a given item is in any of the lists. Whenever it finds such an item, it should add an 'in_list' attribute to the data being passed back to the template. The problem I'm having is that while I can add this extra 'in_list' attribute to the list, it doesn't get picked up by the serializer and added to the serialized data. Here's the code: # views.py def get_viewer_lists_checked(request, *args, **kwargs): user = User.objects.get(id=kwargs['viewer_id']) lists = List.objects.filter(user=user, type=type) item = Item.objects.get(value=kwargs['viewed_id']) if item: for list in lists: if List.contains_item(item, list): list.in_list = True else: list.in_list = False serializer = MemberListsSerializer(lists, many=True) return JSONResponse(serializer.data) # models.py class List(models.Model): user = models.ForeignKey(User) name = models.CharField(_('list'), max_length=128) @classmethod def contains_item(cls, item, list, *args, **kwargs): try: item.lists.get(id=list.id) return True except List.DoesNotExist: return False class Item(models.Model): lists = models.ManyToManyField(List, related_name='items') value = models.IntegerField(_('value')) # serializer.py class MemberListsSerializer(serializers.ModelSerializer): class … -
Getting Max count based on Vehid group by Houseid Django
I am trying to get the Max count of a Vehid together with the housid. So, the problem is something like Houseid Vehid 1 1 1 1 1 2 1 2 1 2 2 1 2 1 2 2 2 3 3 1 3 2 4 1 4 2 4 3 4 3 And the output should be the max occurrence of a vehid used by a houseid. Like in this case. Housed Vehid 1 2 2 1 3 1 3 2 4 3 So, I wrote a Django query ModelClassName.objects.values('houseid','vehid').annotate(Count('vehid')).order_by('houseid') This is giving me the count of each vehid but as I am not sure how to incorporate Max here, I am unable to get the right result. Any help is appreciable. Thanks. -
How to perform SELECT FOR UPDATE with SKIP LOCKED on MySQL with Django
I have a Django project which uses a MySQL v5.5 backend with InnoDB storage. To avoid race condition updates in DB, I'm using select_for_update to lock the rows. Now if this lock stays for a long time, any queries on the locked rows will timeout. I want to avoid this with one of the following options: Skip the rows which are locked, similar to SKIP LOCKED option. Return immediately if some rows you're querying are locked, similar to NOWAIT option. Reduce the lock wait timeout period for specific queries. How do I perform any of these with Django ORM. -
How to compare less than or equals with only date of field having timestamp with timezone field
i am using default auth_user table with field date_joined as type as timestamp with time zone. All i want to check use the lte and gte comparison on only its date not with the time and zone. def get_fm_objects(self, filters): fm = FacilityManager.objects.all().order_by('-id') if filters['from_date']: fm = fm.filter(user__date_joined__gte=filters['from_date']) if filters['to_date']: fm = fm.filter(user__date_joined__lte=filters['to_date']) return fm here FacilityManager is another model and filters['from_date'] and filters['to_date'] are my input dates(it only contains date. eg:2018-1-10). i have a row in auth_user table with date_joined as 2018-01-11 00:56:39.735756+05:30 but when i give From and To date as 2018-01-11 it returns nothing. looking for answers. Thanks in advance. -
JSON API and django database
Hello I'm new with Django I'm traying to create my first application with django using a Json API to get that from the net I wanna to know how to save this data to my database I got the data in a forms.py like that: from django import forms import requests from .models import Series API_KEY = 'af237ff4830b5773f3d23f396e6f8616' class SeriesAPI(forms.Form): serie = forms.CharField(label='Search for Serie', max_length=100) def search(self): result = {} serie = self.cleaned_data['serie'] endpoint = 'https://api.themoviedb.org/3/search/tv?api_key={api_key}&query={serie_name}' url = endpoint.format( api_key = API_KEY, serie_name = serie ) response = requests.get(url) if response.status_code == 200: result = response.json() if result['total_results'] >= 1: id = result['results'][0]['id'] else: return None return id def get_serie(self): result = {} endpoint = 'https://api.themoviedb.org/3/tv/{id}?language=en-US&api_key={api_key}' url = endpoint.format( id = self.search(), api_key = API_KEY ) response = requests.get(url) if response.status_code == 200: result = response.json() return result right now everything's good I got the data and I showed it; I create a new form with only submit input to store the data but I can't do it this is my views.py: def index(request): search_result = {} form = SeriesAPI(request.POST or None) if 'serie' in request.POST: if form.is_valid(): search_result = form.get_serie() else: form = SeriesAPI() return render(request, 'series/serie.html', {'form': … -
Getting first few links from custom google search
i'm very new to web development . I'm using the custom google search engine for my webapp . I don't know if there is a way or api to get , say first 10 links from custom google search . -
Django-rest-auth + Allauth Twitter. Error 89. Invalid or expired token
I'm using Django with Allauth + REST-Auth for SPA social Login and successfully set up Facebook, VK and Google authorization but faced a problem while adding Twitter. It ends up with {"code":89,"message":"Invalid or expired token."} Looks like i'm missing something 'cos standard login with Twitter works as it should Here are my tries: First of all, i've set Twitter login endpoint as described in doc: class TwitterLogin(SocialLoginView): serializer_class = TwitterLoginSerializer adapter_class = CustomTwitterOAuthAdapter It features post method, expecting access_token and token_secret So redirect view was created to receive redirect from twitter, complete login and set token to browser localStorage via template render: class TwitterReceiveView(APIView): def get(self, request, *args, **kwargs): access_token = request.query_params.get('oauth_token') token_secret = request.query_params.get('oauth_verifier') params = {'access_token': access_token, 'token_secret': token_secret} try: s = requests.Session() result = s.post(settings.DOMAIN + reverse('tw_login'), data=params).text result = json.loads(result) except (requests.HTTPError, json.decoder.JSONDecodeError): result = {} access_token = result.get('access_token') context = {'access_token': access_token} return render(request, 'account/local_storage_setter.html', context, content_type='text/html') Have to mention that I tried two methods to start process(get initial token) 1. Used standard allauth url http://0.0.0.0:8080/accounts/twitter/login 2. Created another view (using lib python oauth2) which could be used from SPA: class TwitterGetToken(APIView): def get(self, request, *args, **kwargs): request_token_url = 'https://api.twitter.com/oauth/request_token' authorize_url = 'https://api.twitter.com/oauth/authorize' app = … -
Django: output textfile to be proceeded
i have a small django application that i use to manage my patients data ( i am a doctor with an intermediate level in python/django) I used LaTeX to output my reports via a view function like that def consultation_pdf(request, pk2, pk1): entry = Consultation.objects.get(pk=pk2) source = Patient.objects.get(pk=pk1) # context = Context({ 'consultation': entry, 'patient': source }) context = dict({'consultation': entry, 'patient': source}) template = get_template('clinic/consultation.tex') rendered_tpl = template.render(context, request).encode('utf-8') # Python3 only. For python2 check out the docs! with tempfile.TemporaryDirectory() as tempdir: # Create subprocess, supress output with PIPE and # run latex twice to generate the TOC properly. # Finally read the generated pdf. for i in range(2): process = Popen( ['xelatex', '-output-directory', tempdir], stdin=PIPE, stdout=PIPE, ) process.communicate(rendered_tpl) with open(os.path.join(tempdir, 'texput.pdf'), 'rb') as f: pdf = f.read() r = HttpResponse(content_type='application/pdf') r.write(pdf) return r Now i need to switch to ConTeXT since it fills more my needs. The biggest problem so far is that ConTeXT needs both the source file and the pdf to be saved on the disk, and not simply piping stdin and stdout , respectively. How could i manage to complete this task? so far the only workaround i've found is to generate a tex file … -
When to use NullBooleanField in Django
I have a button that, when clicked, should save in the database that the user has drunk water. I just wanted to check whether NullBooleanField would be the correct way to define this. A broader question that if answered would be useful to the community is a list of optimal circumstances under which to use NullBooleanField. But I'm not asking that here. Just in case you wanted a better challenge. Thank you in advance. -
Django add user to 'team'
I want the logged in user to be able to add users to a team they have created. At the moment I have created a form which lets the user select the user and the team they want to add them to, but they can select from every team in the database rather than just those they have created. Any ideas? These are my models, view and the form i have created. Also help with what to put in my HTML file would be appreciated. Models: class UserTeams(models.Model): userID = models.ForeignKey(User,on_delete=models.CASCADE) teamID = models.ForeignKey(Team,on_delete=models.CASCADE) class Team(models.Model): name = models.CharField(max_length=100) venue = models.CharField(max_length=100) countryID = models.ForeignKey(Countries, on_delete=models.CASCADE) owner = models.ForeignKey(User) View: def invite(request): if request.method == 'POST': form = InvitePlayerForm(request.POST) if form.is_valid(): userteam = form.save(commit=False) userteam.save() else: form = InvitePlayerForm() query = UserTeams.objects.all() return render(request, 'teammanager/invite.html', { "invite": query, "form": form }) Form: class InvitePlayerForm(forms.ModelForm): class Meta: model = UserTeams fields = ['userID','teamID'] -
Django serialization validation optimization for bulk create
I am trying to write an api to process large number of rows of data using bulk_create on zipped csv records. but when serializer.is_valid() is called to validate the data before calling serializer.save(), it takes a long time to validate due to the foreign key constraint for device_id(sensorReading_device). I've tried prefetch_related() & select_related() and nested serializer and the performance is similar or worse as i suspect the modelserializer is committing the n+1 DB roundtripping problem for validation due to the foreign key. The only method which worked is to remove the foreign key in my model and implement as charfield and it became blazingly fast but it means there will be no more foreign key constraint. Is the removal of foreign key the way forward or am I missing something? heres my code and any advice is greatly appreciated! serializer.py class SensorReadingListSerializer(serializers.ListSerializer): def create(self, validated_data): sensor_readings = [SensorReading(**item) for item in validated_data] return SensorReading.objects.bulk_create(sensor_readings) class SensorReadingSerializer(serializers.ModelSerializer) device_qs = Device.objects.all() sensorReading_device = PrimaryKeyRelatedField(label='SensorReading device', many=True, queryset=device_qs) class Meta: model = ReadingsModel.SensorReading fields = ('id', 'device_timestamp', 'server_timestamp', 'payload', 'sensorReading_device') list_serializer_class = SensorReadingListSerializer model.py class Device(models.Model): device_id = models.CharField(primary_key=True, max_length=120) device_deviceType = models.ForeignKey(DeviceType, on_delete=models.CASCADE) device_softwareVersion = models.ForeignKey(SoftwareVersion, on_delete=models.CASCADE) class SensorReading(models.Model): device_timestamp = models.DateTimeField(default=datetime.today) … -
Upgraded Django(1.11) & Django-cms(3.5.0) - pages no longer appearing
So I've successfully upgraded a django site (django 1.4 - 1.11. Python 2.5 - 3.5. Django-CMS 2.4 - 3.5) I started with a fresh database, made the migrations, migrated and everything went fine. No conflicts, no issues. Yes I'm doing it all locally for now. My internet is horrific so I'd rather do it locally, get it working then deploy it. Now I come to the site, enter the admin, everything is there except one particular plugin (snippets) and there are no pages. At all. Everything else is fine though and when I go to publish an empty page, I get the following error: Exception Type: IntegrityError at /en/cms_wizard/create/ Exception Value: (1452, 'Cannot add or update a child row: a foreign key constraint fails (`eo_web_live`.`cms_page`, CONSTRAINT `site_id_refs_id_5f61f09c` FOREIGN KEY (`site_id`) REFERENCES `django_site` (`id`))') Here is the full traceback with settings: Environment: Request Method: POST Request URL: http://127.0.0.1:8000/en/cms_wizard/create/ Django Version: 1.11.10 Python Version: 3.6.3 Installed Applications: ('django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_comments', 'djangocms_admin_style', 'django.contrib.admin', 'djangocms_text_ckeditor', 'cms', 'mptt', 'menus', 'treebeard', 'filer', 'easy_thumbnails', 'sekizai', 'reversion', 'gunicorn', 'compressor', 'form_designer', 'store_locator', 'cms_redirects', 'eo_registration', 'eo_jobs', 'djangocms_link', 'djangocms_file', 'djangocms_picture', 'djangocms_video', 'djangocms_googlemap', 'djangocms_snippet', 'djangocms_style', 'djangocms_column', 'cmsplugin_filer_file', 'cmsplugin_filer_folder', 'cmsplugin_filer_link', 'cmsplugin_filer_image', 'cmsplugin_filer_teaser', 'cmsplugin_filer_video', 'eo_cms', 'eo_cms.plugins.feature_block', 'eo_cms.plugins.teaser_block', 'eo_cms.plugins.profile_block', 'eo_cms.plugins.accordion_block', 'eo_cms.plugins.tabbed_block', … -
Expanding a div when a Django error pops up
So I was currently coding on my password reset form page. I have a div of a specific height. Problem is, that when passwords don't match or they are too short, of course the form will display a message. I chose to show all the errors at the bottom of my form. Problem is, I can't figure to find a way, that when I have an error, the div would expand its height to fit the errors. Any solutions ? //scss #confirm { @include center; @extend #login; width: 30em; height: 70%; #pass-confirm { text-align: center; margin-top: -10%; margin-bottom: 10%; } #std-reg4 { text-decoration: none; color: $color1; margin-left: 43%; margin-top: -8%; font-family: $font2; position: fixed; &:hover { color: $color2; } .fa-times { font-size: 20px !important; } } .password1, .password2 { border-radius: 10px; box-shadow: none; width: 250px; height: 35px; border: 1.5px solid $color1; padding-left: 10px; background-color: white; } .confirm { text-align: center; margin-top: 20%; } .btn-default { @include button; margin-top: 0; } .alert-div { position: absolute; margin-top: 20%; left: 50%; .alert { width: 340px; font-size: 0.8em; background-color: transparent !important; border: none; color: #d01116; transform: translate(-50%, -50%); padding: 0; } } } <div id="confirm"> <form class="confirm" method="post"> {% csrf_token %} <a id="std-reg4" href="{% …