Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Datatable ajax add row on condition
So I'm having some trouble setting up datatable using Ajax. Some context: I have a Ajax that request certain files information. The response contains two sets The files information The users information (to figure out the user of the files). I've completed the entire logic without Datatable but now i want to implement it using datatable. I have 2 condition Is the end date between today and 4 days from now? is the end date after 4 days form now? These condition are used to indicate to the user witch files (project) needs the most attention. CODE TIME (I'm using the Django framework btw) :D The AJAX CALL function ajax_dates() { $.ajax({ url: "{% url 'get_files_dates' %}", type: "GET" }).done(function (object) { date_calculation(object.dates, object.users); }); } THE TWO CONDITION // CONDITION ONE (ATTEMPT using Datatable) // Projecten met een waarschuwing if (enddate.isBetween(today, today.clone().add(4, 'd'))) { // TABLE ROW VOOR ELK TYPE running_waring = ""; running_waring += '<tr>'; running_waring += '<td>'+ checker.first_name + " " + checker.last_name+'</td>'; running_waring += '<td>'+ checker.first_name + " " + checker.last_name+'</td>'; running_waring += '<td id="testing">'+result.name+'</td>'; running_waring += '<td>'+result.word_count+'</td>'; running_waring += '<td>'+enddate.format("D MMM YYYY").replace(".","")+'</td>'; running_waring += '<td>'+enddate.format("HH:mm:ss")+'</td>'; running_waring += '<td>Verloopt binnenkort </td>'; running_waring += '<td> Verloopt' + … -
Add css class to all admin form field
I need to assign a boostrap class to all my user's field in Django admin form, I wrote this code but it does not work. formfield_overrides = { models.CharField: {'widget': TextInput(attrs={'class': 'form-control'})}, models.CharField: {'widget': EmailInput(attrs={'class': 'form-control'})}, models.DateField: {'widget': DateTimeInput(attrs={'type': 'date', 'class': 'form-control'})}, models.EmailField: {'widget': EmailInput(attrs={'class': 'form-control'})}, models.BooleanField: {'widget': CheckboxInput(attrs={'class': 'form-control'})}, } Can you help me? -
invalid PasswordChangeForm
Heyho, I created a model Profile with a OnetoOneField to User. In account_settings view I want to either give the possibility to change the profile information or reset the password. Changing Profile-Information works fine, but when I try to change the password, my PasswordChangeForm is always invalid. Can somebody tell me where my mistake is? Here's the view: def account_settings(request, id): user = Profile.objects.get(id=id) if request.method == 'POST' and 'passwordchange' in request.POST: user_form = PasswordChangeForm(request.user, prefix='password') if user_form.is_valid(): user_form.save() update_session_auth_hash(request, user) messages.success(request, 'Your password was successfully updated!') else: messages.error(request, 'Please correct the error below.') return redirect('profile', user.id) elif request.method == 'POST' and 'profilechange' in request.POST: profile_form = ProfileForm(request.POST, instance=request.user.profile,prefix='profil') if profile_form.is_valid(): profile_form.save() return redirect('account_settings',user.id) #else: #messages.error(request, _('Please correct the error below.')) else: user_form = PasswordChangeForm(user=request.user, prefix='password') profile_form = ProfileForm(instance=request.user.profile,prefix='profil') return render(request, 'app/accountform.html', {'profileuser': user,'user_form': user_form,'profile_form': profile_form}) the template: <div class="col-md-9"> <div class="profile-content"> <form method="post" > {% csrf_token %} {{ profile_form.as_p }} <button type="submit" name="profilechange">Änderungen speichern</button> </form> <form method="post" > {% csrf_token %} {{ user_form.as_p }} <button type="submit" name="passwordchange">Passwort ändern</button> </form> <a href="{% url 'profile' user.profile.id %}" type="submit" class="btn btn-default">Abbrechen</a> </div> </div> -
form.is_valid() always returns false in views.py
form.is_valid() always fails. I tried different ways to handle it but fails every time and it returns false. Please help in figuring out whats wrong with the code. models.py looks like this - class Album(models.Model): album_name = models.CharField(max_length=50, primary_key=True) place = models.CharField(max_length=50) date_pub = models.DateTimeField('date published') def __str__(self): return self.album_name class Images(models.Model): album_name = models.ForeignKey(Album, db_column='album_name') image_name = models.CharField(max_length=40) image = models.FileField(null=True, blank=True) upload_dt = models.DateTimeField(auto_now=True, auto_now_add=False) like_cntr = models.IntegerField(default=0) description = models.CharField(max_length=200, null=True) def __str__(self): return self.image_name forms.py is - class ImagesForm(forms.ModelForm): description = forms.CharField(required=False) class Meta: model = Images fields = ('album_name', 'description',) views.py is - class RandomView(TemplateView): template_name = 'photos/random.html' def get(self, request, album_name): images = Images.objects.filter(album_name=album_name) context = {'album_name':album_name, 'images' : images} return render(request, 'photos/random.html', context) def post(self, request, album_name): form = ImagesForm(request.POST) if form.is_valid(): form.save(commit=False) text = form.cleaned_data['description'] Images.album_name = album_name form.save() else: return HttpResponse("Failed to save") Templates is - <h3>Album : {{album_name }}</h3> {% for image in images %} <img src="{{image.image.url}}" height="400" width="500"> <h4> {{image.image_name }}</h4> <form method="POST" action=""> {% csrf_token %} <span class = "badge">Description</span> {% if image.description %} <h4> {{image.description }} </h4> {% else %} <input type="text" value=" "/> <button type="Submit">Submit</button> {% endif %} </form> {% endfor %} -
how to override GET method in django to make a seen status
I wanna make this thing on the model as I'm using REST API too. I have a model named as seen active = models.BooleanField( verbose_name=_("Is active"), default=True, help_text=_("Inactive devices will not be sent notifications") ) user = models.ForeignKey( SETTINGS["USER_MODEL"], blank=True, null=True, on_delete=models.CASCADE ) and I wanna to override my customise class-based view so that everytime an authenticated user visits a detail view I create an instance in the seen table -
How to use CSRF token in cached views?
I'm using Redis to cache views. But I can't use forms in the cached views because of the CSRF token. How can I use forms in a cached view? -
Django oauth toolkit Permission for access_token generated by client_credential
I am using Django oauth toolkit with django-restframework for implementing a sets of Apis for a client application. My problem is when i genereting a token with grant client_credentials i get 403 in access on my view (in access token table there is not set a user). How can solve this issue ? Best Luca -
Signup page stuck on loading (Waiting for Localhost...) after extending AbstractUser
I created a custom user model called Agent by extending AbstractUser. Now for some reason, my signup page is stuck and I can't figure out why (it was working fine before I created the custom user). When I click the Sign Up button, the page is stuck on Waiting for localhost... There are 2 additional models on top of Agent that are created during registration - AgentBasicInfo and AgentPremiumInfo. AgentBasicInfo is displayed on the sign up page, while AgentPremiumInfo is created in the background, and not actually displayed during registration. When I check my admin page, I see that an Agent model has been created, but no AgentBasicInfo and AgentPremiumInfo instances have been created. This leads me to believe something is getting stuck at or after agent_basic_info = basic_info_form.save(commit=False), but I can't figure out what it is. Here is my code: views.py def signup(request): if request.user.is_authenticated: return HttpResponseRedirect('../dashboard/') if request.method == 'POST': signup_form = SignupForm(request.POST) basic_info_form = AgentBasicInfoForm(request.POST) if signup_form.is_valid() and basic_info_form.is_valid(): agent = signup_form.save(commit=False) agent.is_active = False agent.save() # Creates a basic info form with user input agent_basic_info = basic_info_form.save(commit=False) agent_basic_info.agent = agent agent_basic_info = agent_basic_info.save() # Creates a profile model with the agent's premium information, empty except for … -
CourseModuleUpdateView didn't return an HttpResponse object. It returned None instead
I have the following class for displaying related course module using formsets class CourseModuleUpdateView(TemplateResponseMixin, View): template_name = 'courses/manage/module/formset.html' course = None def get_formset(self, data=None): return ModuleFormSet(instance=self.course, data=data) def dispatch(self, request, *args, **kwargs): self.course = get_object_or_404(Course, id=kwargs['pk'], owner=request.user) super(CourseModuleUpdateView, self).dispatch(request, *args, **kwargs) def get(self, request, *args, **kwargs): formset = self.get_formset() return self.render_to_response({'course': self.course, 'formset': formset}) Url pattern responsible for this CBV url(r'^(?P<pk>\d+)/module/$', views.CourseModuleUpdateView.as_view(), name='course_mudule_update') Issuing a get request I get the following error Traceback: File "/home/mtali/.virtualenvs/educa/lib/python3.5/site-packages/django/core/handlers/exception.py" in inner 41. response = get_response(request) File "/home/mtali/.virtualenvs/educa/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response 198. "returned None instead." % (callback.__module__, view_name) Exception Type: ValueError at /courses/4/module/ Exception Value: The view courses.views.CourseModuleUpdateView didn't return an HttpResponse object. It returned None instead. What is wrong with my code! I am using django 1.11 -
Legacy Django 1.4.22 app to Django 1.11
I am migrating a legacy Django 1.4.22 app to Django 1.11 I have gone through https://groups.google.com/forum/#!topic/django-users/_cES27L7Y18 https://django.readthedocs.io/en/1.4.X/topics/generic-views-migration.html https://www.seedinvest.com/labs/backend/upgrading-from-django-1-4-to-django-1-7 https://bertelsen.ca/updating-django-1-4-to-1-10-learnings/ https://timony.com/mickzblog/2017/09/27/migrate-django-1-4-to-1-11/ Upgrading a django 1.4 project to 1.8 version https://docs.djangoproject.com/en/1.8/releases/1.5/ https://docs.djangoproject.com/en/1.8/releases/1.6/ https://docs.djangoproject.com/en/1.8/releases/1.7/ https://docs.djangoproject.com/en/1.8/releases/1.8/ https://openedx.atlassian.net/wiki/spaces/PLAT/pages/160667796/edx-platform+Django+1.11+Upgrade+Plan https://docs.djangoproject.com/en/1.11/howto/upgrade-version/ Looking for more "hands-on" tips to help me complete this -
django oscar migrations not migrating, other app migrates
I've been quite stuck and I've read the docs over and over again. My models aren't migrating. My prompt would be No changes detected in app "catalogue" but I did make changes. I can't seem to figure out what I'm doing wrong. Sometimes it works and I don't know why. I make note of it and repeat it, it doesn't work. Any suggestion or idea is appreciated. Thanks!!! subapp1 is the shop app using oscar, subapp2 is another app I run python manage.py makemigrations catalogue then python managepy migrate catalogue I've also tried migrating in the subapp1. Result is the same. app/settings.py INSTALLED_APP = [...] + + get_core_apps(['subapp1.catalogue']) I've also forked the migrations folder as indicated in the docs. I also tried without it. (And yes I have my __init.py__ file. app/subapp1/catalogue/models.py from django.db import models from django.utils.translation import ugettext_lazy as _ from subapp2 import models as subapp2_models from oscar.apps.catalogue.abstract_models import AbstractProductImage from oscar.core.loading import get_model product = get_model('catalogue','Product') links = subapp2_models.links class ProductImage(AbstractProductImage): links= models.ForeignKey(links) product = models.ForeignKey('catalogue.Product', related_name='photo_links', verbose_name=_("Product")) class Meta: app_label = 'catalogue' verbose_name = _('link image') def __str__(self): return u"Image of '%s'" % self.product from oscar.apps.catalogue.models import * -
Graphene-django returns null node instead of just node field
I am facing a strange problem with graphene and Django. The documentation seems to lack a solution and I couldn't figure out what I'm doing wrong. I have the following models: Class Sentence(models.model): ref = models.CharField(max_length=30, primary_key=True) body = models.TextField(default=None) Class Summary(models.Model): sentence = models.ForeignKey(Sentence, on_delete=models.CASCADE) text = models.TextField(default=None) (Each sentence can have multiple summaries) And the following schema: Class SentenceType(DjangoObjectType): class Meta: model = models.Sentence filter_fields = {"ref": ["exact"]} interfaces = (graphene.Node, ) Class SummaryType(DjangoObjectType): class Meta: model = models.Summary filter_field = {"text": ["icontains"]} interfaces = (graphene.Node, ) Class Query(graphene.ObjectType): all_sentences = DjangoFilterConnectionField(SentenceType) sentence = graphene.Field(SentenceType, ref=graphene.string(), body=graphene.string()) all_summary = all_provvedimenti = DjangoFilterConnectionField(SummaryType) summary = graphene.field(SummaryType, id=graphene.Int(), text=graphene.string()) def resolve_all_summaries(self, context, **kwargs): return models.Summary.objects.all() It can occur that there is one or more summaries in my database with no corresponding sentence. Now, when I query { allSummaries{ edges{ node{ text sentence{ ref } } } } } If the the sentence exists for the summary, no problem at all. But if there is no corresponding sentence I get: "errors": [ { "message": "Sentence matching query does not exist.", "locations": [ { "line": 6, "column": 9 } ] } ], ..., ..., "data":[ ..., { "node": null }, { "node":{ … -
Serializer List of objects grouping them by foreign key attribute
Similar to the issue found here (and maybe here) I had the problem of having a model like so: class Item(models.Model): name = models.CharField(max_length=128) category = models.ForeignKey(Category) class Category(models.Model): name = models.CharField(max_lenght=64) and wanting to serialize a list grouped by category like so: [{'name': 'category 1', 'items: [ {'name': 'item1}, {'name':'item2'} ]}, {'name': 'category 2', 'items: [ {'name': 'item3}, {'name':'item4'} ]}] -
How to test a Django CreateView
I want to practice testing on Django, and i have a CreateView i want to test. The view allows me to create a new post and i want to check if it can find posts without a publication date, but first i'm testing posts with published date just to get used to syntax. This is what i have: import datetime from django.test import TestCase from django.utils import timezone from django.urls import reverse from .models import Post, Comment # Create your tests here. class PostListViewTest(TestCase): def test_published_post(self): post = self.client.post('/post/compose/', {'author':"manualvarado22", 'title': "Super Important Test", 'content':"This is really important.", 'published_date':timezone.now()}) response = self.client.get(reverse('blog:post_detail')) self.assertContains(response, "really important") But i get this: django.urls.exceptions.NoReverseMatch: Reverse for 'post_detail' with no arguments not found. 1 pattern(s) tried: ['post/(?P\d+)/$'] How do i get the pk for that newly created post? Thank you! -
How can i combine 2 programs written in different programming languages together
I have a django web app and my friends have made a messaging app in erlang and I want to combine both of them so that the users and their friends can communicate. We are trying build something like facebook, their main web languages is php but they use erlang for messanger -
Reduce amount of queries for generic foreign key
Suppose I have these models: class RegionPage(models.Model): area = models.ForeignKey('Area') title = models.CharField(max_length=255) class SomePage(models.Model): someotherfield = models.ForeignKey('SomeClass') title = models.CharField(max_length=255) class Link(models.Model): content_type = models.ForeignKey(ContentType) object_id = models.PositiveIntergerField() content_object = GenericForeignKey('content_type', 'object_id') title = models.CharField(max_length=255) Obviously, I can use neither select_related nor prefetch_related to get access to someotherfield and area fields. But is there any way to reduce amount of queries when you work with generic foreign keys? -
AttributeError: 'module' object has no attribute 'TabularInLine'
What could be the problem in this code I am trying to add Cart in an e-commerce page and it return with an Attribute Error from django.contrib import admin from .models import Cart, CartItem class CartItemInLine(admin.TabularInline): model = CartItem class CartAdmin(admin.ModelAdmin): inlines = [ CartItemInLine ] class Meta: model = Cart admin.site.register(Cart, CartAdmin) -
overriding django-allauth template with my project templates
pasted]1 some templates from Django-Allauth in my project template directory but I can't override them. tree applications/startupconfort/templates -L 1 applications/startupconfort/templates ├── account/ ├── shippingaddress/ └── startupconfort/ and the account folder contains my file applications/startupconfort/templates/account ├── base.html ├── email_confirm.html ├── email.html ├── login.html ├── logout.html ├── password_change.html ├── password_reset_from_key.html ├── password_reset.html ├── password_set.html └── signup.html -
how to extend custum user Model?
I would to create the new UserModel that be Custom from User Model django, so then added extended attribute and methods like Proxy model and One-To-One Link Model togather. I would to using Authentication and permission UserModel django to my defined UserModel for my two type Users that are my defined Admin and staff User. How to using just username and password for Authentication for My UserModels and my other custom fields How to create its and Fill with the ModelForm? -
Video link for registered users
I have a website in which we are now uploading course contents. I now want only authenticated users to access these contents. The video links should not open for other users. My server is on django on aws ec2 instance. How to achieve this? -
Is there a way to set meta data (Title and Description) for login_required pages?
Google is indexing my login_required pages, but it seems as though they are just pulling the title from the link that lead them to the page and then indexing the login form that the page redirects to? The meta description looks something like this: "Sign In. Don't have an account yet? Then please sign up. Login*. Password*. Remember Me. Forgot Password? Sign In. Search · About · Contact · FAQ · Privacy ..." Is there a way to set the meta data for these pages? Or should I just restrict Google from crawling them at all to keep from getting a penalty? -
How to load an image generated in other functions, output the code in the Django binary code
How to load image to bd, well i generate qr image(QRcode)when she is generated, i need to create a new record in bd, to save this image and code himslef This is my model class QRCode(models.Model): user = models.ForeignKey(UserProfile, blank=True, default=None) qr_code = models.CharField(max_length=120) qr_code_img = models.ImageField(upload_to="qr_code_img/", width_field="width_field", height_field="height_field") upcoming_show = models.ForeignKey(SectionUpcomingShow) width_field = models.IntegerField(default=270) height_field = models.IntegerField(default=270) is_active = models.BooleanField(default=True) timestamp = models.DateTimeField(auto_now=False, auto_now_add=True) updated = models.DateTimeField(auto_now_add=False, auto_now=True) def __str__(self): return "{0} - - {1}".format(self.user.username, self.is_active) class Meta: ordering = ["-timestamp"] verbose_name = 'QRCode' verbose_name_plural = 'QRCodes' @property def image_path(self): return os.path.abspath(self.qr_code_img) this is view to gen qrimg def qr_code_generator(hex_code, username, __show__id, __show__name__, __show__q, price): qr_code_generate_himslef = pyqrcode.create(hex_code) generate_name = ''.join(username + '_' + str(__show__id) + '_' + __show__name__ + '_' + str(__show__q) + '_' + str(price) + '.png').replace(" ", "_") qr_code_generate_himslef.png(generate_name, scale=6) print(qr_code_generate_himslef) return qr_code_generate_himslef when i print this function i got this QRCode(content=b'f40a03cb6026d68f0f83c43b47c9e388ed106848', error='H', version=5, mode='binary') this is my save view new_qr_code, created = QRCode.objects.get_or_create(user=get_user_profile, qr_code=hex_code, is_active=True, defaults={"user":get_user_profile, "qr_code":hex_code, "qr_code_img":qr_img, "upcoming_show":get_upcoming_show}) if not created: pass -
Django form is not submitting (submit button not working)
I am using djnago form with angular and django fields but submit button is not working. What corrections are needed? plz help... <body ng-app="angNewsApp"> <form method='POST' action='' enctype='multipart/form-data'> {% csrf_token %} <div ng-controller="demoCtrl"> <h2>Multiple</h2> <input id="inputImage" name="file" type="file" accept="image/*" ng-model="imageList" image="imageList" resize-max-height="800" resize-max-width="800" resize-quality="0.7" resize-type="image/jpg" multiple="multiple" ng-image-compress/> <div> <img ng-src="{% verbatim %}{{item.compressed.dataURL}}{% endverbatim %}" ng-repeat="item in imageList" /> </div> <!-- just do a console.log of {{image1}} to see what other options are in the file object --> </div> <button type="submit">Submit</button> </form> </body> -
Data not getting inserted in db in django
Hi I am trying to select data from a dropdown list and then save it in Category model.There is no problem in retrieving the data but when i check it using Category.objects.all(), I get this <QuerySet [<Category: Category object>, <Category: Category object>, <Category: Category object>, <Category: Category object>]> models.py: from future import unicode_literals from django.db import models from django.contrib.auth.models import User class Category(models.Model): user = models.ForeignKey(User) category= models.CharField(max_length=100) views.py: def get_category(request): cname = request.POST.get("dropdown1") user = request.session.get('user') obj=Category(user_id=user,category=cname) obj.save() return HttpResponse("Registeration succesfull") With get_category i am trying to save entry selected from dropdown.It works fine but i guess nothing is being stored in the db. I tried running this Category.objects.get(category = "abc") I get this error: DoesNotExist: Category matching query does not exist. Can someone tell if this is not the right way to insert data in db. -
How to properly call a url that came from an object ID in django
I want to make a checkout page and also want to call a url which came from an object ID in Django. The products app has its own urls.py, My question is How do you properly call an object ID? . This is the url http://localhost:8000/products/1. I attempt to call it but it return some error. <button type="button" class="btn btn-primary"><i class="fa fa-shopping- cart"> </i> <a href="{% url 'products/1' %}"> Add To Cart </a> </button> urls.py-products url(r'^$', ProductListView.as_view(), name='products'), url(r'^cbv/(?P<pk>\d+)', ProductDetailView.as_view(), name='product_detail'), url(r'^(?P<id>\d+)', 'products.views.product_detail_view_func', name='product_detail_function'), main urls.py url(r'^products/', include('products.urls')), this is the error **Reverse for 'products/1' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: []**