Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to list all foreign keys in django inline admin?
I have two models: class PublishingRestriction(models.Model): id = models.AutoField(primary_key=True) restriction_name = models.CharField(max_length=255, null=False) def __str__(self): return self.restriction_name class Meta: managed = False class ProductRestriction(models.Model): product = models.ForeignKey(Product, null=False, db_column='product_id') id = models.AutoField(primary_key=True) restriction_type = models.ForeignKey( PublishingRestriction, null=False, related_name='restrictions', db_column='restriction_type_id', verbose_name='Restriction type', ) is_restricted = models.BooleanField(default=False, verbose_name='Restriction') reason = models.CharField(max_length=255, verbose_name="Restriction explanation", blank=True) class Meta: unique_together = ('product', 'restriction_type') managed = False And inline admin (inside ModelAdmin for Product): class ProductRestrictionInline(admin.TabularInline): model = ProductRestriction extra = 1 can_delete = False verbose_name_plural = 'Other publishing restrictions' verbose_name = 'publishing restriction' fields = ('restriction_type', 'is_restricted', 'reason') def has_add_permission(self, request): return True I want to display a list of all restriction_type (which are foreign keys) instead of having user add a new row in inline (all restriction types need to be listed in advance - even if ProductRestriction doesn't exist for given Product yet. Is there a vanilla way of achieving it? -
Django - How to see all permissions that wrap a view using custom decorator
I am writing tests for a system in an attempt to ensure that all permissions associated with the view are accurate and accessible to users that actually have the permission associated with them. We have had a few instances where misspellings made it so the view was inaccessible, so this is what I am trying to test. My admin users always have the correct permissions associated with them so naturally the easiest solution to ensure that each view will load for an admin would be to ensure that the permission decorator's permissions for each view are valid permissions stored in the database, however, I cannot seem to find a way to get a URL, resolve it, and then see what permissions are actually associated with the view. For example, here is a simple view: @permissions_required('prospects.view_prospect', 'prospects.change_prospects') def prospects(request, client_url): return render(request, 'prospects/index.html', {}) And here is the decorator @permissions_required def permissions_required(*perms, raise_error=False): """ Decorator for views that checks whether a user has a particular permission enabled, redirecting to the log-in page if necessary. """ def check_perms(user): allowed = all([user.has_perm(perm) for perm in perms]) if not allowed and raise_error: raise PermissionDenied return allowed return user_passes_test(check_perms) I would like to know that … -
Axes with customized django rest framework and simpleJWT
I am a beginner at Django and was building a login system. I wanted to use axes with django rest framework and simpleJWT. According to the documentation for Django-Axes: Modern versions of Django REST Framework after 3.7.0 work normally with Axes out-of-the-box and require no customization in DRF. Now I have built a Custom User for my project who gets authenticated using my own custom authentication backend. For creating the Access and the Refresh tokens I have localhost:8000/api/loginend point which creates both the tokens and stores them as HTTPOnly cookie. The login view is like this : @api_view(['POST']) @permission_classes([AllowAny]) @ensure_csrf_cookie def login_view(request): # print("captcha token = ", request.POST.get('g-recaptcha-response')) Account = get_user_model() EmailId = request.data.get('EmailId') password = request.data.get('password') response = Response() if (EmailId is None) or (password is None): raise exceptions.AuthenticationFailed('username and password required') # get the user with the credentials provided user = Account.objects.filter(EmailId=EmailId).first() if not check_user_validity(user, password): # locking the user raise exceptions.AuthenticationFailed('The credentials are invalid') else: print('user is valid') # get the token values tokenvals = get_jwt_tokens(user) response.set_cookie(key='refreshtoken', value=tokenvals['refresh_token'], httponly=True) response.set_cookie(key="accesstoken", value=tokenvals['access_token']) response.data = { 'access_token': tokenvals['access_token'], 'id': user.id } return response I can refresh the access token using localhost:8000/api/Refresh endpoint. get_jwt_token(user) returns a dictionary with both access … -
Django Q filter foreign key
I'm trying to create a search that takes input from two fields and searches using both. I know how to filter for non foreign key but trying to filter the foreign key gives the error "Related Field got invalid lookup: country" I want jobs to return the results of filtering both query and country. How can I best achieve this? model: class Job(models.Model): title = models.CharField(max_length=50) ... country = models.ForeignKey( Country, blank=True, null=True, help_text="Select if you're hiring within a specific " "country", on_delete=models.PROTECT ) view: def jobs_search(request): form = SearchForm(request.GET) if form.is_valid(): cd = form.cleaned_data jobs = Job.objects.filter(site_id=get_current_site(request).id) \ .filter(paid_at__isnull=False) \ .filter(expired_at__isnull=True) \ .filter( Q(title__icontains=cd['query'], ) | Q(description__icontains=cd['query']) & Q(country__country__icontains=cd['country']) ) \ .order_by('-paid_at') meta_desc = 'Search Results' title = 'Search Results' context = {'meta_desc': meta_desc, 'title': title, 'form': form, 'jobs': jobs} return render(request, 'job_board/jobs_index.html', context) -
Sending Emails to University Domains
Hello I have a django project where users can sign up and then they get a confirmation e-mail. Everthing works fine they are getting the confirmation and can log in afterwards except when they enter a University email. Which has a .edu domain. Then they are not getting any email. However when I send manuelly from gmail they are becoming the email. Do you know how can I solve this issue. EDIT Here are my Email settings EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = '*********@gmail.com' EMAIL_HOST_PASSWORD = '******' DEFAULT_FROM_EMAIL = '*******' EMAIL_PORT = 587 This is the template which the User should get {% autoescape off %} Merhaba {{ user.username }}, Hesabınızı aktifleştirmek için aşağıdaki bağlantıya tıklayın. http://{{ domain }}{% url 'account:activate' uidb64=uid token=token %} {% endautoescape %} I also see that the email was sent under the sent folder but nothing comes to the university mail -
How to display jinja2 template (j2 file) in HTML page with correct format?
I'm able to display jija2 template on HTML page, but the output format is not correct. current output is: Your first name is Tom Your last name is Hanks Expected output is: Your first name is Tom Your last name is Hanks Views.py from django.shortcuts import render from django import forms from jinja2 import Environment, FileSystemLoader class DbNames(forms.Form): first_name = forms.CharField(label="First Name") last_name = forms.CharField(label="Last Name") def index(request): return render(request, "emps/index.html") def form_gen(request): form = DbNames() if request.method == "POST": form = DbNames(request.POST) if form.is_valid(): file_loader = FileSystemLoader('emps/templates/emps') env = Environment(loader=file_loader) template = env.get_template('hello_world.j2') output = template.render(form.cleaned_data) return render(request, "emps/output.html", { "form_data": output }) else: print('ERROR') return render(request, "emps/users.html", { "form": form }) result.j2 Your first name is {{first_name}} Your last name is {{last_name}} -
Reverse for 'update_cart' not found. 'update_cart' is not a valid view function or pattern name
I am new in django and i am developing one application in that on click i am trying to add product in cart.To select product i am using "{%url 'update_cart' product1.slug%}"> in my template,I am including my code here. This is model models.py class cart(models.Model): product=models.ManyToManyField(products,blank=True) total=models.DecimalField(max_digits=100,decimal_places=2,default=0.00) def __unicode__(self): return "cart id: %s" %(self.id) This is views views.py def cartpage(request): c_data=cart.objects.all()[0] return render(request,'cart/cart.html',{'c_data':c_data}) def update_cart(request,slug): c_data = cart.objects.all()[0] try: product1=products.objects.get(slug=slug) except products.DoesNotExist: pass except: pass if not product1 in c_data.product.all(): c_data.product.add(product1) else: c_data.product.remove(product1) return HttpResponseRedirect(reverse("cart")) This is urls urls.py path('cart/',views.cartpage,name='cart'), path('cart/<slug:slug>',views.update_cart,name='update_cart') I have created cart model and registered it in admin...its working properly even in my cart.html page is also working,but if i try to add product on click in cart page its giving me error. please help -
Django starts putting a slash in front of my static url relative path in 3.1
I had this code that worked ok in 3.0.8 <script src="{% static 'js/main.js' %}"></script> with the value in settings: STATIC_URL = ( "static/" # /static/ for django web development, static/ for django-bakery build ) when building with bakery it works only if I supply the relative path. But since 3.1, as per their release notes: The STATIC_URL and MEDIA_URL settings set to relative paths are now prefixed by the server-provided value of SCRIPT_NAME (or / if not set). This change should not affect settings set to valid URLs or absolute paths. (https://docs.djangoproject.com/en/3.1/releases/3.1/#backwards-incompatible-3-1) it puts a / in front of my static url and the build fails. Any ideas how to avoid it? I use django bakery to bake the site into a single file, no server. -
Custom template for PasswordResetConfirmView
I am wanting to create a template for a user to enter new password and confirm password after opening the password reset link. Currently it is leading to a page with title django administration. This is my urls.py: path('reset/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(), name='password_reset_confirm'), I am wanting to know what name should I use for the input fields of new password and confirm password. I searched through the internet and found out many people were using django forms which I am not doing so I wasnt able to find what the name attribute should have in input tag for passwordresetconfirmview. -
Can not restore postgreSQL dump file in AWS
I tried to restore PostgreSQL database from dump file in AWS but an error occurred. it said pg_restore: [archiver] unsupported version (1.14) in file header What should I do? -
Display products in listview by category in the category page(Django)
I am creating an ecommerce website in Django where I will have specific categories of product.Each category will be displayed on its own page in a listview. So I am looking for a template tag to display the product by category in my database in the specific category's page this is the Product model class Product(models.Model): name = models.CharField(max_length=200, verbose_name=('name')) price = models.FloatField() category = models.CharField(max_length=200, null=True, verbose_name=('category') ) available = models.BooleanField(default=False,null=True, blank=True, verbose_name=('available')) image = models.ImageField(null=True, blank=True) class Meta: verbose_name = _('produit') verbose_name_plural = _('produits') def __str__(self): return self.name The shoes category page template {% for product in products %} <div class="col-lg-4"> <img class="thumbnail" src="{{product.imageURL}}"> <div class="box-element product"> <h6><strong>{{product.name}}</strong></h6> <hr> <button data-product="{{product.id}}" data-action="add" class="btn btn-outline-secondary add-btn update-cart">Ajout panier</button> <a class="btn btn-outline-success" href="">Voir</a> <h4 style="display: inline-block; float: right;"><strong>{{product.price}}€</strong></h4> </div> </div> {% endfor %} </div> -
How to return multiple custom filters in a function based view
So I have written three custom filters, from which I need two in my view to display them on my webpage. This is my filters.py class ProductFilter(django_filters.FilterSet): class Meta: model = Product fields = ['title'] class TagFilter(django_filters.CharFilter): field_class = TagField def __init__(self, *args, **kwargs): kwargs.setdefault('lookup_expr', 'in') super().__init__(*args, **kwargs) class MyTagFilter(django_filters.FilterSet): tags = TagFilter(field_name='tags__name') class Meta: model = Product fields = ['tags'] and my view looks this at the moment: def product_list(request): qs = Product.objects.all() product_filter = ProductFilter(request.GET, queryset=qs) tag_filter = MyTagFilter(request.GET, queryset=qs) return render(request, 'cart/product-list.html', {'filter': product_filter}) I tried to make a dictionary out of the two filters and return them in the render method, but this didn't work and they don't show up in my template, which looks like this <div class="row"> <div class="col-sm-12"> <form method="get"> {{ filter.form|crispy }} <button class="btn btn-sm amphibian-button-primary btn-block element-shadow img-audio">Submit</button> </form> </div> Can anybody guide me into the right direction? Thanks a lot! -
Django channels, how to start consuming after connecting
I'm trying to understand the flow of a consumer in Django Channels. I've written the following consumer which performs a small check on a query set and returns a result every minute. I've been able to establish connection with the WebSocket, but I don't understand how later I start consuming it, again, I need it to run the check every 60 seconds, so using sleep somehow? consumer: class CameraOnlineConsumer(JsonWebsocketConsumer): def connect(self): self.farm_name = '1' self.farm_group_name = 'farm_%s' % self.farm_name # Join farm group async_to_sync(self.channel_layer.group_add)( self.farm_group_name, self.channel_name ) # TODO: Once working, add Auth # accept connection self.accept() def camera(self, event): result = self.check_events() # Get updated camera status async_to_sync(self.channel_layer.group_send)( self.farm_group_name, # send result to group { 'type': 'check_events', 'message': result } ) @database_sync_to_async def get_events(self): return PastureEvent.objects.filter(result=8, farm_id=self.farm_name, processed=False).order_by('-time_stamp')[ :2] @database_sync_to_async def update_event(self, query_set): PastureEvent.objects.select_for_update().filter(id=query_set[1].id).update(processed=True) def check_events(self): minute_delta = timedelta(seconds=60) query_set = self.get_events() if not query_set: result = {'camera status': CameraOffline.default_detail, } return result elif len(query_set) == 1: # means that no new events has been recorded since last check. result = {'camera status': CameraOnline.default_detail, 'first time_stamp': str(query_set[0].time_stamp)} return result elif len(query_set) >= 2: # two relevant events received. difference = query_set[0].time_stamp - query_set[1].time_stamp if difference <= minute_delta: if query_set[1]: … -
Django personalized url
I need to use sub-domains (i think) on Django. I have many "room" on my project and i need to build url with name of room. Example : If i have a room named "microsoft" and my domain is http://toto.fr i want to have a final url like : "http://microsoft.toto.fr" to go in room of microsoft. I can have few room then few differents url. How its possible to have this ? Django Sub-Domains can do this ? Thanks you ! -
Generic detail view must be called with either an object pk or a slug in the URLconf
Django is giving me the following error when I try to access /domains/{domain}/{host}: Generic detail view HostDetailPageView must be called with either an object pk or a slug in the URLconf. It appears that DetailView is expecting something different than what I am providing. urls.py urlpatterns = [ path('domains/', DomainsPageView.as_view()), path('domains/<str:domain>', DomainHostsPageView.as_view()), path('domains/<str:domain>/<str:host>', HostDetailPageView.as_view()), path('', TemplateView.as_view(template_name="hosts/index.html")) ] views.py class HostDetailPageView(DetailView): template_name = 'hosts/hostdetail.html' model = Host # Populates list of enabled domains in the context def get_queryset(self): qs = super().get_queryset() filtered = qs.filter(name=self.kwargs['host']) if not filtered.exists(): raise Http404("Host does not exist") # filter by a variable captured from url, for example return filtered.first() def get_context_data(self, **kwargs): return super().get_context_data(**kwargs) -
Sending data from Django websocket channels to client using threading module
I have client react app, and django as server, i have implemented WebsocketConsumer using channels and tried to connect from client and server, it did connected successfully, once connection established i would like to create a Thread in inside connect method of **WebsocketConsumer ** and send data to cliend every after 1 second, if client disconnected kill or stop thread. below is my current implementaion Websocket Connection created successfully once connection established, creating thread to send data to client every after 1 sec import json from channels.generic.websocket import WebsocketConsumer from threading import Thread, Event import threading from time import sleep myThread = threading.Thread() thread_stop_event = Event() class ChatConsumer(WebsocketConsumer): def connect(self): print("connected==========") self.accept() # this send could able to send the messahe to client self.send(text_data=json.dumps({ 'message': {'data': 1} })) global myThread if not myThread.isAlive(): print("Starting Thread") dataThread = DataThread() dataThread.start() def disconnect(self, close_code): pass def receive(self, text_data): print(text_data, "Message from client========") #Thread creation class DataThread(Thread): def __init__(self): print("__init__") self.delay = 1 super(DataThread, self).__init__() self.count = 0 def dataGenerator(self): print("Initialising") global myThread try: while not thread_stop_event.isSet(): print("inside while") self.count = self.count + 1 # AttributeError: 'DataThread' object has no attribute 'send' self.send( {"counter": self.count}) # sleep(self.delay) # print(self.count) except KeyboardInterrupt: print("Keyboard Interrupt") … -
why this paypal-HTML code is not working?
Though I copy pasted from this link ( https://developer.paypal.com/docs/business/checkout/advanced-card-payments/#step-1-enable-your-business-account-for-advanced-credit-and-debit-card-payments ). But card_field is not working as well as it's not showing paypal-button-container. -
How to make a correct get queryset with a list in Django to get values
I have a list of languages. For example languages = ['Russian', 'English', 'German', 'Italian', 'French'] And I need to get the id of each language. I'm trying to do it the following way: languages = ['Russian', 'English', 'German', 'Italian', 'French'] languages_to_save = [] for l in languages: lang_id = Language.objects.get(lang = l) languages_to_save.append(lang_id) But I have an Error: Language matching query does not exist. Though if I change the line to any lanugage in the list, it works correctly. For example: lang_id = Language.objects.get(lang = 'German') Can anyone help with this? -
XMLHttpRequest.send(data) not delivering data to Django view function
Using pure Javascript, my goal is to recreate jQuery's .autocomplete() function for displaying a list of suggestions as a user types input into the search bar. I have written code that listens for "keyup/change/paste/input" events on the input element, i.e search bar. As the user types, I wish to use an XMLHttpRequest GET (or POST) request which will deliver the user's input so far (and information about the search context -- not relevant) to a view function which will in turn filter a Model for objects containing the user's input so far and return those objects in a JSONResponse list to the XMLHttpRequest so that I can display the suggestions on the webpage. I tried to use both GET and POST requests but the data I wished to send to the view function using XMLHttpRequest.send(data) never seemed to deliver to the view function thus inhibiting my progress. In all attempts, printing request.POST (or request.GET) gave empty an QueryDict: <QueryDict: {}> Below are some code snippets: \\ The below JS code is run on once the page is ready, i.e fully loaded addListenerMulti(query, "propertychange change click keyup input paste", function () { // check if value has changed... if (query.value != … -
Django's docker container doesn't catch the environment ALLOWED_HOSTS variable in GitLab CI pipeline
I'm trying to build a GitLab-CI pipeline but Django doesn't seems to catch the ALLOWED_HOST variable passed as environment variable. The project it self is a Django project running in a container. Django needs an ALLOWED_HOSTS and a SECRET_KEY value in its settings in order to work. On my development environment as well as on my production server, the variables are passed to Django via an env-file. Django settings sample: SECRET_KEY = os.environ.get('SECRET_KEY') ALLOWED_HOSTS = os.environ.get("DJANGO_ALLOWED_HOSTS").split(" ") Env-file sample: SECRET_KEY=mydummysecretkey DJANGO_ALLOWED_HOSTS=localhost 127.0.0.1 [::1] This works fine on my dev and my production machines. But when I try to run it in my .gitlab-ci.yml, Django doesn't find the DJANGO_ALLOWED_HOSTS variable. I always got this error: $ docker run --rm $CI_REGISTRY_IMAGE:$CI_COMMIT_SHA py.test ./my_project ALLOWED_HOSTS = os.environ.get("DJANGO_ALLOWED_HOSTS").split(" ") AttributeError: 'NoneType' object has no attribute 'split' ERROR: Job failed: exit code 1 This is quite strange because Django catches the SECRET_KEY variable well. As you can see in the code snippet bellow, I even did an echo on the variable which is well displayed. FYI: Django is running in a Docker container and the CI-pipeline build the image (and pushes it to the Gitlab registery) on the first job in order to test it … -
Dynamically calculate batch_size for bulk operations in Django
Currently, we are updating/creating bulk objects in batches which is not optimal, because we have defined the batch size as fixed, but object size can be different due to difference in data. If the object size is less then given batch size, the performance is not optimal; and if the object size is more, then it can causes memory issue. (1153, "Got a packet bigger than 'max_allowed_packet' bytes") Is there a way, where I can calculate the optimal batch_size, to give it as argument while calling bulk_create/update. PS: I am not allowed to change the max_allowed_packet -
Django Social-auth redirecting to wrong domain
I have python-social-auth setup with django and it works fine in development. However, the redirection doesn't work in production, the reason being that once the user has logged in, the user is redirected to 192.168.1.100 which is my server's local IP. I've tried adding: ABSOLUTE_URL = "example.com" SOCIAL_AUTH_LOGIN_REDIRECT_URL = 'https://example.com' ALLOWED_EXTERNAL_OPENID_REDIRECT_DOMAINS = ['https://example.com'] in settings.py, to no avail. Furthermor, Steamopenid still displays 192.168.1.100 on the login page: "Note that 192.168.1.100" is not affiliated to Valve." How can I specify to steamopenid a different domain? Thanks in advance! -
Django HomeView query performance improvement
Whenever a user goes homepage I do query operations to send data with context to the homepage template, is there any better way to do query operations? class HomeView(LoginRequiredMixin, View): """ Display homepage with appropriate context.""" template_name = 'pages/home.html' login_url = 'login' redirect_field_name = '' def get(self, request, *args, **kwargs): current_user = request.user fitness_person_of_current_user = current_user.fitness_person_user daily_person_of_current_user = fitness_person_of_current_user.dailyperson_set.filter( date_added__date=timezone.now().today().date())[0] daily_exercise_program_of_current_user = daily_person_of_current_user.exerciseprogram_set.filter( date_added__date=timezone.now().today().date())[0] daily_diet_program = daily_person_of_current_user.dietprogram_set.filter( date_added__date=timezone.now().today().date())[0] # first object of set is oldest daily_person, last object of set is newest daily_person last_seven_days_daily_persons = DailyPerson.objects.filter(fitness_user=fitness_person_of_current_user)[:7] context = {'daily_person': daily_person_of_current_user, 'fitness_person': fitness_person_of_current_user, 'daily_exercise_program': daily_exercise_program_of_current_user, 'daily_diet_program': daily_diet_program, 'last_seven_days_daily_persons': last_seven_days_daily_persons} return render(request, self.template_name, context) -
How do I pass argument to a scheduled cron task, in Django?
I've set up a cron job to decrement the IntegerField of all objects, every minute. But it throws the error: TypeError: decrement_days_till_study() missing 1 required positional argument: 'Card' But I have no idea how I might pass this. cron.py from . models import Card def decrement_days_till_study(Card): for card in Card.objects.all(): if card > 1: card.days_till_study -= 10 card.save() My models are in the same folder as a cron.py. I tested cron by having it print a string which worked fine. Any idea on how to solve this? Thanks for reading. -
how to display messages in django template using alertify js?
hi i need to display success messages in my template , but the problem is it doesnt display anything i tried this : <link type="text/css" rel="stylesheet" href="{% static 'css/default.css' %}" /> <script type="text/javascript" src="{% static 'js/alertify.js' %}"></script> <script type="text/javascript" src="{% static 'js/alertify.min.js' %}"></script> <script> {% if messages %} {% for message in messages %} alertify.success({{message}}); {% endfor %} {% endif %} </script> and this is views.py def AddPostDetail(request): formset = AccessoryNameFormSet(queryset=Post.objects.none()) if request.method == 'POST': formset = PostFormSet(request.POST) if formset.is_valid(): for form in formset: form.save(commit=False) if form.cleaned_data !={}: form.save() messages.success(request, 'successed') return redirect(reverse_lazy('posts-list')) return render(request,'post/post-detail.html',{'formset':formset}) but doesnt work ?! is there something i have missed please ?