Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
'str' object has no attribute 'get' django error
I am creating a login form and after filling up the information it is showing 'str' object has no attribute 'get' error views.py file: from django.shortcuts import render,redirect from django.contrib import messages from django.contrib.auth.models import User, auth # Create your views here. def login(request): if request.method == 'POST': username= request.POST['username'] password = request.POST['password'] user = auth.authenticate(username=username,password=password) if user is not None: auth.login(request,user) return("home") else: messages.info(request,"invalid credentials") return redirect('login') else: return render(request,'buy/login.html') -
Not able to refer RabbitMQ used with docker by the image name when deployed on AWS Elastic Beanstalk
I have a docker-compose.yml file on my local machine as: version: '3' services: web: &my_web_app build: . command: gunicorn MyApp.wsgi --workers 3 ports: - "80:8000" depends_on: - rabbitmq rabbitmq: image: rabbitmq:management celery_worker: <<: *my_web_app command: celery -A MyApp worker --autoscale=10,1 --loglevel=info ports: [] depends_on: - rabbitmq Later, I uploaded the docker image named web to my docker registry named myName/web:latest. After that, I created a Dockerrun.aws.json as follows: { "AWSEBDockerrunVersion": 2, "Authentication": { "Bucket": "cred-keeper", "Key": "index.docker.io/.dockercfg" }, "containerDefinitions": [{ "Authentication": { "Bucket": "cred-keeper", "Key": "index.docker.io/.dockercfg" }, "command": [ "celery", "-A", "MyApp", "worker", "--autoscale=10,1", "--loglevel=info" ], "essential": true, "image": "myName/web:latest", "name": "celery_worker", "memory": 175 }, { "essential": true, "image": "rabbitmq:management", "name": "rabbitmq", "memory": 175, "portMappings": [{ "containerPort": 5672, "protocol": "tcp", "hostPort": 5672 }] }, { "Authentication": { "Bucket": "cred-keeper", "Key": "index.docker.io/.dockercfg" }, "command": [ "gunicorn", "MyApp.wsgi", "--workers", "4" ], "essential": true, "image": "myName/web:latest", "memory": 256, "name": "web", "portMappings": [{ "containerPort": 8000, "hostPort": 80 }] } ], "family": "", "volumes": [] } The image named web is a Django (Python's web framework) app, where I used to access my RabbitMQ container using a URL that used the container name in the app like amqp://rabbitmq:5672 and it used to work perfectly fine … -
Django update_or_create not updating but inserting instead
I am not able to update rows in django model when using update_or_create(). It will create a new row but not update it. I don't get any error after running this code in command line. I am sure I am doing something wrong but I cannot figure out what. model.py class Test(models.Model): id = models.AutoField(primary_key=True) date = models.CharField(blank=True, max_length=100, unique=True) bites = models.CharField(blank=True, max_length=100) imgs = models.CharField(blank=True, max_length=100) .\manage.py shell from status.models import Test import pandas as pd d1 = pd.read_csv('data1.csv') 2020-02-10 2355975072768 939 d2 = pd.read_csv('data2.csv') 2020-02-10 2355975072768 938 for model in d1.itertuples(): model, created = Test.objects.update_or_create(date=model.date, bites=model.total_bytes, imgs=model.total_files, defaults={'date': model.date, 'bites':model.total_bytes, 'imgs':model.total_files }) database_sqlite3 output: 1|2020-02-10|2355975072768|939 for model in d2.itertuples(): model, created = Test.objects.update_or_create(date=model.date, bites=model.total_bytes, imgs=model.total_files, defaults={'date': model.date, 'bites':model.total_bytes, 'imgs':model.total_files }) database_sqlite3 output: 1|2020-02-10|2355975072768|939 2|2020-02-10|2355975072768|938 -
Get the value of CharField as integer
I got a model looking like below. I want to get the value of the CharField as 23 not '23' as an example. How can I best approach this without hackie solutions? Use case: I need the price per unit to be timed with the quantity amounts and then it should add the chosen amount of VAT (Which is percentages of the total value of unit price and unit quantity) on top of it class InvoiceItem(models.Model): VAT_AMOUNT = ( ('0', '0%'), ('5', '5%'), ('8', '8%'), ('23', '23%') vat_rule = models.CharField(choices=VAT_AMOUNT, default=23) unit_price = models.DecimalField(max_digits=8, decimal_places=2) quantity = models.DecimalField(max_digits=8, decimal_places=0, default=1) def __str__(self): return self.service def get_total_unit_price(self): item_total = self.unit_price * self.quantity * (1 + self.vat_rule / 100) total = round(item_total, 2) -
django create objects from nested json tree
In my app, i have multiple trees of folders made by self referential foreign keys, each tree has a make and all of them have the same structure. When i'm creating a new make i want to duplicate one of the trees and that isn't hard, for that part i've made a signal, but i don't know how to manage the parent part for the new tree: models.py class Documentation(models.Model): make = models.ForeignKey(Make, blank=True, null=True, default=None, on_delete=models.CASCADE) name = models.CharField(max_length=200) parent = models.ForeignKey('self', blank=True, null=True, default=None, related_name='children', on_delete=models.CASCADE, verbose_name='Folder') def __str__(self): return self.name I had a few unsuccessful attempts and i've kinda ran out of ideas. First try: obj = Make.objects.first() for doc in obj.documentation_set.all(): if not doc.parent: doc.name = instance.name # replace the index folder's name (this should be different) doc.pk = None doc.make = instance doc.save() Second attempt, making a json family tree and try to create objects based on it, but i should make a dynamic for loop because the structures might change at some point and i haven't managed to make a piece of code that would iterate and create objects out of it: def get_family_tree(doc): children = doc.children.all() data = dict() if not children: data['name'] … -
Django RF error related to hyperlinked relationship
I am new to Django RF, I am getting this error and stuck with it for 2 days now, I can't figure out how to resolve this and continue, I tried what I could in various ways and this isn't working. In normal django, I use the PostImage model with a formset so that I can upload and store multiple images, but here I am not sure how this works. Error Could not resolve URL for hyperlinked relationship using view name "posts_api:detail_post". You may have failed to include the related model in your API, or incorrectly configured the `lookup_field` attribute on this field. These are the codes I have. serializer class PostImageSerializer(serializers.HyperlinkedModelSerializer): post = serializers.ReadOnlyField() class Meta: model = PostImage fields = ['post', 'images',] # in django this is a formset class PostSerializer(serializers.HyperlinkedModelSerializer): user = serializers.ReadOnlyField(source='user.username') post_date = serializers.ReadOnlyField() postimage_set = serializers.HyperlinkedRelatedField(many=True,read_only=True,view_name='posts_api:detail_post',) class Meta: model = Post fields = ['id','title', 'post_date', 'updated', 'image', 'slug', 'user', 'postimage_set'] # the image in this field is of Post model views def create_post_api_view(request): user = request.user post = Post(user=user) serializer = PostSerializer(post, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) def detail_post_api_view(request, slug): try: post = Post.objects.get(slug=slug) except Post.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) serializer … -
django unnecessary query in Form and View
I am a newbie of django. Please help me There is the API which delete alchol object from like_alchlols field in My Model, but i think there are unnecessary queries. So i want to fix it beauty My Model class MyUser(AbstractBaseUser): user_id = models.CharField(max_length = 200, unique=True) like_alchols = models.ManyToManyField(Alchol, through='MyUserAlchol', blank=True) My Form class DeleteLikeAlcholForm(forms.Form): user_id = forms.CharField() alchol_id = forms.CharField() def clean_user_id(self): data = self.cleaned_data['user_id'] try : obj = MyUser.objects.get(user_id = data) except ObjectDoesNotExist: raise forms.ValidationError("MyUser object does not exist") return data def clean_alchol_id(self): user_id = self.cleaned_data['user_id'] data = self.cleaned_data['alchol_id'] try : obj = Alchol.objects.get(pk=data) except ObjectDoesNotExist: raise forms.ValidationError("invalid alchol_id") try : myUser = MyUser.objects.get(user_id = user_id) obj = myUser.like_alchols.get(pk=data) except ObjectDoesNotExist: raise forms.ValidationError("You dont like this alchol") return data My View class DeleteLikeAlcholView(APIView): parser_classes = [FormParser] def post(self,request): LOG.info("Request DeleteLikeAlcholView") LOG.info_items(request.POST.items()) form = DeleteLikeAlcholForm(request.POST) status = form.is_valid() if status == False: msg = form.errors.as_json() LOG.info(msg) return JsonResponse({"status" : status, "msg" : msg}) user_id = request.data['user_id'] alchol_id = request.data['alchol_id'] user = MyUser.objects.get(user_id=user_id) alchol = Alchol.objects.get(pk = alchol_id) user.like_alchols.remove(alchol) msg = "Success to remove like_alchol" return JsonResponse({"status" : status, "msg" : msg}) As above, queries occur for searching MyUser object and Alchol object please help me -
'import scipy' hangs in python django after deploying on apache2
I wrote a python django app that imports scipy, as well as many other python modules. It runs perfectly fine when I run django's development server. Recently I deployed the app on apache2. It runs very smoothly and everything looks fine until the app tries to import scipy. Then the site hangs and does nothing. No error message appears in the apache logs. When I run django with DEBUG=True I also don't get an error message, but instead the site just hangs. Scipy was installed with pip in a virtual environment, just like all the other modules (django, wagtail, numpy, and dozens others). Only scipy gives these problems, all the others work fine. I reinstalled scipy, with no effect. When I run python on the command line (using the same virtual env) and I import scipy, it works. So it looks like it's specific to apache2. I'm stumped and I'm not sure where to even look or debug anymore, given that only scipy has this issue even though it didn't get any special treatment compared to the other modules. I'm also not sure what additional info would be pertinent here. If anyone has a suggestion then I would be happy … -
Django admin page written text is not displaying on web page
Ignore the title. I got problem on displaying text written and save on admin page. I just create new app with name about. using command python manage.py startapp about and all the below files are inside this app. Models.py from django.db import models # Create your models here. class About(models.Model): title = "About me" discription = models.TextField() def __str__(self): return self.title admin.py from django.contrib import admin from .models import About # Register your models here. admin.site.register(About) # Register your models here views.py: from django.shortcuts import render from django.http import HttpRequest from .models import About # Create your views here. def about(request): abouts = About.objects.all() return render(request, 'about/about.html', {'abouts': abouts}) urls.py from django.urls import path from . import views app_name = 'about' urlpatterns = [ path('', views.about, name='about'), ] about.html <p style="color: white;">{{ abouts.discription }}</p> Problem is that the text written inside discription didn't showing on about.html page. please help me. -
Best way in Django to allow user-customizable field labels
I would like to add several generic text fields to a model and allow the user (customer) to decide what to label them. For example, with an "asset" model, one customer may want to track "location" while a different customer may want to track "owner". The label would be global for an application deployment. I've searched the docs and SO for a recommended way to do this but I can't find anything. Most related answers talk about using the inner Meta class in the models, but that doesn't allow user customization. EDIT: To clarify, I'm only looking to allow customization of the label that is visible on the GUIm. I don't care what the actual field names are under the covers (they could be field1, field2, etc.) Two ideas that I came up with are: Store the label names in a config file. It would be trivial to have the customer edit the text file to customize it, but a little more complicated to allow them to modify it in the admin GUI and save the updated config. Create a "customizations" model that has label names, and create a single instance. That has the benefit of making it easily modifiable … -
How to use Reportlab in a Django project
I was wondering how could I create a pdf report using reportlab. I'm developing a web site and I'm using Django. In my project I charged a lot of icons, and I was using a Javascript function(PrintThisjs), but it doesn't work well. Seems like Reportlab is a good solution. Thanks :) -
Django send email with digital signature
Please, help me send Django email with signature. It must be like it I'm try this. But I don't now how get signature. signature = str(gpg.sign(basetext, detach=True)) Now signature is None. body = """ This is the original message text. :) """ basemsg = MIMEText(body) gpg = gnupg.GPG() basetext = basemsg.as_string().replace('\n', '\r\n') signature = str(gpg.sign(basetext, detach=True)) if signature: signmsg = messageFromSignature(signature) msg = MIMEMultipart(_subtype="signed", micalg="pgp-sha1", protocol="application/pgp-signature") msg.attach(basemsg) msg.attach(signmsg) print(msg.as_string(unixfrom=True)) else: print('Warning: failed to sign the message!') -
Old celery periodic tasks still running
So I have been battling this issue for a while now and will need help with it. I have been a periodic task that used to run every day at 11pm. This task generates reports for each user. I then changed it to run every 10 minutes instead, instead it ignores all of the new instructions to generate the reports and only does them at the same 11pm. I tried deleting the tasks from the database (using django-celerybeat) but the problem still persists. I am using redis. Right now what I want is a sure way of actually starting all the tasks from the ground up, without having old tasks pop up. How do I clean the tasks and make sure this same task never comes up? -
How to implement CCAvenue Order status and refund API with Python?
CCAvenue OrderStatus and Refund API are not working for me. I tried the following URL but it returns a blank response. https://secure.ccavenue.ae/transaction/transaction.do?command=orderStatusTracker&enc_request=<entrypted_data>&access_code=<accesscode>&request_type=STRING%version=1.1 -
How to resolve No Reverse Match in Django
I am having this error when i try to post a new post, it was not giving me the error before not until I added file upload function to the create post page and now when I try to create posts after uploading files in get this error NoReverseMatch at /post/new/ Reverse for 'post-detail' not found. 'post-detail' is not a valid view function or pattern name. Here is my views.py codes below from django.contrib import messages from django.contrib.auth.mixins import (LoginRequiredMixin, UserPassesTestMixin) from django.contrib.auth.models import User from django.urls import reverse_lazy, reverse from django.http import HttpResponseRedirect, Http404 from django.shortcuts import render, get_object_or_404 from django.views.generic import (ListView, DetailView, CreateView, UpdateView, DeleteView) from .models import Post, Comment from django.core.files.storage import FileSystemStorage from .forms import CommentForm from . import models def home(request): context = { 'posts': Post.objects.all() } return render(request, 'blog/home.html', context) def upload(request): if request.method == 'POST': uploaded_file = request.FILES['document'] fs = FileSystemStorage() fs.save(uploaded_file.name, uploaded_file) return render(request, 'blog/post_form.html') class PostListView(ListView): model = Post template_name = 'blog/home.html' context_object_name = 'posts' ordering = ['-date_posted'] paginate_by = 6 class UserPostListView(ListView): model = Post template_name = 'blog/user_posts.html' context_object_name = 'posts' paginate_by = 6 def get_queryset(self): user = get_object_or_404(User, username=self.kwargs.get('username')) return Post.objects.filter(author=user).order_by('-date_posted') class PostDetailView(DetailView): model = Post def post_comment(request, … -
unitest.mock.patch creates a TypeError in client.get()
I have a function based view (simplified below): views.py from .utils import mailgun_validate_email def check_existing_contacts(request): return mailgun_validate_email(request) utils.py def mailgun_validate_email(request): // some code I want to test that it calls the mailgun_validate_email function (also coincidentally a view). I understand you have to patch the path where the function is imported (myapp.views.mailgun_validate_email) rather than where the code lives (myapp.utils.mailgun_validate_email). @patch('myapp.views.mailgun_validate_email') def test_new_contact(self, mock): Client().get('/contacts/validate_contact/') self.assertTrue(mock.called) self.assertEqual(mock.call_count, 1) However this approach results in a TypeError (the test works fine without the Mock): Failure Traceback (most recent call last): File "\tests\test_utils.py", line 123, in test_new_contact response = self.client.get('/contacts/validate_contact/', File "\.venv\lib\site-packages\django\test\client.py", line 518, in get response = super().get(path, data=data, secure=secure, **extra) File "\.venv\lib\site-packages\django\test\client.py", line 344, in get return self.generic('GET', path, secure=secure, **{ File "\.venv\lib\site-packages\django\test\client.py", line 421, in generic return self.request(**r) File "\.venv\lib\site-packages\django\test\client.py", line 496, in request raise exc_value File "\.venv\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "\.venv\lib\site-packages\django\utils\deprecation.py", line 96, in __call__ response = self.process_response(request, response) File "\.venv\lib\site-packages\django\contrib\sessions\middleware.py", line 45, in process_response patch_vary_headers(response, ('Cookie',)) File "\.venv\lib\site-packages\django\utils\cache.py", line 267, in patch_vary_headers vary_headers = cc_delim_re.split(response['Vary']) TypeError: expected string or bytes-like object Where am I going wrong? -
How can I include a template inside another template?
Im new to programming and I looking if there is there a way that I can include a template inside other template. Im working on a project that I want to display on the same page a content of a certain topic and flashcards to test my knowledge of this topic, and Im stuck when trying to display my cards on the same page (I could only make it work using another url). Here is what I have so far: models.py: class Topic(models.Model): author = models.ForeignKey( User, related_name="topic", on_delete=models.CASCADE, null=True) title = models.CharField(max_length=100) body = RichTextUploadingField(blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True) slug = models.SlugField(max_length=120) class Meta: ordering = ["title"] def __str__(self): return self.title def get_absolute_url(self): return reverse('topic:topic-detail', kwargs={ "topic_slug": self.slug,}) class Deck(models.Model): deckTopic = models.ForeignKey( Topic, null=True, blank=True, on_delete=models.CASCADE) description = models.CharField(max_length=510, null=False, blank=True) is_active = models.BooleanField(default=False) def __str__(self): return self.description def get_number_of_cards(self): ''' Returns the number of cards in the decks related card_set ''' return self.card_set.count() get_number_of_cards.short_description = 'Card Count' class Card(models.Model): parentDeck = models.ForeignKey(Deck, on_delete=models.CASCADE) front = models.TextField() back = models.TextField() def __str__(self): return self.front def has_prev_card(self): ''' Returns true if card is not thee first card in the deck. ''' first_card_in_deck = self.parentDeck.card_set.first() if self == first_card_in_deck: return … -
Deleting Label that was created in Models
Hello I have a project where I have a form to post something, but when I am rendering it I become an ugly label. I was wondering if it is possible to delete it. Thanks... I also posted a picture where you can see what I want to delete I searched a lot and found that I can rename the label or set the auto_id to false but they didnt helped maybe I made it wrong views.py class PostList(LoginRequiredMixin,generic.CreateView): template_name = 'home.html' form=PostForm model = PostModel fields=['post'] success_url="/home" def form_valid(self, form): form.instance.author=self.request.user return super().form_valid(form) models.py class PostModel(models.Model): post = models.TextField(max_length=256, unique=True) slug = models.SlugField(max_length=20, unique=True) author = models.ForeignKey(User, on_delete= models.CASCADE,related_name='blog_posts') created_on = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['-created_on'] def save(self, *args, **kwargs): self.slug = self.slug or slugify(self.post) super().save(*args, **kwargs) def __str__(self): return self.post forms.py from .models import PostModel from django import forms from crispy_forms.helper import FormHelper class PostForm(forms.ModelForm): class Meta: model=PostModel fields=['post','author'] unlabelled_fields=('post') def __init__(self, *args, **kwargs): super(PostForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_show_labels = True for field in PostForm.Meta.unlabelled_fields: self.fields[field].label = False home.html [![{% extends "base.html" %} {%block content%} {% load crispy_forms_tags %} <div class="container"> <div class="row"> <!-- Blog Entries Column --> <div class="col-md-6 mt-3 left mx-auto"> {% for … -
Django and Facebook login JS_SDK
I have integrated facebook login using facebook JS_SDK. All the functions like login logout are controlled by facebook login javascript. I was wondering if there's any way to know from django backend that facebook user is logged in? -
Use list of data to make a Table using DjangoTables2
I have a function to query my PostgreSQL database, and it will return a list of records. In views.py I could have: import models data = models.table_data("test_1") #returns for example: [[ID_1, Joe, 28] [ID_2, Lisa, 31] ... ] and data would be bound to the list of records in the table "test_1". Now, I would like to use django_tables 2 to render tables using this data. However, all the tutorials/code I've found online make use of models within models.py How can I make a simple Table with this list? -
Django admin not showing all the rows from the database
Code in admin.py class social_postAdmin(admin.ModelAdmin): list_display= ('id','user_name','image_tag','media_url','media_type','desc','desc_telugu','location_id','friend_id','hashtag_id') readonly_fields = ['image_tag'] def user_name(self,obj): return ('%s'%(obj.user_id.full_name)) admin.site.register(social_post,social_postAdmin) Code in models.py from django.utils.html import mark_safe class social_post(models.Model): id = models.AutoField(primary_key=True,unique=True) user_id = user_id = models.ForeignKey(user, on_delete=models.CASCADE) media_file = models.FileField(null=True,blank=True) media_url=models.TextField(blank=True,null=True) media_type = models.TextField(blank=True, null=True,choices=MEDIA_TYPE) desc = models.TextField(blank=True, null=True) desc_telugu = models.TextField(blank=True, null=True) location_id = ArrayField(models.CharField(max_length=120),blank=True, null=True) friend_id = ArrayField(models.CharField(max_length=120),blank=True, null=True) hashtag_id = ArrayField(models.CharField(max_length=120),blank=True, null=True) timestamp = models.DateField(blank=True, null=True) #approved = models.BooleanField(default=True) def image_tag(self): return mark_safe('<a href="%s"><img src="%s" width="150" height="150" /></a>' % (self.media_url,self.media_url)) image_tag.short_description = 'Image' I've checked in the database it shows 6 rows but some of them are not appearing on Django admin dashboard...... What is wrong in this code ??? -
How to debug patched method with unittest.mock
I have the following (simplified) FBV: def check_existing_contacts(request): if request.is_ajax and request.method == "GET": print('Function called') return mailgun_validate_email(request) return JsonResponse({"error": "Incorrect AJAX / GET request."}, status=400) I want to test that the mailgun_validate_email function is called: class TestCheckExistingContacts(TestCase): @patch('myapp.mailgun_validate_email') def test_new_contact(self, mock): client = Client() client.get('/check/', HTTP_X_REQUESTED_WITH='XMLHttpRequest') self.assertTrue(mock.called) I am certain the test calls mailgun_validate_email as the print('Function called') displays in the console. However I get an assertion error that the mock.called is False. Where am I going wrong / how can I debug this? -
Error while deploying my Webapp on heroku
2020-07-24T12:14:43.466839+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/" host=scrapyo.herokuapp.com request_id=93b89922-1e3b-4633-8faa-788a0eb031a6 fwd="47.9.76.163" dyno= connect= service= status=503 bytes= protocol=https 2020-07-24T12:14:44.700297+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/favicon.ico" host=scrapyo.herokuapp.com request_id=7374efcb-77f1-4de2-9f7a-d5d8f62427a0 fwd="47.9.76.163" dyno= connect= service= status=503 bytes= protocol=https -
why .isalnum() function not working in python-Django
.isalnum() not working i.e it doesnt validate the username characters key.I am testing on postman but .isalnum() doesnt validate any characters like !@#$%^&*(). Can you tell me, why .isalnum() not working in my case? view.py from django.views import View import json from django.http import JsonResponse class UsernameValidationView(View): def post(self,request): data = json.loads(request.body) username = data['username'] if not str(username).isalnum(): return Jsonresponse({'username_error': 'Username should contains letter between A-Z and 0-9'}, status = 400) return JsonResponse({'username_valid': True}) urls.py from .views import * from django.urls import path from django.views.decorators.csrf import csrf_exempt urlpatterns = [ path('register', RegistrationView.as_view() , name ="register"), path('validate_username', csrf_exempt(UsernameValidationView.as_view()), name="validate_username") ] -
How to use socket programming in django admin list page
I wanna make a real time updating list view in Django admin panel. How I can apply django-channels on django-admin list page.