Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django queryset to json list to js array
I am fairly new to json and javascript and I've been trying to pass django queryset to a js array. I've managed to pass the .values queryset to javascript through json. Django to JSON code def getPorts(request): ports = Port.objects.all() data = serializers.serialize('json', ports, fields=('name')) return JsonResponse(data, safe=False) JS where I am currently stuck at $.ajax({ url: 'getPorts, dataType: 'json', success: function(result){ var ports = JSON.parse(result) console.log(ports[0]); } }); ports[0] gives me something like {model: "Coordinator.port", pk: 1, fields: {…}} fields: {name: "Fa0/1"} model:"Coordinator.port" pk:1 proto:Object Is there a way to extract only the 'name' attribute? I've been trying to treat it like a 2d array but I haven't really been successful -
How do I add headers to a python-oauth2 request?
I'm using the python-oauth2 library to send requests to the Twitter API. I want to do a GET users/show request which needs a parameter to specify the user_id, but the small wiki on the official GitHub page doesn't really explain how to add non-oauth HTTP headers to it's requests. By trying to read the code and understand what the right approach was I tried this: get_info_url = 'https://api.twitter.com/1.1/users/show.json' #user is a Django model with the authorization info for the user access_token = oauth.Token(user.oauth_token, user.oauth_token_secret) client = oauth.Client(consumer, access_token) headers = { 'user_id' : user.twitter_id } resp, content = client.request(url=get_info_url, method="GET", headers=headers) print('Content: ' + str(content)) but it prints Content: b'{"errors":[{"code":50,"message":"User not found."}]}'. How should I do it? -
Django SetPasswordForm will not display bootstap class "form-control"
I am trying to make a "change password"-page by using the SetPasswortForm. The problem is that it does not implement the 'class': 'form-control'-attrribute. Maybe I am missing something, but it should work normally. Here it is: class PasswordChangeForm(SetPasswordForm): old_password = forms.CharField(required=True, widget=forms.PasswordInput( attrs={ 'class': 'form-control', 'type': 'password', 'name': 'password1', 'autofocus': 'autofocus' } ) ) new_password1 = forms.CharField(required=True, widget=forms.PasswordInput( attrs={ 'class': 'form-control', 'type': 'password', 'name': 'password1', } ) ) new_password2 = forms.CharField(required=True, widget=forms.PasswordInput( attrs={ 'class': 'form-control', 'type': 'password', 'name': 'password1', } ) ) class Meta: model = User fields = ( 'old_password', 'new_password1', 'new_password2', ) I did it the same way in my UserCreationForm and it worked. change_password.html: {% load widget_tweaks %} <form method="post"> {% csrf_token %} {{ form.non_field_errors }} <table style="margin-bottom: 1.5em;"> <tr><td><label for="{{ form.old_password.id_for_label }}">Altes Passwort*</label></tr></td> <tr><td><field>{{ form.old_password }}</field></tr></td> <tr><td><label style="margin-top: 1.5em;" for="{{ form.new_password1.id_for_label }}">Neues Passwort*</label></tr></td> <tr><td><field>{{ form.new_password1 }}</field></tr></td> <tr><td><label style="margin-top: 1.5em;" for="{{ form.new_password2.id_for_label }}">Neues Passwort bestätigen*</label></tr></td> <tr><td><field>{{ form.new_password2 }}</field></tr></td> </table> Views.py def change_password(request): if request.method == 'POST': form = PasswordChangeForm(data=request.POST, user=request.user) if form.is_valid(): form.save() update_session_auth_hash(request, form.user) return redirect(reverse('accounts:password_change_done')) else: return redirect(reverse('accounts:change_password')) else: form = PasswordChangeForm(user=request.user) args = {'form': form} return render(request, 'accounts/change_password.html', args) Maybe the code on the views.py is not correct. If you have any idea, let … -
'ValidationError' object has no attribute 'get'
I am making a form using python 3.5 and DJANGO 1.8 and I am getting this error--> I tried reading this Post but I already have returned clean_data so no use AttributeError at /login My forms.py file class UserLoginForm(forms.Form): username=forms.CharField(max_length=40) password=forms.CharField(max_length=40,widget=forms.PasswordInput) def clean(self,*args,**kwargs): username=self.cleaned_data.get("username") password=self.cleaned_data.get("password") user=authenticate(username=username,password=password) if not user: return forms.ValidationError("This user doesn't exist") if not user.check_password(password): return forms.ValidationError("Incorrect Passwordt") if not user.is_active: return forms.ValidationError("User nO longer Active") return super(UserLoginForm,self).clean(*args,**kwargs) Traceback: Environment: Request Method: POST Request URL: http://localhost:8000/login Django Version: 1.8 Python Version: 3.5.4 Installed Applications: ('django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'mainpage', 'signup', 'login', 'rest_framework', 'corsheaders') Installed Middleware: ('django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.security.SecurityMiddleware') Traceback: File "C:\Users\vaibhav2\AppData\Local\Programs\Python\Python35\lib\site-packages\django\core\handlers\base.py" in get_response 132. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\vaibhav2\PycharmProjects\MajorProject\src\login\views.py" in login 15. username=form1.cleaned_data.get("username") Exception Type: AttributeError at /login Exception Value: 'ValidationError' object has no attribute 'get' If there is anything else you people want me to post tell me in the comments .Thanks in advance -
Django autocomplete a foreign key field with a previous value (Forms)
I use form wizard to create a multiple step form based on 2 models. models.py : class Author(models.Model): refCode = models.IntegerField(unique=True) lastName = models.CharField(max_length=20) firstName = models.CharField(max_length=20) birthDate = models.DateField() description = models.TextField() style = models.ForeignKey(Style) class Book(models.Model): refCodeAuthor = models.ForeignKey(Author) title = models.CharField(max_length=100) summary = models.TextField() view.py : class AuthorWizard(SessionWizardView): form_list = [AuthorForm, DescriptionForm, BookForm] def done(self, form_list, form_dict, **kwargs): form_values={} for form in form_list: form_values.update(form.cleaned_data) auth = Author(**form_values) auth.save() return render(self.request, 'done.html', { 'form_values':form_values, }) I have 3 steps, corresponding to form_list AuthorForm DescriptionForm BookForm When I am on BookForm, i don't want to display refCodeAuthor but autocomplete this field with the value of refCode in the step AuthorForm. The user create a author then he add his books, he don't have to choose a refCodeAuthor although isn't in the same model. How can I achieve that ? -
unable to resolve host.no adress associated with hostname
so here are my class which I have used ..I have added internet permission in mainifest...I want to know how can I connect my local server to my app and access data of JSON generated through local server to my app (I have used my mobile phone to test this...no emulator is used) Main Activity package com.example.kiran.retrofitbasic; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.widget.TextView; import android.widget.Toast; import java.util.List; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; import retrofit2.Retrofit; import retrofit2.converter.gson.GsonConverterFactory; public class MainActivity extends AppCompatActivity { TextView mtextview; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mtextview = (TextView)findViewById(R.id.textcheck); getheroes(); } private void getheroes(){ Retrofit retrofit = new Retrofit.Builder() .baseUrl(apiinterface.API.base_url) .addConverterFactory(GsonConverterFactory.create()) //Here we are using the GsonConverterFactory to directly convert json data to object .build(); //creating the api interface apiinterface.API api = retrofit.create(apiinterface.API.class); Call<List<Hero>> call = api.getheroes(); call.enqueue(new Callback<List<Hero>>() { @Override public void onResponse(Call<List<Hero>> call, Response<List<Hero>> response) { List<Hero> heroList = response.body(); mtextview.setText(heroList.get(0).getFirstname()); } @Override public void onFailure(Call<List<Hero>> call, Throwable t) { Toast.makeText(getApplicationContext(), t.getMessage(), Toast.LENGTH_SHORT).show(); } }); } } **apiinterface class ..here i have used my local ip adress to connect ** package com.example.kiran.retrofitbasic; import java.util.List; import retrofit2.Call; import retrofit2.http.GET; /** * Created by kiran on 2/20/2018. */ public class apiinterface … -
Image is not displaying in django template
I am having problem with displaying image in the Django template.Apart from imagefield other field are showing properly.Please find below template and model.Note that I haven't declared any image field in my model.Any help will be much appreciated. Model.py class any(models.Model): Status=models.CharField(max_length=10,choices=Status_choices,default='SUCCESS') Smoke=models.CharField(max_length=10,choices=Smoke_choices,default='SUCCESS') Sanity=models.CharField(max_length=100,choices=Sanity_choices,default='YES') Template: <table class = "table table-striped table-bordered"> <thead> <tr> <th>Tag</th> <th>Smoke</th> <th>Status</th> <th>Sanity</th> </tr> </thead> {% for result in results %} <tbody> <tr> <td> {% if result.Status == SUCCESS %}<img src='/static/test/img/release.png' class="img-fluid rounded" alt="Generic placeholder thumbnail" width="20" height="20"/> {% elif result.Status == FAILURE %} <img src='/static/test/img/block.png' class="img-fluid rounded" alt="Generic placeholder thumbnail" width="20" height="20"/> {% elif result.Sanity == NO %}<img src='/static/test/img/thumbs-down.png' class="img-fluid rounded" alt="Generic placeholder thumbnail" width="20" height="20"/> {% endif %} </td> <td>{{ result.Smoke }}</td> <td>{{ result.Status }}</td> <td>{{ result.Sanity }}</td> </tr> </tbody> {% endfor %} -
Django 1.11.8 - Slug - Unexpected Keyword argument
I am new to django and I have started building my first app a couple of days ago. I first went through the MDN Tutorial and the Django Tutorial - building 2 "dummy" apps. I am currently trying to develop a photo gallery app that will display all pictures belonging to a certain album. I am able to accomplish that using in my urls.py and a class-based view, though, I would like to get a cleaner URL using . I would like my URL to look like mysite.com/myapp/my-album-name vs mysite.com/myapp/1 I know they are similar questions that have been asked here, I've went through most of them, read the Django doc about Single Object Mixins, Class Based Views and I am still not understanding how to get slug to work. So far I've tried to: Implement a slug field in my models and the corresponding slug values in my admin.py file: models class Album(models.Model): album_name = models.CharField(max_length=100, help_text="Enter the name of your album" ) album_creation_date = models.DateField(auto_now_add=True) album_modified_date = models.DateField(auto_now=True) slug = models.SlugField(max_length=50) Views class albumPictures(generic.DetailView): model = Album Admin class AlbumAdmin(admin.ModelAdmin): list_display = ('album_name', 'album_creation_date') slug = prepopulated_fields = {'slug': Album.album_name} admin.site.register(Album, AlbumAdmin) Error Message: <class 'Albums.admin.AlbumAdmin'>: (admin.E030) The … -
Ajax form submit not working second time [duplicate]
This question already has an answer here: Event binding on dynamically created elements? 19 answers I am using Django and here are the get and post methods. After refreshing page, on first form submit, Ajax jquery is called. On success, it returns json.msg which is another form rendered as given in below post call. When I try to submit this rendered form, ajax is not called but it directly calls the django POST method. On ajax success, I tried '$('#school').unbind('submit').submit();'. This way, it ensured to call ajax on every form submit. But, the above method, refreshed the whole page which I do not want. May I know how can I unbind the previous submit without page refresh or get Ajax called(and not direct django post) on every submit. def get(self, request): ... ... return render(request, self.template_name, {'form':next_form_obj}) def post(self, request): ... t = get_template('school/fun_activities.html') msg = t.render({'form': next_form_obj}, request) return JsonResponse({'msg': msg}) Here's the Ajax call. $('#school').on('submit', function(event){ $.ajax({ type: 'POST', url: '/school/fun/', data: $("#school").serialize(), success: function (json) { event.preventDefault(); $('#msg-list').append(json.msg); #json.msg is another form }, error: function(data) { $("#msg-list-div").html("Something went wrong!"); } }); return false; }); HTML: <form id = "school" method="post" action="."> <input type="submit" value="Next" /> </form> -
Show model values as multi select options in admin
I am trying to store use the values from two different models to show as choices in form and store them in new model. Here is what I have now. models.py class Employee(models.Model): name = models.CharField(max_length=200) class Product(models.Model): code = models.CharField(primary_key=True, max_length=5) class JobQueue(models.Model): emp_name = models.CharField(max_length=200) product_code = models.CharField(max_length=5) forms.py class JobQueueForm(forms.ModelForm): emp_choices = Employee._meta.get_field('name').choices product_code_choices = Product._meta.get_field('code').choices emp_name = forms.ChoiceField(choices = emp_choices) product_code =forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple, choices=product_code_choices) def save(self, commit=True): return super(JobQueueForm, self).save(commit = commit) class Meta: model = JobQueue fields = ('emp_name', 'product_code') admin.py class JobQueueAdmin(admin.ModelAdmin): form = JobQueueForm fieldsets = ( (None,{ 'fields': ('emp_name', 'product_code'),}), ) def save_model(self, request, obj, form, change): super(JobQueueAdmin, self).save_model(request, obj, form, change) admin.site.register(models.Employee, AuthorAdmin) admin.site.register(models.Product, ProductAdmin) admin.site.register(models.JobQueue, JobQueueAdmin) I do have values stored in Employee and Product models, but I dont see them as options in JobQueue model in Admin portal. Am I missing anything here? -
StreamField – TypeError: 'bool' object is not iterable
Build: Wagtail CMS(1.13.1) with Django(1.11) in python3.6. I am trying to create a pretty basic Streamfield block(CardBlock), but keep getting a type error. It is very similar to the examples in documentation, but I can not get it to work... class CardBlock(StructBlock): image = ImageChooserBlock() heading = CharBlock(classname="full title") caption = RichTextBlock() class Meta: icon = 'image' class HomePage(Page): intro = RichTextField(blank=True) showcase_title = RichTextField(blank=True) card = StreamField([('card', CardBlock())], default=True) content_panels = Page.content_panels + [ FieldPanel('intro', classname="full"), MultiFieldPanel([ FieldPanel('showcase_title'), StreamFieldPanel('card'), ]), ] django is trying to "get_db_prep_value()". So, Wagtail tries to "get_prep_value()", for all children(streamchild instances) in value, as shown below. wagtail/wagtailcore/blocks/stream_block.py (line 257): def get_prep_value(self, value): if value is None: # treat None as identical to an empty stream return [] return [ { 'type': child.block.name, 'value': child.block.get_prep_value(child.value), # assign a new ID on save if it didn't have one already 'id': child.id or str(uuid.uuid4()), } for child in value # child is a StreamChild instance ] I am uncertain as to what this value is. What in my block classes needs to be changed to correct this value variable? -
ManyToManyField returns none in template
So I have these 2 models. My Course model is linked with a ManytoMany field to TeacherData. When I try to display teacher though, I get courses.TeacherData.none. What is wrong ? class TeacherData(models.Model): name = models.CharField(max_length=30) surname = models.CharField(max_length=50) teacher_ID = models.CharField(unique=True, max_length=14) notes = models.CharField(max_length=255, default=None, blank=True) class Meta: verbose_name = "Teacher Data" verbose_name_plural = "Teachers Data" def __str__(self): return self.surname class Course(models.Model): study_programme = models.ForeignKey('StudyProgramme', on_delete=models.CASCADE, default='') name = models.CharField(max_length=50, unique=True) ects = models.PositiveSmallIntegerField(validators=[MaxValueValidator(99)]) description = models.TextField() year = models.PositiveSmallIntegerField(validators=[MaxValueValidator(99)]) semester = models.IntegerField(choices=((1, "1"), (2, "2"), ), default=None) teacher = models.ManyToManyField('TeacherData', verbose_name="Taught By") slug = models.SlugField(max_length=140, unique=True) def __str__(self): return self.name <ul> {% for c in courses.all %} <li>{{ c.study_programme }}</li> <li>{{ c.name }}</li> <li>{{ c.ects }}</li> <li>{{ c.description }}</li> <li>{{ c.year }}</li> <li>{{ c.semester }}</li> <li>{{ c.teacher }}</li> {% endfor %} </ul> def courses(request, slug): query = Course.objects.get(slug=slug) context = {'courses': Course.objects.filter(slug=slug), 'lectures': query.lectures.order_by('lecture_category'), } return render(request, 'courses/courses.html', context) -
Regular expression for an alphanumeric string of 10 characters
I need to compose an expression for the urls.py file The get-variable var can be an alphanumeric string of 10 characters. The link looks like this http://127.0.0.1:8000/?var=fea40u7b94 -
Django: Creating multiple objects of the same instance and then list them in DRF
I want to create multiple objects of the same instance in Django Rest Framework and then return a list of these objects. So lets say I have this model: class City(models.Model): ... class House(models.Model): city = models.Foreignkey(City, ...) ... class Resident(models.Model): house = models.ForeignKey(House, ...) I now want to be able to hit a route with a postrequest like this: localhost:8000/api/city/createresidents/ And get back JSON like this: { [ { residentid = "<some_number>", residentname = "<some_name>", }, { residentid = "<some_number>", residentname = "<some_name>", }, ... ] } And in the body of the postrequest I append information about the House and the created residents, maybe which street it is, what last name the residents have, or some other data about the house or the residents from their respective model. How would I go about doing that if the view should allways create, let's say 4 residents? I tried modifying the perform_create() method of the CreateModelMixin but I could'nt get it to work. Any help would be much appreciated! -
Django fixtures with specific data
I have an app with 3 models that refer to each other in a parent-child way: class A(Model): # ... class B(Model): a = ForeignKey(A) # ... class C(Model): b = ForeignKey(B) # ... In my production database, I have hundreds objects of type A, with thousands of child objects below it. I now want to create a fixture for only a (specific) handful objects. If I run this command, my output will become huge: python manage.py dumpdata ca_myapp -o /tmp/my_app_dump.json However, when I restrict the output using this command: python manage.py dumpdata ca_myapp.A -o /tmp/myapp_dump.json --pks pk1, pk2, pk3 Then only the A objects are deserialized, but not their children. How can I easily create a fixture file with a handful of objects and their children? -
django 1.11 Cannot extend templates recursively when using non-recursive template loaders
I have django 1.11.2 and I instaled django-mobile=0.7.0. When I want to go to admin panel I recive an error: ExtendsError at /admin/ Cannot extend templates recursively when using non-recursive template loaders Request Method: GET Request URL: http://127.0.0.1:8000/admin/ Django Version: 1.11.2 Exception Type: ExtendsError Exception Value: Cannot extend templates recursively when using non-recursive template loaders I recive an error in first line {% extends "admin/base.html" %} {% extends "admin/base.html" %} {% load admin_static %}{% load suit_tags %} {% block branding %} {% endblock branding %} My templates settings: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ os.path.join(BASE_DIR, 'templates'), ], 'APP_DIRS': False, 'OPTIONS': { 'context_processors': [ 'django.contrib.auth.context_processors.auth', 'django.template.context_processors.debug', 'django.template.context_processors.i18n', 'django.template.context_processors.media', 'django.template.context_processors.static', 'django.template.context_processors.tz', 'django.template.context_processors.csrf', 'django.template.context_processors.request', 'django.contrib.messages.context_processors.messages', 'django_mobile.context_processors.flavour', ], 'loaders': ( 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', 'django.template.loaders.eggs.Loader', 'django_mobile.loader.Loader', ), 'debug': DEBUG, }, }, ] TEMPLATE_LOADERS = TEMPLATES[0]['OPTIONS']['loaders'] Middleware classes: MIDDLEWARE_CLASSES = [ 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.security.SecurityMiddleware', 'django_mobile.middleware.MobileDetectionMiddleware', 'django_mobile.middleware.SetFlavourMiddleware', ] -
django oscar commerce: Conflicting 'stockrecord' models in application
I am using oscarcommerce for my django project. I want to extend the "StockRecord" model to include some more fields. So I forked the partner app as follows. (boscar is my app name) python manage.py oscar_fork_app partner boscar/ It successfully forked and new files were added to boscar/partner folder. I added 'boscar.partner' in my installed apps. Now I added new fields in StockRecord models as follows boscar/partner/models.py from django.db import models from oscar.apps.partner.abstract_models import AbstractStockRecord class StockRecord(AbstractStockRecord): effective_price = models.FloatField(default=0, null=True) is_instock_item = models.BooleanField(default=False, null=True) instock_quantity = models.IntegerField() from oscar.apps.partner.models import * # noqa Now when I try to make migrations it shows the following error. RuntimeError: Conflicting 'stockrecord' models in application 'partner': <class 'oscar.apps.partner.models.StockRecord'> and <class 'boscar.partner.models.StockRecord'>. I already successfully forked the catalogue and order models and that are working fine. Only this "StockRecord" models showing this error. -
How input date in my template ListView (request.POST.get) in Django
I have a class jourListView(ListView). I want to input date in my html template and then retrieve the date to make a filter. My class jourListView(ListView) refers to two linked tables. I am stuck at level. How to make my code functional? here are my models, views and template. class jour(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE, related_name='jour') date = models.DateField(blank=True, null=True) commentaire = models.CharField(max_length=500, blank=True, null=True) class Meta: managed = False db_table = 'jour' unique_together = (('id'),) verbose_name = 'JOUR' verbose_name_plural = 'JOUR' id = models.AutoField(primary_key=True) def get_absolute_url(self): return reverse("jour_detail",kwargs={'pk':self.pk}) def __str__(self): return str(self.date) ## class activite(models.Model): jour = models.ForeignKey('blog.jour',on_delete=models.CASCADE, related_name='jour' ) name= models.CharField(max_length=500, blank=True, null=True) class Meta: managed = False db_table = 'activite' unique_together = (('id'),) verbose_name = 'ACTIVITÉ' verbose_name_plural = 'ACTIVITÉ' id = models.AutoField(primary_key=True) def __str__(self): return self.type def get_absolute_url(self): return reverse("jour_list") My view: class jourListView(ListView): model = jour def get_context_data(self, **kwargs): if request.method == 'POST': date_insert = request.POST.get('date_ref') context = super(jourListView, self).get_context_data(**kwargs) context['count'] = self.get_queryset().count() return context def get_queryset(self): return jour.objects.filter(date__lte=timezone.now()).filter(user=self.request.user).filter(date__in=date_insert) My html template: {% if user.is_authenticated %} <div class="container text-center"> <form class="form-signin" id="login_form" method="post" action="/blog/list/"> {% csrf_token %} <br> <input type="date" name="date_ref" class="form-control" placeholder="SAISIE DATE " value="" required autofocus> <br> <button class="btn btn-lg btn-primary btn-block" type="submit">OK</button> </form> </div> … -
Is there a way to find where a line code is executed?
I'm using python 3.5 and downloaded an updated version of my project from bitbucket. When I try to makemigrations I get: django.core.exceptions.FieldDoesNotExist: users.user has no field named 'surname' Is there a way to find where this is executed? Because in my models.py I have users.lastname. Thank you in advance! -
Loading images as base64 calls from Javascript
I am trying to implement a small photo show via a django webserver. Below you can find the javascript code that loads the pictures into the images array and changes the images every x miliseconds. It works if I only load one picture (without the loop) from my django server but it stops working with any kind of loop. I would love to know why it does not work this way and would be more than happy to receive some other feedback about code improvements. I am not very familiar with ajax calls yet. Moreover: Django Templates Engine provides a easy way to simplify urls used in the templates. Is there a way to use the {{% url %}} tag inside a .js File as well? window.images = []; window.current = 0; window.imageCount = 2; function loadImages(){ for(var i = 0; i < window.imageCount; i++){ loadNextImage(i); } showImage(); } function loadNextImage(i) { // https://wiki.selfhtml.org/wiki/JavaScript/XMLHttpRequest/ var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function() { if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { window.images.push("data:image/jpeg;base64," + xmlhttp.responseText); } }; xmlhttp.open('GET', "http://127.0.0.1:8000/mirror/"+i); xmlhttp.send(null); } function showImage() { if(window.current >= window.imageCount){ window.current = 0; } alert("current window count = "+ window.current); document.getElementById('imgshow').src = window.images[window.current]; … -
Is there an equivalent for _collect_sub_objects method in Python 3?
I'm trying to implement a method that duplicate Django model instances and its related objects. The solution is in this stackoverflow post. But _collect_sub_objects method seems to be deprecated in python 3. Somebody could tell me if its a new version in recent versions of python? -
Getting credential using GoogleAPI - HttpResponseRedirect status_code=302
I get this error : HttpResponseRedirect' object has no attribute 'authorize' I've printed HttpResponseRedirect object and I have something like this: HttpResponseRedirect status_code=302, "text/html; charset=utf-8", url="https://accounts.google.com/o/oauth2/auth?client_id=..." I've copied this url to my browser and it does work. When I run app locally everything works fine, but now I moved my app to pythonanywhere recently and it stopped working. Here is my code: def get_credentials(user): home_dir = os.path.expanduser('~') home_dir = BASE_DIR + '/oauth2/' + user.username credential_dir = os.path.join(home_dir, '.credentials') if not os.path.exists(credential_dir): os.makedirs(credential_dir) credential_path = os.path.join(credential_dir, 'calendar-python-quickstart.json') storage = Storage(credential_path) credentials = storage.get() if not credentials or credentials.invalid: print(True) FLOW = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES,redirect_uri="http://XXXXXX.pythonanywhere.com/accounts/google/login/callback/") FLOW.params['state'] = xsrfutil.generate_token(SECRET_KEY, user) authorize_url = FLOW.step1_get_authorize_url() return HttpResponseRedirect(authorize_url) return credentials class EventTeamToggleAPI(LoginRequiredMixin, APIView): authentication_classes = (authentication.SessionAuthentication,) permission_classes = (permissions.IsAuthenticated,) def get(self, request, *args, **kwargs): self.slug = self.kwargs.get('slug') team = get_object_or_404(Team,slug=self.slug) updated = False added = False user_other_teams = Team.objects.filter(user_team_events=self.request.user).exclude(pk=team.pk) games = Game.objects.filter(Q(team_home=team) | Q(team_away=team)) if self.request.user.google_cal==True: credentials = get_credentials(self.request.user) http = credentials.authorize(Http()) service = build('calendar', 'v3', http=http) {...} return(...) Can someone explain to me what is the problem ? Thanks -
unit tests returning True when using python requests even if DB entry is empty
Recently I've tried using requests to make requests to my local server then use django's unittests to test whether or not they are there. I know usually unittests makes temp database entries then tests those, but I want to test my actual project DBs so I used requests. Problem is for the vader entry it should return false (so I think) because it's missing the conversation_id key. Therefore it doesn't get entered into the DB (I checked it's not there). The Luke entry is there (as it should be). So why is the vader entry returning True? Is it still sending to a temp DB? import requests from django.test import TestCase from convoapp.models import InputInfo from django.urls import reverse import sqlite3 def add_message(request): fields = ['name', 'conversation_id', 'message_body'] if request.method == 'POST': form = InputInfoForm(request.POST) #validate/ DB won't update if form is invalid if form.is_valid(): InputInfo.name = request.POST.get('name') InputInfo.conversation_id = request.POST.get('conversation_id') InputInfo.message_body = request.POST.get('message_body') form.save() else: form = InputInfoForm(request.POST) return render(request, 'blank.html') class InputInfoTestCase(TestCase): def setUp(self): post_request = requests.session() post_request.get('http://127.0.0.1:8000/message/') csrftoken = post_request.cookies['csrftoken'] luke_data = {'name': 'Luke', 'conversation_id': '1', 'message_body': 'I am a Jedi, like my father before me','csrfmiddlewaretoken' : csrftoken} vader_data = {'name': 'Vader', 'message_body': 'No, I am your … -
Django with Gspread and OAuth breaks POST
For a project in Django, we're using Gspread to get data from a spreadsheet and OAuth for authentication. However, since OAuth has been added, POST stops working. The Trainig class with post(): class TrainingList(APIView): permission_classes = (IsAuthenticated,) def get(self, request): worksheet = get_sheet(request.GET.get('sheet', 'Data')) list_of_records = worksheet.get_all_records() return JsonResponse(list_of_records, safe=False, status=status.HTTP_200_OK) def post(self, request): worksheet = get_sheet(request.GET.get('sheet', 'Data')) data = json.loads(request.body.decode('utf-8')) if validate_data_has_all(data): worksheet.append_row( [data["date"], data["days"], data["firstname"], data["lastname"], data["team"], data["training"], data["company"], data["city"], data["cost"], data["invoice"], data["info"]]) return JsonResponse(data, safe=False, status=status.HTTP_201_CREATED) else: return JsonResponse([], safe=False, status=status.HTTP_400_BAD_REQUEST) And the traceback: Traceback (most recent call last): File "C:\Python\backend\env\lib\site-packages\django\core\handlers\exception.py", line 35, in inner response = get_response(request) File "C:\Python\backend\env\lib\site-packages\django\core\handlers\base.py", line 128, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Python\backend\env\lib\site-packages\django\core\handlers\base.py", line 126, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Python\backend\env\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "C:\Python\backend\env\lib\site-packages\django\views\generic\base.py", line 69, in view return self.dispatch(request, *args, **kwargs) File "C:\Python\backend\env\lib\site-packages\rest_framework\views.py", line 489, in dispatch response = self.handle_exception(exc) File "C:\Python\backend\env\lib\site-packages\rest_framework\views.py", line 449, in handle_exception self.raise_uncaught_exception(exc) File "C:\Python\backend\env\lib\site-packages\rest_framework\views.py", line 486, in dispatch response = handler(request, *args, **kwargs) File "C:\Python\backend\unleashedapp\trainings\views.py", line 60, in post data = json.loads(request.body.decode('utf-8')) File "C:\Python\backend\env\lib\site-packages\rest_framework\request.py", line 385, in __getattribute__ return getattr(self._request, attr) File "C:\Python\backend\env\lib\site-packages\django\http\request.py", line 255, in body raise RawPostDataException("You cannot access body after reading from … -
Django multibase administration site
I newbe in Django, so excuse me for question, but I can't find solution. I try to work with multibases. f.ex. (sqlite3). First of it is default (in file db.sqlite3) and second is 'depend' in file depend.sqlite3. I set something in settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), }, 'depend': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'depend.sqlite3'), } } and after: python manage.py inspectdb --database 'depend' > models.py and change column-key, I have: from django.db import models class AllFiles(models.Model): db_id = models.IntegerField(primary_key=True) filename = models.CharField(max_length=100, blank=True, null=True) ... my router.py states now: class AuthRouter: """ A router to control all database operations on models in the auth application. """ def db_for_read(self, model, **hints): """ Attempts to read auth models go to auth_db. """ if model._meta.app_label == 'depend': return 'depend' return None ... and next I add my 3 tables from new DB into admin-site with: admin.site.register(models.AllFiles) admin.site.register(models.ImportingDict) admin.site.register(models.InputDir) when server (localhost:8000) is running, and admin is logged, I have in admin-view (http://localhost:8000/admin/) 3 new position with 3 new tables, but when try do something with one of them, get: Exception Type: OperationalError Exception Value: no such table: all_files what I missing? what is wrong? Should I register …