Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to create an empty file using apache user in django or python instead of actual user of server
I need to create an empty file when createEmptyFile() is triggered in UI. But it is giving error "touch: cannot touch 'hello.txt': Permission denied" because instead of creating file with actual user (actualuser), it is creating with apache user This is a django app using apache server, and using 'os' module and with 'touch' command i need to create file def createEmptyFile(): print getpass.getuser() os.system('touch hello.txt') I expect file to be created but it is giving "touch: cannot touch 'hello.txt': Permission denied" because of file is creating using another user(apache) instead of actual user(anotheruser) Output: apache touch: cannot touch 'hello.txt': Permission denied -
How to use "create" model manager method on model without 'id' key
I have defined a django model as below: class MyModel_1(models.Model): ref_1 = models.ForeignKey(MyModel_2, on_delete=models.CASCADE) ref_2 = models.ForeignKey(MyModel_3, on_delete=models.CASCADE) class Meta: db_table = 'my_model_1' unique_together = (('ref_1 ', 'ref_2 '),) when i attempt to use a create() method on the model i get the below error: *** django.db.utils.ProgrammingError: column MyModel_1.id does not exist LINE 1: ...ref_1_id", "ref_2_id") VALUES (1, 12) RETURNING "... Why is the create method attempting to insert an id column even though i have not created one with it.. -
how to serve media files in django app nginx server?
I am testing my django app in production mode (debug=false) using nginx, gunicorn, postgresql. Though I am able to render static files, I am unable to access files stored in 'media' folder. In my settings.py following are the variables set: MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') # also tried another combination: MEDIA_ROOT = 'media' Also in urls.py the MEDIA_ROOT settings are as follows: urlpatterns = [ path('admin/', admin.site.urls), path('venter/', include('appname.urls')), ]+static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) And in my /etc/nginx/sites-available/ file I have the following settings: server { listen 80; server_name website.com www.website.com ; location = /favicon.ico { access_log off; log_not_found off; } location /static { root /home/a/btawebsite; } location = /media/ { root /home/a/btawebsite; } location / { include proxy_params; proxy_pass http://unix:/home/a/myproject.sock; } } However while rendering the xlsx file stored in my django database as follows it throws me NOT found error. {{file.output_file.url}} I have tried every combination of configurations required for rendering MEDIA files but unable to achieve the outcome. Thanks. -
How to update the fields of a model in which user model is inherited with some fields of user model?
I am working on a problem where I need to update some fields of user model with one field of the model in which it is inherited. Using updateview with that model shows errors. How am I supposed to do it? thanks in advance. models.py class UserProfile(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE, default=None, null=True) role = models.CharField(max_length=50, choices=Roles) verified =models.BooleanField(default = False,blank=True) photo = models.ImageField(upload_to='images', blank=True, default='default/testimonial2.jpg') def __str__(self): return self.user.username views.py class UserUpdateView(UpdateView): fields = ('first_name','last_name','email','photo') model = UserProfile success_url = reverse_lazy("NewApp:logindex") -
Clean request.POST object and checking if it is valid
I have the following form in HTML: <form method="POST"> {% csrf_token %} <button type='submit' name='manager_approve' value='{{ leave.leave_id }}' class='btn btn-success btn-md'>Approve</button> </form> I am processing this request in my view as follows: class ProcessLeaveRequest(TemplateView): template_name = 'LMSAdmin/process_leave_request.html' def get(self, request, *args, **kwargs): return render(request, self.template_name, {'leave_requests': GetLeaves.process_results(request)}) def post(self, request): if 'manager_approve' in request.POST: leave = Leaves.objects.get(id=request.POST['manager_approve']) return redirect('process_leave_request') Is there a way to run is_valid() and cleaned_data() functions of form class on this request.POST['manager_approve'] without creating a form object? Any help will be really appreciated. -
I'm syncing application details from external database with an api call, getting error none type has no attribute strip
ef get_applications(token): """ Get applications from eInsight """ url = '{0}/tip/rest/v1/model/Application'.format(TROUX_URL) headers = { 'Authorization': 'Bearer {0}'.format(token), } qsargs = { 'select': '*', 'limit': 1000, } while True: response = requests.get(url, params=qsargs, headers=headers) data = response.json() for app in data['model']: yield app if '_next' in data: url = data['_next']['model']['nextUrl'] qsargs = None else: return def update_application(token, eapp): """ Use data from eInsight to update applications in camp-backend """ app = Application.objects.filter(attributes__application_uuid__iexact=eapp['_id']) eapp_name = eapp['name'].strip() ef sync_applications(): """ Main Function to sync applications from eInsight """ token = get_token() futures = list() with ThreadPoolExecutor(max_workers=5) as executor: for app in get_applications(token): # future = executor.submit(update_application, app) # futures.append(future) update_application(token, app) -
Hide content from template using cbv
I'm using standart django template sintaxis for hiding a part of content from template depends on user status. For example {% if request.user.head_of_dept or request.user.seller or request.user.is_staff %} I know how to use the dispatch function to restrict user rights, for example class CustomCrudUserMixin(): def dispatch(self, request, *args, **kwargs): """Return 403 if flag is not set in a user profile. """ if not request.user.head_of_dept or request.user.seller or request.user.is_staff: return HttpResponseForbidden() return super().dispatch(request, *args, **kwargs) Sometimes templates contain a lot of places where I have to use restrictions, I'm wondering if there's a way to redo the dispatch function so that don't have to use the syntax {} at the template? -
How to correctly test authenticated POST method with Pytest in Django
I want to test an authenticated post method on an API using Pytest. This is what I am doing so far: def test_auth_user_can_create(self, client): url = api_reverse('crud-simulation_api') data = { "project": "testproject", .... } response = client.post(url, json=data) assert response.status_code == 200 This doesn't work because it gives me back a 401 (Unauthorized) instead of a 200. That makes sense since the fixture is a client and not an admin client. Yet if I pass in admin_client instead of client it gives me a Bad Request. The data that I send should be fine though. I also tried to pass in the headers like so (since I use JWT authorization): token = "bigassstringwhichismytoken" headers = { "Authorization": "JWT " + token } If somone could point me into the right direction that would be fantastic! Thanks a lot in advance -
Django Form looping through form fields but display 1 of each field in html row
I have a form which dynamically creates a number of fields based on the number of a variable in my HTML I then loop through the form to display the fields but I need to be like so: row 1 = "Field 1, Field 2" instead it is like: row 1 = "Field 1, Field 1" row 2 = "Field 2, Field 2" Form Code: class AttendingForm(forms.ModelForm): class Meta: model = Attending fields = ('name', 'type') def __init__(self, *args, **kwargs): self.ticket_count = kwargs.pop('count') super(AttendingForm, self).__init__(*args, **kwargs) for i in range(1, self.count): self.fields['%d name' % i] = forms.CharField() self.fields['%d type' % i] = forms.ChoiceField() HTML Code Snippet: <form method="post"> <section> <h1>Manage Attendees</h1> <div class="content-section"> {% for field in form %} <div class="form-field"> <label for="visitor_name">Name {{ field }} </label> </div> <div class="form-field"> <label for="visitor_name">Type</label> {{ field }} </div> {% endfor %} <div class="form-field"> <input type="submit" value="Submit" class="button button-black"> </div> </div> </section> </form -
how to delete record using modal in Bootstrap 4
hwo to make a modal appear once the user click the delete button where the modal contains a confirmation for the delete proccess. what happen: once the user click delete the system take him to new page and display the content of the modal if the user click YES button the system delete the record and redirect him to list page. what i want: once the user click the delete button the modal must appear asking the user if he want to delete. and when he click YES button the system must delete the record and redirect him to list page. views.py def delete(request,pk): dbEntry = get_object_or_404(suspect,pk=pk) if request.method =="POST": dbEntry.delete() return redirect("list") return render(request,"blog/delete.html",{"dbEntry":dbEntry}) list.html {% extends "testbootstarp.html" %} <a href="{% url 'delete' obj.pk %}" data-target="#modal-suspect" class="btn btn-danger">delete</a> <script type="text/javascript"> $(document).ready(function(){ $('#modal-suspect').modal(); }); </script> delete.html <div class="modal fade" id="modal-suspect"> <div class="modal-dialog"> <div class="modal-content"> <form method="post" action="{% url 'delete' dbEntry.pk %}" class="delete-form"> {% csrf_token %} <div class="modal-header"> <h5 class="modal-title" >Delete Suspect</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <p class="lead"> Are you sure you want to delete this suspect <strong>{{suspect.suspect_name}}</strong></p> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">No</button> <button type="submit" class="btn btn-danger">yes</button> </div> </form> </div> </div> … -
How to test a method decorated with @staff_member_required in class based views?
I have a view like so: class MyView: @staff_member_required def post(self, request): #some logic I'm using pytest https://pytest-django.readthedocs.io/en/latest/ for testing. I tried this: @pytest.mark.django_db def test_upload_payments(rf): with open("tests/fixtures/test_payments.csv") as f: request = rf.post("/invoice_admin/upload_payments/", {"invoice_file": f}) resp = MyView().post(request) assert resp.status_code == 201 However, i get an error: request = <WSGIRequest: POST '/invoice_admin/upload_payments/'>, args = (), kwargs = {} @wraps(view_func) def _wrapped_view(request, *args, **kwargs): > if test_func(request.user): E AttributeError: 'WSGIRequest' object has no attribute 'user' /usr/local/lib/python3.6/dist-packages/django/contrib/auth/decorators.py:20: AttributeError If i remove @staff_member_requred, everything works fine - the tests runs as expected. How do I fix this? I don't really care about being an admin with the right credentials for testing -- i just want to "force login" and be able to run the test. -
I already have Mysql but these will thrwing an error what will i do
django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module. Did you install mysqlclient? -
How to get the slug of current user?
I am working on a problem where I need to get the slug of current user for updating their information.In model I have stored the username in slug but I cannot access slug in template. I have tried using request.user to get the username in slug but it displays page not found error. models.py class UserProfile(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE, default=None, null=True) role = models.CharField(max_length=50, choices=Roles) verified =models.BooleanField(default = False,blank=True) photo = models.ImageField(upload_to='images', blank=True, default='default/testimonial2.jpg') slug = models.SlugField(unique=False, blank=True) def save(self, *args, **kwargs): self.slug = slugify(self.user.username) super(UserProfile, self).save(*args, **kwargs) def __str__(self): return self.user.username template <a class="nav-link " href="{% url 'NewApp:userupdate' slug=request.user %}" ><span class="glyphicon glyphicon-user"></span> {{request.user.username}} </a> url url(r'^userupdate/(?P<slug>[-\w\d]+)/$',views.UserUpdateView.as_view(),name='userupdate'), -
Python Poetry [EnvCommandError] when adding a package
Python's Poetry always throws me [EnvCommandError] whenever I try to add a package. This same error appears also when I try to install dependencies i.e. poetry install Mind that, 1.) I installed poetry correctly (using curl which is provided in their website) 2.) I am trying to integrate poetry with Docker, so I'm planning to entirely isolate the development with docker only not with any other virtual environment (if there is a 'better' way to do this kindly say so) 3.) I'm in the first stage of development:setting up. Nothing's really concrete yet and I'm trying to first organize the packages I'm gonna use and this is the error I get Initialization is fine: poetry init it shows interactive installation but with modification or any kind of using the poetry: poetry add bs4 it returns me: [EnvCommandError] Command ['C:\\Users\\username\\AppData\\Local\\pypoetry\\Cache\\virtualenvs\\muser-py3.7\\Scripts\\python.exe', '-' ] errored with the following return code 101, and output: Unable to create process using 'C:\Users\username\AppData\Local\Programs\Python\Python37\python.exe -' input was : import sys if hasattr(sys, "real_prefix"): print(sys.real_prefix) elif hasattr(sys, "base_prefix"): print(sys.base_prefix) else: print(sys.prefix) Exception trace: C:\Users\username\.poetry\lib\poetry\_vendor\py3.7\cleo\application.py in run() at line 94 status_code = self.do_run(input_, output_) C:\Users\username\.poetry\lib\poetry\console\application.py in do_run() at line 88 return super(Application, self).do_run(i, o) C:\Users\username\.poetry\lib\poetry\_vendor\py3.7\cleo\application.py in do_run() at line 197 … -
i have problem with one to one extends user model
hi friends i want extends user model with fields from other table (structure) as foreignkey .. i will show you my models and the error after creation of super user from django.db import models from django.contrib.auth.models import User from immob.models import structure from django.db.models.signals import post_save from django.dispatch import receiver class Profile(models.Model): User = models.OneToOneField(User, on_delete=models.CASCADE) structure_id = models.ForeignKey(structure, on_delete=models.CASCADE, default=0) @receiver(post_save, sender=User) def create_user_utilisateur(sender, instance, created, **kwargs): if created: Profile.objects.create(User=instance) @receiver(post_save, sender=User) def save_user_utilisateur(sender, instance, **kwargs): instance.profile.save() Error message: [p-amc-dgps-er@192-168-150-254 Invest_App]$ python3 manage.py createsuperuser Username (leave blank to use 'p-amc-dgps-er'): admin Email address: admin@admin.dz Password: Password (again): Error: Your passwords didn't match. Password: Password (again): Traceback (most recent call last): File "/usr/lib/python3.6/site-packages/django/db/backends/base/base.py", line 239, in _commit return self.connection.commit() psycopg2.errors.ForeignKeyViolation: ERREUR: une instruction insert ou update sur la table �� compte_profile �� viole la contrainte de cl�� ��trang��re �� compte_utilisateur_structure_id_id_df7f99e8_fk_immob_str �� DETAIL: La cl�� (structure_id_id)=(0) n'est pas pr��sente dans la table �� immob_structure ��. -
How to save a django "with" template tag value and reuse it in other templates?
I have a template tag that reads values from the URL. For example the searched term is cancer. After searching, the next page that appears would have a with Searched terms: Cancer. And I would like the value cancer to appear in all of my webpages until the user does a new search. Pages I have work this way: Search.html > display.html > explore.html Search.html is where the user enters what they want to search for. I have a searchedterms.html which is included into all 3 templates and contains the Javascript code to read from the URL. By using a JavaScript code, I managed to display searched terms: cancer in display.html but in explore.html the value is empty. I want to be able to save "cancer" to the tag and use it in other templates. ?conditions=cancer in search.html: <input required="" type="text" name="conditions"> in display.html: {% with searched_terms='searchedterms.html' %} {% include searched_terms %} {% endwith %} in explore.html: {% with searched_terms='searchedterms.html' %} {% include searched_terms %} {% endwith %} in searchedterms.html: <div id="searched" class="container"></div> <script type="text/javascript"> var urlParams = new URLSearchParams(window.location.search); function getUrlParameter(name) { name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]'); var regex = new RegExp('[\\?&]' + name + '=([^&#]*)'); var results = … -
How to solve AJAX cross-domain problems with csrftoken
I want to use the csrf_token to solve the Cross-domain problem about ajax, but I have some problems here is my json : {"id": 1, "distribution_box_id": "abc123", "timestamp": "2019-07-11T07:00:00", "lock1": 0, "lock2": 0, "temperature": 26.0, "humidity": 10.0, "latitude": 35.15409152643205, "longitude": 109.45553839575084, "smoke_detector": 0} $.ajax({ url: 'http://localhost/app1/distributionboxdata/1', method: 'post', headers: { 'Csrf-Token': '@play.filters.csrf.CSRF.getToken.map(_.value)' }, data: { name: '@name' }, success: function (data, textStatus, jqXHR) { location.reload(); },//I don't know what to put here error: function (jqXHR, textStatus, errorThrown) { debugger; } }); -
Django rest framework bulk: Correct URL syntax for bulk operations?
I'm attempting to carry out bulk DELETEs/PUTs on my Django API, mymodel inherits from the BulkModelViewSet In my urls.py file I define the URL used to interact with my model: router.register(r"v1/mymodels", mymodels_views_v1.MyModelViewSet) this allows me to GET, POST, PUT and DELETE on the URL (works perfectly at present): www.my-api.com/v1/mymodels/{{mymodel_id}} Can I use this same URL for bulk operations? If so, what is the correct syntax? eg: www.my-api.com/v1/mymodels/[{{mymodel_id1}},{{mymodel_id2}}] If not, what changes should I make? Thanks -
Cannot import python library on django server hosted on docker
I am running a django server on docker. I have added numpy and pandas in the requirements.txt file. Next I run docker-compose build . Both the libraries show as installed correctly. But now when I start the server and then run a python script that imports these libraries, the script fails to execute and I get no output. I tried executing the same script without importing those 2 libraries, and it executes properly giving out the expected print statement. What could have gone wrong here? -
table row order not changing after ajax call in django
The problem is i want to update the table row with drag and drop .using Jquery Ui for it.. i have an map_order field in model for swquence. but when i call ajax for that the changing is only happening in browser not in database i have tried to save the map_order but its not working HTML <tbody id="#layerTable"> {% for layer in layers %} <tr data-pk="{{ layer.id }}" class="ui-state-default"> <td><input type="checkbox" name="ids" value="{{ layer.id }}" /></td> <td> <a href="{% url 'mapport.maps.layers.one' map.id layer.id %}">{{ layer.name }}</a> </td> <td>{{ layer.heading }}</td> <td>{{ layer.class_group }}</td> <td> <span class="glyphicon glyphicon-resize-vertical"></span> {{ layer.map_order }}</td> <td>{{ layer.map_server }} </td> <td> {% if layer.sql_schema %}{{ layer.sql_schema }}.{{ layer.sql_table }}{% endif %} </td> </tr> JS <script type="text/javascript" charset="utf-8"> $(document).ready(function() { $("tbody").sortable({ stop: function(event, ui) { sort = {}; window.CSRF_TOKEN = "{{ csrf_token }}"; $("tbody").children().each(function(){ sort[$(this).data('pk')] = $(this).index(); }); {#var csrftoken = $('input[name="csrfmiddlewaretoken"]').val();#} $.ajax({ url: "{% url "mapport.maps.layers.all" map.id %}", type: "post", data:{sort, csrfmiddlewaretoken: window.CSRF_TOKEN, }, }); console.log(sort) }, }).disableSelection(); }); </script> Views.py class LayerView(BaseView) @csrf_exempt def sort(self): for index, layer_pk in enumerate(self.request.POST.getlist('layer[]')): self.layers.get_object_or_404(Layer, pk=int(str(layer_pk))) self.layers.map_order = index self.layers.save() Output is show the layer.id and index but not saving the layer.map_order {531: 15, 822: 14, 886: 20, … -
Django: Missing component after deployment
Django: Missing component after deployment. Missing app-component "accounts" after deployment on production-server. Symptoms: Changes to the model had no effect. Dropping the database deleted the UserProfile Model. Server: nginx, gunincorn on digitalocean Operations to perform: Apply all migrations: admin, auth, contenttypes, sessions, tweets Running migrations: No migrations to apply. :/home/django/django_project# tree ├── accounts │ ├── __init__.py │ ├── __init__.pyc │ ├── __pycache__ │ │ ├── __init__.cpython-36.pyc │ │ ├── __init__.cpython-37.pyc │ │ ├── admin.cpython-36.pyc │ │ ├── admin.cpython-37.pyc │ │ ├── forms.cpython-36.pyc │ │ ├── forms.cpython-37.pyc │ │ ├── models.cpython-36.pyc │ │ ├── models.cpython-37.pyc │ │ ├── urls.cpython-36.pyc │ │ ├── urls.cpython-37.pyc │ │ ├── views.cpython-36.pyc │ │ └── views.cpython-37.pyc │ ├── admin.py │ ├── admin.pyc │ ├── api │ │ ├── __init__.py │ │ ├── __init__.pyc │ │ ├── __pycache__ │ │ │ ├── __init__.cpython-36.pyc │ │ │ ├── __init__.cpython-37.pyc │ │ │ ├── serializers.cpython-36.pyc │ │ │ ├── serializers.cpython-37.pyc │ │ │ ├── urls.cpython-36.pyc │ │ │ └── urls.cpython-37.pyc │ │ ├── serializers.py │ │ ├── serializers.pyc │ │ ├── urls.py │ │ └── urls.pyc │ ├── apps.py │ ├── forms.py │ ├── forms.pyc │ ├── models.py │ ├── models.pyc │ ├── templates │ │ ├── accounts │ … -
Displaying file's uploading percentage (a variable) on sweetalert
How do we actually create a variable which is the file's uploading percentage on sweetalert? I'm using PyCharm as a platform and Django as a GUI framework. I've actually look at several types of questions pertaining to Ajax, PHP and sweetalert (can't find a specific problem related to mine), and tried some of the to mix and match some of the solutions, unfortunately, none of them work. As stated below is my curent code: In html: <form id='upload' method="post" enctype="multipart/form-data" onsubmit="myFunction()"> {% csrf_token %} <input name="datas" type="file" id="datas"/> <input type="submit" value="Submit" name="btnform3" style="height:6%; width:75%"/> </form> <script> function myFunction() { Swal.fire({ title: 'Status:', text: 'Files Uploading...', imageUrl:'static/widget-loader-lg-en.gif', html: '<h3 id="status"></h3>', showConfirmButton: false, allowOutsideClick: false, }) } function _(el) { return document.getElementById(el); } function uploadFile() { var file = _("datas").files[0]; var formdata = new FormData(); formdata.append("datas", file); var ajax = new XMLHttpRequest(); ajax.upload.addEventListener("progress", progressHandler, false); ajax.addEventListener("load", completeHandler, false); ajax.open("POST","static/upload.php"); ajax.send(formdata); } function progressHandler(event) { var percent = (event.loaded / event.total) * 100; _("status").innerHTML = Math.round(percent) + "% uploaded... please wait"; } function completeHandler(event) { _("status").innerHTML = event.target.responseText; } In upload.php: <?php $fileName = $_FILES["datas"]["name"]; // The file name $fileTmpLoc = $_FILES["datas"]["tmp_name"]; // File in the PHP tmp folder $fileType = $_FILES["datas"]["type"]; // … -
How to pass a keyword with an API request on a local server?
I need to send a string with the API request and store it in a variable which is oid here. How do i pass it with the url???? p.s. I am very new to Django and thus the basic doubt. -
enable html form in django rest ui
I need no enable 'html form' button in django rest api user interface. How to enable this option ? -
Problem to save data from a form to the session
I am trying to save the data from a form to the session but it seems that it's not the right datatype. I have tried model_to_dict and cleaned as it is working fine for my other form that takes similar data in entry but it didn't work. class ActivitiesForm(forms.Form): activity = forms.ModelChoiceField(label='Select your activities', queryset=Activity.objects.all()) target_group = forms.ChoiceField(label='Who is the report destined to?', choices=OutputOutcomeImpact.TARGETGROUP) class Activities(TemplateView): template_name = 'blog/activities.html' context = {'title': 'Activities selection page'} def get(self, request): form_act = ActivitiesForm() form_act.fields['activity'].queryset = Activity.objects.filter(categories__sectors__name=request.session['sector']['name']) self.context['form_act']=form_act return render(request,self.template_name, self.context) def post(self,request): form_act = ActivitiesForm(request.POST) if form_act.is_valid(): print(form_act.is_valid(),form_act.cleaned_data['activity'],type(form_act.cleaned_data['activity']),type(model_to_dict(form_act.cleaned_data['activity'])),form_act['activity']) request.session['activity'] = model_to_dict(form_act.cleaned_data['activity']) request.session['target_group'] = model_to_dict(form_act.cleaned_data['target_group']) return redirect('/about', self.context) Here's the type of data that I get from the print and the error: True Municipal waste incineration <class 'blog.models.Activity'> <class 'dict'> <select name="activity" required id="id_activity"> <option value="">---------</option> <option value="Municipal waste incineration" selected>Municipal waste incineration</option> <option value="Plastic upcycling">Plastic upcycling</option> </select> Internal Server Error: /activities/ . . . AttributeError: 'str' object has no attribute '_meta' Hope it helps. Thanks.