Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Users cannot update profile info
I'm trying to let users change their profile information but instead of changing the existing profile, form.save() saves it as a new entry under the same user. (example, bio would say 'What's up', they go to edit and no visible info is changed but another set of info is put in my userprofile table.) I tried using SQL commands and it returned something about an error near 'IT', which isn't in my code. I've tried getting my user.profile and then trying to edit the info through that (i.e user.profile.sex = form.cleaned_data['sex']). I've looked through the docs and the only thing I found that makes sense is Model.save(force_update=True) but where would I put it in my view and how could I link it to the user? View with the SQL I tried... @login_required def edit_prof(request): if request.method == 'POST': form = EPIF(request.POST, instance=request.user) if form.is_valid(): user_id = request.user.id conn = sqlite3.connect('db.sqlite3') cur = conn.cursor() sex = form.cleaned_data['sex'] dob = form.cleaned_data['dob'] r_stat = form.cleaned_data['relationship_stat'] locale = form.cleaned_data['location'] bio = form.cleaned_data['bio'] cur.execute(''' UPDATE profs_customuserprofile SET sex = {}, dob = {}, relationship_stat = {}, location = {}, bio = {} WHERE ID = {}; '''.format(sex, dob, r_stat, locale, bio, user_id)) content = form.save(commit=False) … -
Server error 500 when deploy django to Heroku
I got following server error 500 when deploying django app to heroku. I have worked on this problem for 2 days to fix, but have no idea to solve the problems. I assume djangorestframework cause this problems because it has favicon.ico which leads "GET /favicon.ico HTTP/1.1" 404 77" but no idea. Does anyone detect issues? Thank you for your support in advance!! 2019-07-23T12:03:44.622777+00:00 app[api]: Release v23 created by user atnihs-do-21@hotmail.co.jp 2019-07-23T12:03:51.865737+00:00 heroku[web.1]: Starting process with command `gunicorn alumate.wsgi --log-file -` 2019-07-23T12:03:55.314454+00:00 heroku[web.1]: State changed from starting to up 2019-07-23T12:03:55.130912+00:00 app[web.1]: [2019-07-23 12:03:55 +0000] [4] [INFO] Starting gunicorn 19.9.0 2019-07-23T12:03:55.132168+00:00 app[web.1]: [2019-07-23 12:03:55 +0000] [4] [INFO] Listening at: http://0.0.0.0:20191 (4) 2019-07-23T12:03:55.132311+00:00 app[web.1]: [2019-07-23 12:03:55 +0000] [4] [INFO] Using worker: sync 2019-07-23T12:03:55.138103+00:00 app[web.1]: [2019-07-23 12:03:55 +0000] [10] [INFO] Booting worker with pid: 10 2019-07-23T12:03:55.150027+00:00 app[web.1]: [2019-07-23 12:03:55 +0000] [11] [INFO] Booting worker with pid: 11 2019-07-23T12:03:55.000000+00:00 app[api]: Build succeeded 2019-07-23T12:04:30.649490+00:00 heroku[router]: at=info method=GET path="/" host=alumate.herokuapp.com request_id=0f1e339a-08fc-4b93-9c1b-1db28b675f76 fwd="210.150.77.215" dyno=web.1 connect=1ms service=835ms status=500 bytes=234 protocol=https 2019-07-23T12:04:30.649933+00:00 app[web.1]: 10.99.197.226 - - [23/Jul/2019:12:04:30 +0000] "GET / HTTP/1.1" 500 27 "https://dashboard.heroku.com/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.142 Safari/537.36" 2019-07-23T12:04:31.116073+00:00 heroku[router]: at=info method=GET path="/favicon.ico" host=alumate.herokuapp.com request_id=381749d5-0137-4017-bd1b-8bb8cb6feef1 fwd="210.150.77.215" dyno=web.1 connect=0ms service=186ms status=404 bytes=258 protocol=https … -
i'm having problem of accessing object in array with template language
{% for number in appliers|length|times %} {% if connector|get_by_index:number == commission.id %} {{appliers|get_by_index:number}} {% endif %} {% endfor %} i have made custom_template filter and it have worked great but the problem is that i can't access appliers[number]'s class variables. I tried accessing by {{appliers|get_by_index:number.email}} and it wouldn't work... please can any one can tell me how to solve this? -
How to delete all the files associated with the users when I delete the user
I am trying to make an web application in Django.Here I have created different fields in user model including profile picture and other pictures.When I delete a user,the files associated with the user doesn't get deleted.I want to delete the files,profile picture and other pictures when I delete the user. I am using django2.2 and I have customized my own user model and admin panel. In my user model I have added 'Profile Picture' field and 'CV' field. When I add a user in my model the profile picture are stored in 'Media/"%username/"' directory.I want to delete the files associated with the user when I delete the user.So I have written 'on_delete=..' in the () of username but it gives an error.So is there any possible way to do it? import .. import os def user_directory_path(instance, filename): return os.path.join('media', instance.username, filename) class User(AbstractBaseUser): username = models.CharField(max_length=200, unique=True, on_delete = os.remove(str(user_directory_path))) profile_photo = models.ImageField(default='media/download(1).png', upload_to = user_directory_path) cv = models.FileField(upload_to = user_directory_path) active = models.BooleanField(default=True) staff = models.BooleanField(default=False) admin = models.BooleanField(default=False) moderator = models.BooleanField(default=False) date_joined = models.DateTimeField(_('date joined'), default=timezone.now) I wanted to delete the files this way username = models.CharField(max_length=200, unique=True, on_delete = os.remove(str(user_directory_path))) but some errors come -
Django Media Files during development
How can I serve media files during development? The 'image' attribute has no file associated with it. When I try to upload a new file, I get this error: SuspiciousFileOperation at /admin/accounts/userprofile/4/change/ The joined path (/media/me.jpg) is located outside of the base path component (/home/django/django_project/static-serve/media) models.py image = models.ImageField(upload_to='/media',blank=True) urls.py ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) settings.py MEDIA_ROOT = '/home/django/django_project/static-serve/media/' MEDIA_URL = 'media/' -
Python Django - Show all assigned objects on the web page
I am developing web app for tracking orders. And I would like to display all orders which were created by a user via detailView. models.py class Order(models.Model): ... user = models.ForeignKey(MyUser, on_delete=models.CASCADE) order_number = models.CharField(max_length=150) class MyUser(models.Model): eid = models.CharField(max_length=7) name = models.CharField(max_length=150) surname = models.CharField(max_length=150) views.py class UserDetailView(generic.DetailView): model = MyUser template_name = "database/user_detail.html" def get_queryset(self): return Order.objects.all().order_by("-id") user_detail.html {% extends "base.html" %} {% block content %} <body> <h1> {{ user.eid }} {{ user.name }} {{ user.surname }} </h1> {% for order in orders %} order.order_number {% endfor %} {% endblock %} With this code I receive error: page not found: No Order found matching the query. If i delete the def get_queryset() in the views.py, it shows only the users eid and name. Not sure how I can get all the assigned orders to the particular user. -
Upon login redirection is not happening django
On my localhost (127.0.0.1:8000) i have configured a Login page and upon login its not redirecting to "Automation page (form_name_view". Note:- when i click login button nothing it happening whether with right credentials or wrong. In views.py from django.contrib.auth import authenticate,login,logout # Create your views here. def login_view(request): context = {} if request.method == "post": username = request.post['username'] password = request.post['password'] user = authenticate(request, username=username, password=password) if user: login(request, user) return HttpResponseRedirect(reverse('IP form')) else: context["error"] = "Provide valid credentials" return render (request,"first_app/login.html", context) else: return render (request,"first_app/login.html", context) def form_name_view(request): #this is the view to which i want to redirect if request.method == "POST": #some code In Models.py from django.db import models from django.contrib.auth.models import User # Create your models here. class Login(models.Model): username = models.CharField(max_length=50,) password = models.CharField(max_length=32,) def __str__(self): return self.user.Username In admin.py from django.contrib import admin from first_app.models import Login # Register your models here. admin.site.register(Login) In login.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Login</title> </head> <body> <h1> Please Login</h1> <form method="post"> {% csrf_token %} <table> <tr> <td><label for="username">Enter username: </label></td> <td><input type="text" name="username" id="username" required></td> </tr> <tr> <td><label for="username">Enter password: </label></td> <td><input type="password" name="password" id="password" required></td> </tr> <p> {{ error }} </p> </table> <input type="submit" … -
How to fix "AttributeError: module has no attribute 'wsgi' " in wfastcgi
I try to set up my django 2.2.2 project 'WebGUI' on IIS 10 (Windows Server 2019), but sadly i cant get it to work. wfastcgi is installed and enabled, I created a web.config and declared a python fastcgi handler in there. the keys should be correct and as far as i know thats all i'm supposed to configure. the web.config: <configuration> <system.webServer> <handlers> <add name="Python FastCGI" path="*" verb="*" modules="FastCgiModule" scriptProcessor="c:\python\python37-32\python.exe|c:\python\python37-32\lib\site-packages\wfastcgi.py" resourceType="Unspecified" requireAccess="Script" /> </handlers> </system.webServer> <appSettings> <!--Required Settings--> <add key="WSGI_HANDLER" value="WebGUI.wsgi.application" /> <add key="PYTHONPATH" value="C:\inetpub\wwwroot\WebGUI" /> <add key="WSGI_LOG" value="d:\wfastcgi.log" /> <add key="DJANGO_SETTINGS_MODULE" value="WebGUI.settings" /> </appSettings> </configuration> my settings.py says WSGI_APPLICATION = 'WebGUI.wsgi.application' and my wsgi.py: from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'WebGUI.settings') application = get_wsgi_application() Error occurred while reading WSGI handler: Traceback (most recent call last): File "c:\python\python37-32\lib\site-packages\wfastcgi.py", line 791, in main env, handler = read_wsgi_handler(response.physical_path) File "c:\python\python37-32\lib\site-packages\wfastcgi.py", line 633, in read_wsgi_handler handler = get_wsgi_handler(os.getenv("WSGI_HANDLER")) File "c:\python\python37-32\lib\site-packages\wfastcgi.py", line 603, in get_wsgi_handler handler = getattr(handler, name) AttributeError: module 'WebGUI' has no attribute 'wsgi' StdOut: StdErr: -
Django password-reset-confirm not working
I want to implement the Django reset password function but it gets stuck when it tries to sent the email. Error code: Reverse for 'password_reset_confirm' not found. 'password_reset_confirm' is not a valid view function or pattern name. error-code-picture I´ve tried the form with crispy and I´ve tried to let Django do it all alone (without my views) but it´s not working. urls: path('password-reset/', auth_views.PasswordResetView.as_view(template_name='web/users/password_reset.html'), name='password_reset'), path('password-reset/done/', auth_views.PasswordResetDoneView.as_view(template_name='web/users/password_reset_done.html'), name='password_reset_done'), path('password-reset-confirm/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(template_name='web/users/password_reset_confirm.html'), name='password_reset_confirm'), password-reset-confirm view (just the form): <form method="POST"> {% csrf_token %} <div class="form-group"> {{ form.email }} <label for="username" class="control-label">Email</label><i class="bar"></i> </div> <div class="button-container"> <input type="submit" class="button" value="Passwort ändern"/> </div> </form> I think the problem is that it´s not passing the uidb64 and the token to the email template. -
How to upload a list of files in database using django?
I want to upload multiple files in django that needs to be stored in a specific folder and the path of those files to be kept in the database. That field should also a no file option if the user does not want to upload any file. I am unable to find any solution to the above stated problem. def post(self, request, *args, **kwargs): print('req :', request.data) token = request.headers['authorization'] data = {'token': token} payload_decoded = jwt.decode(token, settings.SECRET_KEY) try: valid_data = VerifyJSONWebTokenSerializer().validate(data) user = valid_data['user'] self.request.user = user except ValidationError as v: print("validation error", v) serializer = QuestionsSerrializer(data=request.data) oa = Questions.objects.filter(user = user).values('outside_asset') if serializer.is_valid(raise_exception=True): serializer.save(user=self.request.user) form = UploadForm(request.POST, request.FILES) if form.is_valid(): for each in form.cleaned_data['outside_asset']: form = Questions.objects.create(user=user, outside_asset=each) form_data = form.save() form_data.save(user=self.request.user) return Response({'msg': 'Request Accepted'}, status=status.HTTP_200_OK) else: return Response({'msg': 'Invalid data'}, status=status.HTTP_400_BAD_REQUEST) The files received in request should be saved to a specific folder and their path should be stored in a single field in database -
Django view unit test conflict with custom template tag
I create a custom templatetag for my django project that returns an image url as favicon # myapp/templatetags/customtags.py @register.simple_tag def get_shop_favicon(): ''' get shop favicon ''' return Shop.objects.first().favicon.url and use it in base.html like this <!doctype html> {% load storefront_tags %} <head> <link rel="icon" href="{% get_shop_favicon %}" type="image/png" sizes="16x16"> </head> <body> ... </body> this part works great but after create test function to testing my view got an AttributeError as follow AttributeError: 'NoneType' object has no attribute 'favicon' and this is my test class # test.py from django.test import TestCase from django.urls import reverse class ProductViewTest(TestCase): ''' testing product views and urls ''' def test_get_product_list_status_code(self): ''' test to get all products ''' url = reverse('prodcuts') # url name response = self.client.get(url) self.assertEqual(response.status_code, 200) Note: with out template tag it works well -
django_crontab CRONJOBS can't read app from apps
I'm using django1.9, crontab, python2.7. I'm constrained with python2.7 for some reasons. my setting about crontab is as follow: CRONJOBS = [ ('*/1 * * * *','myapp.process.order_process','>>/logs/orders.log') ] I'm trying to add crontab task using python manage.py crontab add but it return RunTime Error: RuntimeError: No job with hash d3e49affa727e41dd02184fcad40b787 found. It seems the crontab is out of sync with your settings.CRONJOBS. Run "python manage.py crontab add" again to resolve this issue! I realized the error is because crontab can't recognize myapp which is under the folder named apps, so I changed CRONJOBS settings to CRONJOBS = [ ('*/1 * * * *','apps.myapp.process.order_process','>>/logs/orders.log') ] It actually works! However, here comes the new issue. since I used two different ways to use myapp: one is using myapp directly, another is using apps.myapp (in CRONJOBS), crontab run returns error of model conflicting. In short, my question is what the setting of crontab should be like when my app in under the folder of apps? Many Thanks!!! -
How to get login time and logout time of multiple users/students using django views
So I have written a view for getting login time and logout time of a student. Now I want to perform the same procedure for n number of students so how should I do it? Here's my view: def timestamp(request): TodayStartdate = datetime.now().strftime("%Y-%m-%d") + " 00:00" TodayEnddate = datetime.now().strftime("%Y-%m-%d") + " 23:59" Attendance = Attendance.objects.filter(reader_Timestamp__range=(TodayStartdate, TodayEnddate)) Login = Timestamp.first() Logout = Timestamp.last() print(Login) print(Logout) return render(request, 'app/timestamp.html') -
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?