Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
DJANGO Generic View Cannot Find Attribute 'as_view' [duplicate]
This question already has an answer here: How to require login for Django Generic Views? 9 answers I have a Django app where I have the following code: [app]/urls.py urlpatterns = [ path('', views.IndexView.as_view(), name='index'), ... ] [app]/views.py from django.http import HttpResponseRedirect from .models import Chat from .models import Message from django.shortcuts import render from django.shortcuts import get_object_or_404 from django.urls import reverse from django.views import generic from django.utils import timezone from django.contrib.auth.decorators import login_required @login_required() class IndexView(generic.ListView): template_name = "trout_line/index.html" context_object_name = 'latest_chat_list' def get_queryset(self): """Return the last five published questions.""" return Chat.objects.filter(start_date__lte=timezone.now()).order_by('-start_date')[:5] and a template at [app]/templates/[app]/index.html. When I run the server I receive the following message. ... path('', views.IndexView.as_view(), name='index'), AttributeError: 'function' object has no attribute 'as_view' I thought I followed the tutorial closely, but obviously I am missing something. Any help would be appreciated. I am running Python 3.6 and Django 2.1.2 on Ubuntu 16 -
I would like to only allow one entry for a row in a model in Django, is this possible?
Im building an inventory management web app (stock room manager). I have a model class: class location(models.Model): loc_room = models.CharField(max_length=20, blank=True, null=True) loc_section = models.IntegerField(blank=True, null=True) loc_shelf = models.CharField(max_length=4, blank=True, null=True) And a model class: class box(models.Model): box_contents = models.CharField(max_length=300, blank=True, null=True) location_id = models.ForeignKey('location', null=True) Is there a way that I could limit the number of boxes per location to only one entry? Its for a store room that only has one box per 'location'. E.g What I would like: At location Room: A, Section 1, Shelf 2 there should only ever be 1 x box with contents: 'Screwdriver, drill, shampoo'. E.g What is currently the case: At location Room: A, Section 1, Shelf 2 = 1 x box with contents: 'Screwdriver, drill, shampoo' ALSO 1 x box wiith contents: 'Towel rack, cups' At the moment, employees can add as many boxes per location as they like but I would like to limit this to one box as each location can physically only contain one box. -
How to use csrf (csrftoken) cookie session with django-rest-framework-social-oauth2
I have setup django-rest-framework-social-oauth2 to retrieve a token from django using facebook provider : curl -X POST -d "grant_type=convert_token&client_id=<client_id>&client_secret=<client_secret>&backend=facebook&token=<facebook_token> https://dev.myapp.com/api/auth/convert-token Everytime i do a request to my app, i add the token to the header : curl -i https://dev.myapp.com/api/users -H "Authorization: Bearer mytoken123" Everything works so far I am using ReactJs as frontend and do the above request from reactjs: axios.post("https://dev.myapp.com/api/auth/convert-token", postData).then(res => {console.log(res);} If the user closes the windows, he gets logged out as he does not have access to the token anymore, and if he goes back to my application, he has to login again. I would like to be able to use browser cookie to save the token i get from django-rest-framework-social-oauth2 and secure it with csrf protection to let the user access to my app without to click on "login" again and again I dont know how to do it and i dont know if it is possible? How should I setup django-rest-framework-social-oauth2, to get the csrftoken and use it for each API call ? The only solution I have got is to create another view that will create the csrftoken from django.shortcuts import render_to_response from django.template.context_processors import csrf def my_view(request): c = {} c.update(csrf(request)) data='my … -
How can I integrate existing MongoDB Database to generate Django Models and view in the admin site?
How can I integrate existing MongoDB Database to generate Django Models and view in the admin site? Can I use inspectdb for this? Are there any packages for this? How to connect Django to existing MongoDB Database? Thank you! -
displaying url in admin using model admin
class DirectAdmin(admin.ModelAdmin): def order_pdf(obj): # return "<a href='{}'>pdf</a>".format( url=reverse('orders:admin_order_pdf', args=[obj.id]) return "http://localhost:8000" + url order_pdf.allow_tags = True order_pdf.short_description = 'PDF bill' list_display=['id','name','price','phone_number',order_pdf] admin.site.register(Product) admin.site.register(Category) admin.site.register(Direct,DirectAdmin) this is my admin.py here in the admin section of my objects i want to display link where the link should act as anchor where it should redirect to that particular link in next tab but when i run this code i could see the uri but i want to make that section in my pdf as an anchor which redirects and opens in another tab is that possible,if yes please can you ttell me how ?? -
Django mode help_text before input widget
I'm looking how to create something like with Django. On models.py, I have something like class Fund(models.Model): success_targeted = models.TextField( help_text="Please specify what the successful outputs (what maybe be produced) and outcomes (what change it could lead to) would be for your participation in this event. These can include learning goals being met, collaborations, reports etc." ) On forms.py, I have something like class FundForm(ModelForm): class Meta: model = Fund The form is being render using django-crispy-forms {% crispy formset formset.helper %} The current render is with the help_text after the widget. How can I move the help_text to before the widget? -
How can solve this issue "cannot be considered a valid collection"
I'm running this code below but I'm getting an error that may probably come from this line of code "X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=random_state, test_size=test_size)". I found similar problems from this platform but the solutions provided don't mutch with my issue. Please assist me. @permission_required('admin.can_add_log_entry') def upload_file(request): template='upload_file.html' if request.method == 'GET': return render(request, template) CSV_file=request.FILES['csv_file'] if not CSV_file.name.endswith('.csv'): messages.error(request, 'This is not a CSV file') # return HttpResponseRedirect(reverse('add_pull_requests')) data_set=CSV_file.read().decode('UTF-8') io_string=StringIO(data_set) next(io_string) dataset=csv.reader(io_string, skipinitialspace=True, delimiter=',') csv_list=list(dataset) # prediction_dataset=[] for row in csv_list: if row[11]=='Non-Reopened': row[11]=0 else: row[11] = 1 if row[9]=='Rejected': row[9]=0 else: row[9]=1 prediction_dataset = [row[3], row[4], row[5], row[6], row[7], row[8], row[9], row[10]] X = [prediction_dataset] y = row[11] print(X) print(y) test_size = 0.2 random_state = 5 clf = tree.DecisionTreeClassifier() X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=random_state, test_size=test_size) # clf = tree.DecisionTreeClassifier() clf = clf.fit(X_train, y_train) # y_pred = clf.predict(X_test) print(accuracy= accuracy_score(y_test,y_pred)*100) return render(request, template,{"csv_list": csv_list}) -
Django login input fields not showing
Im following a tutorial which creates uses the auth app to login etc. For some reason, the input fields arent showing for the username and password (they were showing before). Code is: login.html <h2>Login</h2> <form method="post"> {% csrf_token %} {{form.as_p}} <button type="submit">Login</button> </form> views.py from django.views import generic from django.views.generic.edit import CreateView, UpdateView, DeleteView from django.http import HttpResponse from django.shortcuts import render from django.db.models.query import QuerySet from .models import Subject def index(request): return render(request, 'minerva/lout.html') class ListView(generic.ListView): template_name = 'minerva/list.html' context_object_name = 'all_subjects' def get_queryset(self): return Subject.objects.all() def crew(request): return render(request, 'minerva/crew.html') def profile(request): return render(request, 'minerva/profile.html') def lout(request): return render(request, 'minerva/index.html') def lscreen(request): return render(request, 'minerva/login.html') def login(request): return render(request, 'registration/login.html') urls.py from django.urls import path, include from . import views from django.conf.urls import url app_name = 'minerva'#namespace urlpatterns = [ path(r'', views.index, name='index'), path('list',views.ListView.as_view(), name = 'list'), path('crew',views.crew, name = 'crew'), path('profile',views.profile, name = 'profile'), path('lout',views.lout, name = 'lout'), path('lscreen',views.lscreen, name = 'lscreen'), path('accounts/', include('django.contrib.auth.urls')), path('accounts/login',views.login, name='login'), ] -
Which is better django or nodejs?
I'm really confused about learning django or node.js Many websites say that node.js provide more opportunities nad some say django is more dynamic. Please help me make a decision. -
Django object - field choice
I am building gallery app and I want Django to be able to serve choice of field for one object in the model. I am uploading full picture and thumbnail of the image in my model. I want user to be able to choose between "auto created thumbnail" which would use django-imagekit's field called ImageSpecField or upload their own thumbnail via my own defined field called ResizedImageFieldFile. Full image field would be served by standard ImageField so that ImageSpecField can generate thumbnail from it. For simplicity sake : can that be achieved using same object called thumbnail and form written in a way that there is choice between auto and own thumbnail or I am doomed to use two objects called for ex. thumbnail and thumbnail_auto. Thank you! -
Cross Platform Single Sign On
Want to know some best ways how to achieve Single Sign On for cross platform django projects. I have a monolithic application which is getting converted to Multi Tenant system. The core part of the monolithic application is converted and divided into micro services but there are portions and part of monolithic application which will take time to get converted. So currently I cannot remove monolithic application hence needed a way to implement Single Sign On for these two application running in parallel. Monolithic Stack:- Python, Django1.10, mysql, MultiTenantSystem Stack :- Python, Django2.1, Postgres Some references :- https://github.com/aldryn/django-simple-sso https://medium.com/@MicroPyramid/django-single-sign-on-sso-to-multiple-applications-64637da015f4 -
elastic search model init() raise key error
According to the documentation I've created class with some of my model fields to perform search later. Also I've created conection with default params. But I can't call init() for UserIndex from elasticsearch_dsl import DocType, Text, Boolean, Date, Keyword from elasticsearch_dsl.connections import connections connections.create_connection(hosts=['localhost'], timeout=20) class UserIndex(DocType): pk = Text() phone_number = Text() nickname = Text() name = Text() birth_date = Date() class Meta: index = 'user' After UserIndex.init() command I'm getting an error: File ".../lib/python3.6/site-packages/elasticsearch_dsl/document.py", line 138, in init i.save(using=using) File ".../lib/python3.6/site-packages/elasticsearch_dsl/index.py", line 289, in save current_settings = self.get_settings(using=using)[self._name]['settings']['index'] KeyError: '*' -
Sending warning/error emails, with preset time intervals between them
In Django when I have a critical or non-critical/warning 'error', I send an email to a specified address depending on error. The issue is that sometimes, the staff receives multiple messages with the same error in a short interval of time. I need a mechanism that after sending an error type will not send a new message for the same error in a preset time interval, maybe increasing the time intervals between sending. Also, I need a reset mechanism if the error is not triggered anymore. I prefer something that doesn't involved retaining info in the database. I don't have any code, because I don't have a clear plan to implement it. I thought of using a general variable, maybe a dictionary, and reset it after a time, if no error is trigger, but I don't know how can work with 'spacing' warning emails. -
Django: Writing tests for template tag
I am using django-qr-code to generate QR codes. I wonder how to write a test if the QR code generation works properly. Do you have any tips? <img src="{% qr_url_from_text attendee.ticket_code size='M' %}" alt="Ticket QR code"> -
how can i show just spicific url in barre link with django
i devlop an application to a blog using django The problem is when I open a link to a publication For example, https: // localhost: 8000 / article / 89 / And I want to open another link to a brochure and see this https: // localhost: 8000 / article / 89 / article / 80 / Whenever you click a link, the same thing happens Is there a solution please view.py articles def show_article(request, id): post = get_object_or_404(articles, id=id) add = comment_put.objects.all().filter(user_put = id).order_by('-id') art = articles.objects.get(pk = id) first = articles.objects.order_by('-id')[:1] three = articles.objects.order_by('-id')[:4] is_liked = False if post.likes.filter(id=request.user.id).exists(): is_liked = True context = { 'art': art, 'add': add, 'post': post, 'first': first, 'three': three, 'is_liked': is_liked, 'total_likes': post.total_likes(), } return render(request, 'home/article.html', context) urls.py url(r'article/(?P<id>\d+)/$', views.show_article, name='show_article'), -
Send file as a response not file path. How to Send xlsx file as a response in python
I have read data from mysqldb and write into xlsx file and stored into directory using xlsxwriter. Now i want to send a response as a xlsx file not file path. Can you please anyone help me to do this. cursor.execute(query) filter_data = _cursor.fetchall() workbook = xlsxwriter.Workbook('report.xlsx') worksheet = workbook.add_worksheet() for row, x in enumerate(total_data): for col, y in enumerate(x): worksheet.write(row, col, str(y)) workbook.close() I want to send a response as a xlsx file in python. I tried like below response = HttpResponse(content_type='application/ms-excel') response['Content-Disposition'] = 'attachment; filename="report.xlsx"' return response The above statement i have used. But am getting the following error didn't return an HttpResponse object. It returned None instead. -
How to get past this warning -> RemovedInDjango110Warning: Operator '=' is deprecated and will be removed in Django 1.10. Use '==' instead
I was trying to create a user instance in Django. newuser = User.objects.create(username = username, email = email) and got this warning and stuck here with a user created in the database. project/new_env/lib/python3.6/site-packages/django/template/smartif.py:168: RemovedInDjango110Warning: Operator '=' is deprecated and will be removed in Django 1.10. Use '==' instead. I am using Django 1.9.5 and python3.6.6. -
How to create a custom action endpoint that corresponds to put and executes a function in the model class?
Am using Django Rest Framework: v3.7 and Django v1.11 and Dynamic Rest v1.9.2 I have the following in my MyModel Class: class MyModel(): # .. fields declared here.. def change_status(self): #... other code not crucial allowed = self.status in possible_new_states if allowed: return self.save() return True I have the following ViewSet class MyModelViewSet(DynamicModelViewSet): """ VendorQuotations API. """ permission_classes = (IsAuthenticated,) queryset = MyModel.objects.all() serializer_class = MyModelSerializer @action(detail=True, methods=['put'], name='Change Status', url_path='change-status', url_name='change_status') def status(self, request, pk=None): """Update the status.""" And the following Serializer: class VendorQuotationSerializer(DynamicModelSerializer): The DynamicModelSerializer inherits from serializers.ModelSerializer and the DyanmicModelViewSet inherits from viewsets.ModelViewSet I wanted to have an endpoint like /my_models/:id/change_status to point at the status method in the viewset which in turn somehow execute the change_status method at the model level. I looked at django rest docs and did copy the example for the change_password but I am not sure how to connect the dots between the viewset and the model. Please advise -
How to migrate particular table in django
In model file already some of table migration and added records to that tables. Now, I tried to add a additional tables but its not migrating. class Ranking(object): id=models.AutoField(primary_key=True, unique=True) name= models.TextField() user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) model = models.ForeignKey(DecisionModel, on_delete=models.CASCADE) created = models.DateTimeField(auto_now_add=True) modified = models.DateTimeField(auto_now=True) How can i makemigration & migrate particular table? Thanks for the solution in advance. -
Django: Should I use LocMemCache caching?
I am using this QR code generator. There is a specific part in the documentation about caching. I read that LocMemCache should not be used in production. Is that also the case for these QR codes? Is there a caching that you can recommend instead, or is that approach fine at the beginning with a smaller page? CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', }, 'qr-code': { 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', 'LOCATION': 'qr-code-cache', 'TIMEOUT': 3600 } } QR_CODE_CACHE_ALIAS = 'qr-code' -
Django refuses to use DB view
I have the following scenario: I have defined the right view in the database, taking care that the view is named according to the django conventions I have made sure that my model is not managed by django The view is working fine by itself. When triggering the API endpoint, two strange things happen: the request to the database fails. I have logging enabled at the postgres level, and copy-pasting the exact same request into a db console client works, without modifications whatsoever. the request to the DB gets retried lots of times (more than 30?). Why is this happening? Is there a django setting to control this? (I am sending the request to the API just once, manually with curl) -
Bound task in celery is not able to access instance variable in django project
I have setup celery in my django project using official documentation at http://docs.celeryproject.org/en/latest/django/first-steps-with-django.html#using-celery-with-django So my MyApp/tasks.py have content from celery import shared_task class Someclass(): def __init__(self, x, y): self.x = x self.y = y @shared_task(bind=True) def func1(self): '''This does not work''' return self.x + self.y @shared_task(bind=True) def func2(self, a, b): '''This works well''' return a + b When I run In [9]: o = Someclass(3, 4) In [10]: o.func1.delay() Out[10]: <AsyncResult: afc6b151-d71c-4f46-a916-6917f98c681f> I get the error AttributeError: 'func1' object has no attribute 'x' When I run In [11]: o.func2.delay(3, 4) Out[11]: <AsyncResult: 3b227f00-8d9c-472b-b7d8-8b4b6261f689> This works perfectly How can I make func1 working so that it can use instance variables e.g. x and y? -
Django: Caching solution
My Django application is running via Heroku and I am now looking into adding caching. I found many different solutions such as MemCachier, Amazon ElastiCache [...]. Can you recommend one or the other? What do you use for caching? -
Django how to save formset with a foreign key?
I have two models employee and child(Enfant) related by a foreignkey, like models.py class Enfant(models.Model) : id_emp = models.ForeignKey(Employee, on_delete=models.CASCADE) id_Enfant=models.IntegerField(blank=True,primary_key=True) views.py form = EmployeeForm(request.POST or None) form_EnfantForm_formset =formset_factory(EnfantForm, formset=EnfantFormSet) if request.method == 'POST' if form.is_valid() : #pdb.set_trace() new_employee=form.save() EnfantForm_formset0 = form_EnfantForm_formset.save(commit=False) EnfantForm_formset0.employee= new_employee EnfantForm_formset0.save() I need to save employee record and enfant records -
In Django app, get File from some specific Folder and save it to Database table
I have a Django app and in one of my function, I want to read some files from the Specific folder and Save it into the Database. I want to save those uploaded files to my MEDIA_ROOT folder only. My Model class look like. class EmailTemplates(models.Model): templates = models.FileField(validators=[validate_file_extension]) def __str__(self): return str(self.templates) I am trying to read some file from some specific folder and save it to the database. fa = open(template_addr + '/mail_html.html', 'w') email_templates_instance=EmailTemplates.objects.create(templates=File(fa)) I want to read the file and then save it to my EmailTemplates table and create uploaded folder in my MEDIA_ROOT. What is going wrong here? If someone can suggest me something then please suggest me.