Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Publish button doesn't do anything (django forms)
I am following an online django course and one of the exercises includes creating a blog. One of the elements of the blog includes a "Publish" button. But when I click on that button, it doesn't do anything. I have checcked and re-checked the code in HTML, views.py, and urls.py but I don't see whats missing. This is the code: HTML: Publish views.py: @login_required def post_publish(request,pk): post = get_object_or_404(Post,pk=pk) post.publish() return redirect('post_detail',pk=pk) urls.py: url(r'^post/(?P\d+)/publish/$',views.post_publish,name='post_publish'), -
Filtering queryset by next 30 days and date passed
I'm not sure if It's due to lack of sleep, but I cannot for the life of me figure out what's causing this issue. AttributeError: 'datetime.date' object has no attribute 'utcoffset' I'm trying to filter a queryset based on two conditions. If the date has already passed. If the date is within the next 30 days. Model class Member(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, blank=True, null=True) ... membership_expiry = models.DateField(null=True, blank=True) club_membership_expiry = models.DateField(null=True, blank=True) medical_expiry = models.DateField(null=True, blank=True) View get_context_data override def get_context_data(self, **kwargs): context = super(MembershipReport, self).get_context_data(**kwargs) members = Member.objects.all() now = date.today() thirty_days = now + timedelta(days=30) context['membership_overdue'] = members.filter(Q(membership_expiry__lte=now) | Q(membership_expiry__gte=now, membership_expiry__lte=thirty_days)) return context I've tried using date.today() datetime.now() and django's timezone.now() all three throw the same error. -
Django: Lazy Load <img>
Django 2.0, Python 3.4 view_album.html <p>Album Title Here</p> {% for image in album.get_images %} <img src="{{ image.foo }}"> {% endfor %} foo is a function which returns a url to the image. I don't want to have users wait for all the images foo functions to run and return before loading the page. Albums could contain 30+ images. I want all the images on one page, no pagination. Don't need some fancy load-while-scrolling thing. I just want the page to load and the images to load after. Is there a simple way to achieve this? -
Django combining data from separate HTML forms to Django View
I have a django application that needs to returns post.request data from two separate parts (products and entries). At the moment, the template is setup as two separate HTML forms and what I need to do is to combine it into one. Therefore upon clicking the button the values for product ID and entry quantity are both passed to the view. I can't work out how to do this so would appreciate any help. HTML Template File: <body> {% for product in products %} <form method="POST"> {% csrf_token %} {{ product.name }} <br/> {{ product.id }} <input type="hidden" name='product_id' value='{{ product.id }}'> <button>Product Object and ID</button> </form> {% endfor %} {% for cart in my_carts_current_entries %} <form method="POST"> {% csrf_token %} <br/> <input type="hidden" name='entry_quantity' value='{{ cart.quantity }}'> <button>Entry Quantity</button> </form> {% endfor %} </body> Views.py def test_view(request): cart_obj, new_obj = Cart.objects.new_or_get(request) my_carts_current_entries = Entry.objects.filter(cart=cart_obj) products = Product.objects.all() if request.POST: product_id = request.POST.get('product_id') print(product_id) product_obj = Product.objects.get(id=product_id) print(product_obj) entry_quantity = request.POST.get('entry_quantity') print(entry_quantity) # Entry.objects.create(cart=cart_obj, product=product_obj, quantity=entry_quantity) return render(request, 'carts/test.html', {'cart_obj': cart_obj, 'my_carts_current_entries': my_carts_current_entries, 'products': products}) -
DRF json 404 insetad of html page
I would like to replace default django 404 (and other in the future) with the DRF response, as easy as it is possible, just to return (standard DRF response): { "detail": "Not found." } So I put this code in my url.py file. from rest_framework.exceptions import NotFound from django.conf.urls import handler404 handler404 = NotFound When I set Debug flag (in the set Ture I'm geting 500, when set it to False 404 but in the html form. I've read doc here: http://www.django-rest-framework.org/api-guide/exceptions/ but to be honest I don't know how to put this into reality. it seems to be easy, but somehow I failed to implement this (above code comes form the other SO threads). Thank you in advance -
Can't get the authorization right while getting the Access Token from Twitter API
Following this doc, I finally got the steps 1 and 2 working by copypasting this answer. Why my original solution didn't work is still beyond me, but whatever I was doing wrong there seems to carry on in this third step, since I get an HTTP Error 401: Authorization Required. The Oauth header I produce is the following: Oauth oauth_consumer_key="omitted", oauth_nonce="ozlmgbmrxftmmfaxnngbpsulickqwrkn", oauth_signature="3ZxJu%252Bv%2FjxyPmghiI85xnuPv3YQ%253D", oauth_signature_method="HMAC-SHA1", oauth_timestamp="1518820400", oauth_token="omitted", oauth_version="1.0" which seems to be exactly the way the doc I linked in the beginning wants it. So maybe my signature is wrong? I can't really figure it out since I do it in a pretty standard way. This is my code for the callback url up until the request to oauth/access_token: def logged(request): print('Processing request from redirected user...') token = request.GET.get('oauth_token', '') user = twitterer.objects.get(oauth_token=token) #my model for the user that's signing in with twitter verifier = user.oauth_verifier = request.GET.get('oauth_verifier', '') url = 'https://api.twitter.com/oauth/access_token' dir_path = path.dirname(path.realpath(__file__)) with open(path.join(dir_path, 'credentials.txt'), 'r') as TweetCred: creds = TweetCred.read().split(linesep) oauth_consumer_key = creds[0].split()[1] consumer_secret = creds[2].split()[1] oauth_nonce = '' for i in range(32): oauth_nonce += chr(random.randint(97, 122)) oauth_timestamp = str(int(time.time())) parameter_string = ('oauth_consumer_key=' + urllib.parse.quote(oauth_consumer_key, safe='') + '&oauth_nonce=' + urllib.parse.quote(oauth_nonce, safe='') + '&oauth_signature_method=HMAC-SHA1' + '&oauth_timestamp=' + oauth_timestamp + … -
server side implementation in python, Django that will automatically perform some tasks and update my website build in Django
I want to develop a website in Django that will scrap some data from the various links, process it and stores in a database and update the website and after an hour the process of scraping, processing and updating continues. I want to know the architecture of this implementation, how it will work, how I would code my server in what technology (REST, node.js). I know this I require a database in Django project, website design but how and where can I code the loop of scrapping->process->update website. what is server side in Django? -
Django-CKEditor can't insert or drag image into rich text editor
I'm installing Django-CKEditor in Django 2.0 Now I have seen the CKEditor rich text editor,and can editor text.But I can't insert or drag image into it. I guess there are something wrong with my model. models.py: # encoding:utf-8 from django.db import models from ckeditor.fields import RichTextField # Create your models here. class Article(models.Model): title = models.CharField(max_length=50, verbose_name='文章标题') desc = models.CharField(max_length=50, verbose_name='文章描述') content = RichTextField(null=True, blank=True,verbose_name='文章内容') category = models.CharField(default="other",max_length=30, verbose_name='标签名称') date_publish = models.DateTimeField(auto_now_add=True, verbose_name='发布时间') image = models.ImageField(upload_to="media/%Y/%m", default=u"media/default.png", max_length=100) class Meta: verbose_name = '文章' verbose_name_plural = verbose_name ordering = ['-date_publish'] def __str__(self): return self.title settings.py: STATIC_URL = '/static/' MEDIA_URL = '/media/' CKEDITOR_UPLOAD_PATH = "uploads/" CKEDITOR_CONFIGS = { 'default': { 'toolbar': None, }, } urls.py: urlpatterns = [ path('blog/', include('blog.urls')), path('admin/', admin.site.urls), path(r'^ckeditor/', include('ckeditor_uploader.urls')), ] Any friend can give me some suggestions? -
Django nested transactions - “with transaction.atomic()” -- Seeking Clarification
In reference to: Django nested transactions - “with transaction.atomic()” (I'm new here and thus not allowed to comment on the original question.) The original question is: given this... def functionA(): with transaction.atomic(): #save something functionB() def functionB(): with transaction.atomic(): #save another thing ...if functionB fails and rolls back, does functionA roll back too? Kevin Christopher Henry replies with, "Yes, if an exception happens in either function they will both be rolled back." He then quotes the docs... https://docs.djangoproject.com/en/2.0/topics/db/transactions/#django.db.transaction.atomic ...which state... atomic blocks can be nested. In this case, when an inner block completes successfully, its effects can still be rolled back if an exception is raised in the outer block at a later point. This documentation quote doesn't seem to address the original question. The doc is saying that when the INNER BLOCK (which is functionB) completes successfully, its effects can still be rolled back if the OUTER block (which is functionA) raises an exception. But the question refers to the opposite scenario. The question asks, if the INNER block (functionB) FAILS, is the OUTER block (functionA) rolled back? This doc quote doesn't address that scenario. However, further down in the doc we see this example... from django.db import IntegrityError, … -
Return fields that are related to a model by a foreignkey
class SenderInfo(models.Model): #to create unique id numbers sender = models.CharField(max_length=15) id_number = models.IntegerField(blank=True, null=True) class Messages(models.Model): message_sender = models.ForeignKey(SenderInfo, related_name='messages') message_body = models.TextField() I want to just return all the messages for each instance of SenderInfo. So I can see all the messages a user has made. I know how to see the Senders of a particular message but what's the simplest method to achieve the opposite? -
Logging into a Django server with Cypress.io
Must be missing something obvious but I am very much stuck on logins into Django due to its CSRF protection. I looked Check out our example recipes using cy.getCookie() to test logging in using HTML web forms but that really doesn't help that much if the first thing it recommends is disabling CSRF. What Django wants: This is what a normal, CSRF-protected, Django login view is expecting in its incoming POST data: csrfmiddlewaretoken=Y5WscShtwZn3e1eCyahdqPURbfHczLyXfyPRsEOWacdUcGNYUn2EK6pWyicTLSXT username=guest password=password next It is not looking for the CSRF in the request headers and it is not setting x-csrf-token on the response headers. And, with my code, I am never passing in the csrf token which gets Django to return a 403 error. Cypress.Commands.add("login", (username, password) => { var login_url = Cypress.env("login_url"); cy.visit(login_url) var hidden_token = cy.get("input[name='csrfmiddlewaretoken']").value; console.log(`hidden_token:${hidden_token}:`) console.log(`visited:${login_url}`) var cookie = cy.getCookie('csrftoken'); // debugger; var csrftoken = cy.getCookie('csrftoken').value; console.log(`csrftoken:${csrftoken}:`) console.log(`request.POST`) cy.request({ method: 'POST', form: true, url: login_url, // body: {'username': 'guest', 'password': 'password', 'csrfmiddlewaretoken': cy.getCookie('csrftoken').value} body: {'username': 'guest', 'password': 'password', 'csrfmiddlewaretoken': hidden_token} }) }) Cypress's error: I suspect that the POST data has something to do with the token being undefined via the both the hidden form input or the cookie acquisition approach, as shown … -
Django error missing positional argument (request)
I am trying to build a webapp with Django and using Djano class based views to call other functions within views.py. I'm fairly new to programming and think I'm confusing myself here. I'm getting following error: make_connection_to_user() missing 1 required positional argument: 'request' Views.py: from .models import UserInfo def make_connection_to_user(request): current_user = UserInfo.objects.get(user_id=request.user.id) user_token = current_user.access_token connection = MyApp(user_token) return connection def get_user_info(): used = make_connection_to_user().users_get_space_usage().used allocated_space = make_connection_to_user().users_get_space_usage().allocation.get_individual().allocated return used, allocated class DashboardMainPage(View): def get(self, request): used_space = get_user_space_info()[0] allocated_space = get_user_space_info()[1] return render(request, 'analyzer/dashboard.html', {'used_space': used_space, 'allocated_space': allocated_space}) Urls.py: urlpatterns = [ path('dashboard/', views.DashboardMainPage.as_view(), name='dashoard'), ] -
Django Correct Usage of Models.Cascade (on_delete)
I am trying to work what is the correct usage of the models.cascade statement. I have two models Cart and Entry. If I delete an Entry the deletion is not updated on the Cart Entry. I have checked this via the admin interface. My models.py is as below: class Cart(models.Model): user = models.ForeignKey(User, null=True, blank=True, on_delete=models.CASCADE) count = models.PositiveIntegerField(default=0) total = models.DecimalField(default=0.00, max_digits=10, decimal_places=2) updated = models.DateTimeField(auto_now=True) timestamp = models.DateTimeField(auto_now_add=True) objects = CartManager() def __str__(self): return "Cart:{} User:{} Items:{} Total:£{}".format(self.id, self.user, self.count, self.total) class Entry(models.Model): product = models.ForeignKey(Product, null=True, on_delete=models.CASCADE) cart = models.ForeignKey(Cart, null=True, on_delete=models.CASCADE) quantity = models.PositiveIntegerField(default=0) -
how to properly override serializer save on a POST request in DRF?
I have a model that has a DateTime field and a serializer for that model. I have an API endpoint that is POST only to create the model object, but the problem is the service that will be POSTing to this endpoint will send a completely different date/time value, and so this will need to be correct on Django's end before creating the object. Normally (without DRF), I would just override the models save method, but now with the introduction of DRF, I'm confused if I should be override the save method for the model or the serializer? I'm thinking if I override the save method for the model so that it reformats the date/time value before saving. Then the serializer.is_valid() itself will throw an error when receiving the wrong date time format since the serializer maps directly to the model fields and has no knowledge of the models save method? What is the best way to go about doing this? models.py class Job(models.Model): name = models.CharField(max_length=150) age = models.CharField(max_length=200) start_time = models.DateTimeField() class Meta: unique_together = ('name', 'age', 'start_time') serializers.py class JobSerializer(serializers.ModelSerializer): name = serializers.CharField() age = serializers.CharField(required=False) start_time = serializers.CharField(required=False) class Meta: model = Job fields = ('name', … -
Conflict of app name in Django with old app name
I am sort of new to Django so I'm using the tutorial on the offical website here So I created an environment, installed django 2.0.2 and any other packages I needed. Then I opened a terminal and created my polls app with python manage.py startapp polls. As I progressed, I decided I wanted to do some things differently and as I'd not really progressed very far, I just deleted my project files and started fresh. However, on the second pass through when I tried creating my polls app, I get an error that "'polls' conflicts with the name of an existing Python module and cannot be used as an app name." I have tried deleting the environment and creating a new one but that doesn't work. I tried starting a brand new project, that doesn't work either. There was no problem creating the app the first time so I'm guessing that it is still located somewhere. Is there a method for completely removing apps in django 2.0.2? All the resources I've seen are for earlier versions. -
Customize raw_id field query on an inline form
How do I customize the spyglass query in an inline form for a raw_id foreignkey? I tried overriding formfield_for_foreignkey but that did nothing and I think it's because it's for dropdown foreignkeys rather than raw_id. I also tried a custom widget but that doesn't seem to work on inline. -
IntegrityError: NOT NULL constraint when trying to save a model instance
I know this has been asked a lot but none of the answers were able to help me I have two models: one that stores messages and one that stores sender info: class SenderInfo(models.Model): #to create unique id numbers sender = models.CharField(max_length=15) id_number = models.IntegerField(blank=True, null=True, default=None) class Messages(models.Model): message = models.ForeignKey(SenderInfo, related_name='messages') message_body = models.TextField() And when I try to make an instance and save() it I keep getting IntegrityError: NOT NULL constraint failed: appconvo_messages.message_id -
How to insert dynamic data from HTML file to DynamoDB through Django?
I am trying to insert dynamic data from HTML form to DynamoDB table via Django. I am using put-item to insert a single item, but I can't figure out how to access the field using ID (If that is possible) and insert data IN DynamoDB using that ID? Please help ! I am posting the code below. views.py def Contact(request): if request.POST: name = request.GET.get('name') email = request.GET.get('email') subject = request.GET.get('subject') message = request.GET.get('message') Contact.object.create(name, email, subject, message) models.py import boto3 # Get the service resource. from django.db import models dynamodb = boto3.resource('dynamodb', region_name="us-west-2", endpoint_url="http://localhost:8080") class Contact(models.Model): name = models.CharField(max_length=32, unique=True) email = models.CharField(max_length=32, unique=True) subject = models.CharField(max_length=32, unique=True) message = models.CharField(max_length=32, unique=True) Contact.object.create(name, email, subject, message) table = dynamodb.Table('ContactForm') table.put_item( Item={ 'name': models.Contact.name, 'email': models.Contact.email, 'subject': models.Contact.subject, 'message': models.Contact.message, } ) print("Put Item Success") -
Stripe does not accept my token
I am trying to create a django shopping site. But I can't get stripe to work. I don't belive it is anything workng in my code. It works fine withe the "tok_visa" sendt with javascript. But it does not accept my token. I have even tried manuelly writing it in. views.py if form.is_valid(): token = form.cleaned_data['token'] try: stripe.Charge.create( amount = 20000, currency = "nok", description = ""+form.cleaned_data['etternavn']+", "+form.cleaned_data['fornavn'], source = token, ) form.save() return HttpResponse("<p>"+form.cleaned_data['fornavn']+"</p>") except stripe.CardError as e: form.add_error("Kortet ble ikke akseptert "+token) Jquery Stripe.setPublishableKey('pk_test_H1PZQA7ypCa8UIlEy6S9ovhE'); $( '#payment-form' ).submit(function(e){ $form = $(this); $form.find('button').prop('disabled', true); Stripe.card.createToken($form, function(status, response){ if(response.error){ $form.find('.payment-errors').text(response.error.message); $form.find('button').prop('disabled', false); } else{ var token = response.id; $form.find('input[id="id_token"]').val(token); $('#id_token').val(token); $form.get(0).submit(); } }); return false; }); Thank you for the help -
How to do a Customer Logger for Django to Capture Response and Request
I'm looking into differen't ways to capture the response object, request object, and performance in Django to create a custom json elk logger that will build audit logs. I'm not sure what approach is best to take here. I was looking at custom middleware but I've never done that. I tried to look up if it was possible to use a decorator to do this but doesn't seem like it. Also, I use the django rest framework so I also have to figure out how to integrate the middleware if thats the route or whatever solution to DRF as well. Looking for suggestions. -
Why do I not get any content with python requests get, but still a 200 response?
I'm doing a requests.get(url='url', verify=False), from my django application hosted on an Ubuntu server from AWS, to a url that has a Django Rest Framework. There are no permissions or authentication on the DRF, because I'm the one that made it. I've added headers such as headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'}, but wasn't able to get any content. BUT when I do run ./manage.py shell and run the exact same command, I get the output that I need! -
AttributeError when creating a new user
I am getting this error: Internal Server Error: /signup/ Traceback (most recent call last): File "C:\python\lib\site-packages\django\core\handlers\exception.py", line 41, in inner response = get_response(request) File "C:\python\lib\site-packages\django\utils\deprecation.py", line 142, in __call__ response = self.process_response(request, response) File "C:\python\lib\site-packages\django\middleware\clickjacking.py", line 32, in process_response if response.get('X-Frame-Options') is not None: AttributeError: 'str' object has no attribute 'get' When trying to render this view: def signup(request): if request.method == 'POST': form = SignUpForm(request.POST) if form.is_valid(): new_user = form.save(commit=False) new_user.is_active = False new_user.save() current_site = get_current_site(request) subject = "Activate your DC-Elects account" message = render_to_string('registration/account_activation_email.html', { 'user': new_user, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(new_user.id)), 'token': account_activation_token.make_token(new_user), }) new_user.email_user(subject, message) return reverse('elections:account_activation_sent') else: form = SignUpForm() return render(request, 'registration/signup.html',{ 'form': form, }) The error message is not very descriptive, but the email is sending with the link correctly, so I'm very confused as to why there is an error. How do I prevent this error and render the next view correctly? -
how to run our function in Django restframwork
I want to run my function to do something in a request to url of serializer my serializer : class usersSerializer(ModelSerializer): class Meta: model=users fields="__all__" my view for serializer: class usersCreate(generics.CreateAPIView): queryset=users.objects.all() serializer_class=usersSerializer my function: def f(): now=datetime.now() now10=now + timedelta(minutes = 10) quer=users.objects.last() rcode=randint(1000,9999) a=SMS(users_id=quer,code=rcode,expireTime=now10) a.save() SMS is another table users_id ====> foreigne key to id in users table I want to when I send request to user create url changed two table : users SMS models: class users(models.Model): number=models.CharField(verbose_name="userNumber",max_length=11) name=models.CharField(verbose_name="name",max_length=40) createTime=models.DateTimeField( auto_now_add=True,auto_now=False) status=models.BooleanField(default=False) class SMS(models.Model): users_id=models.ForeignKey(users,on_delete=models.CASCADE,default=0) code=models.PositiveSmallIntegerField(verbose_name="randomCode") expireTime=models.DateTimeField() status=models.BooleanField(default=False) -
Django won't serve on Apache/Fedora 23 VM since i changed PCs
I recently got a new PC and put my Fedora 23/Apache VM on it. I had Django site serving successfully previously through this VM before switching PCs. Now when i run: systemctl start httpd.service i don't appear to get errors, but when i put the ip address (inet, non-loopback) in my web browser, nothing happens, no data is sent. my etc/hosts file: 127.0.0.1 localhost localhost.localdomain localhost4 localhost4.localdomain4 ::1 localhost localhost.localdomain localhost6 localhost6.localdomain6 my httpd.conf file: ServerName localhost when i run 'hostname -f', i get "localhost". is there another IP address i need to add to any of the above files in order to get this working? i looked at other posts related to this, but couldn't figure out which IP address, if any, to add. help? -
Overwrited delete method doesn't work when cascading delete
I have an application which simulates the comportment and arborescence of xml balises. My first model, IdBalise, is used to link parents with children. It is linked with diferent balise models with a GenericForeignKey : class IdBalise(models.Model): idBalise=models.AutoField(primary_key=True) parent = models.ForeignKey('IdBalise', on_delete=models.CASCADE, related_name="parentbal", null=True, blank=True) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') I use then many balise models like the one below : class BiblBalise(Balise): idbal = GenericRelation(IdBalise, content_type_field="content_type", object_id_field="object_id", on_delete=models.CASCADE) baliseName='bibl' In order to delete the balise content when I delete an IdBalise, I overwrited the delete method of IdBalise : def delete(self): self.content_object.delete() super(IdBalise, self).delete() It works perfectly. When I delete an IdBalise, its related content (for instance, the entry in BiblBalise) is deleted. My problem is, when I delete a parent, the children's content doesn't delete. The children IdBalise are deleted, because of the on_delete=models.CASCADE on the "parent" field. But their content (for instance, the entry in BiblBalise) isn't deleted. Why my overwrited delete method doesn't work when the children IdBalise is deleted ? Any ideas ? Thanks