Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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, … -
404 Not Found with nginx/apache2/django for static files on ubuntu
I'm setting up a Django project to run on apache web server (ubuntu) on port 80, which is working fine. To serve static content, I have set up nginx as a reverse proxy server operating on port 81. However, I keep getting 404 errors (from nginx) when trying to access the static content. My configurations are as follows. nginx: server { listen 81; listen [::]:81; server_name <my server's IPv4 address>; location ^~ /static/ { root /root/project-dir; proxy_pass http://localhost:80; proxy_set_header Host $host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; } } apache (relevant part): <VirtualHost *:80> Alias /static/ /root/project-dir/static/ ProxyPass /static http://localhost:81/ ProxyPassReverse /static http://localhost:81/ </VirtualHost> Django settings.py (relevant part): STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.normpath(os.path.join(BASE_DIR, 'myapp/static')), ] STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static") I also noticed that if I adjust my nginx configuration to: server { listen 81; listen [::]:81; server_name <my server's IPv4 address>; location ^~ /static/ { root /root/project-dir; } } then I am able to access the static content through my browser at <my server's IPv4 address>:81/static/path/to/content.jpg. However the static content doesn't load in my Django templates (using {% static <name> %}). My directory structure is: root - project-dir --- static <static root> ----- <collected static content here> --- … -
comparing two JSON API responses requested by two different users. Spotify API
The goal is to create a platform where two users can request Spotify data then responses are compared. I already have one piece of the puzzle solved, ie. for a single user, to access their spotify data, implemented the OAuth flow and all. The logic for comparison, I havent really looked at that piece yet. Firstly, was wondering how I'd be able to access one endpoint for a response{which I have already implemented), save that response and use the same endpoint for another user, and perform logic comparison of both responses. I was thinking about using sessions but I got lost. This is what I have so far. urls.py urlpatterns = [ path("", views.home, name="home"), path("login/" , views.login , name="login"), path("authorize/", views.callback, name="redirect"), path("liked/" , views.liked, name="liked"), ] views.py def login(request): authorize_url = oauth.get_authorize_url() return redirect(authorize_url) def callback(request): code = request.GET.get("code") if code is not None: token = oauth.get_cached_token()["access_token"] request.session["token"] = token return redirect(reverse("liked")) else: return redirect(reverse("login")) def liked(request): sp= Spotify(auth=request.session.get("token")) results = [] iter = 0 while True: offset = iter * 50 iter += 1 curGroup = sp.current_user_saved_tracks(limit=50, offset=offset)['items'] #yet to complete logic for display def home(request): template_name="display.html" return render(request, template_name) display.html <a href="{% url 'login' %}">LOGIN</a> -
Testing exception handling with Django models
I have a model named MyModel. I want to get an instance of the model from the database. If it's not there, get throws an exception, which I plan to catch, and then create a new instance to push into the database. Here's an example piece of code: 1: try: 2: my_model = MyModel.objects.get(keyval=something) 3: except MyModel.DoesNotExist: 4: my_model = MyModel(keyval=something, moar=data) 5: my_model.save() 6: do_something_with(my_model) I'm writing unit tests, and I don't want this function to ever hit the database (I'm not testing the database, I'm testing the function). I would expect this to work, but it doesn't: mock_myob = Mock() with patch('mymodule.models') as mock_models: mock_models.MyModel.objects.get.side_effect = mock_models.DoesNotExist() mock_models.MyModel.return_value = mock_myob with patch('django.utils.timezone.now', return_value=testdate2): testee = testfunc(something, data) mock_myob.save.assert_called_with(something, data) Unfortunately, when it hits line 2, above, it tells me "TypeError: 'Mock' object is not iterable" I couldn't possibly be the first person to run into this. What am I doing wrong? -
Django in digitalocean
With django running on digital ocean, how could i download a file that is on amazon web services and then manipulated. Is there a / temp folder or something, which frees that access for manipulation? -
why its showing empty path didnt match any of these
Using the URLconf defined in My_Ecom_Project.urls, Django tried these URL patterns, in this order: admin/ account/ ^static/(?P.)$ ^media/(?P.)$ The empty path didn't match any of these. -
Django: jQuery to trigger a form submit onchange of checkbox and retain the values on the reload
When one or more of the checkboxes in hostform are checked, I want to trigger a form submit. This is triggered successfully with the code below. However, the page reloads on the form submit, making any box that is checked go immediately back to being unchecked. I thought the localStorage.input line would fix this, but apparently not. Any suggestions? HTML: <div class="container-lg"> <!-- section for checkboxes --> <div class="row justify-content-center"> <div class="col-6"> <h2>Host</h2> <form id="hostform" class="form-inline" role="form" action="" method="post"> {% csrf_token %} <input type="checkbox" class="form-control" id="one" name="hm" value="one" onchange="triggerPost('one')"> <label for="one">One</label> <br> <input type="checkbox" class="form-control" id="two" name="hm" value="two" onchange="triggerPost('two')"> <label for="two">Two</label> <br> </form> </div> .... </div> jQuery: <script> function triggerPost(idnum) { $('#hostform').on("submit", function () { localStorage.input = $("#"+idnum).checked; }); $('#hostform').submit() }; </script> -
django DRF: custom permission class: function based views: how to pass or access some params from view
I have from rest_framework import permissions class CheckPermission(permissions.BasePermission): def has_permission(self, request, view): # access the allow parameter from view # if request.user.subscription type matches the value in allow array i.e [0,1,2,3] # then ok @api_view(['GET']) @permission_classes([CheckPermission]) def hello_world(request): allow=[0,1,2,3] print(request.user) return HttpResponse( JSONRenderer().render({"message": "Hello, world!"}), status=200, content_type="application/json" ) @api_view(['GET']) @permission_classes([CheckPermission]) def hello_world2(request): allow=[0,3] print(request.user) return HttpResponse( JSONRenderer().render({"message": "Hello, world2!"}), status=200, content_type="application/json" ) Here i am using a custom permission class. It will check if the request.user.subscription value matches any in the allow array values I saw in class based views we can access params using getattr(view, "allow", []), but in function based view its not working, In class based views i found this answer which does that. https://stackoverflow.com/a/19429199/2897115 -
How to update in ModelViewSet, Django Rest Framework
It is possible to update in ModelViewSet? I want to do an update in the ModelViewSet, not in the Serializer MySerializer in serializers.py class MyModelSerializer(serializers.ModelSerializer): class Meta: model = MyModel fields = '__all__' # I know the update will do here def update(self, instance, validated_data): pass MyViewSet in views.py class MyModelViewSet(viewsets.ModelViewSet): queryset = MyModel.objects.all() serializer_class = MyModelSerializer # I would like to do the update here, # because before updating I will do more things def update(self, request, *args, **kwargs): # Before updating, do something ... ... return Response(response) Any idea or suggestion?