Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django favorite button
I'd like to implement a bookmarker (favorites button) for the end user of the site, so that they can store their favourite adventures. models.py class Favorit(models.Model): related_adventure = models.ForeignKey(Adventure, on_delete=models.CASCADE, related_name='favorit') user = models.ForeignKey(User, on_delete=models.CASCADE) def __unicode__(self): return '%s %s'%(self.related_adventure.name, self.user.username) in the views.py @login_required def favorit_adventure(request,adventure_pk): user = request.user adventure = Adventure.objects.get(pk=adventure_pk) if(Favorit.objects.get(user = request.user and related_adventure == adventure_pk)): print ('geht') # If no new bookmark has been created, # Then we believe that the request was to delete the bookmark messages.success("Erfolgreich") if not created: favorit.delete() return HttpResponseRedirect(request.META.get('HTTP_REFERER')) and .html so .html The idea is to write a def and to add the adventure from the current template, giving the pk(primary key). The problem is to give the appropriate adventure to the view. Then a new instance favorite should be created. My problem is that no action happens when clicking the button. What is there to do? Thanks in advance -
How to query Haystack to get similar items [Python, Haystack, ElasticSearch]
I am trying to ge similar posts when a post ID is sent as a payload to an endpoint (RESTful API) using Haystack and ElasticSearch: original_post = Article.objects.get(id=pk) #pk is 2 for example related_items = SearchQuerySet().more_like_this(original_post.title) result = related_items[0].object.title print(result) This throws an Error: AttributeError: 'str' object has no attribute '_meta' I am new to Elastic Search. What am I doing wrong? -
Django form csv
I have a form that I want to use for predictions but when a user submits the form I want it to be in stored in a variable in a csv fomrat so I can perform Xgboost prediction on every form and after it outputs the prediction. from django.db import models from django import forms from django.core.validators import MaxValueValidator, MinValueValidator # Create your models here. type_loan=(("Cash loan","Cash loan"), ("Revolving loan","Revolving Loan")) Gender=(("Male","Male"), ("Female","Female")) Yes_NO=(("YES","YES"),("NO","NO")) status=(("Single","Single"), ("Married","Married"), ("Widow","Widow"), ("Seprated","Divorce")) Highest_Education=(("Secondary","Secondary"), ("Incomplete Higher","Incomplete Higher"), ("Lower Secondary","Lower Secondary"), ("Academic Degree","Academic Degree")) Income_type=(("Working","Working Class"), ("State Servant","Civil Servant"), ("Commercial Associate","Commercial Associate"), ("Pensioner","Pensioner"), ("Student","Student"), ("Businessman","Business Owner")) class Applicant(models.Model): name=models.CharField(default="Jon Samuel",max_length=50,null="True") Birth_date=models.DateField(default="2018-03-12",blank=False, null=True) Status=models.CharField(choices=status,max_length=50) Children=models.IntegerField(default=0,validators=[MinValueValidator(0),MaxValueValidator(17)]) Highest_Education=models.CharField(choices=Highest_Education,max_length=50) Gender=models.CharField(choices=Gender, max_length=50) loan_type=models.CharField(choices=type_loan, max_length=50) own_a_car=models.CharField(choices=Yes_NO,max_length=50) own_a_house=models.CharField(choices=Yes_NO,max_length=50) def __str__(self): return self.name -
Django 1.11 annotation GROUP BY is wrong
With model relations like this Risk <-- RiskGroup --> Group I am trying to achieve a query resembling this SELECT risk.id, ( SELECT array_agg(bg.name) as names FROM hazards_riskgroup rgroup JOIN (SELECT * FROM base_group ORDER BY name) as bg on rgroup.group_id = bg.id WHERE risk_id = risk.id GROUP BY risk_id ORDER BY risk_id ) AS conf FROM hazards_risk risk ORDER BY conf NULLS LAST ; And I have gotten as far as group_names = ( RiskGroup.objects .filter(risk_id=OuterRef('pk')) .annotate(names=ArrayAgg('group__name')) .order_by() .order_by("group__name") .values('names') ) qs = Risk.objects.annotate( conf=Subquery(group_names) ).order_by() But that wil produce something along the lines of this query SELECT risk.id, (SELECT ARRAY_AGG(U2."name") AS "names" FROM "hazards_riskgroup" U0 INNER JOIN "base_group" U2 ON (U0."group_id" = U2."id") WHERE U0."risk_id" = (risk.id) GROUP BY U0."id", U2."name" ORDER BY U2."name" ASC) AS "conf" FROM hazards_risk risk ORDER BY conf NULLS LAST Notice that the generated GROUP BY becomes GROUP BY U0."id", U2."name", where I want just GROUP BY U2."name". Best I've been able to gather, is that it is related to some default ordering on models, but as you can tell, I've already accounted for that by inserting .order_by(). So I'm a little lost. I tried annotating with Raw sql instead, but in that … -
Django - How to get a custom user model with get_object_or_404
I'd like to retrieve an instance of my User class, which extends AbstractBaseUser . I'd also like to filter my users by a primary key using the django get_object_or_404 shortcut, but this won't work: from django.shortcuts import get_object_or_404 from django.conf import settings user = get_object_or_404(settings.AUTH_USER_MODEL, pk=pk) The following exception is raised: "ValueError at /v1/users/24c47b4a-920e-47c7-902c-80c64c0dd657/ First argument to get_object_or_404() must be a Model, Manager, or QuerySet, not 'str'. In my settings.py, this is what my AUTH_USER_MODEL looks like: AUTH_USER_MODEL = 'users.User' Is there a way to achieve this? -
Get list inside the annotate in django ORM
I have 3 tables:- class Profile(models.Model): id = models.AutoField(primary_key=True) name = models.CharField() ..... #some more field ..... class ProfileTestMapping(models.Model): id = models.AutoField(primary_key=True) profile = models.ForeignKey(Profile) test = models.ForeignKey(Test) ..... #some more field .... class Test(models.Model): id = models.AutoField(primary_key=True) name = models.CharField() ..... #some more field .... 1 profile has many tests. So I want to get the data like this:- This is a raw array I am writing for the example purpose. profileList = [ { profileName: 'any-name', ...... otherProfileDetails ....... testList: [ { name: testName, id: 463743 }, { name: testName2, id: 463743 } ] } ] I am getting the count of test mapped with the profile using annotate but not getting the details of the test which are mapped with the profile. -
Django when tried to Like a post, value is changing but also gives error NoReverseMatch at /something/something/
I am working on a project on django app, where user can like or dislike a post. Like and dislike buttons are working fine, also value is saved in database. But when button "Like" is clicked it shows this error: NoReverseMatch at /gallery/likes/ Reverse for 'detail' with keyword arguments '{'pk': 9}' not found. 1 pattern(s) tried: ['gallery\/(?P[^/]+)$'] but i don't want this error. model.py class Album(models.Model): caption = models.TextField() photo = models.FileField() uploader=models.ForeignKey(User,on_delete=models.CASCADE,default=None) likes = models.ManyToManyField(User, related_name='likes',blank=True) def __str__(self): return self.caption def get_absolute_url(self): return reverse('gallery:detail', kwargs={"pk": self.pk}) url.py app_name = 'gallery' urlpatterns = [ path('', views.IndexView.as_view(), name='index'), path('<album_id>',views.detail, name='detail'), path('likes/',views.like_post, name='like_post'), path('album<pk>/delete',views.AlbumDelete.as_view(), name='album-delete'), ] views.py def detail(request,album_id): album = get_object_or_404(Album, pk=album_id) is_liked = False if album.likes.filter(id=request.user.id).exists(): is_liked = True context = { 'album' : album, 'is_liked' : is_liked, } return render(request, 'gallery/detail.html', context) def like_post(request): album = get_object_or_404(Album, id=request.POST.get('album_id')) is_liked = False if album.likes.filter(id=request.user.id).exists(): album.likes.remove(request.user) is_liked = False else: album.likes.add(request.user) is_liked = True return HttpResponseRedirect(album.get_absolute_url()) detail.html <form action="{% url 'gallery:like_post' %}" method="post" > {% csrf_token %} {% if is_liked %} <button type="submit" name="album_id" value="{{album.id}}" class="btn btn-danger">DisLike</button> {% else %} <button type="submit" name="album_id" value="{{album.id}}" class="btn btn-primary">Like</button> {% endif %} </form> I'm new to django so I'm unable to understand what's the … -
Django form.isValid() always return false in custom user model
I have a custom user model in django following this tutorial. But when I update a user, I receive the error message "User with this Email address already exists.". As my model extends AbstractBaseUser, does this isn't handled by django itself? My view: @login_required def user_add_edit(request, pk=None): user = get_user_model() if request.method == 'POST': if pk: form = UserChangeForm(request.POST) else: form = UserCreationForm(request.POST) if form.is_valid(): user = form.save(commit=False) msg = '' if len(user.last_name) > 0: user.last_name = user.last_name.title() if len(user.first_name) > 0: user.first_name = user.first_name.title() user.password(user.set_password(request.POST['password2'])) user.save() messages.add_message(request, messages.SUCCESS, 'User updated with success. %s' % msg) data = {'valid': True} return JsonResponse(data) else: data = {'valid': False, 'formMsg': [v for k, v in form.errors.items()]} return JsonResponse(data) else: if pk: selected_user = get_object_or_404(user, pk=pk) form = UserChangeForm(request.POST or None, instance=selected_user) else: selected_user = get_user_model() form = UserCreationForm(request.POST or None, instance=selected_user, initial={'password1': "", 'password2': "", 'first_name': "", 'last_name': "", 'email': ""}) return render(request, 'users/add_edit.html', {'form': form, 'selectedUser': selected_user}) -
Django Rest Framework resource doesn't respond to request with invalid token
I have Django project with ViewSet model inherited from Django Rest Framework models.GenericViewSet At the top of the ViewSet I've set up authentication with permission_classes = (permissions.IsAuthenticated,) When I make a request with an existing token, it works as expected. But if the token doesn't exist, the server seems to never respond. How can I debug this behavior? Or probably do I need something else for this permission class to properly process invalid tokens? I need the server to respond with something about wrong credentials. For example, 401 and some custom message (if there is no better alternative). -
How to display recent items for personalization in a web app?
In GitHub, you will notice that when you want to reference existing issues or mark an issue under projects GitHub intelligently will show you the most recent items that you visited recently first. I’m using django to build a web app and i like to incorporate the same feature. Do i have one giant table that stores all the items that all users visit? If so how do I then join that back with the main table I am supposed to search on to produce the sort correctly? I cannot obviously add a new date time column called “visited” to the main table as that will mean there is no personalization What am I missing in terms of understanding? -
Django Page not found using simple path
Im using django version 2.1.4. Created app 'main' inside my project and trying to get to its urls.py to show sentence "text" under the admin/main/test/ However while admin/ and admin/main/ are working, admin/main/test/ gives error Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/admin/main/test Using the URLconf defined in statystyki.urls, Django tried these URL patterns, in this order: main/ admin/ [name='index'] admin/ login/ [name='login'] admin/ logout/ [name='logout'] admin/ password_change/ [name='password_change'] admin/ password_change/done/ [name='password_change_done'] admin/ jsi18n/ [name='jsi18n'] admin/ r/<int:content_type_id>/<path:object_id>/ [name='view_on_site'] admin/ auth/group/ admin/ auth/user/ admin/ main/movie/ admin/ ^(?P<app_label>auth|main)/$ [name='app_list'] The current path, admin/main/test, didn't match any of these. My files: statystyki/urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('main/', include('main.urls')), path('admin/', admin.site.urls), ] main/urls.py from django.urls import path from .views import test_response urlpatterns = [ path('test/', test_response), ] views.py from django.shortcuts import render from django.http import HttpResponse def test_response(request): return HttpResponse('test') Could you help me to find the issue which is causing this? I already added 'main' to installed apps in settings.py -
Multiple auth backends for django auth - how to set it through the entire app
The django auth backend conflicts with social_auth backend and raises the multiple auth backends in calling login() but the login() is being called through LoginView.as_view(). So how can I set it through the entire app or to pass the backend to LoginView.as_view()? path('login/', django.contrib.auth.views.LoginView.as_view ( template_name='login.html', ), name='login'), -
Getting database info and sending it as XML file in django
I'm working on a django webservice which needs to handle database information from a SQL-server database. My database structure looks like this: As you can see I've got a table which holds orders Data_Orders which is refrenced by the Data_Models tablewhich stores the relation between each order and the corresponding models. This table also refrences Data_ModelColors where an ID is stored used to determine the name of the color in the Data_Color table. last, there is a Data_ModelSizes table which holds the information i'm most intrested in, the ammount. Whith this setup I am able to specify the amount of models to add to the orders for each color and size. Now I have to convert information from this database to XML files to send in a HttpResponse in django. As you can see each order also specifies a company to send it to(bottom left of the diagram). I need to generate XML files with orders for each company whenever I get a request from said company. I've created a function that is able to send an XML file in a HttpResponse like this: def index(request): template = loader.get_template('orders/testTemplate.xml') tpcontext = {'orderinfo': 'testordername'} return HttpResponse(template.render(tpcontext, request)) I'm currently using a … -
problem in class-based views in django SyntaxError: invalid syntax
I'm following django 2.1 tutorial, based on this link https://docs.djangoproject.com/en/2.1/topics/class-based-views/ Here is my Code for books/urls.py from django.urls import path, re_path from . import views from book.views import BookListView app_name = 'book' urlpatterns = [ path('', views.index, name = 'index') path('list/', BookListView.as_view(template_name="media/templates/book/book_list.html")), ] Below is my book/views.py from django.shortcuts import render from .models import Author, Book, BookInstance, Genre from django.views.generic import ListView def index(request): num_books = Book.objects.all().count() num_instances = BookInstance.objects.all().count() num_instances_available = BookInstance.objects.filter(status__exact = 'a').count() num_author = Author.objects.count() context = { 'num_books' : num_books, 'num_instances' : num_instances, 'num_instances_available' : num_instances_available, 'num_author' : num_author, } return render(request, 'book/index.html', context) class BookListView(ListView): model = Book Error I'm getting is File "E:\DJango\mysite\book\urls.py", line 8 path('list/', BookListView.as_view(template_name="media/templates/book/book_list.html")), ^ SyntaxError: invalid syntax -
Creating an object A with a ForeignKey to object B, when creating an object B
When creating posts in a text editor in the Django administration panel, I upload files. I want to link this file with the current post through a foreign key. The problem is that the post has not yet been created, but I need to refer to it. My model: class UploadFile(models.Model): upload_by = models.ForeignKey(settings.AUTH_USER_MODEL, default=1, on_delete=models.CASCADE, related_name="uploaded_file_author") file = models.FileField(null=True, blank=True, upload_to='files/%Y/%m/%d/',) post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name="file_post") My view: @require_POST def file_upload(request): reqfile = UploadFile.objects.create(file=request.FILES['file'], upload_by=request.user, **post="need an object here")** return JsonResponse({'fileurl': reqfile.file.url}) -
Getting error by Django insert queries caused by duplicates
I am trying to add some data to a table (made in Django) How can I avoid de error caused by duplicates? class Prefixe(models.Model): remote_as = models.CharField(max_length=250) prefix_list = models.CharField(max_length=250, unique=True) def insert(): p = Prefixe(remote_as='Apress', prefix_list='Berkeley') p.save() If I don't use object oriented, I can fix it with postgres: INSERT INTO "peer_table" ("remote_as","prefix_list")VALUES('{}','{}')ON CONFLICT DO NOTHING""" Right now I get an error when duplicates -
Multiple Objects Returned Exception when entering wrong password in Django
I am using cookie cutter Django and on the url http://localhost:8000/accounts/login/ whenever I enter a wrong password I am getting the following traceback and a 500 Internal Server Error on the network console. I am using sqlite database. I am not able to understand why I am getting this error because when I create an empty project using the same database no such error is thrown. Environment: Request Method: POST Request URL: http://localhost:8000/accounts/login/ Django Version: 2.1.4 Python Version: 3.6.7 Installed Applications: ['django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.admin', 'crispy_forms', 'allauth', 'allauth.account', 'allauth.socialaccount', 'rest_framework', 'widget_tweaks', 'core.users.apps.UsersAppConfig', 'core.userManagement.apps.UsermanagementConfig', 'debug_toolbar', 'django_extensions'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'debug_toolbar.middleware.DebugToolbarMiddleware'] Traceback: File "/home/power/Documents/Projects/core/venv/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner 34. response = get_response(request) File "/home/power/Documents/Projects/core/venv/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 126. response = self.process_exception_by_middleware(e, request) File "/home/power/Documents/Projects/core/venv/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 124. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/power/Documents/Projects/core/venv/lib/python3.6/site-packages/django/views/generic/base.py" in view 68. return self.dispatch(request, *args, **kwargs) File "/home/power/Documents/Projects/core/venv/lib/python3.6/site-packages/django/utils/decorators.py" in _wrapper 45. return bound_method(*args, **kwargs) File "/home/power/Documents/Projects/core/venv/lib/python3.6/site-packages/django/views/decorators/debug.py" in sensitive_post_parameters_wrapper 76. return view(request, *args, **kwargs) File "/home/power/Documents/Projects/core/venv/lib/python3.6/site-packages/allauth/account/views.py" in dispatch 137. return super(LoginView, self).dispatch(request, *args, **kwargs) File "/home/power/Documents/Projects/core/venv/lib/python3.6/site-packages/allauth/account/views.py" in dispatch 80. **kwargs) File "/home/power/Documents/Projects/core/venv/lib/python3.6/site-packages/django/views/generic/base.py" in dispatch 88. return handler(request, *args, **kwargs) File "/home/power/Documents/Projects/core/venv/lib/python3.6/site-packages/allauth/account/views.py" in post 102. if form.is_valid(): File "/home/power/Documents/Projects/core/venv/lib/python3.6/site-packages/django/forms/forms.py" in is_valid 185. return … -
How to iterate formsets with inline structure
I face up with the problem of inability to iterate through my formsets. I have already create an inline structure between Client model(form) and Phone model(formset). My aim is to be able to store more than one phone for each client. The issue is that despite the fact that I can create more than one inlines, when it comes the phase of storing, my code only stores the last phone and not each phone as expected. models.py class Client(models.Model): name = models.CharField(max_length=50, verbose_name="Όνομα") surname = models.CharField(max_length=50, verbose_name="Επίθετο") amka_amesa = models.BigIntegerField( validators=[MaxValueValidator(99999999999)],null=True,blank=True, verbose_name="AΜΚΑ Άμεσα Ασφαλισμένου") amka_emesa = models.BigIntegerField( validators=[MaxValueValidator(99999999999)], unique=True, null=True, blank=True, verbose_name="ΑΜΚΑ Έμεσα Ασφαλισμένου") am_asfa = models.CharField( max_length=11, validators=[RegexValidator(r'^\d+$')], null=True, blank=True, verbose_name="Α.Μητρώου Ασφαλισμένου") address = models.CharField(max_length=100, null=True, blank=True, verbose_name="Διεύθυνση") ika_branch = models.ForeignKey(Client_IKA_Branch, null=True, blank=True, verbose_name=u'Υποκατάστημα Ασφαλισμένου') notes = models.CharField(max_length=100, null=True, blank=True, verbose_name="Σημειώσεις") #active field=1 #inactive field=0 INACTIVE, ACTIVE = range(0, 2) ACTIVITY_OPTIONS = ( (INACTIVE, 'Ανενεργός'), (ACTIVE, 'Ενεργός'), ) activity = models.IntegerField(choices=ACTIVITY_OPTIONS, null=True,default=ACTIVE) class Phone(models.Model): MOBILE, WORK, HOME = range(0, 3) CATEGORIES = ( (MOBILE, 'Κινητό'), (WORK, 'Δουλειά'), (HOME, 'Σπίτι'), ) number = models.CharField(max_length=14, null=True) category = models.IntegerField(choices=CATEGORIES, null=True,default=MOBILE) client = models.ForeignKey(Client, null=True) def __unicode__(self): return self.number def get_absolute_url(self): return reverse('client_list') forms.py class ClientForm(ModelForm): class Meta: model = Client exclude=('activity',) … -
How to send dict of dict from Django to javascript
I want to send data from Django to JavaScript so I can write all logic in JS + Vue and keep html clean. In Django I have context={'names':{'fn':'john','ln':'cena'}} return render(request,'app/page1.html',context) in page1.html template I have <script type="text/javascript"> var names="{{names}}"; </script> In javascript how can I access names.fn & names.ln ? I have two more related questions: Is this a preferred Django way to send data directly from Django to JS when template is rendered. (The only other method I know is through Ajax call. Here I dont want to do additional Ajax call after the page is rendered) From security stand point, is it better to keep Django data related logic {% if x > y %} inside templates or is it ok to move the logic part to JS + Vue and just keep data structure in the template. I ask this because when i check page source in a browser window, I can see entire JS code but I cannot see anything that's inside a Django condition statement in html : {% if x>y %} ----THIS IS INVISIBLE IN A BROWSER---- {% endif %} Thanks -
Combine a queryset with a newly created object
There is a new object (not yet saved): obj = MyObject() q = MyObject.objects.all() Is there any way to combine obj and q? -
How to store data in database from views.py Django?
This is my models: class ledger1(models.Model): name = models.CharField(max_length=32) Closing_balance = models.DecimalField(max_digits=10,decimal_places=2,blank=True,null=True) class journal(models.Model): Date = models.DateField(default=datetime.date.today) By = models.ForeignKey(ledger1,on_delete=models.CASCADE,related_name='Debitledgers') To = models.ForeignKey(ledger1,on_delete=models.CASCADE,related_name='Creditledgers') Debit = models.DecimalField(max_digits=10,decimal_places=2,null=True) Credit = models.DecimalField(max_digits=10,decimal_places=2,null=True) And in my views I have done this: qscb = journal.objects.filter(User=request.user, Company=company_details.pk, By=ledger1_details.pk, Date__gte=selectdatefield_details.Start_Date, Date__lte=selectdatefield_details.End_Date) qscb2 = journal.objects.filter(User=request.user, Company=company_details.pk, To=ledger1_details.pk, Date__gte=selectdatefield_details.Start_Date, Date__lte=selectdatefield_details.End_Date) total_debitcb = qscb.aggregate(the_sum=Coalesce(Sum('Debit'), Value(0)))['the_sum'] total_creditcb = qscb2.aggregate(the_sum=Coalesce(Sum('Credit'), Value(0)))['the_sum'] if(ledger1_details.group1_Name.balance_nature == 'Debit'): closing_balance = opening_balance + total_debitcb - total_creditcb else: closing_balance = opening_balance + total_creditcb - total_debitcb I want to store the value of 'closing_balance' into my model field named 'Closing_Balance'....And automatically update it when any changes are made... Any idea anyone how it is possible in django? Thank you -
Download Static Files by name Django
I am new to Django and am creating a site where user uploads a file (test.png etc). The file is then processed and a new file (test.csv) is created in the local directory. ../django/myproject/mysite/csv/test.csv Users can keep uploading files and more .csv files are created. A result page will show the .csv files and the user can download those files. However, I'm confused as I can't download them. views.py def make_csv(request): ... csv_filename = str(in_csv_file) #send to result page return render(request,'thesite/results.html', {"csv_filename": csv_filename}) views.py (same as above file) def download_csv(request, csvfile): path = os.path.join(SETTING_DIR) filename = path + csvfile + ".csv" filewrapper = FileWrapper(open(filename, 'rb')) response = HttpResponse(filewrapper, content_type='text/csv') response['Content-Length'] = os.path.getsize(filename) response['Content-Disposition'] = 'attachment; filename="{}"'.format(csvfile +".csv") return response results.html <tbody> <tr> <td></td> <td>{{csv_filename}}</td> <td><a href='/thesite/download_csv/{{csv_filename}}' do i add something here? >Download</a></td> </tr></tbody> urls.py urlpatterns = [ ... path('results/', views.results, name='results'), path('download_csv/(?P<csvfile>.+)$/', views.download_csv, name='download_csv'), or do I add smt here??] I'm sorry if my question is unclear. Thank you for your help. -
The parameters are escaping in href in an activation email Django 2.0
I am sending an activation email but in the email the link seems to be escaped, showing as follows. http://localhost:8000/activate/b&#39;MzIw&#39;/token--here/ Where it should be http://localhost:8000/activate/b'MzIw'/token--here/ In urls.py re_path(r'^activate/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>.....)/$', views.activate, name="activate"), The token is displaying as it is but the uidb64 is escaping. What's wrong here? -
React axios CSRF 403 FORBIDDEN when deploying django to DigitalOcean
The following action creator setup works just fine locally. However, when deploying the site in DigitalOcean I keep getting CSRF 403 FORBIDDEN and thus, fails to authenticate the user. ERROR -> POST https://app-machinespector.com/auth/signin/ 403 (Forbidden) Action creator that authenticates user. I'm loading the cookie but not using it anywhere (since it's not necessary). It's value is undefined... import axios from 'axios'; axios.defaults.xsrfCookieName = 'csrftoken'; axios.defaults.xsrfHeaderName = 'X-CSRFToken'; import { browserHistory } from 'react-router'; import cookie from 'react-cookie'; import { AUTH_USER, } from './types'; # load and print cookie --> undefined const csrftoken = cookie.load('csrftoken'); console.log(csrftoken); export function signinUser({email, password}){ return function(dispatch){ axios.post('/auth/signin/', { email, password }) .then(response => { dispatch({ type: AUTH_USER }); localStorage.setItem('token', response.data.token); browserHistory.push('/machines'); }) .catch(() =>{ dispatch(authError('Log in credentials are invalid')); }); } } Django production settings: from .base import * # noqa DEBUG = False # SECRET CONFIGURATION # ------------------------------------------------------------------------------ # See: https://docs.djangoproject.com/en/dev/ref/settings/#secret-key # Raises ImproperlyConfigured exception if DJANGO_SECRET_KEY not in os.environ SECRET_KEY = env('DJANGO_SECRET_KEY') # ALLOWED_HOSTS # ------------------------------------------------------------------------------ ALLOWED_HOSTS=["app-machinespector.com", "localhost", "127.0.0.1"] # CSRF # ------------------------------------------------- CSRF_USE_SESSIONS = False CSRF_COOKIE_HTTPONLY = False CSRF_COOKIE_NAME = 'csrftoken' CSRF_HEADER_NAME = 'X-CSRFToken' # WEBPACK CONFIGURATION # ------------------------------------------------------------------------------ WEBPACK_LOADER = { 'DEFAULT': { 'BUNDLE_DIR_NAME': 'bundles/prod/', # end with slash 'STATS_FILE': str(ROOT_DIR.path('webpack-stats-prod.json')), … -
ModuleNotFoundError at /auth/complete/google-oauth2/
Hi I am currently struggling with my social-auth-django as it keeps giving me ModuleNotFoundError at /auth/complete/google-oauth2/ No module named 'social_auth' When I click the login button, It redirects to the google authentication perfectly, yet After entering my credentials, and when it redirects to my website it kept giving me that error message :") I am new to the web development Environment and I'll be glad if anyone can help :D Thank you Here is also a segment of my code (settings.py) AUTHENTICATION_BACKENDS = ( 'social_core.backends.open_id.OpenIdAuth', # for Google authentication 'social_core.backends.google.GoogleOpenId', # for Google authentication 'social_core.backends.google.GoogleOAuth2', # for Google authentication 'django.contrib.auth.backends.ModelBackend',) SOCIAL_AUTH_PIPELINE = ( 'social_auth.backends.pipeline.social.social_auth_user', 'social_auth.backends.pipeline.associate.associate_by_email', 'social_auth.backends.pipeline.user.get_username', 'social_auth.backends.pipeline.social.associate_user', 'social_auth.backends.pipeline.social.load_extra_data', 'social_auth.backends.pipeline.user.update_user_details', 'social_auth.backends.pipeline.user.create_user')