Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Minimal max_length of a Django CharField to store the output of the sign method of a Signer object (django.core.signing)
I have to sign a value, in my case emails, and I have to store the signed value in a Django CharField. I am using the Signer.sign method of the django.core.signing module. Since I would like to insert also the max_length parameter for the db field, my question is, what would be the minimal value I can put in the max_length in order to always successfully store it in the db. -
Update view not working? Django
The users are able to create an aircraft post at this url: url(r'^upload/aircraft/$', aircraft_create, name="aircraft_create"), I've created a summary page where all of the users posts are displayed. They're able to edit and delete their posts here. The url: url(r'^account/uploads/$', upload_overview, name="account_uploads"), However, I want the user to be able to edit their posts on their summary page. The way I got it set it now, is that they can edit at upload/aircraft/edit, but I want to to be account/uploads/edit. I've set it up like that but it's not doing anything? Any clues as to what it might be? Aircraft/views.py def aircraft_create(request): form = aircraft_form(request.POST or None) if form.is_valid(): instance = form.save(commit=False) instance.user = request.user instance.save() messages.success(request, "Your upload has been successfully added!") return HttpResponseRedirect(instance.get_absolute_url()) else: messages.error(request, "There seems to be something wrong. Have a look again..!") context = {"form":form,} return render(request,'aircraft/aircraft_form.html', context) Template {% if UploadedAircraft %} {% for upload in UploadedAircraft %} <div class="col-lg-offset-0 col-md-4 col-sm-3 item"> <div class="box"><a href="{{ upload.get_absolute_url }}"><img src="{{ upload.image.url }}" width="200px" height="200px" alt="{{ upload.title }}"/></a> <h3 class="name"><a href="{{ upload.get_absolute_url }}">{{ upload.name }}</a></h3> <a href="{% url 'aircraft_update' %}"><button class="btn">Edit</button></a> <a href="{% url 'aircraft_delete' %}"><button class="btn">Delete</button></a> </div> Summary page view def upload_overview(request): uploaded_aircraft = Aircraft.objects.filter(user=request.user) … -
django-schedule openURL is not defined
I have installed django-scheduler in my project but when trying to click on an event to edit or delete it I get to following error in console Uncaught ReferenceError: openURL is not defined at HTMLAnchorElement.onclick This is happening on the following html (which is in the django-scheduler url schedule/calendar/daily using the standard templates): <a href="#" onclick="openURL('/schedule/event/delete/29/?next=/schedule/calendar/daily/contractor2/%3Fyear%3D2017%26month%3D4%26day%3D23', event);"> <span class="glyphicon glyphicon-remove"></span> </a> What have I got wrong? -
Modifying django form field choices with few hundred items causes freeze / not responsive
I want to dynamically modify a field choices in django form. Because item's list is pretty long (more then 650 items), I store them in django cache. However, when I want to inject them as field choices, application become unresponsive (sometime returns ERR_EMPTYRESPONSE). My view: class HomeView(TemplateView): template_name = 'web/pages/homepage.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) categories = cache.get_or_set('categories_list', Category.objects.values('uuid', 'code', 'name'), 3600) categories_choices = [(o['uuid'], '{} ({})'.format(o['name'], o['code'])) for o in categories] print(categories_choices) #its printing proper choices here context['form'] = SearchForm() context['form'].fields['category'].choices = categories_choices #this line causes freeze/timeout return context Any idea what is happening there? Maybe 600+ items as dropdown choices is too many? -
Django check if authenticated user is same as the author of the post?
I want to display edit button only if the user is authenticated as the author of the post. example: 1.example.com/username1 2.example.com/username2 i want to take to user to the edit profile page, i got all the permission working correctly and set the views accordingly. My Problem: i loggedin as username1 so i should not be able to access example.com/username2/edit/. i got this to work in the views by adding some permissions, but i dont want to display the edit button when the loggedin username1 views the page of username2. Now i use {% if user.is_authenticated %} and this results in display the edit button on page of username2 even though the loggedin user is username1. Any simple solutions that can be used in the templates directly? -
Extending Django Admin templates
I try to modify django admin templates I created custom template with the name corresponding to template, that I want to override. I try the following {% extends "admin/change_form.html" %} <h1>HELLO</h1> If I reload the page I dont see h1 tag. If I try {% extends "admin/change_form.html" %} {% block field_sets %} <h1>HELLO</h1> {% endblock %} I seen only h1 tag and dont see model's editing fields. What have I do to see form and h1 tag in same time ? -
Django-paypal works in IPN simulator but not in sandbox
I have written an IPN following the django-paypal IPN tutorial, however mine does not seem to work. It works no problem on the PayPal IPN Simulator, and I receive the IPN and the code executes, however when I try to do it in Sandbox mode, the payment goes through by no response. Views: from django.core.urlresolvers import reverse from django.shortcuts import render from paypal.standard.forms import PayPalPaymentsForm def view_that_asks_for_money(request): # What you want the button to do. paypal_dict = { "business": "receiver_email@example.com", "amount": "100.00", "item_name": "Yep", "invoice": "Turbo deadly", "notify_url": "http://myip/paypal/", "return_url": "https://www.example.com/your-return-location/", "cancel_return": "https://www.example.com/your-cancel-location/", "custom": "Upgrade all users!", # Custom command to correlate to some function later (optional) } # Create the instance. form = PayPalPaymentsForm(initial=paypal_dict) context = {"form": form} return render(request, "payment.html", context) from paypal.standard.models import ST_PP_COMPLETED from paypal.standard.ipn.signals import valid_ipn_received def show_me_the_money(sender, **kwargs): ipn_obj = sender category = Category(name="Got IPN") category.save() if ipn_obj.payment_status == ST_PP_COMPLETED: category = Category(name="Good Buzz, complete") category.save() else: category = Category(name="Bad Buzz, not complete") category.save() valid_ipn_received.connect(show_me_the_money) invalid_ipn_received.connect(show_me_the_money) URLS: etc etc etc... url(r'^paypal/', include('paypal.standard.ipn.urls')), url(r'^test/$', views.view_that_asks_for_money, name='ask') ] When I send my IPN to : http://myip/paypal/ it works but not through sandbox. -
Some ambiguities with the nesting of modules in the structure (Django)
I have module "patientmodule" and template in it where I point on the <a href="{% url 'appointments' id=patient.id %}">List of appointments</a> but this pattern doesn't exist in the urls.py he exists in the inner module "appointments/urls.py" How I can correctly point url, becouse now I see next error: "Reverse for 'appointments' with arguments '()' and keyword arguments '{'id': 1}' not found. 0 pattern(s) tried: []" -
Django: reverse() and get_absolute_url() returns different output for same object?
When used with flatpages reverse() and get_abolute_url() returns different outputs: >>> about = FlatPage.objects.get(id=2) >>> >>> about <FlatPage: /about-us/ -- About us page> >>> >>> about.get_absolute_url() '/about-us/' >>> >>> >>> reverse('django.contrib.flatpages.views.flatpage', args=[about.url]) '/%2Fabout-us/' ## from where %2F comes from ? >>> Here is the sitewide urls.py (sitewide): from django.conf.urls import url, include from django.contrib import admin from django.contrib .flatpages import urls as flatpage_urls # from . import blog urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'', include(flatpage_urls)), ] Although, I am able to access to about page at http://127.0.0.1:8000/about/ but what's going on ? -
nginx, django, gunicorn can't reach domain. Bad Request(400)
I can reach my site when going to my IP address but I can not when I go to my domain name. Here is my nginx config file (I have changed the IP and domains for privacy): server { listen 80; server_name my.ip.address example.com www.example.com; location = /facivon.ico { access_log off; log_not_found off; } location /static/ { root /home/tony/vp/vp/config/; } location / { include proxy_params; proxy_pass http://unix:/home/tony/vp/vp/vp.sock; } } And this is my productions settings.py file: from .base import * DEBUG = False ALLOWED_HOSTS = ['127.0.0.1', '0.0.0.0', 'my.ip.address', 'example.com', '.example.com'] ROOT_URLCONF = "urls.production_urls" SECURE_CONTENT_TYPE_NOSNIFF = True SECURE_BROWSER_XSS_FILTER = True SECURE_SSL_DIRECT = True SECURE_SSL_REDIRECT = False SESSION_COOKIE_SECURE = True CSRF_COOKIE_SECURE = True X_FRAME_OPTIONS = 'DENY' SECURE_HSTS_SECONDS = 3600 SECURE_HSTS_INCLUDE_SUBDOMAINS = True SECURE_HSTS_SUBDOMAINS = True SECURE_HSTS_PRELOAD = True # Database # https://docs.djangoproject.com/en/1.11/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'vp', 'USER': 'vp', 'PASSWORD': os.environ["VP_DB_PASS"], 'HOST': 'localhost', } } MEDIA_ROOT = os.path.join(BASE_DIR, "media") MEDIA_URL ='media/' STATIC_ROOT = os.path.join(BASE_DIR, 'static/') And yes my domain is connected to digital ocean. What could be causing the Bad Request? Thanks in advance! -
Django Admin - ModelAdmin.add_form_template example
I want a custom template for one of my models Docs say that there is ModelAdmin.add_form_template method. How can I use this method ? How can I pass data from js in custom template to Django, so I can save it ? -
Django pagination with bootstrap
I am about to add a pagination to my list of contacts. I am sitting over it the whole day and have no idea what I mixed up. Important thing is that I do have a working filters - so I can narrow the list. But from my understanding pagination should work anyway. In my case I see nothing so my guess is first "if" fails. If you could point me in the right direction. Best regards. Views.py def ContactsList(request): contacts_list = Contact.objects.all() Contacts_filter = LFilter(request.GET, queryset=contacts_list) #pagination page = request.GET.get('page', 1) paginator = Paginator(contacts_list, 20) try: contacts = paginator.page(page) except PageNotAnInteger: contacts = paginator.page(1) except EmptyPage: contacts = paginator.page(paginator.num_pages) return render(request, 'index.html', context, {'filter': contacts_filter}) Template part: {% if contacts.has_other_pages %} <ul class="pagination"> {% if contacts.has_previous %} <li><a href="?page={{ contacts.previous_page_number }}">&laquo;</a></li> {% else %} <li class="disabled"><span>&laquo;</span></li> {% endif %} {% for i in contacts.paginator.page_range %} {% if library.number == i %} <li class="active"><span>{{ i }} <span class="sr-only">(current)</span></span></li> {% else %} <li><a href="?page={{ i }}">{{ i }}</a></li> {% endif %} {% endfor %} {% if contacts.has_next %} <li><a href="?page={{ contacts.next_page_number }}">&raquo;</a></li> {% else %} <li class="disabled"><span>&raquo;</span></li> {% endif %} </ul> {% endif %} -
Django admin - create custom html page for model and pass values from js to db
I have a model, that describes polygon on map. I need a way to create that polygons by clicking on google maps inside Django admin and then save that polygons coordinates in db. So, I need to perform following steps: Create a new html template with map. Somehow pass this template in Django in page of editing model Pass values from js in html page to django database after finishing editing How can I pass custom html with js to model editing page and then save data from js in django db ? I dont look for polygons creation logic, but for a way to connect it with django. -
Django rest framework group by fields and add extra contents
I have a Ticket booking model class Movie(models.Model): name = models.CharField(max_length=254, unique=True) class Show(models.Model): day = models.ForeignKey(Day) time = models.TimeField(choices=CHOICE_TIME) movie = models.ForeignKey(Movie) class MovieTicket(models.Model): show = models.ForeignKey(Show) user = models.ForeignKey(User) purchased_at = models.DateTimeField(default=timezone.now) I would like to filter MovieTicket with its user field and group them according to its show field, and order them by the recent booked time. And respond back with json data using Django rest framework like this: [ { show: 4, movie: "Lion king", time: "07:00 pm", day: "23 Apr 2017", total_tickets = 2 }, { show: 7, movie: "Gone girl", time: "02:30 pm", day: "23 Apr 2017", total_tickets = 1 } ] I tried this way: >>> MovieTicket.objects.filter(user=23).order_by('-booked_at').values('show').annotate(total_tickets=Count('show')) <QuerySet [{'total_tickets': 1, 'show': 4}, {'total_tickets': 1, 'show': 4}, {'total_tickets': 1, 'show': 7}]> But its not grouping according to the show. Also how can I add other related fields (i.e., show__movie__name, show__day__date, show__time) -
python filter none values
I have: 1. models.py class Post(models.Model): ROOT_CHOICES = ( ('Manufacturing', 'Manufacturing'), ('Transportation', 'Transportation'), ('Installation', 'Installation'), ('Operation', 'Operation'), ) root1 = models.CharField(max_length=250, choices=ROOT_CHOICES, default='Manufacturing') root2 = models.CharField(max_length=250, choices=ROOT_CHOICES, null=True, blank=True) root3 = models.CharField(max_length=250, choices=ROOT_CHOICES, null=True, blank=True) root4 = models.CharField(max_length=250, choices=ROOT_CHOICES, null=True, blank=True) 2. views.py def post_detail(request, slug): post=get_object_or_404(Post, slug=slug) if request.method == "POST": form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.post=post comment.save() return redirect('data:post_detail', slug=post.slug) else: form=CommentForm() template = 'data/post_detail.html' context = {'form':form,'post':post} return render(request, template, context) 3. html <div class="col-sm-3"> <div class="post-parameters"> <p class="text-parameters"> Root: {{ post.root1 }}, {{ post.root2 }}, {{ post.root3 }}, {{ post.root4 }}</p> </div> </div> It looks like this, right now, in my html file: Root:Manufacturing, None, None, None which is correct. However I would like not to show the ,if any, None values e.g. Root:Manufacturing -
[Django]django.db.utils.IntegrityError
my app named mainsite I have the table class named Weather in models.py class Weather(models.Model): tpr = models.CharField(max_length=5) wet = models.CharField(max_length=5) ur = models.CharField(max_length=5) li = models.CharField(max_length=5) observe_time = models.DateTimeField(default=None) I don't want my observe_time set any deafult value So I set to None . I have made migrations. when I made migrate Then the traceback happen: File "manage.py", line 22, in execute_from_command_line(sys.argv) File "C:\Users\User\Anaconda3\lib\site-packages\django\core\management__init__.py", line 354, in execute_from_command_line utility.execute() File "C:\Users\User\Anaconda3\lib\site-packages\django\core\management\__init__.py", line 346, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\User\Anaconda3\lib\site-packages\django\core\management\base.py", line 394, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\User\Anaconda3\lib\site-packages\django\core\management\base.py", line 445, in execute output = self.handle(*args, **options) File "C:\Users\User\Anaconda3\lib\site-packages\django\core\management\commands\migrate.py", line 222, in handle executor.migrate(targets, plan, fake=fake, fake_initial=fake_initial) File "C:\Users\User\Anaconda3\lib\site-packages\django\db\migrations\executor.py", line 110, in migrate self.apply_migration(states[migration], migration, fake=fake, fake_initial=fake_initial) File "C:\Users\User\Anaconda3\lib\site-packages\django\db\migrations\executor.py", line 148, in apply_migration state = migration.apply(state, schema_editor) File "C:\Users\User\Anaconda3\lib\site-packages\django\db\migrations\migration.py", line 115, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "C:\Users\User\Anaconda3\lib\site-packages\django\db\migrations\operations\fields.py", line 62, in database_forwards field, File "C:\Users\User\Anaconda3\lib\site-packages\django\db\backends\sqlite3\schema.py", line 179, in add_field self._remake_table(model, create_fields=[field]) File "C:\Users\User\Anaconda3\lib\site-packages\django\db\backends\sqlite3\schema.py", line 147, in _remake_table self.quote_name(model._meta.db_table), File "C:\Users\User\Anaconda3\lib\site-packages\django\db\backends\base\schema.py", line 111, in execute cursor.execute(sql, params) File "C:\Users\User\Anaconda3\lib\site-packages\django\db\backends\utils.py", line 79, in execute return super(CursorDebugWrapper, self).execute(sql, params) File "C:\Users\User\Anaconda3\lib\site-packages\django\db\backends\utils.py", line 64, in execute return self.cursor.execute(sql, params) File "C:\Users\User\Anaconda3\lib\site-packages\django\db\utils.py", line 98, in exit six.reraise(dj_exc_type, dj_exc_value, traceback) File "C:\Users\User\Anaconda3\lib\site-packages\django\utils\six.py", line 685, in reraise raise … -
Users created posts not being returned to template? Django
the user is able to create a post and it will be shown the in the list. I've also created a users profile/summary page where the user can edit/delete their posts. Currently, it's showing blank and I'm not quite sure why? Model class Aircraft(AircraftModelBase): user = models.ForeignKey(User) manufacturer = SortableForeignKey(Manufacturer) aircraft_type = SortableForeignKey(AircraftType) View def upload_overview(request): uploaded_aircraft = Aircraft.objects.filter(user=request.user) return render(request,'account/upload_overview.html',{'UploadedAircraft':uploaded_aircraft}) Template <div class="container"> <div class="row aircraft"> {% if UploadedAircraft %} {% for upload in UploadedAircraft %} <div class="col-lg-offset-0 col-md-4 col-sm-3 item"> <div class="box"><a href="{{ upload.aircraft.get_absolute_url }}"><img src="{{ upload.aircraft.image.url }}" width="200px" height="200px" alt="{{ upload.aircraft.title }}"/></a> <h3 class="name"><a href="{{ upload.aircraft.get_absolute_url }}">{{ upload.aircraft.name }}</a></h3> </div> </div> {% endfor %} {% else %} <h2 class="text-center">No uploaded aircraft posts..</h2></div> {% endif %} </div> -
Reload the table without refreshing the page in Django
Have small table that needs to be updated every 10 seconds with new data. Entire website is working in Django. JSON is parsing data into 1 table and rewriting the data every 10 seconds in database. The website is showing the data from the database. The procedure I need is to refresh the front-end table with new data every 10 seconds - it would be the AJAX I assume, can you help me write the code for it? It would not append data to the table, just keep refreshing it. Example - The table in the database has fixed 10 rows of data and it is being refreshed by JSON. The front-end would always show 10 rows, so every 10 seconds, the table (front-end) would always show 10 rows with the new data. Here are the python files views.py def prices(request): prices = Price.objects.all().order_by('id') return render(request, 'prices.html', {'prices':prices}) prices.html <div class="col-md-8"> <table class="table table-striped"> <thead> <tr> <th>TYPE</th> <th>NAME</th> <th>PRODUCT</th> <th>VALUE</th> </tr> </thead> <tbody> {% for price in prices %} <tr> <td>{{ price.type }}</td> <td>{{ price.name }}</td> <td>{{ price.product }}</td> <td>{{ price.value }}</td> </tr> {% endfor %} </tbody> </table> </div> urls.py urlpatterns = [ url(r'^prices/', product_views.prices, name='prices'), url(r'^admin/', admin.site.urls), ] -
Validation fails on ModelForm
Hi I'm trying to teach my self Django while making a small Task management app. I have a Model class Task(models.Model): track = models.ForeignKey(Track, on_delete=models.SET_NULL, null=True) title = models.CharField(max_length=100) description = models.CharField(max_length=265, blank=True) done = models.BooleanField(default=False) def __str__(self): return self.title and related ModelForm class TaskForm(forms.ModelForm): class Meta: model = Task fields = ['track', 'title', 'description', 'done'] When form is posted taskForm.is_valid() is returning False. This is post_task method: def post_task(request): form = TaskForm(request.POST) if form.is_valid(): form.save(commit=True) else: print(form.errors) return HttpResponseRedirect('/') and the form tag on the page: <form action="post_url" mehod="post"> {% csrf_token %} {{ task_form.as_p }} <input type="submit" value="Add"/> </form> Even though I've filled in all the data I'm getting validation error, this is the console print: <ul class="errorlist"><li>track<ul class="errorlist"><li>This field is required.</li></ul></li><li>title<ul class="errorlist"><li>This field is required.</li></ul></li></ul> All values have been passed in the request: [23/Apr/2017 12:34:38] "GET /post_url/?csrfmiddlewaretoken=VqUx3EM9yGFzS88kYRtTWtniaCV8ZukxymylPILlxHBohtfEyhD3epOKOjKNIVCU&track=1&title=testTitle&description=testDescription HTTP/1.1" 302 0 Thanks! -
Transform Data from Django ORM to custom CSV format
Given the following models: class Stream(models.Model): name = models.CharField(max_length=32) label = models.CharField(max_length=32) ... class Data(models.Model): class Meta: ordering = ['timestamp'] timestamp = models.DateTimeField(db_index=True) # in UTC ! data = models.FloatField() stream = models.ForeignKey(to=Stream, editable=False) ... I need to output results in the following (CSV) format: Example output: Timestamp,A,B,C,D 2017/03/03:00:01:00,4,2,1.9,3 2017/03/03:00:01:15,4,3,1.8.3 ... A,B,C and D are streams labels. Values are from Data.data field. -
Django server doesn't response during request
I have function named as validate_account() that return boolean. It goes to db, and do some manipulation with duration of 7 seconds. So, when I make another requests to server, it doesn't response during these 7 seconds for any request. How can I fix it? Maybe by starting new process? @login_required @csrf_protect def check_account(request): username = request.session['current_account'] account = get_object_or_404(Account, username=username) # takes 7 seconds login_status = validate_account(account.username, account.password) response = { 'loginStatus': login_status } response = json.dumps(response) return JsonResponse(response, safe=False) -
PDF file without content in Django
Hello friends, I want to ask you for help. I created a web form that generates PDF files. Everything is fine. Automatically Send PDFs via Email is OK. Unfortunately, the form fields that are not added to the models.Model are not included in the PDF (contents). PDF documents display (postal_code) as blank field. I don't know what to do. Where is the problem? model.py class Order(models.Model): name = models.CharField(max_length=50) forms.py CHOICES=[('item1','1xx'), ('item2','2xx')] class OrderCreateForm(forms.ModelForm): postal_code = forms.ChoiceField(choices=CHOICES, widget=forms.RadioSelect()) class Meta: model = Order fields = ['name', 'postal_code'] form.html <form action="." method="post" class="order-form"> {{ form.as_ul }} <p><input type="submit" value="Send"></p> {% csrf_token %} </form> tasks.py from celery import task from oferty.models import Order from django.template.loader import render_to_string from django.core.mail import EmailMessage from django.conf import settings import weasyprint from io import BytesIO @task def order_created(order_id): order = Oferta.objects.get(id=order_id) subject = 'New nr {}'.format(order.id) message = 'Hallow, {}!\n\nBlaBlaBla.\ BlaBlaBla {}.'.format(order.imię, order.id) email = EmailMessage(subject, message, 'admin@myshop.com', [order.email]) html = render_to_string('orders/order/pdf.html', {'order': order}) out = BytesIO() stylesheets = [weasyprint.CSS(settings.STATIC_ROOT + 'css/pdf.css')] weasyprint.HTML(string=html).write_pdf(out, stylesheets=stylesheets) email.attach('order_{}.pdf'.format(order.id), out.getvalue(), 'application/pdf') email.send() pdf.html <html> <body> <h1>Test</h1> <p> {{ order.name }}<br> {{ order.postal_code }} </p> </body> </html> Do you give me any hint of which way ? Your help would be … -
Handling exception through a decorator in Django
I am trying to create a error handling decorator in django and where the logging happens in the decorator in case of an exception and the exception is raised back to the decorated function which then sends an error http response. But when I try do this, If I add a Except block in the decorated function after the exception from decorator is raised back, then only the except block of the decorated function is getting executed and the except block of the decorator is left unexecuted. MyDecorator.py def log_error(message): def decorator(target_function): @functools.wraps(target_function) def wrapper(*args, **kwargs): try: return target_function(*args, **kwargs) except Exception as e: print('except block of the decorator') exceptiontype, exc_obj, exc_tb = sys.exc_info() filename = traceback.extract_tb(exc_tb)[-2][0] linenumber = traceback.extract_tb(exc_tb)[-2][1] mylogger(message=str(e),description='Related to Registration',fileName=filename,lineNumber=linenumber, exceptionType = type(e).__name__) raise return wrapper return decorator Decorated function @log_error('message') def action(self, serializer): try: .................. .................. .................. .................. return Response(status=status.HTTP_200_OK, data={ "message":'link sent successfully'}) except Exception as e: print('except block of the decorated function') return Response(status=status.HTTP_500_INTERNAL_SERVER_ERROR, data={"message" : 'error sending link'}) This is printing the line except block of the decorated function and not the line except block of the decorator If I remove the Except block from the decorated function then the except block of … -
Django - Authentication credentials were not provided
I'm working with an endpoint that seems to be built on Django. Attempting to setup basic aJax communication to it via POST I wrote: jQuery.ajax({ type: "POST", url: "http://API-ENDPOINT-URL", data: "", dataType: "json", crossDomain: false, beforeSend: function(xhr){ xhr.setRequestHeader('Authorization', 'Token <TOKEN THAT I WAS PROVIDED>' ) }, success: function(results) { reqListener(results) } }); With those code a few things happened: I first got a CORS error since I'm trying to build on my local server. I installed this chrome extension to bypass it. (I have no access to the server to enable CORS) 2.I get this error in the console: XMLHttpRequest cannot load http://API-ENDPOINT-URL. Response for preflight has invalid HTTP status code 401 looking at the Chrome console for the network request I see this comes back: {"detail":"Authentication credentials were not provided."} What am I missing? Am I incorrectly sending the authentication token? -
Unable to import django.db in models.py
i have a Django project with a chat app inside it, this is the project file: gadgetry: |__src: |__chat(the app): | |__rest_framework | |__serializers.py | |__models.py | |__views.py | |__chatbotx1(folder contain python files): | |__gender.py |__chatbot: |_settings.py when i use check and makemigrations there are no error and the project is working when i try to visit website, but when i click on a button to activate the chatbotx1-> gender.py file i get this error: chat.models.DoesNotExist: arabic_names matching query does not exist. i think the problem in importing of the models in my app because in: serializers.py from chat.models import chat, user_info, arabic_names (C0111:Missing module docstring) from chat.rest_framework import serializers (E0401:Unable to import 'chat.rest_framework') gender.py: from chat.models import arabic_names (Unable to import 'chat.models') models.py: from django.db import models (Unable to import 'django.db') class arabic_names(models.Model): Name= models.TextField(default='defult name') Gender= models.TextField(default='defult gender') def __unicode__(self): return self.Name ,self.Gender wsgi.py import os import sys os.environ['DJANGO_SETTINGS_MODULE'] = 'chatbot.settings' from django.core.wsgi import get_wsgi_application application = get_wsgi_application() PS: I am using Django10,Python3.5,MySQL