Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
return html after ajax POST
I am using an ajax call to POST a form to create an object. Once the object is created in my views, I use the object instance to render a template, footemplate say. What I would like to have happen is that footemplate is inserted into my current page, i.e. the one that contains the form. Particularly I am trying to add it to a div with id='result-container'. However when I return the rendered template it actually loads the page by itself. views def object_create(request): .... return render(request, template, template_context) AJAX $('#object-create').on('submit', function(event){ event.preventDefault(); var myform = document.getElementById('object-create'); var fd = new FormData(myform ); var post_url = $(this).attr('action'); $.ajax({ url : post_url, data : fd, cache: false, processData: false, contentType: false, type : "POST", success : function(data) { $('#result-container').html(data) }, error : function() { alert("error") } }); }); How can I return the html as text only, instead of actually generating the page on its own? -
Having trouble uploading file to Google Cloud Storage from Django(Local Windows ENV
I'm currently developing a web app that will use Google Cloud Storage for User Document uploads. I've run into a roadblock, however. When I attempt to proceed with the upload I keep getting a [Errno 2] No such file or directory: 'Marty McFly-Paycheck-06_ConditionalDirectives.pdf'. This error is confusing to me because I assumed that the file would be taken directly from my form's file upload. Am I wrong in assuming this? Should I be saving then serving the files somehow? Current Code for uploading documents to Cloud Storage #Uploading Documents function def upload_documents(bucket_name,source_file_name,destination_blob_name): storage_client = storage.Client() storage_bucket = storage_client.get_bucket(bucket_name) blob = storage_bucket.blob(destination_blob_name) blob.upload_from_filename(source_file_name) print("Document Uploaded") from .forms import DocumentUpload # Create your views here. def get_upload(request): # If this is a POST request, we will process the data -- sending it to Google Cloud Storage if request.method == 'POST': #create a form instance populated with data -- (Bound to the data previously entered that might need correction) name = request.POST['name'] titleofdocument = request.POST['titleofdocument'] doc_file = request.POST['doc_file'] fullUpload = name + "-" + titleofdocument + "-" + doc_file print(titleofdocument,name,doc_file) print(fullUpload) form = DocumentUpload(request.POST) upload_documents("upload_documents",fullUpload,"SampleBlob") else: form = DocumentUpload() return render(request, 'document-upload.html',{'form':form}) Full Stack Trace in question Marty McFly-Paycheck-06_ConditionalDirectives.pdf Internal Server Error: /upload-documents/ … -
Django: access class name in class based generic views
Using django 1.11 class based generic views ListView, DetailView & CreateView: the DRY principle works well here, but still I find quite some repetitive work in writing the templates. For each model M, a m_list,html, m_detail.html and m_form.html needs to be written. If the class name of an object could accessed from within the template, a more generic template could be written to serve multiple models. There must be a way? -
How i can find 14 migrations and apply them?
enter image description hereHow i can find 14 migrations and apply them? How easy is it to solve this problem? -
How to append/delete data from JSONField in django
I have a JSONField which i has some data like this : {'key_one' : 'val_one, 'key_two' : 'val_two'} I want to add data to it as well as deleting data from it. So far i can just give it a value not appending to it. I'm using mySql database -
Django admin foreign key dynamic verbose name
I have 100s of related models which all inherit from a base abstract class and need to define the verbose name to that of the return of the unicode method in the related class. For example in the case below it should be "Nick Name" The models.py: class Student(models.Model): user = models.OneToOneField(User) first_name = models.CharField(max_length=100,blank=True) nick_name = models.CharField(max_length=100,blank=True) def __unicode__(self): return self.nick_name class Subject(models.Model): subject = models.CharField(max_length=100,blank=True) user = models.ForeignKey(Student,verbose_name="Nick Name") -
Django admin login with staff status does not show all the permissions?
I have been trying to make an app which has 2 types of users : student and teacher. I have added permissions in both the models and they worked fine. Now when I gave the teacher acoount a staff status the entire data of the student profile does not show up . Can anyone help me out here? enter image description here Thanks -
KeyError: 'image'
When I trying to save detail, I have this error: KeyError: 'image'. I can't understand, why? Error in views.py views.py: @user_passes_test(lambda u: u.is_superuser) def new_detail(request): ImageFormSet = modelformset_factory(DetailImage, form=ImageForm, extra=10) if request.method == 'POST': form = DetailForm(request.POST) formset = ImageFormSet(request.POST, request.FILES, queryset=DetailImage.objects.none()) if form.is_valid() and formset.is_valid(): detail_form = form.save() detail_form.save() for form in formset.cleaned_data: images = form['image'] # HERE IS THE PROBLEM photo = DetailImage(detail=detail_form, image=images) photo.save() return redirect('/new_detail/') else: form = DetailForm(request.POST) formset = ImageFormSet(queryset=DetailImage.objects.none()) return render(request, 'shop/new_detail.html', {'form': form,'formset': formset}) forms.py ... class ImageForm(forms.ModelForm): image = forms.ImageField() class Meta: model = DetailImage fields = ('image',) models.py ... class DetailImage(models.Model): detail = models.ForeignKey(Detail, related_name='images', on_delete=models.CASCADE) image = models.ImageField(upload_to='details', null = True, blank = True) -
django imagefield display image and have browse button for the form
In my django app, I have been able to include image for an imagefield form, however there is no browse button to upload a new image. How do I include this browse button to upload a new image ? Currently it looks like this: https://imgur.com/a/Qu4JE And here is my form code: class PictureWidget(forms.widgets.Widget): def render(self, name, value, attrs=None): html = Template("""<img src="$link" height=50 width=50 />""") logging.debug("value %s" % value.url) return mark_safe(html.substitute(link=value.url)) class EmployeeFaceImageUploadForm(forms.ModelForm): face_image = forms.ImageField(widget=PictureWidget) class Meta: model = Employee fields = ("face_image",) -
Django - How to pass value after submit when editing form?
I'm trying to pass a data to my form when it's being edited I have the following code: form = senalesEipForm(request.POST or None, instance=eip,prefix='form') new_data_2 = None form2 = reglasForm(request.POST or None, instance=regla,prefix='form3') form3 = patronInicioForm(request.POST or None,initial={'minutos':minuto_inicio,'hora':hora_inicio,'dia_mes':dia_mes_inicio,'mes':mes_inicio,'semana':semana_inicio}, prefix="form3") form4 = patronFinalForm(request.POST or None,initial={'minutos':minuto_fin,'hora':hora_fin,'dia_mes':dia_mes_fin,'mes':mes_fin,'semana':semana_fin}, prefix="form4") print form2 if form.is_valid() and form2.is_valid() and form3.is_valid() and form4.is_valid(): nuevo_minuto_inicio = form3.cleaned_data['minutos'] nuevo_hora_inicio = form3.cleaned_data['hora'] nuevo_dia_mes_inicio = form3.cleaned_data['dia_mes'] nuevo_mes_inicio = form3.cleaned_data['mes'] nuevo_semana_inicio = form3.cleaned_data['semana'] new_data_1 = '0' + '' + nuevo_minuto_inicio + '' + nuevo_hora_inicio + '' + nuevo_dia_mes_inicio + '' + nuevo_mes_inicio + '' + nuevo_semana_inicio nuevo_minuto_fin = form4.cleaned_data['minutos'] nuevo_hora_fin = form4.cleaned_data['hora'] nuevo_dia_mes_fin = form4.cleaned_data['dia_mes'] nuevo_mes_fin = form4.cleaned_data['mes'] nuevo_semana_fin = form4.cleaned_data['semana'] new_data_2 = '0' + '' + nuevo_minuto_fin + '' + nuevo_hora_fin + '' + nuevo_dia_mes_fin + '' + nuevo_mes_fin + '' + nuevo_semana_fin form.save(commit=False) form2.save(commit=False) pfin = new_data_2 print pfin form2.save() form.save() In this case, basically what I want is get the data from form3 and form4 and pass it to form2, I tried with initial but it's not working when I use instance I tried with JavaScript but not working.... What can I do to solve this? for example, what's in pfin I need it in form3.properties properties is a field … -
django rest framework hyperlinkrelatedfield for one table using its primary key
I have a table called 'users' and 'location'. Users table has a foreign key that relates to location table. I have a users serializer to get the JSON. What would I do to get the hyperlinks for the users table using its primary key? In django rest framework documentation, I couldn't find a solution. I tried using hyperlinkrelatedfield. But still I couldn't achieve this. Can someone help me in finding the solution? I need the URL like 127.0.0.1:8000/users{userid}. It should give the JSON of the user whose userid is specified in the URL -
split data and save values using django rest framework
I have models- class Web2Types(models.Model): name = models.CharField(max_length=200, unique=True) status = models.IntegerField(default=0) class Web2Domains(models.Model): domain = models.CharField(max_length=255, unique=True) web2type = models.ForeignKey(Web2Types) Now I have a string containing commas, I want that string first split by comma then all values of that list will save into Web2Domains model. I tried some methods in serializer.py but got confused. -
Javascript arrays and updating <ul><li></li></ul> elements with a loop?
I'm struggling with this one a little. I'm a junior python developer by trade and I have been asked to build a website. Naturally I said yes and chose Django. Regardless, I'm having a little issue building a calendar widget. I'm using AJAX to pass the request back to the view, and update certain elements based on whether the user is requesting the previous/next month of days. function getPreviousMonth( event ) { $.ajax({ type: "GET", dataType: "json", url: "{% url 'events' %}", data: { 'month': previousMonth, 'year': previousYear } }) .done(function(response) { console.log(response); nextMonth = response.next_month; nextYear = response.next_year; previousMonth = response.previous_month; previousYear = response.previous_year; currentMonth = response.current_month; currentYear = response.current_year; $('#currentMonth').text(currentMonth); $('#currentYear').text(currentYear); }); }; This all seems to be working well. In the response object I have an array of lists (I think, certainly correct me if I am wrong). On the template side I am using Django to setup the calendar from an array of days arrays: {% for week in weeks %} <ul class="days"> {% for day in week %} {% if day == 0 %} <li></li> {% else %} <li>{{ day }}</li> {% endif %} {% endfor %} </ul> {% endfor %} All looks nice (and … -
store infinity in postgres json via django
I have a list of tuples like below - [(float.inf, 1.0), (270, 0.9002), (0, 0.0)] I am looking for a simple serializer/deserializer that helps me store this tuple in a jsonb field in PostgreSQL. I tried using JSONEncoder().encode(a_math_function) but didn't help. I am facing the following error while attempting to store the above list in jsonb field - django.db.utils.DataError: invalid input syntax for type json LINE 1: ...", "a_math_function", "last_updated") VALUES (1, '[[Infinit... DETAIL: Token "Infinity" is invalid. Note: the field a_math_function is of type JSONField() -
Is it good way to send POST request using jQuery in Django?
form.py class UserCreateForm(forms.ModelForm): username = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Username'})) class Meta: model = User fields = ['username'] views.py def test(request): if request.method == "POST": return redirect('/test_done/') html CODE : <form class="form-horizontal" method="post" action="."> {% csrf_token %} <div class="form-group"> <label class="control-label" for="id_username">Username(ID)</label> <div>{{ form.username }}</div> </div> <div class="form-group"> <div> <button class="btn btn-default" id="btn_test" type="submit">Create</button> </div> </div> </form> On that code, If I click Createbutton on <button class="btn btn-default" type="submit">Create</button>, on views.py, returned redirect to some uri. But I want do this process by only using jQuery or javascript without html post. Like this. $('#btn_test').click(function () { #alert('It works and you will be gone to redirect uri from views.py') #sleep 3-5sec #do post send }); How can I do this? EDIT: I thought using ajax post call, But wonder there any good way not being ajax. -
How to parse a string list query param in DRF serializers?
I'm building a REST API to handle user requests in the following form: localhost:8000/search/?categories=<category1>,<category2>&parts=<id1>,<id2> Where , is supposed to be the delimiter for the parser. My view processes the request and passes the query params to the serializer, but I just cannot get the raw strings parsed to a list of strings. My attempt so far: class StringListField(serializers.ListField): child = serializers.CharField() class LookupPartsSerializer(serializers.Serializer): categories = StringListField() parts = StringListField() class LookupParts(APIView): def get(self, request, format=None): serializer = LookupPartsSerializer(data=request.query_params) return Response(request.query_params) My desired output is like: { "categories": [ "<category1>", "<category2>" ], "parts": [ "<id1>", "<id2>" ] } But now I'm getting: { "categories": [ "<category1>,<category2>" ], "parts": [ "<id1>,<id2>" ] } So basically I'm looking for an option to pass a delimiter argument to the StringListField or add some custom parsing method. NOTE: I'm aware, that if I change the query pattern from ?categories=<category1>,<category2>... to ?categories=<category1>&categories=<category2>... then I'd get the desired results, but I'd like to stick to my original approach. -
Page not found in Django (404)
I have a little problem with Django 2.0. In my case the debugger responded me this message: Page not found (404) Request Method: GET Request URL: http://localhost:8000/ Using the URLconf defined in bajkowo.urls, Django tried these URL patterns, in this order: admin/ bajki/ The empty path didn't match any of these. You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. I'v check the views and urls but i can;t find the bug or typo. Could anyone to check my code? urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('bajki/', include('bajki.urls')), ] bajki/urls.py from django.urls import path from . import views urlpatterns = [ path('bajki/',views.lista_bajek, name='lista_bajek'), ] bajki/views.py from django.shortcuts import render def lista_bajek(request): return render(request, 'bajki/lista_bajek.html', {}) The def lista_bajek should responde me a blank webiste, but responding me a error code 404. Of course I created the bajki/templates/bajki/lista_bajek.html -
No module named 'encodings' error while starting uwsgi
I referred to following three links to upgrade python to 3.6.3 version and create virtual environment and then tried to server django via nginx/uwsgi. However, i'm struggling with the error saying "no module named encodings". If I used below command then the django can be accessed. However, If run over the config file it will raise error saying "no module named encodings". "uwsgi --http :8080 --home /home/testuser1/myproject --chdir /home/testuser1/myprojecttss -w myprojecttss.wsgi " https://www.digitalocean.com/community/tutorials/how-to-serve-django-applications-with-uwsgi-and-nginx-on-centos-7#setting-up-the-uwsgi-application-server https://www.digitalocean.com/community/tutorials/how-to-set-up-uwsgi-and-nginx-to-serve-python-apps-on-centos-7#set-up-an-app-directory-and-a-virtualenv Error Log: (myproject) [test@VM_134_114_centos ~]$ systemctl status uwsgi -l * uwsgi.service - uWSGI Emperor service Loaded: loaded (/etc/systemd/system/uwsgi.service; enabled; vendor preset: disabled) Active: active (running) since Sat 2018-01-20 20:29:47 CST; 9min ago Main PID: 11381 (uwsgi) Status: "The Emperor is governing 0 vassals" CGroup: /system.slice/uwsgi.service `-11381 /usr/local/bin/uwsgi --emperor /etc/uwsgi/sites Jan 20 20:38:16 VM_134_114_centos uwsgi[11381]: uwsgi socket 0 bound to UNIX address /run/uwsgi/myprojecttss.sock fd 3 Jan 20 20:38:16 VM_134_114_centos uwsgi[11381]: uWSGI running as root, you can use --uid/--gid/--chroot options Jan 20 20:38:16 VM_134_114_centos uwsgi[11381]: setuid() to testuser1 Jan 20 20:38:16 VM_134_114_centos uwsgi[11381]: Python version: 3.6.3 (default, Jan 17 2018, 14:02:51) [GCC 4.8.5 20150623 (Red Hat 4.8.5-16)] Jan 20 20:38:16 VM_134_114_centos uwsgi[11381]: Set PythonHome to /home/testuser1/myproject Jan 20 20:38:16 VM_134_114_centos uwsgi[11381]: Fatal Python error: Py_Initialize: Unable to get … -
Django Social Auth error: "Missing required parameter: client_id" while trying to authenticate with Google Outh2
I have installed and configured social-auth-app-django and added an option to sign up with google in my login page. But whenever I click the link, I get this error -
Django - unhashable type: 'ReturnDict' error on invoking a view
I am trying to create an API but the serializer is failing . I am not able to figure out what is gone wrong . View : elif request.method == 'POST': data = { 'user':request.user,'skill_item':Skill.objects.get(pk=request.data.get('skill_id')) } serializer = UserSkillSerializer(data=data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response({serializer.errors}, status=status.HTTP_400_BAD_REQUEST) Serializer : class UserProfileSerializer(serializers.ModelSerializer): skill_item =SkillSerializer(read_only=True,many=True) class Meta: model = User fields = '__all__' def create(self, validated_data): user = User.objects.create(username=validated_data.get('username'),email=validated_data.get('email'),password=validated_data.get('password')) user.set_password(validated_data.get('password')) user.save() UserProfile.objects.create(user=user, user_skills=skill_item) return user class UserSkillSerializer(serializers.ModelSerializer): user = UserProfileSerializer(read_only=False) skill_item = SkillSerializer(read_only=False) class Meta: model = UserSkill fields= '__all__' Model : # This class will more or less map to a table in the database and defines skills at the application level class Skill (models.Model): # this defines a required name that cannot be more than 100 characters. skill_name = models.CharField(max_length=100,unique=True) class Meta: app_label = "wantedly_webapp" # This class will more or less map to a table in the database and defines the many to many relationship between user-skill, this is our intermediate model class UserSkill(models.Model): """ A Model for representing skill in user profile """ unique_together = (('user', 'skill_item'),) user = models.ForeignKey('UserProfile',on_delete=models.CASCADE,related_name='current_user_skills') skill_item = models.ForeignKey(Skill,on_delete=models.CASCADE) def __str__(self): """Return a human readable representation of the model instance.""" return "{}".format(self.skill_item.skill_name) # … -
Postgtes a lot of request
I have Django, Python i call - ps -aux postgres 46214 2.4 0.4 252824 139052 ? Ss 15:24 0:07 postgres: postgres mydb [local] SELECT postgres 46216 1.7 0.4 252664 136680 ? Ss 15:24 0:04 postgres: postgres mydb [local] SELECT I have so many such lines (> 10). And very long communication to my database through the /admin page Kill the process does not work - it is restored after some time. As a result, I can not see the database because the request is very long and is terminated by timeout Can anybody help? Or can someone come across this? -
Followers not getting added
I am trying to add followers to my blogger database but unable to do so. I am getting 404 error( No blogger matches with the given query). views.py def follow(request,user_id): user=request.user print(user_id) userFollow=get_object_or_404(Blogger,id=user_id) if request.method=="POST": userFollow.follows.add(user) return redirect('winterblog:blogger_detail',user_id) models.py class Blogger(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE,null=True) follows = models.ManyToManyField('self', related_name='following', symmetrical=False) def __str__(self): return self.user.username @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Blogger.objects.create(user=instance) Help would be appreciated. Thanks! -
Django user uploaded media files in development
I have image field in one of the my models in my project. That image is uploaded by users and working correctly in localhost. But, I can't get it work in production. I'm using heroku to deploy my project and here is my scripts: settings.py MEDIA_URL = "/media/" MEDIA_ROOT = "https://myapp.herokuapp.com/live-static/media-root" urls.py from django.conf.urls import url, include from django.contrib import admin from django.conf import settings from django.conf.urls.static import static from django.contrib.auth import views as auth_views import debug_toolbar from .views import signup, SignInView, ResetPasswordView, ConfirmPasswordResetView urlpatterns = [ url(r'^', include('music.urls', namespace='music')), url(r'^__debug__/', include(debug_toolbar.urls)), url(r'^login/$', SignInView.as_view(), name='login'), url(r'^logout/$', auth_views.LogoutView.as_view(), name='logout'), url(r'^register/$', signup, name='register'), url(r'^password_reset/$', ResetPasswordView.as_view(), name='password_reset'), url(r'^password_reset/done/$', auth_views.password_reset_done, name='password_reset_done'), url(r'^reset/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$', ConfirmPasswordResetView.as_view(), name='password_reset_confirm'), url(r'^reset/done/$', auth_views.password_reset_complete, name='password_reset_complete'), url(r'^admin/', admin.site.urls), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) \ + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) models.py class Album(models.Model): owner = models.ForeignKey(User) title = models.CharField(max_length=127) artist = models.CharField(max_length=63) release_date = models.DateField() logo = models.ImageField(blank=True, upload_to='album_logos', default='album_logos/no-image.jpg') t_added = models.DateTimeField(auto_now_add=True) slug = models.SlugField(null=True, blank=True, max_length=63) Why images aren't uploaded and displayed in production? -
Django loaddata provide database fixture
I want to switch a site from using sqlite to postgres. Backed up the data into a json with python manage.py dumpdata > db.json then switched the database details in the settings file to postgres now when I try to load using python manage.py loaddata < db.json I get the error below. (djangoenv) muiruri_samuel@pluscolor:~/webapp/revamp$ python manage.py loaddata < db.json usage: manage.py loaddata [-h] [--version] [-v {0,1,2,3}] [--settings SETTINGS] [--pythonpath PYTHONPATH] [--traceback] [--no-color] [--database DATABASE] [--app APP_LABEL] [--ignorenonexistent] fixture [fixture ...] manage.py loaddata: error: No database fixture specified. Please provide the path of at least one fixture in the command line. -
python manage.py makemigrations no module named error
Thats the error after using command from title, Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "C:\Users\DELL\SrdW\lib\site-packages\django\core\management\__init__.py" , line 371, in execute_from_command_line utility.execute() File "C:\Users\DELL\SrdW\lib\site-packages\django\core\management\__init__.py" , line 347, in execute django.setup() File "C:\Users\DELL\SrdW\lib\site-packages\django\__init__.py", line 24, in se tup apps.populate(settings.INSTALLED_APPS) File "C:\Users\DELL\SrdW\lib\site-packages\django\apps\registry.py", line 89, in populate app_config = AppConfig.create(entry) File "C:\Users\DELL\SrdW\lib\site-packages\django\apps\config.py", line 116, i n create mod = import_module(mod_path) File "C:\Users\DELL\AppData\Local\Programs\Python\Python36-32\lib\importlib\__ init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 941, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked ModuleNotFoundError: No module named 'django.contrib.staticfilesblog' Thats mysite/settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles' 'blog.apps.BlogConfig',] Also blog\models.py from django.db import models from django.utils import timezone class Post(models.Model): author = models.ForeignKey('auth.User') title = models.CharField(max_length=200) text = models.TextField() created_date = models.DateTimeField( default=timezone.now) published_date = models.DateTimeField( blank=True, null=True) def publish(self): self.published_date = timezone.now() self.save() def __str__(self): return self.title I set up virtual enviroment end creat project mysite than startapp blog and when i try to makemirgations this error …