Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Breaking a forloop in django
I am currently working on a dna to protein translator. The code works pretty well. However, I'd like to improve it with some if statements: Here's the views.py code where I type the if statements: class TranslatorView(View): template_name = 'main/translated.html' stop_codon= { "taa":"Stop", "tag":"Stop", "tga":"Stop", "TAA": "Stop", "TAG": "Stop", "TGA": "Stop", } def translate_amino(self, codon): return self.amino_mapper.get(codon, "") def build_protein(self, request, phrase): if len(phrase) % 3: messages.error(request, 'CHAIN MUST BE DIVISIBLE BY 3') return () protein = [] for i in range(0, len(phrase), 3): codon_stop= self.stop_codon.get(phrase,"") amino = self.translate_amino(phrase[i: i + 3]) if amino: protein.append(amino) elif not amino: messages.error(request, "PROTEIN WAS NOT FOUND") return () elif codon_stop: #Here's where I think the error is: break return protein What I want to do is if the function detects a phrase from stop_codom, the for loop should break. However, the for loop still continues. -
Django Forms: Connecting two functions together for Email Verification
I have created a basic Create User form (username, email, password1, password2) called CreateUserForm and i would like to create an email verification process. It is simple enough to do using one function. But i want to add an additional function that asks the user to accept Terms and Conditions before a verification email is sent. In addition the terms and conditions has to be on a separate html template page. I have also created a Terms and Conditions form which is just a simple BoolianField. I am getting an error saying: ''User' object has no attribute 'get'. Do i have to use a request.get somewhere in my code? A steer in the right direction would be helpful. My code is below: view.py: def registerPage(request): form = CreateUserForm() if request.method =='POST': form = CreateUserForm(request.POST) if form.is_valid(): instance = form.save(commit=False)# Save user data but do not commit to database return redirect('accept_terms') and instance #accept_terms is the name of the registration/terms_and_conditions.html else: form = CreateUserForm() return render(request,'registration/register.html', {'form': form}) def AcceptTerms(request): form = Terms_Conditions() if request.method =='POST': form = Terms_Conditions(request.POST) if form.is_valid(): userform = registerPage # I want to get the saved User data from the registerPage function send_verification_email(request, userform) #Sends verification … -
Django rest_framework / validate PATCH request
I'm new in Django Rest framework. I'm trying to do some test task (simple RestAPI service) but it failed. I've created model Order, serializer OrderSerializer(HyperlinkedModelSerializer), and OrderViewSet(ModelViewSet). (nothing special, use code from tutorial). I tested GET/POST and it works good. But PATCH request works strange. I do PATCH with different fields in payload (which don't exist in the model) and there is no error in response, response code is 200 always. models.py class EOrderStatus(Enum): Unknown = 0 Created = 1 Paid = 2 Failed = 3 class Order(models.Model): _status = models.SmallIntegerField(default=EOrderStatus.Created.value) create_date = models.DateTimeField(default=now, editable=False) pay_date = models.DateTimeField(blank=True, null=True) description = models.CharField(max_length=50, blank=True) serializers.py class OrderSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Order fields = ['id', 'status', 'create_date', 'pay_date', 'description'] views.py class OrderViewSet(viewsets.ModelViewSet): queryset = Order.objects.all() serializer_class = OrderSerializer PATCH /api/orders/1, status code 200 { "dessssss": "aaa", "statttttt": "11" } My question is: why status code is 200? I supposed that I must to receive error something like "invalid fields ...". Do I need to write patch-validator for each model/serializer? And 2nd question: model Order contains enum-field _status. What is the best way don't use _status in request/response, but use property "status" instead? (string type, EOrderStatus.Created.name) -
Django static files are not getting copied into docker container on second time build
My docker container got buggy somehow. So I refactored a bit and made it up and running. After making some changes in my CSS files, I noticed the files doesn't reflect. Then I rebuild the image, run the container again. The result is the same. Previously copied changes are inside the container, not new edits. Here's my Dockerfile FROM python:3.7-alpine # set environment variables ENV PYTHONUNBUFFERED 1 COPY requirements.txt . RUN apk add --no-cache --virtual .build-deps \ ca-certificates gcc linux-headers musl-dev \ libffi-dev jpeg-dev zlib-dev \ && pip install -r requirements.txt \ && find /usr/local \ \( -type d -a -name test -o -name tests \) \ -o \( -type f -a -name '*.pyc' -o -name '*.pyo' \) \ -exec rm -rf '{}' + \ && runDeps="$( \ scanelf --needed --nobanner --recursive /usr/local \ | awk '{ gsub(/,/, "\nso:", $2); print "so:" $2 }' \ | sort -u \ | xargs -r apk info --installed \ | sort -u \ )" \ && apk add --virtual .rundeps $runDeps \ && apk del .build-deps RUN mkdir /code WORKDIR /code COPY . . EXPOSE 8000 RUN python manage.py collectstatic --noinput # Tell uWSGI where to find your wsgi file (change this): ENV … -
Django: Join two tables in a single query
In my template I have a table which I want to populate with data from two different tables which use foreign-keys. The solution I find while googling around is to use values(), example of my queryset below: data = Table1.objects.all().filter(date=today).values('table2__price') My template {% for item in data %} <tr class="original"> <td>{{ item.fruit }}</td> <td>{{ item.table2__price }}</td> </tr> {% endfor %} It do fetch price from table2, but it also make the data (item.fruit) from Table1 disappear. If I remove the values field, Table1 populates accordingly. Anyone have any feedback of what I am doing wrong? Thanks -
Graphene response None even when it works on server
I was added to a project where we use Graphene and Graphene-django-plus, and i'm making a test for a resource that uploads a file, and link with other 2 tables, my module is like this Model class ClientDocumentation(Resource, File): file = models.FileField(upload_to='uploads/', null=True) client = models.ForeignKey(Client, on_delete=models.CASCADE) document = models.ForeignKey(Document, on_delete=models.CASCADE) class Meta: db_table = 'client_documentation' Schema class ClientDocumentationType(ModelType): class Meta: model = ClientDocumentation interfaces = [graphene.relay.Node] connection_class = CountableConnection permissions = ['view_clientdocumentation'] filter_fields = { #'nombre': ['exact', 'icontains', 'istartswith'], #'habilitado': ['exact'] } class ClientDocumentationCreate(ModelCreateMutation): class Meta: model = ClientDocumentation exclude_fields = ["creado_en", "actualizado_en"] allow_unauthenticated = True permissions = ['add_clientdocumentation'] documentation_type = graphene.Field(ClientDocumentationType) @classmethod def mutate_and_get_payload(cls, root, info, **data): client_id = from_global_id(data["client"])[1] client = Client.objects.get(id=client_id) document_id = from_global_id(data["document"])[1] document = Document.objects.get(id=document_id) documentation = ClientDocumentation.objects.create( client=client, document=document, file=data["file"] ) return cls(documentation_type=documentation) Test def test_create(self): documentation = self.documentation.build() client = self.client.create() client.id = to_global_id(type='ClientType', id=client.id) document = self.document.create() document.id = to_global_id(type='DocumentType', id=document.id) response = self.client.execute( ''' mutation ($input: ClientDocumentationCreateInput!){ clientdocumentationCreate( input: $input ){ clientDocumentation{ id } } } ''', variables = { "input": { "file": SimpleUploadedFile( "file.txt", b"these are the file contents!" ), "client": client.id, "document": document.id } } ) print(response) data = response.data['clientdocumentationCreate']['clientDocumentation'] self.assertEqual(data, client.id) The print i set on the … -
Heroku 30s timeout error, how to make Django views variable creation as a background task (worker)?
I am facing a heroku 30s time out error with my django webapp. The reason it is taking long is because of the views variables created (reddit api onto context) Here is the code for the same. def home(request): reddit = praw.Reddit(client_id='L685-1uBBrLbKQ', client_secret='_Fk5nW1L2h3VRR6BVnkusMh43QQ_gg', user_agent='Shivam Anand') hot_posts = reddit.subreddit('AskReddit').top(time_filter="day", limit=7) x = [] y = [] for post in hot_posts: x.append(post.title) y.append(post.url) print(x) print(y) z = [] for url in y: comments = [] submission = reddit.submission(url=url) submission.comments.replace_more(limit=0) for count in range(10): comments.append(submission.comments[count].body) z.append(comments) top_EarthPorn = reddit.subreddit('EarthPorn').top(limit=100) EarthPorn_links = [] for post in top_EarthPorn: EarthPorn_links.append(post.url) request.session['EarthPorn_links'] = EarthPorn_links return render(request, template_name='base.html', context=context) How do i make sure the context dict data is being created every hour or so as a background process? which libraries can one use to achieve so -
workon is not recognized as the name of a cmdlet,django
I want to creat my first app on django3 I had created a virtual env on cmd and then called it on vscode terminal but it shows this error OS :windows & spelling is correct btw): The term workon is not recognized as the name of a cmdlet ,function,script file, or operable program. How can I check and verify the path -
Django ModelForm: Defining a value not passed into the template
I have a ModelForm, and I want to only pass some of the fields into the template. I would like to save one particular field to define after the POST request has been sent. Here is the ModelForm: class CreateListingForm(ModelForm): class Meta: model = models.ListingModel fields = ['name', 'image', 'description', 'price', 'category'] widgets = { 'description': Textarea() } And here is the Model: class ListingModel(models.Model): name = models.CharField(max_length=30) image = models.ImageField(upload_to='images') description = models.CharField(max_length=1000) price = models.PositiveIntegerField() category = models.CharField(max_length=15) objects = models.Manager() owner = models.CharField(max_length=100) In the next code block, I am attempting to define the owner field according to the current user logged in (request.user.username): @login_required(redirect_field_name=login_view) def create_listing(request): if request.method == "GET": return render(request, "auctions/createlisting.html", { "CreateListingForm": forms.CreateListingForm() }) elif request.method == "POST": form = forms.CreateListingForm(request.POST, request.FILES) if form.is_valid(): try: form.owner = request.user.username print(form.owner) form.save(commit=True) except Exception: return HttpResponseRedirect(reverse("create_listing_error")) return HttpResponseRedirect(reverse("index")) #TODO Now, when I say print(form.owner), the result is correct. However when I save the ModelForm, the owner field is left blank. Am I not defining the value of the owner field correctly? -
Django custom superuser can't create new user in admin panel
I created a custom user model and I can create new superuser with manage.py but when I login to admin panel, I can't add new user (although is_superuser column is true in database). This is my models.py: class MyUser(AbstractUser): email = models.EmailField(unique=True) department = models.ForeignKey(to=Department, on_delete=models.CASCADE, null=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username', 'password'] I also tried with custom UserManager but still not working: class MyUserManager(UserManager): def create_superuser(self, username, email=None, password=None, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) u = self._create_user(username, email, password, **extra_fields) u.save() return u class MyUser(AbstractUser): email = models.EmailField(unique=True) department = models.ForeignKey(to=Department, on_delete=models.CASCADE, null=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username', 'password'] objects = MyUserManager() Here is my admin panel screenshot: screenshot -
Django Channels ERROR: TypeError: object.__init__() takes exactly one argument (the instance to initialize)
I am using a custom JWT Authentication Middleware for verifying of JWT. import jwt from urllib.parse import parse_qs from channels.db import database_sync_to_async from django.contrib.auth import get_user_model from django.contrib.auth.models import AnonymousUser from django.conf import settings from rest_framework_simplejwt.tokens import AccessToken @database_sync_to_async def get_user(user_id): User = get_user_model() try: user = User.objects.get(id=user_id) return user except User.DoesNotExist: return AnonymousUser() class TokenAuthMiddleware: """ Custom middleware (insecure) that takes user IDs from the query string. """ def __init__(self, inner): # Store the ASGI application we were passed self.inner = inner async def __call__(self, scope, receive, send): # Look up user from query string (you should also do things like # checking if it is a valid user ID, or if scope["user"] is already # populated). token = parse_qs(scope["query_string"].decode())["token"][0] AccessToken(token).verify() payload = jwt.decode(token, settings.SECRET_KEY, algorithms=['HS256']) scope["user"] = await get_user(int(payload["user_id"])) return await self.inner(dict(scope), receive, send) I am getting the error TypeError: object.__init__() takes exactly one argument (the instance to initialize) I followed the official docs Can anyone guide me where is exactly the issue? -
Widgets in django forms are not working... What shall I do?
Without widgets form works correctly. It must be simple solution without calling super.init. In documentation it is exactly as I wrote here... class ForumForm(ModelForm): class Meta: model = Forum fields = ['publisher', 'topic', 'text', 'date'] widgets = { 'publisher': TextInput(attrs={'class': 'form-control'}), 'topic': TextInput(attrs={'class': 'form-control'}), 'text': Textarea(attrs={'class': 'form-control'}), 'date': DateTimeInput(attrs={'class': 'form-control'}) } -
Connection refused', Backend api working. Connection error when api call from Frontend code
django application have both backend code n frontend. this deployed on droplet. backend api working. but connection refuse error when accessing api from fronend code. I have check all post related this 'connection refuse issue', but didnt work. I m unable to understand what would be the cause. Could u plz any one help me here. -
Getting NameError in django views.py , as NameError : name 'edit_load_table' is not defined
name 'edit_load_table' is not defined Request Method: GET Request URL: http://127.0.0.1:8000/edit_load/N193 Django Version: 3.1.4 Exception Type: NameError Exception Value: name 'edit_load_table' is not defined Exception Location: C:\Users\Virti Parekh\projects\try\total_load\views.py, line 45, in edit_load Python Executable: C:\Users\Virti Parekh\AppData\Local\Programs\Python\Python37\python.exe Python Version: 3.7.6 Python Path: ['C:\\Users\\Virti Parekh\\projects\\try', 'C:\\Users\\Virti ' 'Parekh\\AppData\\Local\\Programs\\Python\\Python37\\python37.zip', 'C:\\Users\\Virti Parekh\\AppData\\Local\\Programs\\Python\\Python37\\DLLs', 'C:\\Users\\Virti Parekh\\AppData\\Local\\Programs\\Python\\Python37\\lib', 'C:\\Users\\Virti Parekh\\AppData\\Local\\Programs\\Python\\Python37', 'C:\\Users\\Virti ' 'Parekh\\AppData\\Local\\Programs\\Python\\Python37\\lib\\site-packages'] Server time: Sat, 05 Dec 2020 19:04:19 +0000 I want to fetch particular empId data from table "edit_load_table". When I m clicking load details (as an anchor tag) it will fetch the data of particular empId data in tabular format. This is my models.py code class facultyload(models.Model): empId = models.CharField(max_length=20) name = models.CharField(max_length=50) total_load = models.IntegerField() def __str__(self): return self.empId class edit_load_table(models.Model): empId = models.CharField(max_length=20) name = models.CharField(max_length=50) subject_abv = models.CharField(max_length=10) subject_load = models.IntegerField() subject_type = models.CharField(max_length=10) id_key = models.IntegerField() semester = models.CharField(max_length=20) def __str__(self): return self.empId This is my views.py code def edit_load(request, empId): editload = edit_load_table.objects.get(str=empId) return render(request,"edit_load.html",{'editload':editload}) As my empId contains both letters and numbers so I gave str=empId. In my urls.py I have pass path('edit_load/<str:empId>',views.edit_load) Anyone can help me to solve this error as I m new to Django and python. Thank You! -
Pass HTML File from Django View To Django Template
I am trying to pass through an html file from my Django view via a django template. This is my view: def sample_function(request, product_id, slug=None): from django.template import loader product_data = get_object_or_404(Product, id=product_id) country_code = request.session.get('country_code') form = CountryForm(initial={'country': country_code}) form_estimate = CountryEstimateForm(initial={'country_estimate': country_code}) test = loader.get_template('home/custom_options.html') return render(request, 'request_custom_order.html', {'product':product_data,'country': form, 'country_estimate': form_estimate,'test':test}) This is my html: <div> {{ test }} </div> However, if I just do {{ test }} I get: <django.template.backends.django.Template object at 0x7fcd03203080> If I do {{ test|safe }} I just get blank. Could someone help me understand what I am doing wrong? -
What will be the best suited Web Framework for making ERP like application?
What will be the best suited web framework for making large scale web based application? .Net Core/ EF Core Spring/Hibernate Django Laravel -
Deploying Django Project on Pythonanywhere
I uploaded my app that worked fine on my local machine to pythonanywhere. I got it to work but instead of showing the homepage of my website it shows the "It worked, welcome to Django" page. Could someone please help me? This is my wsgi file import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'vorakor.settings') application = get_wsgi_application() THis is my settings.py file INSTALLED_APPS = [ 'website', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ['templates'], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] -
django rest framework default css
I run a DRF project on pythonanywhere.com and the admin page does not have any style and it's kind of hard to navigate as an admin. The following errors are thrown in the google chrome console and the request response. -
Indexing messages in django
I am currently working on a dna to protein translator. The code works pretty well. However, I'd like to improve it with the messages framework in django: https://docs.djangoproject.com/en/3.1/ref/contrib/messages/ What I did is put three if statements in the functions translate and build protein so that when this statement is true, it raises a message. However, when the message appears, they also appear the other messages.errors. Is there any way I can print the message I want. Here's the views.py code where I type the if statements: class TranslatorView(View): def translate(self, request, phrase): translation = "" for letter in phrase: if letter.lower() in self.rna_mapper: translation += self.rna_mapper[letter.lower()].upper() if letter.isupper() else self.rna_mapper[letter] else: translation = "INVALID DNA CHAIN" return translation def translate_amino(self, codon): return self.amino_mapper.get(codon, "") def build_protein(self, request, phrase): protein= [] i = 0 while i < len(phrase): codon = phrase[i: i + 3] amino = self.translate_amino(codon) if amino: protein.append(amino) else: messages.error(request, "PROTEIN WAS NOT FOUND") i += 3 if len(phrase) % 3: messages.error(request, 'CHAIN MUST BE DIVISIBLE BY 3') return() else: return protein And here's the template where the messages appear: {% extends "base.html"%} {% block content%} <div > <h2 class = "display-3">DNA TRANSLATED SUCCESFULLY </h2> <br> <br> <br> <h2> … -
Django: decorator causes 'function' object has no attribute 'get' when wrapping view in urls
I am using Django defender, watch_login() decorator to add brute-force prevention to my custom login view: def user_login(request): if request.user.is_authenticated: if request.user.is_active: return redirect('home:home') if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') user = authenticate(username=username, password=password) if user is not None: if user.is_active: login(request, user) return redirect('home:home') else: return HttpResponse('Account is disabled') else: messages.error(request,'Sorry, the username or password you entered is not correct') return redirect('main:user_login') return render(request, 'main/user_login.html') However, when I wrap the function with the decorator in my urls.py file I get the error: 'function' object has no attribute 'get'. I have tried using the decorator in views.py with now arguments by simply doing @watch_login() However, that does not seem to be working. How can I add this wrapper to my function in the urls.py file? I have also tried this:Wrapping/decorating a function in urls.py vs in views.py And I still get the same error ('function' object has no attribute 'get') -
Bootstrap classes to Django UpdateView
Built-in UpdateView View class create form in my app, but I want add to form Bootstrap class in my HTML, how can i do it? class ProfileUpdate(UpdateView): model = Profile fields = ['first_name', 'last_name', 'patronymic', 'profile_picture', 'bio'] template_name = 'profiles/profile_form.html' success_url = '' -
how customize is_valid to accept empty chars
I try to sign_up User, and I want get possibility to name User with empty chars example "Mr Somebody" but method is_valid not pass my form. How can I modify method is_valid to take empty chars in User name? def sign_up(request): context = {} form = UserCreationForm(request.POST or None) if request.method == "POST": if form.is_valid(): form.save() return render(request, 'accounts/index.html') context['form'] = form return render(request,'registration/sign_up.html', context) -
F() expressions and select_for_update() in Django
When it comes to avoiding race conditions in Django, can F() expressions and select_for_update() be used interchangeably? -
How to access a MySQL server hosted on a Virtual Machine using another Virtual Machine?
I have created 2 Ubuntu 20.04 VMs using VirtualBox. I have a Django App on one VM and MySQL DB on the other VM. How do I access the MySQL DB using the first VM? I used the inet from the output of ifconfig for the IP Address What I tried: On the VM having MySQL DB: -> Change the 'bind_adress' field to '0.0.0.0' in '/etc/mysql/mysql.conf.d/mysqld.cnf' -> Created a new user using "CREATE USER 'test'@'IP_Address1' IDENTIFIED BY 'password';" -> Ran "sudo ufw allow from IP_Address1 to any port 3306" On the VM having the Django App: -> Tried to connect to the Virtual Machine using "mysql -u 'test' -h 'IP_ADDRESS2' -p" The error I'm getting: "Unknown MySQL host 'address'" -
Django3.1 error when I try to save post with tags
I have a view inside posts app where I try to save a post with tags. Whenever I add a new tag to the post, I get this error: value error at create My view is this one: class PostCreateView(CreateView): template_name = 'posts/create.html' form_class = PostCreationForm model = Post def get_success_url(self): return reverse('posts:detail', kwargs={"slug": self.object.slug}) def form_valid(self, form): form.instance.user = self.request.user form.save() # this is where the error occurs tags = self.request.POST.get("tag").split(",") for tag in tags: current_tag = Tag.objects.filter(slug=slugify(tag)) if current_tag.count() < 1: create_tag = Tag.objects.create(title=tag) form.instance.tag.add(create_tag) else: existed_tag = Tag.objects.get(slug=slugify(tag)) form.instance.tag.add(existed_tag) return super(PostCreateView, self).form_valid(form) The form I'm using is as follow: class PostCreationForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(PostCreationForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_method = "post" self.helper.field_class = 'form-group' self.helper.layout = Layout( Field('title', css_class="form-control", placeholder='Post title'), Field('content', css_class="form-control", placeholder='Post content'), Field('category', css_class="form-control"), Field('image', css_class="form-control"), Field('tag', css_class="form-control", placeholder='tag1, tag2') ) self.helper.add_input(Submit('submit', 'Create New Post', css_class='btn btn-underline-primary')) tag = forms.CharField() class Meta: model = Post fields = ['title', 'content', 'category', 'image', 'tag'] This is the Post model: class Post(models.Model): title = models.CharField(max_length=150, unique=True) content = RichTextUploadingField() # content = models.TextField() publish_date = models.DateTimeField(auto_now_add=True) image = models.ImageField(blank=True, null=True, upload_to='uploads/') user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) slug = models.SlugField(default="slug", editable=False) category = models.ForeignKey(Category, on_delete=models.CASCADE, default=1, …