Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I manually ask Django to translate a string (which I know there is a translation for)?
I just implemented translations for my learning-to-code-side-project, and it works great! I also use django-modeltranslation for models, and no problems there either. As a finishing touch I wanted to create a view that changes the language. It should take a single keyword argument - the language_code of the desired language, e.g. "en-us", "de", "nb" and so on, and also should accept the GET parameter next, which I then forward the user to after the language settings have been updated. E.g.: http://127.0.0.1:8000/en-us/change-language/nb/?next=/en-us/dashboard/ In this example url /en-us/ is the current language, /change-language/ is the location of the change-language-view (so to speak), /nb/ is the desired language, and ?next=/en-us/dashboard/ is the current url in the current language (and thus where users will be redirected after having their language changed, and after the url have been translated to a new language, e.g. "/nb/kontrollpanel/") I made the URL-translations work with resolve and reverse as seen below: def change_language_view(request, **kwargs): #get and validate the language user is trying to change to language_code = kwargs.get('language_code', None) try: assert [lang[0] for lang in settings.LANGUAGES if lang[0] == language_code], _("%(selected_languages)s not in %(settings_languages)s"%{language_code, settings.LANGUAGES}) except (AssertionError, TypeError) as err: raise Http404(_("Couldn't find that language: ")) #get the next … -
How to send signal from nodemcu to Django website
How to send a signal from nodemcu to Django website Actually I want an IP address of nodemcu to find its location In my project, I want to location of that nodemcu and that location will display to admin of geopy map in Django website and I don't want to use PHP and SQL language. please help me, please. -
Django check if post value exists in db
I'm trying to submit two forms with one submit button. First I want to check if form 1 already exists in the db, if id does then just post the second form using the "ticker" from first form as Foreginkey. But seem to get an error: 'UserTickerForm' object has no attribute 'get' My code: if request.method == 'POST': request_form_user_ticker = UserTickerForm(request.POST) request_form_trade = TradesForm(request.POST) if request_form_user_ticker.is_valid() and request_form_trade.is_valid(): if not User_Ticker.objects.filter(portfolio=select_portfolio, ticker=request_form_user_ticker.get('ticker')).exists(): user_ticker_instace = request_form_user_ticker.save(commit=False) user_ticker_instace.portfolio = select_portfolio user_ticker_instace.save() trade_instance = request_form_trade.save(commit=False) trade_instance.ticker = request_form_user_ticker.get('ticker') trade_instance.save() else: trade_instance = request_form_trade.save(commit=False) trade_instance.ticker = request_form_user_ticker.get('ticker') trade_instance.save() Does anyone know who this is happening and what I can do to fix this? -
Image submit button: POST data includes name.x and name.y but not name
This is my input element: <input class="desktop_hidden" type="image" alt='Submit' src="{% static 'auctions/images/button.png' %}" value="Post Comment" name="make_comment"> When I submit this, I get an error "ValueError: The view auctions.views.listing_page didn't return an HttpResponse object. It returned None instead." When I inspect the POST data, it has "make_comment.x: 0", and "make_comment.y: 0", but not "make_comment: Post Comment" that it has when I use a normal submit button. I'm guessing I'm missing something basic in the html, what is it?? -
How to interact with DB from a button on Django when your 'item' change every refresh (Python)
I'm looking for a way to change an 'item' (the one displayed on the page) in the DB. But first, I should have 2 buttons on the page. And secondly, The 'item' shown is random from the DB. So the problem is : How can I change the item info in the DB knowing that the button will refresh the page to send it in the request. (I remind you that my item is random and so, change every refresh) So, I need a way to change it or a way to randomize the page but not when I send a POST request My views.py : (Messy but it's ok xD) def review(request): loop = True i = 0 while loop and i < len(Cartes.objects.filter(user_id_shared_id__exact=request.user.id).values_list('pk', flat=True))*4: i = i + 1 pks = Cartes.objects.filter(user_id_shared_id__exact=request.user.id).values_list('pk', flat=True) if len(pks) == 0: loop = False return redirect('/create/') random_pk = choice(pks) card = Cartes.objects.get(pk=random_pk) obj, created = Review.objects.get_or_create( card_id_id=card.id, user_id_id=request.user.id, ) print(card.id, "///", obj.id) date_3_days = obj.review_date + datetime.timedelta(days=3) date_7_days = obj.review_date + datetime.timedelta(days=7) date_21_days = obj.review_date + datetime.timedelta(days=21) date_42_days = obj.review_date + datetime.timedelta(days=42) if obj.review_level == 1: loop = False elif obj.review_level == 2 and datetime.date.today() >= date_3_days: loop = False elif obj.review_level … -
Django User password field different from what it's supposed to be
When working with projects with Django, usually the password field in the admin page is disabled and just shows information like this: algorithm: pbkdf2_sha256 iterations: 180000 salt: vakJGB****** hash: mD0TmS************************************** The problem is that it's using an enabled password field which admin users can interact with and I want to stop that. My User model: from django.db import models from django.contrib.auth.models import AbstractUser from prototype.settings import AUTH_USER_MODEL class Agent(AbstractUser): parent = models.ForeignKey(AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=True, related_name='children') -
Configure one API for two apps
My case: I'm creating a SaaS that has two client types, both of which must be able to access the same API, one is built in React and the other in Electron, the API is built in Django. The problem: I'm a bit new to working with APIs, so I don't know what I should do in this case. What I think is that I should upload the API to a cloud and then access it from the clients I need, however I think I would need to implement authentication for the API. My question: Am I right or what should I do? -
How to access "other side" of ManyToMany relationships in Django/Wagtail?
I think I'm lacking the right search term for what I'm looking for here. I've got a model for BookPage that accepts multiple authors in a ParentalManyToMany relationship in Wagtail. I'm able to access each of the authors in a template using this code: {% with author=page.author.all %} {% if author %} {% for aut in author %} <div> {{ aut }} </div> {% endfor %} {% endif %} {% endwith %} This prints each author associated with a book. How do I do the reverse, and get all the books written by a particular author, though? I can't seem to find anything about this in the Wagtail docs. -
Why i couldn't save the student's profile in the database
I'm new at django and trying to extend the custom user to multiple user profiles and when i am trying to save the user it says "Student with this Group already exists." The first user registered normally but when i create the second second one it raise the error even the user model dosen't have a membership with the group here is my code models.py class CustomUser(AbstractUser): USER_TYPE_CHOICES = ( (1, 'student'), (2, 'parent'), (3, 'gard'), (4, 'teacher'), (5, 'secretary'), (6, 'supervisor'), (7, 'admin'), ) is_active = models.BooleanField(default=True) user_type =models.PositiveSmallIntegerField(choices=USER_TYPE_CHOICES,null=True) class Student(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='student_profile') group = models.OneToOneField(Group,related_name='student_group',on_delete=models.CASCADE,null=True) teacher = models.ManyToManyField(Teacher,related_name="student_teacher") def save(self,*args,**kwargs): self.user.is_active = False return super(Student,self).save(*args,**kwargs) class Group(models.Model): name = models.CharField(max_length=255, unique=True) slug = models.SlugField(allow_unicode=True, unique=True) def __str__(self): return self.name def save(self, *args, **kwargs): self.slug = slugify(self.name) retuen super().save(*args, **kwargs) This is my forms.py file views.py def student_signUpView(request,**kwargs): registered = False if request.method == 'POST': user_form = UserSignUpForm(request.POST) profile_form = StudentSignUpForm(request.POST) if user_form.is_valid() and profile_form.is_valid(): user = user_form.save(commit=False) user.set_password(user_form.cleaned_data['password2']) print(user.user_type) user.save() profile = profile_form.save(commit=False) profile.user = user profile.exist = True profile.save() registered = True else: print(user_form.errors,profile_form.errors) else: user_form = UserSignUpForm() profile_form = StudentSignUpForm() return render(request, 'accounts/singup.html',{ 'registered':registered, 'user_form': user_form, 'profile_form': profile_form, }) and here is the … -
redirect to a page with pk on django
This funtion is to update an order, i would like to be redirected to the customer profile page where i can find all this customer's orders. on the costumer profile i have all orders listed with option to modify or delete. i would like to modify and to redirected to the costumer profile page which the url is : path("customer_profile/<int:pk>/", views.Customer_profile, name="customer_profile") def OrderUpdate(request, pk): order = Order.objects.get(id=pk) form = OrderForm(instance=order) if request.method == 'POST': form = OrderForm(request.POST, instance=order) if form.is_valid(): form.save() return redirect('orders') context = {'form':form} return render(request, 'orders/order_form.html', context) -
Can not use UserAdmin fildsets with cutom user model
I tried to customize Django User,which worked fine but I lost things like user_permissions. I don't have user permissions window from which I can give permissions like "can add Product,Can delete cart" etc. I tried this: from django.contrib.auth.admin import UserAdmin fieldsets = UserAdmin.fieldsets + ('Custom fields set', {'fields': ('email', 'staff')}), and UserAdmin.fieldsets += ('Custom fields set', {'fields': ('email', 'staff')}), but these didn't worked for me. If I try to add 'user_permissions' to fieldsets I get error " Unknown field 'user_permissions' specified'". Do I need to define user_permissions fields? class UserManager(BaseUserManager): def create_user(self,email,password=None,is_active=True,is_staff=False,is_admin=False): if not email: raise ValueError("Users must have email") if not password: raise ValueError("Users must have password") user_obj = self.model( email = self.normalize_email(email) ) user_obj.staff = is_staff user_obj.admin = is_admin user_obj.active = is_active user_obj.set_password(password) #inbuild hashing user_obj.save(using = self._db) return user_obj def create_staffuser(self,email,password=None): user = self.create_user(email,password=password,is_staff=True) return user def create_superuser(self,email,password=None): user = self.create_user(email,password=password,is_staff=True,is_admin=True) return user class User(AbstractBaseUser): email = models.EmailField(unique=True,max_length=255) # full_name= models.CharField(max_length=100) active = models.BooleanField(default=True) staff = models.BooleanField(default=False) admin = models.BooleanField(default=False) timestamp= models.DateTimeField(auto_now_add=True) # confirmed= models.BooleanField(default=False) #confirmed email? USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = UserManager() def __str__(self): return self.email def get_full_name(self): return self.email def has_perm(self,perm,obj=None): return True def has_module_perms(self,app_label): return True This is how my admin … -
How to add request.user to manytomanyfield for team members in django?
I was trying to create a custom team model having a manytomanyfield for team members, now i have a form that allows users to create their own team(s), but i dont understand how i can add request.user to the members of the team. Below are the codes: models.py class Team(models.Model): name = models.CharField(max_length=64, unique=True) description = models.CharField(max_length=1024) created_at = models.DateTimeField(auto_now_add=True) members = models.ManyToManyField(User, through='Member') def __str__(self): return f"Team: {self.name} created on {self.created_at}\nMember(s): {self.members}" class Member(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) team = models.ForeignKey(Team, on_delete=models.CASCADE, blank=True) forms.py class TeamRegistrationForm(ModelForm): class Meta: model = Team fields = ["name", "description"] views.py @login_required(login_url="/login/") def teamregister(request): if request.method == "POST": form = TeamRegistrationForm(request.POST) if form.is_valid(): form.save() form.instance.members.add(request.user) # doesn't work :[ print(form.save()) messages.success(request, "Your team has been successfully registered!") return redirect("dashboard") else: form = TeamRegistrationForm() return render(request, "users/team.html", {"form": form}) I tried to use form.instance.members.add(request.user) to add the logged in user to the member of the team but it didn't work. Please help :[ -
Django Rest Framework: Overriding the PATCH or update()
I'm working up at a little IMS system Warehouse - it's products in the store App_form - it's the little form with order ChosenProduct - products which are chosen in order Models.py class Warehouse(models.Model): product_name = models.CharField(max_length=200, unique=True) amount = models.IntegerField() f_price = models.CharField(max_length=255, null=True) posted_user = models.ForeignKey(User, on_delete=models.CASCADE, default=1) def __str__(self): return self.product_name class App_form(models.Model): deleted = models.BooleanField(default=False) name_customer = models.CharField(max_length=200) joined_date = models.DateField(verbose_name='joined date', auto_now_add=True) posted_user = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.surname class ChosenProduct(models.Model): product = models.ForeignKey(Warehouse, on_delete=models.CASCADE) quantity = models.IntegerField() app_form = models.ForeignKey(App_form, on_delete=models.CASCADE, related_name='chosen_products') def __str__(self): return self.product.product_name views.py class WarehouseList(generics.ListCreateAPIView): queryset = Warehouse.objects.all() serializer_class = WarehouseSerializer class WarehouseDetail(generics.RetrieveUpdateDestroyAPIView): queryset = Warehouse.objects.all() serializer_class = WarehouseSerializer class App_formList(generics.ListCreateAPIView): queryset = App_form.objects.all() serializer_class = App_formSerializer class App_formDetail(generics.RetrieveUpdateDestroyAPIView): queryset = App_form.objects.all() serializer_class = App_formSerializer serializers.py In App_formSerializer I rewrote the create method Where after chosing product from Warehouse the product quantity decreases class WarehouseSerializer(serializers.ModelSerializer): class Meta: model = Warehouse fields = ['__all__'] class ChosenProductSerializer(serializers.ModelSerializer): product_info = WarehouseSerializer(source='product', read_only=True) class Meta: model = ChosenProduct exclude = ('app_form',) class App_formSerializer(serializers.ModelSerializer): chosen_products = ChosenProductSerializer(many=True) @transaction.atomic def create(self, validated_data): chosen_products_data = validated_data.pop('chosen_products') app_form = App_form.objects.create(**validated_data) for chosen_product_data in chosen_products_data: chosen_product = ChosenProduct.objects.create(app_form=app_form, **chosen_product_data) product = chosen_product.product product.amount = product.amount - chosen_product.quantity product.save() … -
difference between django db router and custom model admin class
Recently I had a use case where i wanted to configure multiple DB instances in django. I wanted to configure django admin for the same as well. According to the documentation - https://docs.djangoproject.com/en/3.0/topics/db/multi-db/ there are 2 approach Using DB routers Create a custom admin class and modify 5 methods save_object etc - https://docs.djangoproject.com/en/3.0/topics/db/multi-db/#exposing-multiple-databases-in-django-s-admin-interface Does anybody know Why is the other approach listed here, I tried both and DB router is way easier. Is there any drawbacks of using DB router over custom Admin Class. Is there something one should be aware of when using either of the approaches Django masters please help -
404 (Not Found) in ajax post url
jQuery("#myform").submit(function (e) { e.preventDefault(); var formData = new FormData(this); jQuery.ajax({ type:'POST', url:'{% url 'myurl' %}', data: formData, cache:false, contentType: false, processData: false, success: function (data) { alert("Done"); } }); }); The code works perfectly fine in localhost but shows 404 url not found when hosted on server. -
NGINX and TRAEFIK staticfiles are not working with HTTPS in production
I'm developing a website for my association Here. It uses Django 3.0.7 and PostgreSQL. I follow this tutorial to make it works in good condition in development and in production. In development mode all is good, site is working perfectly, static files and media files are served by the Django built-in web server. I test the "vanilla" (coming from the tutorial) production on my local machine it works too. But the tutorial is not complete for me so after completing it, I decided to adapt the code to fit my needs. As I follow the tutorial I created a new docker-compose and a new dockerfile for production. But there are 2 differences between the tutorial and the site I want to set in production: I want to Use TREAFIK to route the traffic on different URL (appli.amis-simserhof.fr) because I will have other projects in the future on the same server with others subdomains.. I want to secure the website using HTTPS. So I use CERTBOT (let's encrypt) to generate certificates. I add this certificates to TREAFFIK in order to use HTTPS and it works. So I adapted the docker-compose file with my new stuff : version: '3.7' services: **traefik: image: … -
DRF Custom Update password got KeyError: 'request'
When I want to update password received error, user = self.context['request'].user KeyError: 'request' Can someone help me with it? serializer: Custom serializer class UserPasswordChangeSerializer(serializers.Serializer): old_password = serializers.CharField(required=True) password = serializers.CharField(required=True) class Meta: model = User fields = ('old_password', 'password') def validate_old_password(self, data): user = self.context['request'].user if not user.check_password(data): raise serializers.ValidationError( {'old_password': 'Wrong password.'} ) return data def update(self, instance, validated_data): instance.set_password(validated_data['password']) return super().update(instance) My action view My action view @action(methods=['patch'], detail=True) def change_password(self, request, *args, **kwargs): user = self.get_object() user.serializer = UserPasswordChangeSerializer(data=request.data) user.serializer.is_valid(raise_exception=True) user.serializer.save() return Response(status=status.HTTP_204_NO_CONTENT) -
How can I make the following pattern in HTML and CSS. Here is my course so far
Design[Please can someone help me design it without using this image.] -
Django ValueError: Related model 'api.User' cannot be resolved
I am going to use the django custom user model. After writing the code, I migrate it on db, and the following error appears. ValueError: Related model 'api.User' cannot be resolved What's problem on my code ? Here is my code. models.py from django.db import models from django.contrib.auth.models import BaseUserManager, AbstractBaseUser, PermissionsMixin from django.utils.translation import ugettext_lazy as _ class UserManager(BaseUserManager): """ A custom user manager to deal with emails as unique identifiers for auth instead of usernames. The default that's used is "UserManager" """ def _create_user(self, email, password, **extra_fields): """ Creates and saves a User with the given email and password. """ if not email: raise ValueError('The Email must be set') email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save() return user def create_superuser(self, email, password, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) extra_fields.setdefault('is_active', True) if extra_fields.get('is_staff') is not True: raise ValueError('Superuser must have is_staff=True.') if extra_fields.get('is_superuser') is not True: raise ValueError('Superuser must have is_superuser=True.') return self._create_user(email, password, **extra_fields) class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(unique=True, null=True) is_staff = models.BooleanField( _('staff status'), default=False, help_text=_('Designates whether the user can log into this site.'), ) is_active = models.BooleanField( _('active'), default=True, help_text=_( 'Designates whether this user should be treated as active. ' 'Unselect this instead of … -
change a variable in Django View and use it in different class of same module / file
I have a class XLS of a third party package QuickXLS inside the view posts/views.py. The app persons for user info contains persons.group_number. Depending on the user's persons.group_number the class XLS should create a different xls-file. I think I could use a variable for that: in posts/views.py ... from quickxls import QuickXLS ... class PostsViewSet(viewsets.ModelViewSet): ... group_no = 0 # <--- this is the variable I would like to change in # accordance to "persons.group_number" ... class XLS(Quick): group_number = PostsViewSet.group_no if group_number == 12: ... ... What kind of request should I use and where is the best place to put it, in order for this to work? -
Can you dictate which fields are required with a conditional statement in Django?
For example, if you were writing a Car model, the code might look like this: class Car(models.Model): make = models.CharField(max_length=20) model = models.Charfield(max_length=20) convertible = models.BooleanField() convertible_choices = (('ht', 'Hard top'), ('st', 'Soft top')) convertible_top = None def save(self): if self.convertible: self.convertible_top = models.CharField(max_length=8, choices=convertible_choices) super().save() I'm not 100% sure if the code above is perfectly functional, but hopefully its illustrative purposes are clear; If the convertible tickbox is checked, the field for convertible_top becomes "active" and offers an input box where the choice could be made such as selecting between choices, typing an input, etc. Is it possible to do this in Django or should you just drop a blank=True in the arguments of the field and only input data if it's required? -
error could not convert string to float: '66,00' or JSONDecodeError: Expecting value: line 1 column 1 (char 0)
hello for some unexplained reason a site that worked fine a week ago it bugged the kind of bug is that if the customer places an order it does not pass and I have this error could not convert string to float: '66,00' or JSONDecodeError: Expecting value: line 1 column 1 (char 0) views.py def processOrder(request): transaction_id = datetime.datetime.now().timestamp() data = json.loads(request.body) if request.user.is_authenticated: customer = request.user order, created = Order.objects.get_or_create(customer=customer, complete=False) else: customer, order=guestOrder(request,data) total=float(data['form']['total']) order.transaction_id=transaction_id if total==float(order.get_cart_total): order.complete=True order.save() if order.shipping==True: ShippingAddress.objects.create( customer=customer, order=order, address=data['shipping']['address'], city=data['shipping']['city'], state=data['shipping']['state'], zipcode=data['shipping']['zipcode'], ) return JsonResponse('payment complete',safe=False) -
Django and GeoDjango - SpatiaLite requires SQLite to be configured to allow extension loading
Here is the (relevant section of) settings.py file in my Django project: SPATIALITE_LIBRARY_PATH='/usr/local/lib/mod_spatialite.dylib' DATABASES = { 'default': { 'ENGINE': 'django.contrib.gis.db.backends.spatialite', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } I have followed all the tutorials and installation instructions on the GeoDjango webpages. I tried following this thread, but could not get "load_extension on" to work. I was having trouble when running "make" and "sudo make install" to the libspatialite file (i was able to unzip it, i did the ./configure --target=macosx but then the rest would not work). The version I downloaded was "libspatialite-5.0.0-RC1.tar.gz" - I am not sure if that has something to do with it. I have tried installing sqlite through their website and have been successful with that. However, i was not sure how to turn load_extension to "on" - i have assumed that is the reason this is not working and i am getting this error : django.core.exceptions.ImproperlyConfigured: SpatiaLite requires SQLite to be configured to allow extension loading. I tried following the function instructions, but could not get that to work either as I am not sure what to put in for the first parameter and when/how I should use the function: sqlite3_load_extension(???, 1). I can run sqlite3 and Spatialite … -
How can I transfer a variable from python script to the Webpage in Django?
I have been at this code for a while. But I haven't been able to fix it. The code is in Django. It doesn't return anything where it is given {{ example }}. I tried many tutorials but they seem to be outdated. How can I transfer variables from python script(not inside the app) to the web-page after receiving an input through forms? -
Getting Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 1 whenever I click on the button in a django project
This is my code for the button in my JavaScript.Whenever I click on the button I get this error Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 1. document.getElementById('payment-info').addEventListener('click', function (e) { submitFormData() }) function submitFormData() { console.log('Payment Button Clicked') var userFormData = { 'name': null, } var shippingInfo = { 'address': null, } shippingInfo.address = form.address.value userFormData.name=form.name.value var url = "/process_order/" fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-CSRFToken': csrftoken, }, body:JSON.stringify({'form': userFormData, 'shipping': shippingInfo}), }) .then((response) => response.json()) .then((data) => { console.log('Success:', data); }) } The error is coming in these two lines 1)submitFormData() and 2) .then((data) => { but I cant figure out why this problem is coming.Is there some error in my views.py