Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Updating a form in Django
I have 2 models. User and Profile for which I have created 2 form classes Forms class UserProfileForm(ModelForm): class Meta: model = Profile fields = ['dob','country'] class UserForm(ModelForm): class Meta: model = User fields = ['username','first_name','last_name','email','password'] My Profile Model class Profile(models.Model): user = models.ForeignKey(User,on_delete = models.CASCADE) country = CountryField() dob = models.DateField(max_length=10) profile_pic = models.ImageField(upload_to='profile_image',blank=True) How Do I save these forms. forms.save() seems to be of no help View def profile(request): print(request.user) form1 = UserForm() form2 = UserProfileForm() if request.method == 'POST': if form1.is_valid() and form2.is_valid(): form1.save() form2.save() return render(request,'account/profile.html',{'form1':form1, 'form2':form2}) -
IntegrityError: null value in column "user_id" violates not-null constraint (Django Rest Framework)
I am new to Django Rest Framework I have created ModelViewset for my models However when I try to create a new instance of my model I get an integrity error IntegrityError: null value in column "user_id" violates not-null constraint Below is the screenshot of the error message that I am getting Below are my models class Patient(models.Model): """Patients model which has all the patients information""" user = models.ForeignKey(User, on_delete=models.CASCADE) first_name = models.CharField(max_length=25) last_name = models.CharField(max_length=35) phone = models.CharField(max_length=18) email = models.EmailField(unique=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) @property def full_name(self): return "%s %s" % (self.first_name, self.last_name) def __str__(self): return self.email class Embryo(models.Model): """A ForeignKey model to the patient""" patient = models.ForeignKey(Patient, on_delete=models.CASCADE) code_name = models.CharField(max_length=100) karyotype = models.CharField(max_length=100) down_syndrome = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) GENDER_CHOICES = ( ("M", "Male"), ("F", "Female"), ) sex = models.CharField(max_length=1, choices=GENDER_CHOICES) def __str__(self): return self.code_name I a using ModelViewSet to create instances for my models below are my views. class PatientsApiView(viewsets.ModelViewSet): """Handles Creating, reading and updating Patients""" serializer_class = serializers.PatientsSerializer queryset = Patient.objects.all() authentication_classes = (TokenAuthentication,) filter_backends = (filters.SearchFilter,) permission_classes = (IsAuthenticated,) search_fields = ("first_name", "last_name", "phone", "email",) def perform_create(self, serializer): serializer.save(user=self.request.user) class EmbroApiView(viewsets.ModelViewSet): """Handles Creating, reading and updating Patients""" serializer_class … -
How to upload image in django 2.0
I know that exists a lot of topic about this issue, but still I dont find a solution. I hope you can understend me! Im working in upload a image from modal form.The issue is that when I try to upload the image, it returned django.utils.datastructures.MultiValueDictKeyError: 'imagen' Trying in found a solution, I tried to print my filled form, after that I pressed in my continue button to save it and this is the output in my console: <tr> <th> <label for="id_monto_boleta">Monto boleta:</label> </th> <td> <input type="number" name="monto_boleta" value="900" required id="id_monto_boleta" /> </td> </tr> <tr> <th> <label for="id_imagen">Imagen:</label> </th> <td> <ul class="errorlist"> <li>Este campo es obligatorio.</li> </ul> <input type="file" name="imagen" required id="id_imagen" /> </td> </tr> It do not have value... views.py def agregar_boleta_honorario(request): if request.method == 'POST': form = FormRegistrarBoletaHonorario(request.POST, request.FILES) print(form) else: form = FormRegistrarBoletaHonorario() return save_all(request, form, 'boletas_honorarios/agregar_boleta_honorario.html') forms.py class FormRegistrarBoletaHonorario(forms.ModelForm): class Meta: model = Boleta_Honorario fields = ( 'rut_paciente', 'rut_medico', 'fecha_boleta', 'monto_boleta', 'imagen', ) models.py class Boleta_Honorario(models.Model): rut_paciente = models.ForeignKey(Paciente, on_delete=models.CASCADE) rut_medico = models.ForeignKey(Medico, on_delete=models.CASCADE) numero_boleta_honorario = models.IntegerField(default=0) fecha_boleta = models.DateTimeField() monto_boleta = models.IntegerField(default=0) imagen = models.ImageField(upload_to='boletas_honorarios_adjuntos/', blank=True) def __str__(self): return str(self.id) template {% load crispy_forms_tags %} <form method="post" enctype="multipart/form-data" data-url="{% url 'boletas_honorarios:agregar_boleta_honorario' %}" id="verificar" class="create-form"> {% … -
Getting WrappedAttributeError when logged into website with djangorestframework freshly installed
I have a website that has a user login function and works fine. I had to install django rest framework and followed the very basic instructions on the first page. Everything seems fine and rest framework works fine, but as soon as I log into my django and go back to rest framework it breaks with this error: WrappedAttributeError at /rest-api/ 'CSRFCheck' object has no attribute 'process_request' I have no idea why this happens or what it means. Searching didn't help. -
Django Views (Object create command: Indentation error)
I'm getting this error below even though I have re-checked and indented everything again. Is there something wrong with the line of code below? order_details = Order.objects.create() TabError: inconsistent use of tabs and spaces in indentation def cart_detail(request, total=0, cart_items = None): try: cart = Cart.objects.get(cart_id=_cart_id(request)) cart_items = CartItem.objects.filter(cart=cart, active=True) for cart_item in cart_items: total += (cart_item.service.price) except ObjectDoesNotExist: pass braintree_total = int(total) client_token = generate_client_token() if request.method == 'POST': try: result = transact({ 'amount': braintree_total, 'payment_method_nonce': request.POST['payment_method_nonce'], 'options': { "submit_for_settlement": True } }) if result.is_success or result.transaction: try: order_details = Order.objects.create( token = client_token, total = braintree_total ) order_details.save() for order_item in cart_items: oi = OrderItem.objects.create( product = order_item.product.name, service = order_item.service.name, price = order_item.product.price, order = order_details ) oi.save() try: '''Calling the sendEmail function''' sendEmail(order_details.id) print('The order email has been sent to the customer.') except IOError as e: return e return redirect('order:thanks', order_details.id) except ObjectDoesNotExist: pass except ObjectDoesNotExist: #not sure if this line is correct return HttpResponse('FAIL') context = { 'cart_items': cart_items, 'total': total, 'client_token': client_token } return render(request, 'cart.html', context) -
filtering DateField on the basis of substring in django
So I am using a DateField for displaying the date. Which when passed to a template using contexts, renders in the format Nov. 4, 2018 Now there are multiple entries of such dates in the database. And I want to filter on the basis of string of the date actually shown. i.e when I type in Nov 4, or nov 4 or NOV 4 in my search input field, it should show the matched result. More like a substring match. Now the only problem is that i do not know how to convert my_model.date field in to Nov. 4, 2018. str(my_model.date) returns 2016-11-04 and I do not want to parse this with month_number-to-month_name map I think, any of the two solutions should work. 1) Django filters that allow me to do so. 2) converting my_model.date into Nov. 4, 2018 string Help please, been stuck on this forever now -
django-rest-framework-social-oauth2 session validation
I'm trying to use https://github.com/RealmTeam/django-rest-framework-social-oauth2 for user authentication. The last paragraph of the doc states that This request returns the "access_token" that you should use on all HTTP requests with DRF. What is happening here is that we are converting a third-party access token (<user_access_token>) in an access token to use with your api and its clients ("access_token"). You should use this token on each and further communications between your system/application and your api to authenticate each request and avoid authenticating with FB every time. I know that the converted tokens are stored in a table named oauth2_provider_accesstoken I was wondering what would be the right approach to validate a request to backend. I mean, assuming the I send the converted token, and the user that's using it in each of the user's request to the backend, do I run a select query on oauth2_provider_accesstoken and check if the user+token combination is valid? Is there a better way of doing this? -
Why I have a loading error for endfor on my html file on django?
I am trying to make a loop inside a template on django and the html file is telling me that I have to load the {% endfor %} ? What do I do ? <div style= "margin-left: 2em"> <form action= "{% url 'filled' %}" method = "POST" role = "form"> <div class="form-group"> <div class="input-group"> <table> <tr> {% for given_value in given_values % } <th>{{given_value.given_value}}</th> {% endfor %} -
Django - refresh textarea after submittin the new data
I have a text area, the context of this area is read from the text file. On my page, I have file upload input, which uploads the new file .views def upload_file(request): if request.method == 'POST': form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): handle_uploaded_file(request.FILES['file']) return redirect('index') return render_to_response('error.html') I am using return redirect('index') which redirects to the index page, but the content of this page is not reload. I am checking the file and it is ok, but page data are not reload. index page in views: def index(request): mail_form = MailForm() upload_form = UploadFileForm() content = { 'mail_form': mail_form, 'upload_form': upload_form, } return render(request, 'index.html', content) On mail_form = MailForm() I was expecting that new object will be created. Bit it is not -
Django and ajax function
I'm trying to run a jquery function on link click and return a modified html. This is the code: Html <li> <a runat="server" href="javascript:void(0);" onclick= "myFunction( '{{ playlist.name }}')" >{{ playlist.name }}</a> </li> Javascript $(document).ready(function() { }); var myFunction = function(playlist){ console.log(playlist); $.ajax({ url: '/ajax/select_playlist/', data: { 'playlist': playlist }, dataType: 'json', success: function (data) { console.log('This is not executing'); console.log(data); $('#to_replace').html(data); }, }); } Views.py: def select_playlist(request): playlist = request.GET.get('playlist', None) selected_playlist = Playlist.objects.get( name = playlist) print(playlist) print(selected_playlist) html = render_to_string('Play/playlist_detail_ajax.html', {'sel_playlist': selected_playlist}) return HttpResponse(html) It works fine right until the ajax function, i can't figure out what i'm doing wrong with that success function. -
How to convert pandas dataframe to queryset or model object in Django
In Django, I converted a model object into a pandas dataframe. After I edit the dataframe, I want to convert the pandas dataframe into a model objcet. However, I have no idea how to do this. Please teach me how to do this. -
target correct image for modal in django template
My template <div> <ul> {% for image in obj.images_set.all %} <li class="col-lg-4 text-center"> <a data-toggle="modal"data-target="#myModal{{forloop.counter0}}"> <img src="{{ image.image.url }}" alt=""/></a> </li> {% endfor %} </ul> </div> {% for image in obj.images_set.all %} <div id="myModal{{forloop.counter0}}" class="modal fade" role="dialog"> <div class="modal-dialog" style="text-align:center;"> <div class="modal-content" style="display:inline-block;"> <img src="{{ image.image.url }}" alt=""/> </div> </div> </div> {% endfor %} Im having a list of tasks. Im looping over the tasks and an obj represents one task.Each task has multiple images(1,2 or 3).The tasks are listed and the images are displaying correctly.Im trying to show a modal popup when clicking on an image inside a task. Im specifying the target with an id using for loop counter.The problem is that im not able to target the correct image as im having a list of images for each task...SO the for loop goes like 0,1,2 for images in first task and then 0,1,2 also for second task and im not able to assign a unique id for the data-target.How do i overcome this? -
Use some other User Model instead of settings.AUTH_USER_MODEL in django oauth toolkit
I am using Django oauth toolkit to implement Oauth in my application. I am already having a user model, but i want to use some other user model which is not AUTH_USER_MODEL. What i can see now is that i can only extend all the models and use my user instead of the AUTH_USER_MODEL, but i would like to know what will be the shortest and cleanest way to implement a separate user model in django oauth toolkit Current implementation is user = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True, null=True, on_delete=models.CASCADE) I want to use a separate AUTH_USER_MODEL -
How to load background image from style.css in django framework
Am using django 2.1 having a problem in displaying a background image which is styled in my css folder I have tried several ways like .testimonials {background: url("/static/images/s8.png"); padding:55px 0; overflow:hidden; } and having an inline customization both didn't work please help <div class="testimonials" style="background: url({% static "images/s8.jpg" %})"> -
I cannot get my dropdown to show in my Django Admin Panel
Hey I've been doing django projects for some time but I realised I do not really like the style of the admin panel so I decided I would redo it What seems to not work is that there's a "View Site" and "Change Password" link which I wanted to put in a dropdown to make it cleaner but when I did the dropdown it just shows white like this: https://gyazo.com/5b6c6f76ce39870cb26f11f83be52221 My code: <div id="header" class = "navbar navbar-collapse fixed-top"> <div id= "branding"> {% block branding %}{% endblock %} </div> {% block usertools %} {% if has_permission %} <div id = "user-tools" style = "overflow: visible !important;"> {% block userlinks %} <div class = "navbar-nav nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" style="overflow: visible !important;"> Dropdown </a> <div class="dropdown-menu" aria-labelledby="navbarDropdown"> {% if site_url %} <a class="dropdown-item-text" href="{{ site_url }}">{% trans 'Visit Site' %}</a> <a class="dropdown-item-text" href="{% url 'admin:password_change' %}">{% trans 'Change password' %}</a> {% endif %} {% if user.has_usable_password %} <a class="dropdown-item-text" href="{% url 'admin:password_change' %}">{% trans 'Change password' %}</a> {% endif %} </div> </div> </div> {% endblock %} {% endif %} {% endblock %} {% endif %} {% block nav-global %}{% endblock %} </div> And these … -
TypeError: __init__() got an unexpected keyword argument 'on_delete'
I built a model: class Channel(models.Model): title = models.CharField(max_length=255, unique=True) slug = models.SlugField(allow_unicode=True, unique=True) description = models.TextField(blank=True, default='') description_html = models.TextField(editable=False, default='', blank=True) subscribers = models.ManyToManyField(User, through="ChannelMembers", on_delete=models.CASCADE,) When I do makemigration it say : TypeError: __init__() got an unexpected keyword argument 'on_delete' And when a delete the on_delete it say: TypeError: __init__() missing 1 required positional argument: 'on_delete' What's worng? -
django How to add data in empty Object
How to add data in empty Object enter image description here Delete Object(2) enter image description here have Object(1) and Object(3) don't have Object(2) enter image description here add new Object ( have Object(4) don't have Object(2) ) enter image description here How to add data (Table Object(2) ) -
save_to_database ['function' object has no attribute '_meta']
I want to transfer excel data to DB(postgres DB) As the guide line of pyexcel, I use function save_to_database but it doesn't working, I don't have a idea where the wrong is..Plz help me i got this error : Internal Server Error: /weekly_upload Traceback (most recent call last):... AttributeError: 'function' object has no attribute '_meta' [04/Nov/2018 21:53:55] "POST /weekly_upload HTTP/1.1" 500 138219 django 1.11.12 form.py view.py weekly_upload.html urls.py trace back: -
django rest framework - allow only certain methods
right now i got a conceptual issue in django rest framework. I got a resource where i only want to allow a client to do a post request on the resource, thats why i use class MyViewSet(mixins.CreateModelMixin, viewsets.GenericViewSet): in my viewset. When i do a post request, it works as expected. When i do a list request, it throws a 405 response, as expected. When i do a retrieve, put, patch or delete method, it throws a 404 instead of a 405...why? How can i make every single request return a 405 despite of the post request? thanks and greetings! -
Django: ERR_TOO_MANY_REDIRECTS
I keep getting this error on my code when the user needs to be redirected to the ProfileCreateFormView so they can fill out the form. I tried several browsers and even incognito mode but still the same. This page isn’t working 127.0.0.1 redirected you too many times. Try clearing your cookies. ERR_TOO_MANY_REDIRECTS I'm using Django 2.1 and python 3.7 class ProfileDetailView(LoginRequiredMixin, DetailView): template_name = 'users/profile.html' def get_queryset(self): qs = models.Profile.objects.all() return qs def dispatch(self, request, *args, **kwargs): try: self.object = self.request.user.profiles except ObjectDoesNotExist: return redirect(reverse_lazy('users:create_profile')) return super().dispatch(request, *args, **kwargs) class ProfileCreateFormView(LoginRequiredMixin, FormView): template_name = 'users/create_profile.html' form_class = forms.ProfileForm `urls.py` app_name = 'users' urlpatterns = [ path('profile/create-profile/', views.ProfileCreateFormView.as_view(), name='create_profile'), ] -
Correct way to test save methods in django ModelAdmin
I have overridden save_related for one of my AdminModels: class TestAdminModel(ModelAdmin): def save_related(self, request, form, formsets, change): super(TestAdminModel, self).save_related(request, form, formsets, change) # do some stuff How would I test if the new save_related functions properly? It seems wrong to write a test and call the method (and I am unaware what I would pass as arguments for form and formsets). Or would this really be the way of testing the additional functionality of save_related? def test_new_save_related(): test_admin = TestAdminModel(Test, AdminSite()) test_admin.save_relate(...) # do some assertion -
Django Background Tasks autodiscovery not working
I have configured background tasks in my Django App according to docs. The structure of my app is as follows: todo_app | task | | | models, tests, urls, admin, apps | | frontend | | | tasks.py | | | models, tests, urls, admin, apps | manage.py | |todo_app | settings, urls, wsgi etc settings.py INSTALLED_APPS = [ ... 'background_task', ... ] BACKGROUND_TASK_RUN_ASYNC = True from background_task import background tasks.py @background(schedule=1) def task_runner(repeat=3): print("hello world") python manage.py process_tasks runs the task when the method is invoked under some view. The issue is that if its invoked under a view it will be invoked way too many times and the repeat will unnecessarily overload. What mistake am I making under the auto discovery? Is it necessary to manually invoke the method even after running python manage.py process_tasks? Thank you. -
Getting author of last post
So I have two models: Thread, ForumPost With a many-to-one relationship (each Thread can have many ForumPosts). I would like to display the author of the last post made into that thread. I'm currently doing: threads = Thread.objects.annotate(replies=Count('forumpost'), lastpost=Max('forumpost')) And I can access it in my view by doing: <td>{{thread.lastpost}}</td> But this only displays the last post ID,not the author. So when I try to do: <td>{{thread.lastpost.author}}</td> It won't display the author, although I have author = models.CharField(max_length=200) In my ForumPost model. So how do I go on about displaying the author, not the ID? -
Django app works locally but deployment on GCP say 500 Server Error, "ImportError: Could not import settings"
On GCP dashboard i get this error but on my machine all works fine: ImportError: Could not import settings 'site.settings' (Is it on sys.path?): No module named settings at __init__ (/base/alloc/tmpfs/dynamic_runtimes/python27g/3b44e98ed7fbb86b/python27/python27_lib/versions/third_party/django-1.4/django/conf/__init__.py:95) at _setup (/base/alloc/tmpfs/dynamic_runtimes/python27g/3b44e98ed7fbb86b/python27/python27_lib/versions/third_party/django-1.4/django/conf/__init__.py:42) at __setattr__ (/base/alloc/tmpfs/dynamic_runtimes/python27g/3b44e98ed7fbb86b/python27/python27_lib/versions/third_party/django-1.4/django/utils/functional.py:207) at <module> (/base/data/home/apps/g~unitutor-221411/1.413727868439486493/main.py:9) at LoadObject (/base/alloc/tmpfs/dynamic_runtimes/python27g/3b44e98ed7fbb86b/python27/python27_lib/versions/1/google/appengine/runtime/wsgi.py:85) at _LoadHandler (/base/alloc/tmpfs/dynamic_runtimes/python27g/3b44e98ed7fbb86b/python27/python27_lib/versions/1/google/appengine/runtime/wsgi.py:299) at Handle (/base/alloc/tmpfs/dynamic_runtimes/python27g/3b44e98ed7fbb86b/python27/python27_lib/versions/1/google/appengine/runtime/wsgi.py:240) This is my app.yaml: application: ********* version: 1 runtime: python27 api_version: 1 threadsafe: true handlers: - url: /static static_dir: static - url: /.* script: main.app libraries: - name: django version: "1.4" - name: jinja2 version: "latest" Obviously i have locally and on GCP a directory "site" contains "settings.py". On my machine the app works well. I try in many ways and read many post but i can't find a solution to solve the "500 Server Error" on GCP. -
django + vue:'Uncaught SyntaxError: Unexpected token <'
When I was deploying django + vue, there is the error "Uncaught SyntaxError: Unexpected token <" in vue project. I click the error, then: and in the network the status code of the js is 200, but the preview shos that: I use the vue-cli 3.0,so this is the directory of the project(dajngo + vue): And this is the code in the settings.py: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ['dist'], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'dist') ] Could you help me? Thank you so much!