Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
In Django how to get the email address of a Foreign key user
I have a User model and a Project connected where the Project connects to User model with foreign key. How can I select the email address of the permitted user with raw query? (I don't want to use ORM). models.py class Project(models.Model): def __str__(self): return str(self.project) project = models.TextField(max_length=150) company_name = models.ForeignKey('Company', on_delete=models.CASCADE, default=1) permitted = models.ForeignKey(User, on_delete=models.CASCADE, default=1) I like to send emails to the permitted users but I need the email address of them. This is the raw query I tried: SELECT COUNT(auth_user.id), ??? FROM pro_projects LEFT JOIN auth_user ON auth_user.id = pro_projects.permitted.id -
Django allAuth, Social Signin After simple email signup from same email as google account
I am using allauth for social signup. First I have Signup my account using Gmail by simply filling out a form and setting up a user name and password. for example the Gmail: > hello@gmail.com, Now I am trying to log in via My google account which is created on the same email as mentioned above. But I am getting an error that the email is already registered instead of giving me this error it should authenticate the user to sign in. -
Query aggregated values with database values with gql and django
I have taken over a project using gql and django. It completely follows the structure of the following example: https://stackabuse.com/building-a-graphql-api-with-django/ Now i want to add extra functionality. Ontop of sending databasevalues to the front end, i would also like to send aggregated ones aswell, like number of elements etc. I've added this to the Node as follows: class DatabaseDataNode(DjangoObjectType): print(DatabaseAnnotationData.objects.filter(database_id__exact=5).count()) #Prints correct value total = DatabaseAnnotationData.objects.filter(database_id__exact=5).count() class Meta: print('Hello world') filterset_fields = { 'databaseid': ['exact'], 'name': ['exact', 'icontains', 'istartswith'], 'imagefile': ['exact', 'icontains', 'istartswith'], 'annotations': ['exact'], 'created_at': ['exact'], 'modified_at': ['exact'], 'slug': ['exact'], 'total': ['exact'] # <-- Doesn't work } interfaces = (relay.Node, ) I also add it to the query: const DATABASE = gql` query Database($name: String, $first: Int, $offset: Int) { database(databasename: $name) { databaseid id name total <---------- Added modifiedAt images(first: $first, offset: $offset) { edges { node { imageid imagefile width height objectdataSet{ edges{ node{ x1 y1 width height concepts{ edges{ node{ conceptId } } } objectid imageid{ imageid } } } } } } } } } ` But when i run it i get an error saying "Cannot query field "total" on type "DatabaseDataNode" How can i implement this, to send the other value aswell? -
Django sessions Ajax query returns undefined instead of int value
So basically I'm creating an e-commerce store. And I want to use Django session and ajax query to implement an add-to-cart functionality to my app and when the user selects a quantity of some product, the selected quantity to be visible in the cart section on the navigation bar. But as I select some quantity and click add to cart button the value up in the cart section changes from 0 to undefined. When I decode the session there is no regarding info for the selected product and its quantity. This is my base Cart class: class Cart(): """ A base Cart class, providing some default behaviors that can be inherited or overwited. """ def __init__(self, request): self.session = request.session cart = self.session.get('session_key') if 'session_key' not in request.session: cart = self.session['session_key'] = {} self.cart = cart def add(self, product, qty): """ Adding and updating the user's cart session data """ product_id = product.id if product_id in self.cart: self.cart[product_id]['qty'] = qty else: self.cart[product_id] = {'price': str(product.price), 'qty': qty} self.save() def save(self): self.session.modified = True This is the add_to_cart_view: def add_to_cart(request): cart = Cart(request) if request.POST.get('action') == 'post': product_id = int(request.POST.get('productid')) product_qty = int(request.POST.get('productqty')) product = get_object_or_404(Product, id=product_id) cart.add(product=product, qty=product_qty) cartqty = … -
Django: Multiple table Model query
I have tried it on the Q object and in the Django ORM but could not generate the query. class Status(models.Model): id = models.AutoField(primary_key=True) name = models.AutoField(null=True, max_length=100) def __str__(self): return self.name class Billing(models.Model): id = models.AutoField(primary_key=True) name = models.AutoField(null=True, max_length=1000) sr_number = models.AutoField(null=True, max_length=100) def __str__(self): return self.name class BillingInfo(models.Model): id = models.AutoField(primary_key=True) billings = models.ForeignKey(Billing, null=True, on_delete=models.SET_NULL) net_amount = models.AutoField(null=True, max_length=100) company = models.AutoField(null=True, max_length=100) def __str__(self): return self.company class BillingOutput(models.Model): id = models.AutoField(primary_key=True) billing_infos = models.ForeignKey(BillingInfo, null=True, on_delete=models.SET_NULL) lbl_name = models.AutoField(null=True, max_length=100) lbl_qty = models.AutoField(null=True, max_length=100) status = models.ForeignKey(Status, null=True, on_delete=models.SET_NULL) def __str__(self): return self.lbl_name I required an equivalent ORM Query for the below raw SQL query: select bio.* from billing bil inner join billing_infos bi on bil.id = bi.billings_id inner join billing_output bio on bi.id = bio.billing_infos_id where bo.status_id = 1 order by bio.id desc; Could someone please help me with this issue? -
Reverse for 'detail_page' with no arguments not found. 1 pattern(s) tried: ['detail\\-page/(?P<slug>[^/]+)\\Z']
urls.py urlpatterns = [ path('', home_page, name='home_page'), path('posts-page/', posts_page, name='posts_page'), path('detail-page/<slug>', detail_page, name='detail_page'), ] views.py def detail_page(request, slug): post = get_object_or_404(Post, slug=slug) context = { 'post': post, } return render(request, 'detail_page.html', context=context) base.html <div class="navbar"> <nav class="navigation hide" id="navigation"> <span class="close-icon" id="close-icon" onclick="showIconBar()"><i class="fa fa-close"></i></span> <ul class="nav-list"> <li class="nav-item"><a href="{% url 'home_page' %}">Forums</a></li> <li class="nav-item"><a href="{% url 'posts_page' %}">Posts</a></li> <li class="nav-item"><a href="{% url 'detail_page' %}">Detail</a></li> </ul> </nav> <a class="bar-icon" id="iconBar" onclick="hideIconBar()"><i class="fa fa-bars"></i></a> <div class="brand">My Forum</div> </div> detail_page.html <!--Topic Section--> <div class="topic-container"> <!--Original thread--> <div class="head"> <div class="authors">Author</div> <div class="content">Topic: {{ post.title }} (Read 1325 Times)</div> </div> <div class="body"> <div class="authors"> <div class="username"><a href="">{{ post.user.fullname }}</a></div> <div>Role</div> <img src="{{ post.user.profile_pic.url }}" alt=""> <div>Posts: <u>45</u></div> <div>Points: <u>4586</u></div> </div> <div class="content"> {{ post.content | safe }} <br> <div class="comment"> <button onclick="showComment()">Comment</button> </div> </div> </div> </div> I have objects in db and i try to get page with post and i get this error, i understand tha problem mix with slug and that something wrong with this argument, but i really idk why -
How to use the power of uvicorn and asgi in django?
I implemented a tiny Django app (v4.0.4) containing a REST API — GET method for retrieving some data. Next, I wanted to run the project using gunicorn+uvicorn since I saw a more benchmark performance than a normal deployment in an article. So I decided to get my own benchmark using wrk tool. Here's what I've got: Command Webserver Protocol Result (Req/Sec) python manage.py runserver 0.0.0.0:8000 Django Default wsgi 13.06 gunicorn bitpin.wsgi:application --bind 0.0.0.0:8000 -w 2 gunicorn wsgi 45.20 gunicorn bitpin.asgi:application --bind 0.0.0.0:8000 -w 2 -k uvicorn.workers.UvicornWorker uvicorn+gunicorn asgi 22.17 However, the above result demonstrates something else! Is the reason that when I want to use asgi I have to use async method instead for my API view? If so how can I change a Django REST API view to an async one? Or might I've missed some configurations? [NOTE]: I ran the benchmark using the following command: wrk -t4 -c11 -d20s -H "Authorization: Token xxx" http://127.0.0.1:8000/api/v1/content/ It is worth mentioning that for this test I used two workers for gunicorn and it is obvious that the higher workers, the better the performance will be. -
Pass option value from select to view
I am trying to create an interactive scatterplot with options from an selectbox as a filter in Django. The problem is that the value from the select box is not passed to the view. views.py def dashboard(request): cool_data = manage_pandas(df_raw) posnr=cool_data['something'].unique() pos = request.GET.get('posi') dff = cool_data.loc[cool_data['posnr'] == pos] dff = dff.astype({'vnum': str}) fig = px.scatter_matrix(dff, dimensions=["a", "b", "c", "d",'e'], color="g") fig.update_traces(diagonal_visible=False) sm = plot(fig, output_type="div") context = { 'posnr' : posnr, 'plot_div':sm } return render(request, "scatterplot/scatterplot.html", context) scatterplot.html <div class = "container" id = "second" style="display:true"> <br><br> <select class="position"> {% for pos in posnr %} <option value="{{ pos }}">{{ pos }}</option> {% endfor %} </select> {% autoescape off %} {{ plot_div }} {% endautoescape %} <script> $("select.position").change(function(){ var posi = $(this).children("option:selected").val(); }); </script> I don't want to use form submit because I want the scatterplot to change automatically based on user input. Thanks -
How to list files by pk
Im newbie and trying to get lists of each backup devices.Im just tried myself and wrote useless thing, help. class Backups(View): @staticmethod def get(request, pk): dvcs = [Device.objects.filter(pk=pk) for pk in glob.glob("/static/backup/*.txt")] form = BackupsForm() context = {'dvcs': dvcs, 'form': form} return render(request, 'Recentbackups.html', context) -
Definig element.sortable()-function
My html table supports changing the row-order using mouse drag and drop. The used jquery-ui version is v1.12.1. It works for old tables (i.e. those whose row count is known since load of the page), but it doesn't work for rows added after the page has been loaded. I think the reason is that the below sortable()-function is inside document.ready()-function. <script type="text/javascript"> <script src="{% static 'js/jquery-ui.js' %}"></script> $(document).ready(function(){ $('#luok_table tbody').sortable({ stop: function( event, ui ){ $(this).find('tr').each(function(i){ $(this).attr("id", $(this).attr("id").replace(/\d+/, i) ); $(this).find(':input').each(function(){ $(this).attr("id", $(this).attr("id").replace(/\d+/, i) ); $(this).attr("name", $(this).attr("name").replace(/\d+/, i) ); }); }); } }); }); </script> If that's the reason, where should I define the sortable()-function ? The table rows are added by jquery-formset-js-script (https://gist.github.com/vandorjw/f884f0d51db3e7caaecd#file-jquery-formset-js) -
How do I write setUpClass() and tearDownClass() creating and logging in a user?(Django Rest FrameWork)
I have this test case written for two models with local permission_classes, [IsAdminUser] and [IsAuthenticated] respectively. After running the test cases both the test are failed and according to the exception messages, it is clear that the user is not getting logged in. class PermissionClassesTest(APITestCase): @classmethod def setUpClass(cls): super(PermissionClassesTest, cls).setUpClass() print('running before tests') cls.user = User.objects.create_user(username='admin', password='qwefghbnm', is_staff= True) cls.client = APIClient() cls.client.login(username=cls.user.username, password='qwefghbnm') @classmethod def tearDownClass(cls): super(PermissionClassesTest,cls).tearDownClass() print('running after test') def test_SalaryDetail_local_permission(self): response = self.client.get('/salaryDetails/') self.assertEqual(json.dumps(response.data), '{"detail": "You do not have permission to perform this action."}') def test_EmployeeDetail_local_permission(self): response = self.client.get('/employeeDetails/') self.assertTrue(status.is_success(response.status_code))``` -
How to create a double range slider linked to two model fields in Django
I am trying to create a double range slider on a CreateView and UpdateView linked to two model fields in Django representing a minimum and maximum value. I found this tutorial but I am hoping there is something more simple which can be built without moving away from class based views to avoid needing to rework lots of views/forms. Any help would be greatly appreciated :) -
Django Form save ForeignKey fields
So I have this ModelForm in my django project: class DateForm(ModelForm): image = forms.ImageField() class Meta: model = Date exclude = ('user',) the Photo model: class Date(models.Model): ... class Photo(models.Model): date = models.ForeignKey(Date, on_delete=models.CASCADE) image = models.ImageField(verbose_name='Photos', upload_to='media/date/photos/') the form: <p class="p-form">Title</p> {{ form.title }} <p class="p-form">Description</p> {{ form.description }} <p class="p-form">Place</p> {{ form.place }} <p class="p-form">Rating</p> {{ form.rating }} <p class="p-form">Photos</p> {{ form.image }} Whenever I try to save my form, its form_invalid method is being called and it doesn't save the form. What is the matter? How do I save extra field of ForeignKey model? How can I get that images sent via form? Thanks! -
how to call filter database with "Id " Django,
I want to make pay form, but I cannot show produk in orederitem, please helping me to show orderitem :v. I am really newbie in here . models.py class Order(models.Model): name = models.ForeignKey(Profile, on_delete=models.SET_NULL, blank=True, null=True) order_data = models.DateTimeField(auto_now_add=True) selesai = models.BooleanField(default=False, blank=True, null=True) status = models.BooleanField(default=False, blank=True, null=True) id_transaksi = models.CharField(max_length=200, null=True) bukti = models.ImageField(null=True, blank=True) ongkir = models.CharField(max_length=200, null=True) total = models.CharField(max_length=200, null=True) total_harga = models.CharField(max_length=200, null=True) pembayaran = models.CharField(max_length=200, null=True) class OrderItem(models.Model): product = models.ForeignKey(Product, on_delete=models.SET_NULL, blank=True, null=True) order = models.ForeignKey(Order, on_delete=models.SET_NULL, blank=True, null=True) quantity = models.IntegerField(default=0) date_added = models.DateTimeField(auto_now_add=True) views.py def pembayaran(request): customer = request.user.profile ido = Order.objects.filter(id) orders = Order.objects.filter(name=customer, selesai=True) pengiriman = Pengiriman.objects.filter(name=customer) OrderItems = OrderItem.objects.filter(order=ido) print(OrderItems) context = {'orders': orders,'pengiriman' :pengiriman , 'OrderItems': OrderItems } return render(request, 'store/pembayaran.html', context) -
how to show 'staff' of certain 'shop' correctly?
as you can see on a picture i have Staff Worker named Max Barren but the thing is he is connected only to one of this shops. How do I write code properly so this staff worker will appear only under one of this shops? views.py def list_view(request): context = {} context['library_dataset'] = VideoLibrary.objects.all() context['staff_dataset'] = Staff.objects.all() return render(request, 'app/list_view.html', context) at views.py i get objects like adress and shop name from VideoLibrary model and staff_name and gender form Staff model to put it in list_view.html models.py class VideoLibrary(models.Model): shop_name = models.CharField(max_length=264) adress = models.TextField(max_length=264, default='') def __str__(self): return self.shop_name class Meta: verbose_name_plural = "Video Libraries" class Staff(models.Model): staff_name = models.CharField(max_length=264) living_adress = models.TextField(max_length=264) gender = models.CharField(max_length=264) age = models.IntegerField() staff_rating = models.IntegerField() shop_name = models.ForeignKey(VideoLibrary, on_delete=models.CASCADE) def __str__(self): return f'{self.staff_name}' class Meta: verbose_name_plural = "Staff" I suppose i got some troubles wtih my code at list_view.html but I don't know how to figure it out list_view.html <div class="main"> {% for data in library_dataset %} Shop name: <br /> <br /> {{ data.shop_name }} <br /> {{ data.adress }} <br /> <td><a href="{% url 'update_shop' data.id %}"> <button type="button">Edit Shop Details</button> </a></td> <br /> Staff that work in the shop: … -
How to refresh JWT TOKEN in django
I'm using jwt token authencation 1.11.0. But every 30 minutes token is expiring how to refresh the JWT token with version of 1.11.0 -
Problem django, accessing database, "django.db.utils.OperationalError: (1043, 'Bad handshake')"
I want to deploy a Django app on a virtual machine hosted on a cluster. For this app i need access to a MySQL database that is also hosted on the cluster. When I launch $ mysql -h 1XX.1XX.1.1XX -u test -p test on the virtual machine, i can access the database. But when i run the django server, i've got an error : django.db.utils.OperationalError: (1043, 'Bad handshake') It is the same error as when the versions of MySQL between the cluster and the VM are different but I installed the same. Thank you for help. -
Google Cloud SECRET_KEY
I'm following the Google Cloud Documentation Running Django on the App Engine standard environment. I reach the part where I'm suppose to create a SECRET_KEY on my .env file and I occured on a error when i'm executing the last line. The error Actually I'm using Windows 11 and Windows PowerShell (i know that lc_all=c is used on Unix & Linux but i don't know what can i use on windows). -
objects.get(id = id) only works randomly
I think somewhat related: link. I create a model entry: def bulk_asset_update(stores, links, img): def do_update(id): task = ThreadTask.objects.get(pk = id) ## <--- DOES NOT EXIST SOMETIMES ... task.is_done = True task.timestamp_end = timezone.now() task.save() task = ThreadTask() task.name = "update" task.save() t = threading.Thread(target = do_update, args = [task.id]) t.setDaemon(True) t.start() return {"id": task.id} Sometimes (every 5th time or so) the ThreadTask.get(pk = id) line fails - so I suspect it might not be written to the database yet maybe? I tried replacing the lines: task = ThreadTask() task.name = "bulk asset update" task.save() with: task = ThreadTask.objects.create(name = "update") which seams to work better. But can I make sure that the task object is really saved first before code execution continues? -
How i can integrate scrapy in django and get spider results in django views?
i want to use scrapy spiders in django views, crawl that spider within django view and store scraped data in python list or dictionary. Is there any easy way to do this? -
DJANGO Supplement to the data list via an intermediate table
I have an intermediate models connection Simplified: Person table: first_name last_name Company table: company_name CompanyEnrollment table: FK Person FK Company I want to create the following array: datas = Person.objects.All(...{All elements of Person supplemented with Company_name}...) There is a case where a person does not have a company_name association Is it possible to solve this with a query? -
create a persistant instance of aiohttp.ClientSession in Django app
I'm trying to create an instance of aiohttp.ClientSession() in a django app. I want to create the object via the ready() hook in apps.py and then access the instance from views.py. From views.py I'm using the my_app_config.my_object to pull back the instance, but I'm seeing weird behaviour. For example 'Timeout context manager should be used in side a task'. Is anyone able to provide a clear example of how I might go about creating an instance of aiohttp.ClientSession() which I can pull into views.py (or indeed any other class in the app) for reuse. -
How to use return two time in a function in Django using async?
I have a model called response. If the user is selected for a duration the response is turning to the default value after that duration time. But I need to return the value until the duration time is over. I think I need to use the async function. I looked at the SO. but couldn't find any solutioın. models.py class Response(models.Model): def_res = models.CharField() expected_res = models.CharField() current_res = models.CharField() is_duration= models.BooleanField(default=False) duration = models.PositiveIntegerField() views.py def manage_response(request): if request.method == "POST": a = Response.objects.filter(id=request.POST.get('resp_id')) a.current_res = a.expected_res a.save() if not a.is_duration == True: return JsonResponse(a.current_res) else: return JsonResponse(a.expected_res ) #after return won't work in sync time.sleep(a.duration) a.current_res = a.def_res return JsonResponse(a.current_res) -
How to update models with proxy tabular inline?
I have the following code. I used a proxy model because I needed to register the same model in admin. I get the message: 'Please correct the error below.' with no error field, and I get no exception. I can't trackdown the error since there is no error in the log file. I can save new info if the table is clear, but I get that error when I try to update info. I think it's trying to overwrite the parent model, Laptop. class Laptop(models.Model): _id = models.ObjectIdField() Type = models.CharField(max_length=30, unique=True) def __str__(self): return self.Name def save_model(self, request, *args, **kwargs): try: return super(Laptop, self).save_model(request, *args, **kwargs) except Exception as e: self.message_user(request, e, messages.ERROR) class LaptopProxy(Laptop): class Meta: verbose_name = 'Info' proxy = True def save_model(self, request, *args, **kwargs): try: return super(LaptopProxy, self).save_model(request, *args, **kwargs) except Exception as e: self.message_user(request, e, messages.ERROR) class InfoForm(InternalModelAdminMixin, admin.TabularInline): model = Info extra = 30 def is_valid(self): log.debug(force_text(self.errors)) return super(InfoForm, self).is_valid() class InfoAdmin(InternalModelAdminMixin, admin.ModelAdmin): inlines = [InfoForm] admin.site.register(Laptop, LaptopAdmin) admin.site.register(LaptopProxy, InfoAdmin) -
Django - Save override to update fields issue
Having trouble with figuring out a way to update fields of a table through the save method override and have the updated value factor in values from previous saved objects that share the same primary key. Let me explain: I have two tables, table A and table B. Table A has a field that is the foreign key PK of table B. Multiple objects in table A share the same foreign key from Table B. Here are some JSON bodies to represent each table. Table A [ { "pk": 1 "count(fk)": "Cat counter", "name" "Jerry" }, { "pk": 2 "count(fk)": "Cat counter", "name" "Max" }, { ... } ] [ Table B { "pk": "Cat counter" "count": 0 }, { "pk": "Dog counter" "Count": 0 } ] Let's say we POST all the values that represent Table A in one POST request. At the same time, I want table B to be updated with the count of cats or dogs through a save method override of Table A. Right now I am doing it this way in Table A's model which does update the count field as I wanted to, but it doesn't seem to remember previous iterations, even though …