Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I check if users belongs to a certain model
I have models: Student, Teacher, and CustomUser. A CustomUser belongs either to student or teacher. When logged in, I want to check if the user is instance of student or teacher in the template html. I've tried the following, but it doesn't work. {% if user is a student %} <a class="dropdown-item" href="{% url 'edit_student_profile' %}">Profile</a> {% elif user is a teacher %} <a class="dropdown-item" href="{% url 'edit_teacher_profile' %}">Profile</a> {% else %} <a>Error. Go signup as teacher or student!</a> {% endif %} -
This is a number guess generator, Please help to pass arguments to checker() function
This is a program for matching out input with random number generated by a function. There are three functions, 'index()' for display the webpage, there we can input a value to check with the random number generated by rangen() , 'rangen()' for generating the random number, 'checker()' for checking the values. here I need to pass the value generated by 'rangen()' to my 'checker()' how it is possible? views.py from django.shortcuts import render from django.http import HttpResponse import random # Create your views here. def rangen(request): rannumber= random.randint(1,3) print(rannumber) return rannumber def index(request): return render(request,'generator/index.html') def checker(request): print(rannumber) if request.method=='POST': innum = int(request.POST['inputnumber']) print(innum) if (rannumber==innum): flag = 'Congratulation!!! Number Matched' return render(request,'generator/index.html',{'flag':flag}) elif(innum>rannumber): flag = 'Oops!!! You Entered a High Value, Try Again!!!' return render(request,'generator/index.html',{'flag':flag}) else: flag = 'Oops!!! You Entered a Low Value, Try Again!!!' return render(request,'generator/index.html',{'flag':flag}) index.html <div class="formclass"> <h1>Random Generator</h1> <form action="checker" method="post"> {% csrf_token %} <h3>Enter you guess</h3> <input type="text" name="inputnumber" placeholder="Enter Your Guess" required><br><br> <button type="submit" name="button">Submit</button> <h1>{{flag}}</h1> </form> </div> No errors when I run the server, but when i provide my guess value it showing ' NAME ERROR: name 'rannumber' is not defined' -
Geting a user object without using request in django signals
From my research online there are many questions related to what i am about to ask. Solutions i saw do not solve my problem because mine is related with django channels and signals . Here is a post save signal code in my consumer(channels). private chat consummer class ChatConsummer(AsyncConsumer): async def websocket_connect(self,event): await self.channel_layer.group_add( "private_chat", self.channel_name, ) data={ 'chats':data_array } def Create_Notify(sender,instance,**kwargs): data={'notificat':'notication'} notification_data={ 'notify':data, } async_to_sync(get_channel_layer().group_send)("private_chat", {"type": "Send_Message",'text':json.dumps(notification_data)}) post_save.connect(Create_Notify,sender=notifyall) So in my code, i am accessing the channel layer outside the consumer function meaning i can not use self.scope['user'] to get the current login user . I am using post_save signal function making it impossible to use request to access the current login in user . So please help me, i need to access the current login user in my post_save signal which calls channel layer out outside a channel consumer function . -
Django is ignoring filters
I am trying to create a simple "Search" feature for my e-commerce website project which has several products in its database. models.py INR='₹' USD='$' CURRENCY_LIST=[(INR,'INR'),(USD,'USD')] subcategory=models.ForeignKey(Subcategory,on_delete=models.CASCADE) category=models.ForeignKey(Category,on_delete=models.CASCADE) name=models.CharField(max_length=50) price=models.DecimalField(max_digits=8,decimal_places=2,db_column='price') currency=models.CharField(max_length=3,choices=CURRENCY_LIST,default=INR,db_column='currency') view_count=models.IntegerField(default=0) @property def combined(self): return self.price+self.currency class Meta: db_table='Products' verbose_name_plural='products' def __str__(self): return self.name serializers.py class Meta: model=Products fields='__all__' views.py def get(self,request): if request.method=="GET": search=request.query_params['search'] sort=request.query_params['sort'] start,end=request.query_params['filter'].split('-') q1=Products.objects.filter(name__icontains=search) q2=Products.objects.filter(subcategory__name__icontains=search) q3=Products.objects.filter(category__name__icontains=search) q1=q1.union(q2,q3) if sort=="low to high": q1=q1.filter(price__gte=start,price__lte=end).order_by('name','price') serializer=ProductsSerializer(q1,many=True) return JsonResponse({"response":serializer.data}) elif sort=="high to low": q1=q1.filter(price__gte=start,price__lte=end).order_by('-price','name') return JsonResponse({"response":serializer.data}) elif sort=="most popular": q1=q1.filter(price__gte=start,price__lte=end).order_by('views') return JsonResponse({"response":serializer.data}) Before the second 'if' block starts(in views.py file), I am getting correct search results. But after that, Django simply returns the same unfiltered queryset. -
Invalid connecting string when using IP adress, hostname seems not an option
Recently I transferred a Django project to a windows server with IIS. Locally on my development workstation everything runs fine. Now on the IIS server, when I'm using manage.py to locally test the site, it trows upon starting the local server an error: "django.db.utils.OperationalError: (com_error(-2147352567, 'Exception occurred.', (0, 'Microsoft OLE DB Provider for SQL Server', 'Invalid connection string attribute', None, 0, -2147467259), None)" Initially I can get it to startup by switching from IP to hostname. If I then proceed to try and browse the site I come upon the following error: "When using DATABASE PORT, DATABASE HOST must be an IP address." Due to this I'm unable to use both the host name or IP address. I've tried different drivers, different ways of creating the connection dictionary. ('ip,port', only IP, only host name) Nothing works when initiating the test server, except for when I use the port and host name. But as said above it then later on runs into a problem with a port nr expecting an IP address and not a hostname. On my dev workstation this db dictionary is working fine, the website runs and data can be accessed: 'default': { 'NAME' : 'database_name', 'ENGINE': 'sqlserver_ado', … -
Render form inside topbar in all routes
I just wanna ask about the best approach to render a form in all routes. Basically what I want is to allow users to login from anywhere within the site by putting the login form in the topbar. Currently, I have a /login/ route whose form is built-up from forms.py and rendered thru a view function. I want to redesign the login flow to the one specified above. Any suggestion would be awesome. Thanks! -
CryptoControl - Python Crypto News API Integration in Python Django
[{ "hotness": 70862.60323026273, "activityHotness": 4.601980262729618, "primaryCategory": "General", "words": 1444, "similarArticles": [ { "_id": "5b363b525b113200191a1d5f", "publishedAt": "2018-06-29T13:42:44.000Z", "title": "Op-Ed: Challenge of Mining Centralization Unveils Bitcoin’s Elegant Design", "url": "https://cryptocontrol.io/r/api/article/5b363b525b113200191a1d5f?ref=5ac11440ec0af7be35528459", "source": { "_id": "59d8c361ef8bf95cc2bfb66f", "name": "Bitcoin Magazine", "url": "https://bitcoinmagazine.com/" }, "sourceDomain": "bitcoinmagazine.com", "thumbnail": null }, { "_id": "5b3865405c5681000f2f7407", "publishedAt": "2018-06-30T14:58:00.000Z", "title": "Arbitration on a Governed Blockchain: EOS’ Crisis of Dispute Resolution", "url": "https://cryptocontrol.io/r/api/article/5b3865405c5681000f2f7407?ref=5ac11440ec0af7be35528459", "source": { "_id": "59d70be3ef8bf95cc2aa2b4f", "name": "CoinTelegraph", "url": "https://cointelegraph.com/" }, "sourceDomain": "cointelegraph.com", "thumbnail": null } ], }] -
How to filter queryset for foreign key that is inherited
I have a class A: class A(models.Model): name = models.CharField(max_length=255) class B that has a foreign key of class A: class B(models.Model): a = models.ForeignKey(A, on_delete=models.CASCADE) then I have class C that is inherited from class B: class C(models.Model): class Meta: managed = True text = models.CharField(max_length=255) Is class C also has foreign key of class A. If it has, how can I get class A objects that satisfies certain requirements of object of class C. I tried to do something like: A.objects.filter(c_text='Hello') But it doesn't work. I can't even get right filter with Pycharm tips. -
django model to access database
Request some help from django community. Iam new to Django. My requirement is 1 - create a DRF which will execute a stored procedure in an existing database( Master data management in MS SQL database) and list down the records . 2 - further when we navigate to each record from point number 1 we display the details of the records with more fields. I have already created a function which uses pyodbc in my view.py file to achive the result and the display the values. But I have read some where that as a best practice it is always better to define a model and then a serializer to define the data structure and display them. Question : 1)Is it a correct approach to define a model for the above senario. 2) As per my knowledge when ever we create a model it creates a database table which I don't want it to be created (as I have the database already with all the necessary table and data). so if point 1 is yes then can you give reference build the model which will not create the table. 3)Further to the above requirement I like to connect multiple database … -
How to list instances in django annotate?
I'm trying to do a Django annotate and want to list some of the object instances by filtering a field. I have two model, which is Category and Article. This Category model has a field called super_category which is a choice field and the coices are "ACADEMIC, OTHER" class Category(models.Model): name = models.CharField( max_length=128, null=False, blank=False, default=None, verbose_name=_("Name"), ) super_category = models.CharField( blank=False, null=False, choices=SC_CHOICES, max_length=10, default=None, ) And now, this is my current annatation result: [ { 'article_count': 716, 'super_category': u'ACADEMIC', 'category_count': 5, }, { 'article_count': 800, 'super_category': u'OTHER', 'category_count': 2, } ] the query for this : Category.objects.only( "id", "articles__id", "super_category", ).values( "super_category", ).annotate( category_count=Count("id", distinct=True), article_count=Count("articles"), ).order_by( "super_category", ) What I wanna do is, adding the articles to the result So at the end, I want something like this: [ { 'article_count': 716, 'super_category': u'ACADEMIC', 'category_count': 5, 'categories': [ { "id": 1, "name": "COMPUTER SCIENCE", "article_count": 15, }, ... ] }, { 'article_count': 800, 'super_category': u'OTHER', 'category_count': 2, 'categories': [ { "id": 1, "name": "MAGAZINE", "article_count": 15, }, ... ] } ] Now, since the additional "categories" is the same object type which I am trying to annotate, I seriously do not know how to do it. -
Celery Worker exited prematurely: signal 9 (SIGKILL) on serializer.is_valid()
I know that there are some questions already about this topic, so I understand the general idea, but this is more specific. In some job that runs on our celery worker, we're creating a lot of objects (about 2000). Seems like every time, at some point, around the 2000th object (1700-1900) we get this error: Worker exited prematurely: signal 9 (SIGKILL) And it always seems to happen around this part of the code: serializer = ModelSerializer(data=model_data) Logger.info("serializer created") if serializer.is_valid() is True: Logger.info("serializer valid") I do see the first log, so I guess the serializer is created successfully, but I don't see the second log. And it's not that the serializer is not valid, because that case is covered as well. I just stop seeing any logs from the job after that line of code (if serializer.is_valid()). When trying to create less objects it seems fine. So my question is why would using a lot of serializer.is_valid() in one celery job cause that process killing? -
FileField not working with ArrayField in Django
Using FileField inside ArrayField in Django For Multiple File Uploads but ArrayField is taking the files as string and not saving the files. If the Above Cannot work is there any other working way in Django for Multiple File Upload. I have tried some of the solutions available but none of those seemed/worked relevently for the case Models.py class Questions(models.Model): def content_file_name(self, name): return outside_asset = ArrayField(models.FileField(upload_to=content_file_name, blank = True,default=False),default=[],blank=True) unquoted_shares = ArrayField(models.FileField(upload_to=content_file_name, blank = True,default=False),default=[],blank=True) capital_gains = ArrayField(models.FileField(upload_to=content_file_name, blank = True,default=False),default=[],blank=True) class Meta: db_table = 'Questionnarie' managed = True views.py outside_asset_list = [] unquoted_shares_list = [] capital_gains_list = [] if form.is_valid(): for x in request.FILES: val = x print('val :', val) files = request.FILES.getlist(val) print('files inside loop :', files) if val == 'outside_asset': for f in files: filename = f outside_asset_list.append(filename) print(outside_asset_list) print('files :', outside_asset_list) elif val == 'unquoted_shares': for f in files: filename = f unquoted_shares_list.append(filename) print('files :', unquoted_shares_list) elif val == 'capital_gains': for f in files: filename = f capital_gains_list.append(filename) print('files :', capital_gains_list) Questions.objects.create(user=user, year=year, outside_asset= outside_asset_list, unquoted_shares=[unquoted_shares_list], capital_gains=[capital_gains_list]) return Response.... All the files sent in request should be uploaded to a specific folder and their path should be saved as a list in the database in … -
How to dynamically populate a many-to-many field in a Django admin form by calling a custom function?
Let's say I have the following model class Plasmid (models.Model): name = models.CharField("name", max_length=255, unique=True, blank=False) map = models.FileField("plasmid map") formz_elements = models.ManyToManyField(FormZBaseElement) and a function called get_plasmid_map_features, which takes a Plasmid.map, analyzes it, and returns a list of formz_elements. I'd like to implement a custom button in the admin Plasmid form (e.g. "Click here to get plasmid features"), which would populate the formz_elements field WITHOUT having to hit Save(I can accomplish this upon form submission easily!), while leaving the values of all other fields untouched (i.e. I only want to change the formz_elements field). Any suggestions? Thanks in advance. -
On loading user email list, showing [email protected] for few seconds in django template?
On loading user email list, showing [email protected] for few seconds in django template. Showing [email protected] It is showing when first time loaded, only for few time. Not found any solution. If any body have any suggestion please reply. On loading, showing [email protected] after few seconds showing email like user@mail.com -
Sessions not saved
My sessions stopped saving after I added a middleware that redirects to the login page if a user hasn't logged in yet. It was working before adding the middleware. I tried using request.sessions.save() and request.session.modified = True but it did not solve the problem Here is my middleware: class LoginMiddleware(object): def __init__(self, get_response): self.get_response = get_response def __call__(self, request): if "name" not in request.session: if request.GET.get("login_name"): request.session["name"] = request.GET.get("login_name") request.session.modified = True response = response = self.get_response(request) else: response = render(request, 'login.html') else: response = self.get_response(request) return response Here is my login view: def Login(request): if "name" in request.session: return foo(request) else: if request.GET.get("login_name"): request.session["name"] = request.GET.get("login_name") request.session.modified = True else: return render(request, 'login.html') return foo(request) Here is my login HTML: <form action="" method="GET"> <input type="text" name="login_name" required> <button type="submit" class="btn btn-success">Submit</button> </form> Here is my URL: urlpatterns = [ path('', views.Login, name='login'), url(foo', views.foo, name='foo'), ] The middleware is added in settings, and it is called. It's supposed to redirect to the login page if there is no request.session["name"], which it does. When I call request.session["name"] from other views, it returns None. Previously, it returned the saved name. Any recommendations? -
Plz help me with this django task
A website that will first randomly generate a number unknown to the website visitor. The visitor needs to guess what that number is. (In other words, the visitor needs to be able to input information.) If the visitor’s guess is wrong, the program should return some sort of indication as to how wrong (e.g. The number is too high or too low). If the visitor guesses correctly, a positive indication should appear. You’ll need functions to check if the visitor input is an actual number, to see the difference between the inputted number and the randomly generated numbers, and to then compare the numbers. -
Django -How to setup the django server for my external address ex : 10.190.12.32 and this ip address has provided of my client
I followed the instructions here to run Django using the built-in webserver and was able to successfully run it using python manage.py runserver. If I access 127.0.0.1:port locally from the webserver, I get the Django page indicating it worked. http://mywebserver:port_django_runs_on I Tried with the above but didn't worked The web server is running so it must be accessible from the outside, I'm just not sure how. I am running Linux with Apache, though I have not configured Django with Apache. Any ideas on how to do this? -
Serialized data from RetrieveAPIView arriving jumbled
I have a serializer that takes prices and matching transaction dates from a model and sends it on via RetrieveAPIView, to be picked up by a ChartJS price chart on the other end: class MyPriceSerializer(serializers.Serializer): prices = serializers.SerializerMethodField() price_dates = serializers.SerializerMethodField() def get_prices(self, obj): return obj.prices.values_list('price', flat=True) def get_price_dates(self, obj): qs = obj.prices.all() qs = qs.extra(select={'datestr':"to_char(price_date, 'DD Mon HH24:MI')"}) return qs.values_list('datestr', flat=True) class ChartData(RetrieveAPIView): queryset = Market.objects.all().prefetch_related('prices') authentication_classes = [] permission_classes = [] serializer_class = MyPriceSerializer My problem is that the data is arriving in a jumbled order, as can be seen from the price_dates here: HTTP 200 OK Allow: GET, HEAD, OPTIONS Content-Type: application/json Vary: Accept { "prices": [ 0.55, 0.57, 0.5, 0.43, 0.45, 0.57, 0.55, 0.48, 0.4, 0.52, 0.6, 0.52, 0.45, 0.43 ], "price_dates": [ "24 Jul 12:08", "24 Jul 12:08", "24 Jul 12:08", "24 Jul 12:09", "24 Jul 12:11", "24 Jul 12:08", "24 Jul 12:08", "24 Jul 12:08", "24 Jul 12:09", "24 Jul 12:08", "24 Jul 12:08", "24 Jul 12:08", "24 Jul 12:08", "24 Jul 12:09" ] } Why is that? Further details: I've confirmed that the prices and price dates are in order in the model itself. For database, I'm using PostgreSQL11. -
Create Rating starts in django
I am new to the django, and I work on datascience project that aims to create a web application that interact with user in order to gather same date in first step after that make recommendation to the user, My issue is I have I model Countries that has country_name, user_rating, and user_id as ManyToMany fields, how I can give to the use the chose to rate country name using the stars rating and then save the rating in user_rating field ? -
How to embed pinterest link to wagtail
I can embed instagram post link or facebook post link to richText of wagtail but i try to add pinterest link wagtail return validation error Wagtail has oembed provider lists like this herespeakerdeck = { "endpoint": "https://speakerdeck.com/oembed.{format}", "urls": [ r'^http(?:s)?://speakerdeck\.com/.+$', ], } app_net = { "endpoint": "https://alpha-api.app.net/oembed", "urls": [ r'^http(?:s)?://alpha\.app\.net/[^#?/]+/post/.+$', r'^http(?:s)?://photos\.app\.net/[^#?/]+/.+$', ], } youtube = { "endpoint": "http://www.youtube.com/oembed", "urls": [ r'^http(?:s)?://(?:[-\w]+\.)?youtube\.com/watch.+$', r'^http(?:s)?://(?:[-\w]+\.)?youtube\.com/v/.+$', r'^http(?:s)?://youtu\.be/.+$', r'^http(?:s)?://(?:[-\w]+\.)?youtube\.com/user/.+$', r'^http(?:s)?://(?:[-\w]+\.)?youtube\.com/[^#?/]+# [^#?/]+/.+$', r'^http(?:s)?://m\.youtube\.com/index.+$', r'^http(?:s)?://(?:[-\w]+\.)?youtube\.com/profile.+$', r'^http(?:s)?://(?:[-\w]+\.)?youtube\.com/view_play_list.+$', r'^http(?:s)?://(?:[-\w]+\.)?youtube\.com/playlist.+$', ], } i looked for pinterest , and i did not found it. -
Django login method not redirecting with logged in user
I've got a LoginForm that I use to log my user in. When they show up to the site they're presented with a log_in form - once they login, I want it to take them to an app launcher page. Currently - when they try to login, it just reloads the log_in page. The app is called 'launcher' My views look like this: def log_in(request): if request.user.is_authenticated: return redirect("launcher:launcher") form = LoginForm(request.POST or None) if request.POST and form.is_valid(): user = form.login(request) if user: try: login(request, user) except Exception as e: logger.warning( "Issue logging in %s, %s", user, request, ) return redirect('launcher:launcher') else: return render(request, "launcher/login.html", {"form": form}) def log_out(request): logout(request) return render(request, "launcher/thanks.html", {"reason": "logged out"}) @login_required(login_url="launcher:log_in") def launcher(request): if not request.user.groups.all(): return render(request, "launcher/no_apps.html") return render( request, "launcher/launcher.html", { "apps": App.objects.filter( groups__in=request.user.groups.all() ).distinct() }, ) The user is logged in and everything but it is failing on this line: return redirect('launcher:launcher') I can't seem to figure out why the logged in user isn't getting passed along when redirected. It is hitting the @login_required decorator on the launcher method and redirecting the (currently logged in) user to the log_in page again. -
How to enable date formatting during edit while still applying crispy forms at the same time
On displaying edit form, date field format is YYYY-MM-DD yet I would like it to display in form of MM/DD/YYYY since am using the bootstrap date picker which I have configured to MM/DD/YYYY. I tried rendering the date using the django defined date filters along side the crispy forms in this way {% load crispy_forms_tags %} <form method="post" novalidate> <div> {{ form.start_date|date: "d M Y"}} </div> </form> The output should be the new date in format MM/DD/YYYY though it says Could not parse the remainder: ': "d M Y"' from 'form.start_date|date: "d M Y"' -
How to write custom views for admin in django?
I have user list in the user admin which has a coloum named domain(email-domain), Now when a user logs in with his mail id, he should only see users of his domain, not other domains. For ex if sourabh@gmail.com is logging in then only gmail users should be visible. Admin screenshot admin.py from .models import User from django.contrib import admin from django.contrib.auth.admin import UserAdmin as BaseUserAdmin class UserAdmin(BaseUserAdmin): list_display = ('email', 'domain','admin', 'is_active', 'is_staff') list_filter = ('admin', 'is_staff', 'is_active', 'groups', 'domain') fieldsets = ( (None, {'fields': ('email', 'password', 'domain')}), ('Permissions',{ 'fields': ( 'is_active', 'is_staff', 'is_superuser', )}), ) add_fieldsets = ( (None, { 'classes': ('wide',), 'fields': ('email', 'password1', 'password2')} ), ) search_fields = ('email',) ordering = ('email',) filter_horizontal = () admin.site.register(User, UserAdmin) models.py from django.contrib.auth.models import BaseUserManager, AbstractBaseUser, PermissionsMixin from django.db import models class MyUserManager(BaseUserManager): def _create_user(self, email, password, domain, is_staff, is_superuser, **extra_fields): if not email: raise ValueError('Users must have an email address') email = self.normalize_email(email) user = self.model( email=email, domain = domain, is_staff=is_staff, is_active=True, is_superuser=is_superuser, **extra_fields ) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, password, domain, **extra_fields): return self._create_user(email, password, domain, False, False, **extra_fields) def create_superuser(self, email, password, domain, **extra_fields): user=self._create_user(email, password, domain, True, True, **extra_fields) user.save(using=self._db) return user class … -
Dictionary value in Python
I have a program which takes a csv file and saves the csv data into a Dictionary and then compares the keys of that dictionary with the values fetched from the database. If a dictionary key is equal to a database value then I want to save that said key with it's respected value in another dictionary for later use. But I am unable to understand how to save the values because I don't know how to iterate through a loop. def LCR(request): template = "LCR\LCR.html" dest = Destination.objects.values_list('dest_num', flat=True) rates = {} # my main dictionary which gets populated later on ratelist = {} csv_file = open(r'.\adoc.csv') data_set = csv_file.read().decode("UTF-8") io_string = io.StringIO(data_set) next(io_string) for column in csv.reader(io_string, delimiter=str(u",")): rates[column[0]] = column[1] for desNum in dest: desNum = str(desNum) # print type(desNum) for num in desNum: for venNum in rates: for VN in venNum: # print rates if num[:2] == VN[:2]: ratelist[venNum] = [rates.values()] I expect to populate ratelist dictionary with both the key and it's respected value. -
How to catch errors from form in Django?
I have a collapse div with login/sign-up forms. How I can catch errors if they are? My form in html: <form method="post" action="{% url 'login' %}"> {% csrf_token %} <p><label for="id_username">Username:</label> <input id="id_username" type="text" name="username" maxlength="30" /></p> <p><label for="id_password">Password:</label> <input type="password" name="password" id="id_password" /></p> <input type="submit" value="Log in" /> <input type="hidden" name="next" value="{{ request.get_full_path }}" /> </form>