Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I display my views output variable in my template in Django?
I have my Django views.py function : def dsctbl2(request): dynamodb=boto3.client('dynamodb', region_name='us-west-2') response = dynamodb.scan( TableName='User-Account') filtered = response['Items'] length = len(filtered) a = [] for k in range(length): accnum = filtered[k]['AccountNum']['S'] uid = filtered[k]['UserId']['S'] f = {} f = dict(AccountNum=accnum,UserId=uid) a.append(f) return (a) The above function filters the UserId and Accountnumber items from a dynamodb table. I need to display the "UserId" and "AccountNum" in my html template in a table's row. Here's my html snippet : <div class="mytable"> <table style="width:96%" class="table table-responsive"> <thead id="head" class="mdb-color lighten-4"> <tr> <th></th> <th class="th-lg">User ID</th> <th class="th-lg">Account Number</th> </tr> </thead> <tbody> {% for r in rows %} <tr> <th scope="row"></th> <td>{{r.AccountNum}}</td> <td>{{r.UserId}}</td> </tr> {% endfor %} </tbody> </table> </div> I've included block content and endblock tags in my html code . What am I doing wrong here ? I'm a beginner in Django. Thanks in advance -
Extra form on ModelFormSet
For my Django project, I am rendering the model formset election_formset = modelformset_factory(Election, exclude=('Complete',), formset=BaseElectionFormSet) in my template: <form method="post" action=""> {{ formset.management_form }} {% for form in formset %} <div class='card'> <div class='card-body w-75 mx-auto'> <div class='row'> <div class='col-6 text-center'> <p>Name<br>{{form.Name}}</p> </div> <div class='col-6 text-center'> <p>Videos<br>{{form.FlipGrid}}</p> </div> </div> <div class='row'> <div class='col-12 text-center'> <p>Description<br>{{form.Description}}</p> </div> </div> <div class='row'> <div class='col-6 text-center'> <p>Allow registration: {{form.CandidateReg}}</p> </div> <div class='col-6 text-center'> <p>Allow voting: {{form.VotingOpen}}</p> </div> </div> </div> </div> {% endfor %} </form> When the formset renders, an extra, blank form is shown at the end of the forms. I only want forms to show that are instances of existing records. Why is there an extra blank formset and how can I prevent it? -
Error: 'QuerySet' object has no attribute, even if the attribute exist
I have the following code: company = Company.objects.filter(account=self.account).only('slug') if company: return redirect(reverse_lazy('company:detail_a', kwargs={'slug': company.slug})) I get the error: 'QuerySet' object has no attribute 'slug' The slug attribute definitely exist(checked in model/database). I tried to access it like in a template. So I tried with other attributes, 'name', because appears when I print the QuerySet. So I think the QuerySet is not evaluated or something like that, but I don't know how to force to do it. -
Django admin: how to predefine field values?
I use Django 1.11.10 and python 3.6; I have Category model that has name and parent. Parent field links to itself. But when I create new Category model, I want choose parent from already created categories that have no parents. So how to predefine this list? class Version(models.Model): name = models.CharField(max_length=50, unique=True) parent = models.ForeignKey('self', null=True, blank=True) ------ class CategoryForm(forms.ModelForm): class Meta: model = Category fields = ['name', 'parent'] class CategoryAdmin(admin.ModelAdmin): form = CategoryForm admin.site.register(Category, CategoryAdmin) -
Mailgun Email sender isn't what its supposed to be
So ive just set up django emails with mailgun, and sent the first email. This is the config I have in Django: EMAIL_BACKEND = config('EMAIL_BACKEND', default='django.core.mail.backends.smtp.EmailBackend') EMAIL_HOST = config('EMAIL_HOST', default='') EMAIL_PORT = config('EMAIL_PORT', default=587, cast=int) EMAIL_HOST_USER = 'postmaster@mg.smartsurvey.xyz' EMAIL_HOST_PASSWORD = config('EMAIL_HOST_PASSWORD', default='') EMAIL_USE_TLS = config('EMAIL_USE_TLS', default=True, cast=bool) DEFAULT_FROM_EMAIL = 'SmartSurvey <noreply@smartsurvey.xyz>' This is the view that sends the email: current_site = get_current_site(request) subject = 'Activate your SmartSurvey account' message = render_to_string('email/email_activation.html', { 'name': user.get_full_name(), 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': account_activation_token.make_token(user), }) user.email_user(subject, message) And I want the sender to be SmartSurvey <noreply@smartsurvey.xyz>, however it currently sends like: noreply=smartsurvey.xyz@mg.smartsurvey.xyz on behalf of SmartSurvey <noreply@smartsurvey.xyz> How can I go about fixing this? -
Djagno many to many relationship. How to get all rows which primary key doesn't exist on another table?
I've 3 models A, B and C. they are as follows: class A(models.Model): name=models.TextFeild() class B(models.Model): name=models.TextFeild() class C(models.Model): a=models.models.ForeignKey(A, on_delete=models.CASCADE, related_name='as') b=models.models.ForeignKey(B, on_delete=models.CASCADE, related_name='bs') I want to get all B's which exist in C with A.name = 'jhon' I've tried taken_tests = C.objects.filter(a.name='jhon') queryset = B.objects.filter().exclude(pk__in=taken_tests) But this gives me all B's. -
Django Rest Docker with MySQL create a superuser
I have dockerized my existing Django Rest project which uses MySQL database. My dockerfile: FROM python:2.7 ENV PYTHONUNBUFFERED 1 RUN mkdir /code WORKDIR /code COPY . /code/ RUN pip install -r requirements.txt And my docker-compose.yml file: version: '3' services: web: build: . command: bash -c "python manage.py migrate && python manage.py runserver 0.0.0.0:8000" volumes: - .:/code depends_on: - db ports: - "8000:8000" db: image: mysql environment: MYSQL_ROOT_PASSWORD: root MYSQL_DATABASE: libraries MYSQL_USER: root MYSQL_PASSWORD: root My commands docker-compose buildand docker-compose up are successful and output of later is: D:\Development\personal_projects\library_backend>docker-compose up Starting librarybackend_db_1 ... done Starting librarybackend_web_1 ... done Attaching to librarybackend_db_1, librarybackend_web_1 db_1 | 2018-02-13T10:11:48.044358Z 0 [Warning] TIMESTAMP with implicit DEFAULT value is deprecated. Please use --explicit_defaults_for_timestamp server option (see documentation for more details). db_1 | 2018-02-13T10:11:48.045250Z 0 [Note] mysqld (mysqld 5.7.20) starting as process 1 ... db_1 | 2018-02-13T10:11:48.047697Z 0 [Note] InnoDB: PUNCH HOLE support available db_1 | 2018-02-13T10:11:48.047857Z 0 [Note] InnoDB: Mutexes and rw_locks use GCC atomic builtins db_1 | 2018-02-13T10:11:48.048076Z 0 [Note] InnoDB: Uses event mutexes db_1 | 2018-02-13T10:11:48.048193Z 0 [Note] InnoDB: GCC builtin __atomic_thread_fence() is used for memory barrier db_1 | 2018-02-13T10:11:48.048297Z 0 [Note] InnoDB: Compressed tables use zlib 1.2.3 db_1 | 2018-02-13T10:11:48.048639Z 0 [Note] InnoDB: Using … -
django postgres LIKE query syntax error at or near "%"
In django, to query JSONB, I do: cursor.execute("""\ SELECT * FROM "somemodel_some_model" WHERE UPPER(("somemodel_some_model"."data" #>> array[0,'fieldX'])::text[]) LIKE UPPER(% %s %) """,[my_string]) .. and I get: IndexError: list index out of range To investigate this, I drop to SQL and do the following: SELECT * FROM "somemodel_some_model" WHERE UPPER(("somemodel_some_model"."data" #>> array[0, 'fieldX'])::text[]) LIKE UPPER(%my_search_string%) ..but, I get: django.db.utils.ProgrammingError: syntax error at or near "%" So, the question is, do I need to escape %? Seems odd -
Django admin: how iterate over form attributes in ModelAdmin
I use Django 1.11.10 and python 3.6; I need to iterate form values in admin. How to do that? class ServerForm(forms.ModelForm): class Meta: model = Server def clean(self): setattr(self, 'field1', 'value1') setattr(self, 'field2', 'value2') class ServerAdmin(admin.ModelAdmin): form = ServerForm def save_model(self, request, obj, form, change): # this works # but how to iterate form? obj.field1 = form.field1 obj.field2 = form.field2 # AttributeError: 'ServerForm' object has no attribute 'items' for key, value in form.items(): setattr(obj, key, value) super(ServerAdmin, self).save_model(request, obj, form, change) -
How to define canvas for pyplot in order to plot in HTML document?
I'm using Django to make a web page. I try to make a bar plot created with matplotlib appear on my web page but receive the following error message saying that I haven't defined the attribute 'canvas': Traceback: File "C:\Python3.6\lib\site-packages\django\core\handlers\exception.py" in inner 35. response = get_response(request) File "C:\Python3.6\lib\site-packages\django\core\handlers\base.py" in _get_response 128. response = self.process_exception_by_middleware(e, request) File "C:\Python3.6\lib\site-packages\django\core\handlers\base.py" in _get_response 126. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\JNPou\Desktop\Den bæredygtige back-up\kogebog\opskriftssoegning\views.py" in Opskriftsside 136. json1 = json.dumps(mpld3.fig_to_dict(bar_plot)) File "C:\Python3.6\lib\site-packages\mpld3\_display.py" in fig_to_dict 167. Exporter(renderer, close_mpl=False, **kwargs).run(fig) File "C:\Python3.6\lib\site-packages\mpld3\mplexporter\exporter.py" in run 45. if fig.canvas is None: Exception Type: AttributeError at /opskriftssoegning/kartoffelsuppe-med-porrer/ Exception Value: 'tuple' object has no attribute 'canvas' Here is my Python code for creating the plot: import matplotlib matplotlib.use('Agg') import json import numpy as np import matplotlib.pyplot as plt, mpld3 import pandas as pd [...] def make_bar_plot(): height = [1, 2, 3, 3.33, 3.67, 4, 4.33, 4.67, 5, 6, 7, 8, 9, 10, 11, 11.33, 11.67, 12, 12.33, 12.67, 13, 14, 15] bars = ('1','2','3','4','5','6','7','8','9','10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23') y_pos_prototype = np.arange(len(bars)) y_pos = pd.Series(y_pos_prototype).to_json(orient='values') #y_pos = np.arange(len(bars)) fig = plt.figure() color_set = red_yellow_green_gradient(height) # Create bars plt.bar(y_pos, height, color=color_set, figure=fig) # Create … -
Android Volley - How to use cookie value in headers
I have backend of my app in Django. I set SessionAuthentication in Django REST Framework so it sends CSRF Token. When I log in into my app I get CSRF token as a cookie. It looks like this(Image from postman): Now I need to use value of csrftoken in another POST method in my app, I need to use it ass XCSRFToken header. Here is my code: LoginActivity: private fun login2() { val req = object : StringRequest(Request.Method.POST, LOGIN_API_URL, Response.Listener { response -> Toast.makeText(this, response, Toast.LENGTH_LONG).show() val user = Intent(this, UserActivity::class.java) startActivity(user) }, Response.ErrorListener { e -> Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show() }) { public override fun getParams(): Map<String, String> { val params = HashMap<String, String>() params.put("username", username.text.toString()) params.put("password", passwd.text.toString()) return params } override fun getHeaders(): MutableMap<String, String> { return super.getHeaders() } } req.retryPolicy = DefaultRetryPolicy(60000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT) volleyRequest!!.add(req) } Activity where I need to set this header: private fun aktualizacja2() { val req = object : StringRequest(Request.Method.POST, UPDATE_URL, Response.Listener { response -> Toast.makeText(this, response.toString(), Toast.LENGTH_LONG).show() Toast.makeText(this, response.toString(), Toast.LENGTH_LONG).show() }, Response.ErrorListener { e -> Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show() }) { public override fun getParams(): Map<String, String> { val params = HashMap<String, String>() params.put("librus_user", usernameEdit.text.toString()) params.put("librus_pswd", passwordEdit.text.toString()) return params } override fun getBodyContentType(): String … -
Django Unit test : `freeze_time` not work well in some cases (Seems like a bug..?)
This is my code for testing the role of TIME_ZONE and `USE_TZ: from django.test.utils import override_settings class TimeZoneTest(TestCase): @override_settings(TIME_ZONE='UTC', USE_TZ=True) @freeze_time("2018-01-04 13:30:55", tz_offset=9) # The reason that I add tz_offset=9 is to make local time samw with `Asia/Seoul` def test_freeze_time1(self): print("TIME_ZONE='UTC', USE_TZ=True") print(datetime.now()) print(timezone.now()) @override_settings(TIME_ZONE='UTC', USE_TZ=False) @freeze_time("2018-01-04 13:30:55", tz_offset=9) def test_freeze_time2(self): print("TIME_ZONE='UTC', USE_TZ=False") print(datetime.now()) print(timezone.now()) @override_settings(TIME_ZONE='Asia/Seoul', USE_TZ=True) @freeze_time("2018-01-04 13:30:55", tz_offset=9) def test_freeze_time3(self): print("TIME_ZONE='Asia/Seoul', USE_TZ=True") print(datetime.now()) print(timezone.now()) @override_settings(TIME_ZONE='Asia/Seoul', USE_TZ=False) @freeze_time("2018-01-04 13:30:55", tz_offset=9) def test_freeze_time4(self): print("TIME_ZONE='Asia/Seoul', USE_TZ=False") print(datetime.now()) print(timezone.now()) Result TIME_ZONE='UTC', USE_TZ=True 2018-01-04 22:30:55 2018-01-04 13:30:55+00:00 .TIME_ZONE='UTC', USE_TZ=False 2018-01-04 22:30:55 2018-01-04 22:30:55 .TIME_ZONE='Asia/Seoul', USE_TZ=True 2018-01-04 22:30:55 2018-01-04 13:30:55+00:00 .TIME_ZONE='Asia/Seoul', USE_TZ=False 2018-01-04 22:30:55 2018-01-04 22:30:55 The strange part is test_freeze_time1(), which tests under TIME_ZONE='UTC', USE_TZ=True, the reason that I think it strange is that datetime.now() doesn't print out UTC time, which is not True if I removed @freeze_time("2018-01-04 13:30:55", tz_offset=9) : from django.test.utils import override_settings class TimeZoneTest(TestCase): @override_settings(TIME_ZONE='UTC', USE_TZ=True) def test_freeze_time1(self): print("TIME_ZONE='UTC', USE_TZ=True") print(datetime.now()) print(timezone.now()) @override_settings(TIME_ZONE='UTC', USE_TZ=False) def test_freeze_time2(self): print("TIME_ZONE='UTC', USE_TZ=False") print(datetime.now()) print(timezone.now()) @override_settings(TIME_ZONE='Asia/Seoul', USE_TZ=True) def test_freeze_time3(self): print("TIME_ZONE='Asia/Seoul', USE_TZ=True") print(datetime.now()) print(timezone.now()) @override_settings(TIME_ZONE='Asia/Seoul', USE_TZ=False) def test_freeze_time4(self): print("TIME_ZONE='Asia/Seoul', USE_TZ=False") print(datetime.now()) print(timezone.now()) Result TIME_ZONE='UTC', USE_TZ=True 2018-02-13 09:10:49.715005 2018-02-13 09:10:49.715018+00:00 .TIME_ZONE='UTC', USE_TZ=False 2018-02-13 09:10:49.715970 2018-02-13 09:10:49.715980 .TIME_ZONE='Asia/Seoul', USE_TZ=True 2018-02-13 18:10:49.716758 2018-02-13 09:10:49.716769+00:00 .TIME_ZONE='Asia/Seoul', USE_TZ=False 2018-02-13 18:10:49.717475 2018-02-13 … -
django to IndexDB synchronization
how can i store in IndexDB and user Authentication is possible or not. if it is possible how can I login with IndexDB data of username and password. using django to sync IndexDB. just mention which indexDB is compatible. I am start searching for pouchDB. -
Can I run Django tests in pycharm community edition?
I have a Django project with a bunch of tests that I have just imported into PyCharm. I managed to get it configured so that I can run the server and that works fine but now I want to run the tests as well. I have tried to create a Path based Test Configuration and given the manage.py path and the test command as well as my settings file as parameters but I get the following cryptic error message: Testing started at 10:12 ... /Users/jonathan/anaconda/bin/python "/Applications/PyCharm CE.app/Contents/helpers/pycharm/_jb_unittest_runner.py" --path /Users/jonathan/Work/GenettaSoft/modeling-web/modeling/manage.py -- test --settings=Modeling.settings.tests Launching unittests with arguments python -m unittest /Users/jonathan/Work/GenettaSoft/modeling-web/modeling/manage.py test --settings=Modeling.settings.tests in /Users/jonathan/Work/GenettaSoft/modeling-web/modeling usage: python -m unittest [-h] [-v] [-q] [--locals] [-f] [-c] [tests [tests ...]] python -m unittest: error: unrecognized arguments: --settings=Modeling.settings.tests Process finished with exit code 2 Empty test suite. It must be running things in the wrong way somehow. Can this not be done at all? Ps. I found Running Django tests in PyCharm but it does not seem related at all (much older version?), cause I get different errors and things look very different. -
Django Custom error page's giving error
I'm trying to make custom error page general 404 and 500. I'm not trying to raise just making a default if it happens for a user, but every place I'm trying to search and follows a tutorial and so on I always ends up in getting an internal error on both 500 and 404 I'm running django=1.11.6, and I'm running debug False because I need to see if it work of course. How can I fix this issue and make it work? And how can I make it so it also gives the user the error text so they can send it to me? Views.py (In my app folder) # Error Handlers def handler404(request): return render(request, 'handlers/404.html', status=404) def handler500(request): return render(request, 'handlers/500.html', status=500) Urls.py (in my main config folder) from django.conf.urls import include, url, handler404, handler500 from django.contrib import admin handler404 = 'staff.views.handler404' handler500 = 'staff.views.handler500' urlpatterns = [ url(r'^', include('staff.urls')), url(r'^admin/', admin.site.urls), ] -
Extend User Model Django 2.0
I'm starting a whole new project using Django 2.0 and python, so I'm at the beginning of deciding how to implement the Multiple User Types. What I've read so far is that I can extend the User built-in model for django so that I would get use of django's authentication process, and create another models that links one-to-one with that user model. But actually I can't understand a little bit. My application has three user types: Participant, Admin, Judge, each of them will view certain pages(templates) and as well as permissions. Can someone provide me with the best practice/approach to start working on those user types. Note: In the future, each user may have different fields than the other, for ex. Judge may have Join date while participant won't...etc -
Safety checks in OneToOne Relation, after a relation already exist, not to be added another one
I have 2 models Account and Company. class Company(models.Model): account = models.OneToOneField(Account, related_name='company', on_delete=models.CASCADE) I want in site and in Django Admin, if a company already correspond to an account' to not be possible for another company to be added, because will give a database error. Besides removing the add/select options in Django Admin, for both site and admin, if the url is accessed directly to be redirected with message to the detail page. -
Loop Pandas table in Django template
I have a Pandas table which filled with values in my view. This view send this data to my template. Unfortunately I can't loop the values despite I can it in python shell. I attach my table and my attempt: My table (MyTable): ID day data _|___________|_____ 0| 2017-01-01|100.0| 1| 2017-01-02|99.8 | 2| 2017-01-03|90.0 | My attempt: {%for i, b in MyTable.itertools() %} <td>{{b['day']}}</td><td> {{b['data']}}</td> {%endfor%} I got the following error message: Could not parse the remainder: '()' from 'MyTable.iterools()' In python shell (where I testing) I could loop the table by the method below. How can I loop my pandas table in Django template? Thank you in advance. -
Django, how to reject a object from a @receiver if some int equals to another int
Im having this doubt, I have a model that stores data from a form, when the data is sent this @receiver stores the data in another model. @receiver(post_save, sender=Invitaciones) def crear_invitado(sender, instance, created, **kwargs): if created: Invitados.objects.create(nombre=instance.nombre, apellido=instance.apellido, tipo_de_cedula=instance.tipo_de_cedula, cedula=instance.cedula) I want this receiver to create the object only if there is not another object with the same "instance.cedula" in it. I tried to make a for cicle throught all the objects in "Intivados.cedula" like this @receiver(post_save, sender=Invitaciones) def crear_invitado(sender, instance, created, **kwargs): data = Invitados.objects.all() for c in data: if int(c.cedula) == int(instance.cedula): cedula_invitacion = print("This person already exists") else: cedula_invitacion = Invitados.objects.create(nombre=instance.nombre, apellido=instance.apellido, tipo_de_cedula=instance.tipo_de_cedula, cedula=instance.cedula) if created: cedula_invitacion This does not seem to work, the else statement is always stored in the model multiple times (equal to the quantity of models inside data) and also the print(), show the same has the quantity of models inside data. If someone has a answer, I would really appreciate it. Thanks. -
jquery - not able to display the needed content with the function
I have this jQuery script that I do not fully understand. I was wondering why I cannot replace the siblings('div') with a class or id? I think my code doesn't work properly. What I was trying to do is replace some content with a button click, and then the second content, replace it again with the second function. All courses get replaced by faculties, but faculties dont get replaced by the departments, when I press on a department, they all show one under another <div class="row"> <div class="col-md-3"> <div class="jumbotron"> <h4>Search courses</h4> <hr> <br> <ul> <li class="btnClick" id="fac_1">Faculty of Mathematics and Informatics</li> <ul> <li class="btnClick2" id="dep_1">Mathematics and Informatics</li> <ul> <li>Informatics</li> <li>Mathematics</li> </ul> </ul> <li class="btnClick" id="fac_2">Faculty of Medicine</li> <ul> <li class="btnClick2" id="dep_2">Medicine</li> <ul> <li>Medical Sciences</li> </ul> </ul> </ul> </div> </div> <div class="col-md-9"> <div class="jumbotron"> <div> <h3>All courses</h3> <ul> <li> <a class="first" href=artificial-intelligence>Artificial Intelligence</a> </li> <li> <a class="first" href=software-engineering>Software Engineering</a> </li> <li> <a class="first" href=surgery>Surgery</a> </li> </ul> </div> <div id="fac_1_tab" style="display:none;"> <h3> Faculty of Mathematics and Informatics courses</h3> <ul> <li> <a class="first" href=artificial-intelligence>Artificial Intelligence</a> </li> <li> <a class="first" href=software-engineering>Software Engineering</a> </li> </ul> </div> <div id="fac_2_tab" style="display:none;"> <h3> Faculty of Medicine courses</h3> <ul> <li> <a class="first" href=surgery>Surgery</a> </li> </ul> </div> <ul> <div … -
Why does my gunicorn listen to my local Django development server on my live server
When I perform gunicorn --log-file=- draft1.wsgi:application to see the gunicorn log of my app, it says Listening at: http://127.0.0.1:8000 which is the local Django development server. Can somebody tell me why it does this on my live django server? Here is the full log: (env) james@postr:~/postr$ gunicorn --log-file=- draft1.wsgi:application [2018-02-13 07:23:33 +0000] [25004] [INFO] Starting gunicorn 19.7.1 [2018-02-13 07:23:33 +0000] [25004] [INFO] Listening at: http://127.0.0.1:8000 (25004) [2018-02-13 07:23:33 +0000] [25004] [INFO] Using worker: sync [2018-02-13 07:23:33 +0000] [25007] [INFO] Booting worker with pid: 25007 -
Forbidden CSRF token missing or incorrect in Django POST request even though I have csrf token in form
I have included csrf_token in data while making AJAX request. But I keep getting 403 as a response when I make a POST request. I checked whether csrf_token is empty or not before making the request. Everything seems fine, what could be triggering the error? Here is my html code: <form method = "POST" > {% csrf_token %} <div class="form-group"> <label for="name">Name:</label> <input type="text" class="form-control" id="name" placeholder="Enter name" name="name" required> </div> <div class="form-group"> <label for="email">Email:</label> <input type="email" class="form-control" id="email" placeholder="Enter email" name="email" > </div> <div class="form-group"> <label for="pwd">Password:</label> <input type="password" class="form-control" id="pwd" placeholder="Enter password" name="pwd" > </div> <div class="form-group"> <label for="name">Website:</label> <input type="text" class="form-control" id="website" placeholder="Enter website" name="website"> </div> <div class="checkbox"> <label><input type="checkbox" name="remember"> Remember me</label> </div> <input type="text" id="submit" class="btn btn-default" value="Submit"> Javascript Code: $("#submit").click(function(){ var finalData = {}; finalData.name = $('#name').val(); finalData.email = $('#email').val(); finalData.pwd = $('#pwd').val(); finalData.website = $('#website').val(); finalData.csrfmiddlewaretoken = $('input[name=csrfmiddlewaretoken]').val(); $.ajax({ url: window.location.pathname, type: "POST", data: JSON.stringify(finalData), contentType: "application/json", success: function(data){ alert('Yo man'); }, error: function(xhr, status, error) { alert(xhr.responseText); } }); }); Python code: def signup(request): if request.method == 'POST': response_json = request.POST response_json = json.dumps(response_json) xy = json.loads(response_json) user = User() user.name = xy['name'] user.email = xy['email'] user.password = make_password(xy['pwd']) user.website = xy['website'] … -
how to create separate superuser for diffrent login in django
I have create a user login page authentication and using django admin login.. how to specify superuser for separate login .. ? and django admin login ... how specify super user for separate login pages please help me -
strange seemingly django related importerror
I have a small django project, in which I am trying to import some functions from another script. The files in question both lie in the same directory, and are views.py and lookup.py. Below is the import section of views.py. from django.shortcuts import get_object_or_404, render from django.template import loader from django.http import HttpResponse,HttpResponseRedirect from django.http import Http404 from django.urls import reverse from django.views import generic import json import random from django.views.decorators.csrf import ensure_csrf_cookie from os import listdir, getcwd import os.path from PIL import Image from app.models import ImageToClassify, ClassifiedImage, User import xlrd from lookup import get_colors, find_row, get_all_colors >> cannot import name 'get_all_colors' When I run these same imports in a separate file, there is no problem. If there is anything else I can add please let me know, this has got me very confused. I can't seem to get a minimal example which breaks, I was trying obviously and then the imports work in a new script. The order of the functions in lookup.py don't matter, nor does the import order or how I try and import the functions. -
How to send a considerably large file of any format from express NodeJS server to Django server
I have written this code to send a file using a port from NodeJS server to Django server using multer and Custom Directives from AngularJS const multerConf = { storage:multer.diskStorage({ filename:function(req,file,next){ const etx = file.mimeType.split('/')[1]; next(null,file,fieldname+'-'+Date.now()+'-'+ext); } }) }; var newName = ''; app.post('/upload', multer(multerConf).single('file'), function(req, res){ if(req.files.file){ req.body.file = req.files.filename; var file = req.files.file; var filename = req.files.file.name; newName = './upload/'+Date.now()+filename; file.mv(newName,function(err){ if(err){ console.log(err); res.send("Upload failed"); }else{ var fileUrl='./upload/'+filename; console.log(fileUrl); } }); const options = { url: 'http://localhost:8000/myAssignmentApp/a_n_d', method: 'GET', headers: { 'Accept': 'application/json', 'Accept-Charset': 'utf-8' } }; request(options, function(err, res) { }); } }); The following code is for the port. server.on('request', (req, res) => { fs.readFile(newName, (err, data) => { if (err) throw err; res.end(data); }); }); server.listen(6000); Is there any other more efficient method to do the same?