Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Use frontend in oauth authorisation with social auth
Usually, when I use social auth lib to create oauth authorisation, I sent request to some url like 127.0.0.1:8000/oauth and then it redirects me to authorisation url of auth server. My problem is that I would like to return json with redirect url so frontend or mobile app could redirect me to it. How can I do it? -
calculate bad month from the given csv
I tried finding the five worst months from the data but I'm not sure about the process as I'm very confused . The answer should be something like (June 2001, July 2002 )but when I tried to solve it my answer wasn't as expected. Only the data of January was sorted. This the the way I tried solving my question and the csv data file is also provided on the screenshot. My solution is given below: PATH = "tourist_arrival.csv" df = pd.read_csv(PATH) print(df.sort_values(by=['Jan.','Feb.','Mar.','Apr.','May.','Jun.','Jul.','Aug.','Sep.','Oct.','Nov.','Dec.'],ascending=False)) -
Where do I find the default settings for my app in Django?
Problem: django.core.exceptions.ImproperlyConfigured: Requested settings, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. Example solution from Django Docs: # Put this before accessing settings from django.conf import settings if not settings.configured: settings.configure(default_settings=myapp_defaults, DEBUG=True) Okay but, where do I find my app's default settings? My file structure is: -
How to Remove Upper and Lower Limit Arrows in frontend of html Input type = 'number' While working with Form Api in django?
I would like to remove upper and lower arrows of html input type='number' in django while working with ModelForm, which will show in frontend? Html code: <form action=""> <input type="number"> </form> In normal forms we can use the below css code to remove arrows: input[type="number"]::-webkit-inner-spin-button, input[type="number"]::-webkit-outer-spin-button { -webkit-appearance: none !important; margin: 0 !important; } OR input[type=number]::-webkit-inner-spin-button, input[type=number]::-webkit-outer-spin-button { opacity: 1 !important; } But in django as we know we work with Form Api,so its might be the reason according to me, for it is not working so how can we do it in FormApi? -
Custom linkhandler does not show up in PageLinkChooser
I am following the Wagtail docs to create a custom link handler: myapp.handlers.py from django.contrib.auth import get_user_model from wagtail.core.rich_text import LinkHandler class UserLinkHandler(LinkHandler): identifier = 'user' @staticmethod def get_model(): return get_user_model() @classmethod def get_instance(cls, attrs): model = cls.get_model() return model.objects.get(username=attrs['username']) @classmethod def expand_db_attributes(cls, attrs): user = cls.get_instance(attrs) return '<a href="mailto:%s">' % user.email my_app/wagtail_hooks.py from wagtail.core import hooks from my_app.handlers import MyCustomLinkHandler @hooks.register('register_rich_text_features') def register_link_handler(features): features.register_link_type(LinkHandler) However, the handler does not show up in the admin widget. The expected behaviour is it should be in an option in the link type bar: I've followed the docs exactly, is there something missing? -
Django Rest + FireBase For Phone number Authentication with OTP
Hello everyone I Dont have much code to display as I am hard time gaining knowledge regarding firebase phone number authentication. Story is I am not using firebase db my clients may be international so I want to use minimal authentication mechanism for sending otp codes and we came with firebase as ultimate solution as It allows 10000 sms per month and it fulfills our need. The documentation I Found in web are totally based on firebase database where front end directly hits firebase database and backend doesnot even need to take care in such circumstances. I Just want to verify user otp code and provide refresh token and access token with simple jwt ( I dont know if this is correct or not) I Found only best two docs or articles that best fits my requirement. Article 1 Article 2 This is my custom user model class User(AbstractBaseUser, PermissionsMixin): CLIENT=1 DATA_ENTRY=2 ROLE_CHOICES = ( (CLIENT, 'CLIENT'), (DATA_ENTRY, 'DATA_ENTRY') ) phone_number = models.CharField(_("phone number"), max_length=60, unique=True) first_name = models.CharField(_("first name"), max_length=150, blank=True) middle_name = models.CharField(_("middle name"), max_length=150, blank=True) last_name = models.CharField(_("last name"), max_length=150, blank=True) role = models.PositiveSmallIntegerField(choices=ROLE_CHOICES, blank=True, default=1) email = models.EmailField(_("email address"), blank=True) is_staff = models.BooleanField( _("staff status"), default=False, … -
How to do SELECT COUNT(*) GROUP BY of ForeignKey field in Django?
Let's say we have three models: class Category(models.Model): name = models.CharField(max_length=255) class Platform(models.Model): name = models.CharField(max_length=255) class Product(models.Model): name = models.CharField(max_length=255) category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name='products') platform = models.ForeignKey(Platform, on_delete=models.CASCADE, related_name='products') class SellingItem(models.Model): name = models.CharField(max_length=255) product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='selling_items') price = models.DecimalField(max_digits=5, decimal_places=2) The idea here is to get a total of the different categories and platforms based on a SellingItem's queryset. My initial approach is: categories = queryset.values('product__category__id', 'product__category__name', 'product__category__label').annotate(total=Count('product__category__id')) # noqa: E501 platforms = queryset.exclude(product__platform__isnull=True).values('product__platform__id', 'product__platform__name', 'product__platform__label').annotate(total=Count('product__platform__id')) # noqa: E501 The problem is that the result is not grouped... The code is working on based on a Product's queryset if removing all product__ in the previous code. -
recently made blogsite i need guidance with user permissions (DJANGO PYTHON MYSQL)
i made a blog site sometime ago with python and django and used mysql as a database the viewers can see all written blogs and comments ,but to write blogs and comments viewers have to login or signup ...thats all good but the problem is that when i want to edit or delete a blog or comment , any logged-in user can edit or delete any comment or blog , i want to implement user permissions so that only the user who wrote the blog /comment can edit /delete it ,not every one my views from django.shortcuts import render,redirect from django.contrib.auth.models import User,auth from django.contrib import messages from app.models import signup,blog from app.forms import CommentForm,Blogform # Create your views here. def signup1(request): if request.method == "POST": Realname = request.POST['realname'] Username = request.POST['username'] sEmail = request.POST['semail'] sPassword = request.POST['spassword'] if User.objects.filter(username=Username).exists(): messages.info(request, "user exists") return redirect("/") else: user = User.objects.create_user(username=Username, email=sEmail, password=sPassword, first_name=Realname) user.save() auth.login(request, user) print("user made") return redirect("/") else: form1 = signup.objects.all() return render(request, 'Signup.html', {'signup': form1}) def login(request): if request.method == "POST": username =request.POST['lgusername'] password =request.POST['lgpassword'] user =auth.authenticate(username=username,password=password) if user is not None: auth.login(request,user) return redirect("/") else: messages.info(request,"invalid username or password") return redirect("/login") else: return render(request,"login.html") def logout(request): … -
Why is my IntegerField not editable Django
Please nudge me in the direction, I'm creating a bidding site (like ebay) where logged in users can bid on items. I have an integerfield for customers to input their new bids for the item but the problem is that from the front end, the new_bid is not clickable (from the customers side). Please advise. MODELS.PY class Auction(models.Model): ABSTRACT = 'AB' MODERN = 'MN' ILLUSTRATION = 'IN' select_category = [ ('ABSTRACT', 'Abstract'), ('MODERN', 'Modern'), ('ILLUSTRATION', 'Illustration') ] title = models.CharField(max_length=25) description = models.TextField() current_bid = models.IntegerField(null=False, blank=False) image_url = models.URLField(verbose_name="URL", max_length=255, unique=True, null=True, blank=True) new_bid = models.IntegerField(null=False, blank=False, default=0) category = models.CharField( choices=select_category, max_length=12, default=MODERN, null=True, blank=True ) created_at = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['-created_at'] def __str__(self): return self.title FORMS.PY class BidForm(forms.ModelForm): class Meta: model = Auction fields = ['new_bid'] labels = { 'new_bid': ('Choose your maximum bid'), } VIEWS.PY each_listing = Auction.objects.get(pk=listing_id) form = BidForm(request.POST) if form.is_valid: new_bid_entry = (request.POST['new_bid']) new_bid_user = request.user new_bid_listing = each_listing form.save() if new_bid_entry > Auction.current_bid(): Bids.objects.create(new_bid_entry=new_bid_entry, id=id, user=request.user) messages.add_message(request, messages.SUCCESS, "Your bid is currently the highest") else: messages.add_message(request, messages.ERROR, "Your bid must be higher than the previous bid") else: form = BidForm() context = {'form': form} return render(request, 'auctions/index.html', context) URLS.PY path("bid/<int:listing_id>/", … -
Default values in model property based on another property in the same model django
I want to send default values based on another key in the same model and I'm using Django with Postgres, for example, if the type = 'owner' || 'admin' so the can_edit property should be true otherwise it should be false. models.py class Role(models.Model): name = models.CharField(max_length=255) type = models.ForeignKey(Type, on_delete=models.CASCADE, null=True) can_edit = models.BooleanField(null=True) serializers.py class RoleSerializer(serializers.ModelSerializer): class Meta: model = Role fields = ['id', 'name', 'type', 'can_edit'] views.py @api_view(['POST', 'GET']) def roles_handler(request): if request.method == 'POST': role = RoleSerializer(data=request.data) role.is_valid(raise_exception=True) role.save() return Response({'data': role.data, 'success': True}) -
Why my translations in django i18n don't work
I've been following 3 different tutorials for text translation in django, and with none of them my translation has worked, however I was doing exactly the same steps as in the tutorials. Django just doesn't translate my text, it goes without any kind of error. My last try was with this course: https://www.youtube.com/watch?v=AlJ8cGbk8ps. But just to be sure I'm adding my code below settings.py # Internationalization # https://docs.djangoproject.com/en/4.0/topics/i18n/ LANGUAGE_CODE = 'es' TIME_ZONE = 'UTC' USE_I18N = True USE_TZ = True views.py from django.utils.translation import gettext as _ # Create your views here. def index(request): context = { 'hello':_('Hello'), } return render(request, 'index.html', context) index.html {% load i18n %} <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <h1>{{ hello }}</h1> <h2>{% trans "My name is Dawid" %}</h2> </body> </html> My locale folder looks like this: I think I should also mention that I use virtual environment, but when I switched it off it doesn't work either. Whether I switch LANGUAGE_CODE to es or pl it takes no effect. I've compiled them too. -
HTTPSConnectionPool Max retries exceeded 403 forbidden
I was deployed a django app in production pythonanywhere. I'm getting this error but I'm not getting this error on localhost: HTTPSConnectionPool(host='www.hetzner.com', port=443): Max retries exceeded with url: /a_hz_serverboerse/live_data.json I'm using the requests library to use an api. def index(request): response = requests.get("https://www.hetzner.com/a_hz_serverboerse/live_data.json") data = response.json()['server'] p = Paginator(data, 20) pn = request.GET.get('page') page_obj = p.get_page(pn) context = { 'data': data, 'page_obj': page_obj } return render(request, 'index.html', context) its working on local host but not on pythonanywhere I also tried to disable validation and I added try and except but still it's not working link : http://rodayey.pythonanywhere.com/ -
Is postgres 14 compatible with Django3.2.3 and Django framework 3.12.4?
I am using the following versions as of now Django Rest Framework is 3.12.4 Python version is 3.9 Django version is 3.2.3 PostgreSQL 13.5 Is postgres 14 compatible with the above versions? PostgreSQL 14 RC 1 now available in Amazon RDS Database Preview Environment thanks! -
'SafeString' object has no attribute 'total_seconds'
I am writing a custom template tags in django. Now, I explain you briefly. My final goal is to have in my template a duration field as hours and minutes. At the moment, I have a duration field that provides also the seconds, which I am not interested to be shown. So the goal is 1 hour = 01:00 but at the moment I have 01:00:00. I wrote this function which is working when I use it in my views but, I need also to use it inside django template. custom_tags.py from django import template register = template.Library() @register.simple_tag def duration(td): total_seconds = int(td.total_seconds()) hours = total_seconds // 3600 minutes = (total_seconds % 3600) // 60 if minutes < 1: minutes = '00' elif minutes < 2: minutes = '01' elif minutes < 3: minutes = '02' elif minutes < 4: minutes = '03' elif minutes < 5: minutes = '04' elif minutes < 6: minutes = '05' elif minutes < 7: minutes = '06' elif minutes < 8: minutes = '07' elif minutes < 9: minutes = '08' elif minutes < 10: minutes = '09' return '{}:{}'.format(hours, minutes) template <td> {% if mix.mission.duration_dual is not None %} <strong>{% duration … -
Image compression - Reverse arguments '(8, '')' not found - how do i pass slug
I am setting up image compression. def compress(image): im = Image.open(image) # create a BytesIO object im_io = BytesIO() #resize image im = im.convert("RGB") im = im.save(im_io,'JPEG', quality=70, optimize=True) # create a django-friendly Files object new_image = File(im_io, name=image.name) return new_image class Post(models.Model): slug = models.SlugField(max_length=100, allow_unicode=True, blank=True) image = models.ImageField(storage=PublicMediaStorage(), upload_to=path_and_rename, validators=[validate_image]) def save(self, *args, **kwargs): #image compression start if self.image: # call the compress function new_image = compress(self.image) # set self.image to new_image self.image = new_image #image compression end super(Post,self).save(*args, **kwargs) When the user submits the form i get this error Reverse for 'post-detail' with arguments '(8, '')' not found. 1 pattern(s) tried: ['post/(?P<pk>[0-9]+)/(?P<slug>[-a-zA-Z0-9_]+)/$'] I believe the error is caused by this line super(Post,self).save(*args, **kwargs) because the slug is not being passed in, however i cannot figure out how to pass the slug. -
Slug turns into a number when navigating to the next step in django
I tried searching for this problem here but I didn't find anything, I hope someone can help answering or sending a link to a solution on stackoverflow... I have been creating a blog, and when I click on the post title, it goes to 'post_details.html' and in the URL shows a slug with the post title. Like here: examplename.com/blog/brooklyn-nets-at-miami-heat-preview/ But when I click to write a comment on the post it takes me to a form page, but the slug title disappear, it just shows the post number. Like this: examplename.com/blog/3/add-comment Can someone explain why is this happening? I want to know how to solve this and understand from where it comes this number that shows up. Post_detail.html {% block content %} <h2 class="title"> <a class="post-title" href="{{ post.get_absolute_url }}"> {{ post.title }} </a> </h2> <p class="date"> Publicado em {{ post.created }} por {{ post.author }} </p> {{ post.body|linebreaks }} <hr> <h3>Comments</h3> {% if not post.comments.all %} Nobody commented yet...<a href="{% url 'blog:commentview' post.pk %}">Add a comment</a> {% else %} <a href="{% url 'blog:commentview' post.pk %}">Add a comment</a> {% for comment in post.comments.all %} {{ comment.name }} {{ comment.date }} <br> {{ comment.body }} {% endfor %} {% endif %} <a … -
Retrieve data if a choice in Django models.TextChoices is met
Program versions: Django 3.1.13 Python 3.8.10 My models.py: # Create your models here. class Odorant(models.Model): Pubchem_ID = models.IntegerField(primary_key = True) Name = models.CharField(max_length =50) Ruletype = models.TextChoices ('Ruletype', 'Satisfied Unsatisfied') Rule_of_Five = models.CharField(max_length = 20, choices = Ruletype.choices) Rule_of_Three = models.CharField(max_length = 20, choices = Ruletype.choices) Ghose_Filter = models.CharField(max_length = 20, choices = Ruletype.choices) I would love to retrieve all the odourants that satisfies one of the rules and also the ones that satisfy all the rules at the same time and show them in html page. I have already configured urls.py and views.py but I miss the correct function to query the database. If more code is needed, feel free to ask. Any suggestion? Thank you all. -
URL.py includes no longer works together, only one or the other
My base urls.py in the root folder is laid out as such: from django.contrib import admin from django.urls import path, re_path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('apps.main.urls')), path('', include('apps.login_app.urls')), ] But this is only seeing the apps.main.urls urls.py in its own app. It will not see the apps.login_app.urls. Though when commenting out apps.main.urls, the apps.login_app.urls start working. Any help on this would be greatly appreciated. -
Using django-widget-tweaks for multiple fields
I use django-widget-tweaks for validation like this {% if form.is_bound %} {% if form.action.errors %} {% render_field form.action class="form-control is-invalid" %} {% for error in form.action.errors %} <div class="has-error"> {{ error }} </div> {% endfor %} {% else %} {% render_field form.action class="form-control is-valid" %} {% endif %} {% else %} {% render_field form.action class="form-control" %} {% endif %} It works well but when I use two fields, my code will be. {% if form.is_bound %} {% if form.action.errors %} {% render_field form.action class="form-control is-invalid" %} {% for error in form.action.errors %} <div class="has-error"> {{ error }} </div> {% endfor %} {% else %} {% render_field form.action class="form-control is-valid" %} {% endif %} {% else %} {% render_field form.action class="form-control" %} {% endif %} {% if form.is_bound %} {% if form.action2.errors %} {% render_field form.action2 class="form-control is-invalid" %} {% for error in form.action2.errors %} <div class="has-error"> {{ error }} </div> {% endfor %} {% else %} {% render_field form.action2 class="form-control is-valid" %} {% endif %} {% else %} {% render_field form.action2 class="form-control" %} {% endif %} It doesn't look cool... If I use three, four fields code will be longer and longer. Is there any best practice for this purpose?? -
ERROR: Could not find a version that satisfies the requirement apturl==0.5.2 (from versions: none)
--> Building on the Heroku-20 stack -----> Using buildpack: heroku/python -----> Python app detected -----> No Python version was specified. Using the buildpack default: python-3.9.10 To use a different version, see: https://devcenter.heroku.com/articles/python-runtimes -----> Installing python-3.9.10 -----> Installing pip 21.3.1, setuptools 57.5.0 and wheel 0.37.0 -----> Installing SQLite3 -----> Installing requirements with pip ERROR: Could not find a version that satisfies the requirement apturl==0.5.2 (from versions: none) ERROR: No matching distribution found for apturl==0.5.2 ! Push rejected, failed to compile Python app. ! Push failed -
Django not showing group manage options in admin page
Recently, I deployed a Django web app. However, when I'm accessing the admin page, I'm not getting the expected interface to add or remove a user from a certain group: At the of inspecting the page, I'm receiving the following messages: any idea about how to handle these errros? Thanks! -
Create recommendation system from values in Django template
I'm trying to create a recommendation system in Django where I get the user with the highest rating. The rating is linked to the user as a Foreign-Key as seen in the code below: models.py class Bid(models.Model): project = models.ForeignKey( ProjectOrder, default="null", on_delete=models.CASCADE) made_by = models.ForeignKey( settings.AUTH_USER_MODEL, null=True, blank=True, default="null", on_delete=models.CASCADE ) date = models.DateField(auto_now_add=True) assign = models.BooleanField(default=False) def __str__(self): return self.project.title + " - " + self.made_by.username class Meta: ordering = ['-date'] class Rating(models.Model): username = models.ForeignKey(User, on_delete=models.CASCADE) score = models.IntegerField(default=0, validators=[ MaxValueValidator(5), MinValueValidator(0), ]) review = models.TextField(max_length=250, blank=True, null=True) reviewed_by = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True, related_name="reviewed_by") def __str__(self): return str(self.username) Template {% for bid in client_bids_assign %} <div class="p-2 my-2 d-fle" style=" border-radius: 10px; gap: 10px; box-shadow: 0 0.5px 2px rgba(128, 128, 128, 0.651); " > <small id=""> <p class="badge bg-info">{{ bid.made_by }}</p> <!-- star rating --> <fieldset class="starability-result mx-auto" data-rating="{{rating}}"> Rated: {{rating}} stars </fieldset> <p class="text-muted">{{ bid.date }}</p> </small> <form method="POST"> {% csrf_token %} <fieldset class="d-none"> <input type="text" name="bidId" id="bidId" value="{{ bid.id }}" /> </fieldset> {% if bid.assign is False %} <button class="btn btn-sm btn-outline-success" type="submit" value="{{ bid.id }}" > Assign <i class="fa fa-check-circle"></i> </button> {% else %} <button class="btn btn-sm btn-outline-danger" type="submit" value="{{ bid.id }}" > … -
Adding custom expression in values() in Django for postgresql Database
As per official Django docs for values() , The values() method also takes optional keyword arguments, **expressions, which are passed through to annotate() I wants to get result of "ts_rank_cd(textsearch, query) AS rank" as column as postgresql is getting here : https://www.postgresql.org/docs/9.6/textsearch-controls.html So my question, can I get similar column result in Django, using it's values() method and **expressions . Also I didn't found any example in net which uses values() function with **expressions argument. Please help in explaining how to use this argument, and can this will solve my issue? For safer side, I wants to use as much Django's inbuild function as possible for security purpose. -
How to use android external Jar with Beeware project
I got problem statement to create Android test application using python. Now the problem is device comes with FPS sensor and SDK which supports API's to call the FPS functionalities I am not sure if and how we can use the SDK jar files to call those extra API's Will be grateful if someone can throw some lights on how this can be achieved using beware or any other way using python and how ? -
How should I implement a joinable event that can be joined by tens of users in django in the cheapest way?
I honestly have no idea how to implement this request that I have, and even I am at loss on how to properly structure my question on what I'm exactly asking for. So, there will be a website. Users can log on it. Users can join an event at a click of a button. I'm just wondering on how they will be registered by the program to have joined the event? What serves it? Will there be a database where events are created, listed, and deleted? Is that plausible? Cheaper than any other alternatives? Moreover, there will be external information from an app that will be involved in the event, like an API that can tell me info about the user, during the event. The user will be able to join multiple events. I don't know what to do honestly. Thank you!