Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django merge duplicate rows
I have a table like this. id|name |user_id |amount| --|---------------------|------------|------| 1|Name1 |1 | 4| 2|Name1 |1 | 7| 3|Name2 |1 | 5| I want to merge rows that have the same name and user_id and that should look like this: id|name |user_id |amount| --|---------------------|------------|------| 1|Name1 |1 | 11| 2|Name2 |1 | 5| Django ver = 3.1 -
Uncaught TypeError: Cannot read property 'style' of null when using data-SOMETHING attribute to pass parameter to JavaScript function
I'm new to coding and I'm trying to hide a paragraph using JavaScript. This is my HTML {% for post in posts %} <div class="container p-3 my-3"> <div class="card"> <div class="card-block px-1"> <h4 class="card-title"> <a href="{% url 'profile' post.user.id %}">{{ post.user }}</a> </h4> <p class="card-text" id="{{ post.id }}">{{ post.content }}</p> <textarea style="display: none;" id="edit-view">{{ post.content }}</textarea> <p class="card-text" id="time">Posted on: {{ post.timestamp }}</p> {% if post.user == request.user %} <button type="button" class="btn btn-primary" id="edit-btn" data-text="{{ post.id }}">Edit</button> {% endif %} <button type="button" class="btn btn-primary" id="save-btn" style="display:none;">Save</button> <p class="card-footer">{{ post.like }} Likes</p> </div> </div> </div> {% endfor %} Looking at the source code I could verify that the post.id context is correctly displayed in both the data-text attribute and the id of the paragraph I want to hide. This instead is my JavaScript function (which I have in a separate js file): function edit(text) { // hide content document.querySelector(`#${text}`).style.display = 'none'; } I'm calling the function after loading the DOM and applying and event listener to all buttons with id of edit-btn: document.addEventListener('DOMContentLoaded', function() { // Adding event listener document.querySelectorAll('#edit-btn').forEach(function(button) { button.onclick = function() { console.log('Button clicked!') edit(); } }); }); Nevertheless I get the above error, as if the parameter … -
How do I solve this error in my view? Local variable 'result' referenced before assignment
This view complains of the local variable result being referenced before being assigned, please help me arrange well. def UploadTeachersView(request): if request.method == 'POST': form = NewTeachersForm(request.POST, request.FILES) dataset = Dataset() new_persons = request.FILES['file'] imported_data = dataset.load(new_persons.read(), format='xls') result = ImportTeachersResource().import_data(dataset, dry_run=True) # Test the data import if result.has_errors(): messages.info(request,f"Errors experienced during import.") else: ImportTeachersResource().import_data(dataset, dry_run=False) # Actually import now messages.info(request,'Details uploaded successfully...') else: form = NewTeachersForm() return render(request, 'new_teacher.html',{'form':form, 'result':result}) -
HTTP 403 , running django with Nginx + Passenger + Django + Virtualenv
I just starting to learn how to use Pushion Passenger with nginx on my internal server. First, here is my passenger-memory-stats (penumpang:3.8) debian@debian-mon-lama ~/penumpang sudo /usr/sbin/passenger-memory-stats Version: 6.0.8 Date : 2021-04-07 14:41:42 +0700 ... ---------- Nginx processes ---------- PID PPID VMSize Private Name ------------------------------------- 24731 1 68.0 MB 0.4 MB nginx: master process /usr/sbin/nginx -g daemon on; master_process on; 24736 24731 68.2 MB 0.6 MB nginx: worker process 24737 24731 68.2 MB 0.7 MB nginx: worker process 24738 24731 68.2 MB 0.6 MB nginx: worker process 24739 24731 68.2 MB 0.6 MB nginx: worker process ### Processes: 5 ### Total private dirty RSS: 2.95 MB ----- Passenger processes ------ PID VMSize Private Name -------------------------------- 24717 298.3 MB 2.5 MB Passenger watchdog 24721 1190.6 MB 5.5 MB Passenger core ### Processes: 2 ### Total private dirty RSS: 8.05 MB Looks slight different than https://www.phusionpassenger.com/docs/advanced_guides/install_and_upgrade/nginx/install/oss/buster.html here is my nginx site-enabled (penumpang:3.8) debian@debian-mon-lama ~/penumpang cat /etc/nginx/sites-enabled/penumpang.site #FROM https://www.phusionpassenger.com/library/config/nginx/intro.html server { server_name debian-mon-lama; root /home/debian/penumpang; passenger_enabled on; passenger_python /home/debian/virtualenv/penumpang/3.8/bin/python; } venv created by debian@debian-mon-lama ~/penumpang virtualenv --prompt '(penumpang:3.8)' --python /usr/local/bin/python3.8 --system-site-packages /home/debian/virtualenv/penumpang/3.8/ here is my passenger_wsgi.py debian@debian-mon-lama ~/penumpang cat ./passenger_wsgi.py import sys, os #FROM https://help.dreamhost.com/hc/en-us/articles/360002341572-Creating-a-Django-project INTERP … -
i was creating a website using django and i got an error can anyone help me its a a typeerror
TypeError at /contact contact() got an unexpected keyword argument 'name' Request Method: POST def contact(request): global contact if request.method == "POST": name = request.POST.get('name') email = request.POST.get('email') phone = request.POST.get('phone') desc = request.POST.get('desc') contact =contact(name=name,email=email,phone=phone,desc=desc,date=datetime.today()) contact.save() return render(request,'contact.html') -
Django postgresql query stuck when searching on negavie condition
I have this class name: Maybe it is the class Follower(models.Model): language = models.ManyToManyField( "instagram_data.Language", verbose_name=_("language_code_name"), blank=True) class Language(models.Model): code_name = models.CharField(max_length=6, null=True, blank=True) def __str__(self): return self.code_name While searching for specific name it return values fast (few sec), (i.g language.code_name = "he"): he lang While adding the check for language.code_name != "ar", it can take few minutes ! Maybe design issue ? -
Ordered list with M2M for different models?
How can I create a List model that has many-to-many relationships with multiple different models in a specific order? E.g. models.py class ItemA(models.Model): ??? class ItemB(models.Model): ??? class List(models.Model): ??? Shell: a1 = ItemA.objects.create() a2 = ItemA.objects.create() b1 = ItemB.objects.create() b2 = ItemB.objects.create() list1 = List.objects.create() list2 = List.objects.create() # ??? Some code here that can associate # a1, a2, b1, b2 (in that order) with list1 and # a1, b1, a2, b2 (in that order) with list2 # so that list1.items can return a1, a2, b1, b2 (in that order) # and list2.items can return a1, b1, a2, b2 (in that order) Is this even possible? -
Django 3.2 AttributeError: 'TextField' object has no attribute 'db_collation'
I've an existing project on Django 3.1 and I upgraded my project to Django 3.2. I created an app called payment on my project. But When I make migrations. It trow an error AttributeError: 'TextField' object has no attribute 'db_collation' from django.db import models from django.conf import settings from django.utils.translation import gettext_lazy as _ # Create your models here. from simple_history.models import HistoricalRecords class TransactionType(models.TextChoices): CASH_IN = 'IN', _('Cash In') CASH_OUT = 'OUT', _('Cash Out') class TransactionMethod(models.TextChoices): STUDENT_TR = 'STT', _('Student Transaction') BANK_TR = 'BKT', _('Bank Transaction') SCHOOL_TR = 'SLT', _('School Transaction') Teacher_TR = 'TRT', _('Teacher Transaction') DONATE_TR = 'DET', _('Donate Transaction') class Payment(models.Model): id = models.AutoField(primary_key=True) created_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT, related_name="created_by") updated_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT, related_name="updated_by") transaction_amount = models.FloatField("Transaction amount") transaction_type = models.CharField(max_length=3, choices=TransactionType.choices, default=TransactionType.CASH_IN,) transaction_method = models.CharField(max_length=3, choices=TransactionMethod.choices, default=TransactionMethod.STUDENT_TR,) transaction_note = models.CharField(null=True, blank=True, max_length=200) is_approved = models.BooleanField(default=False) is_approved_by_user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT, related_name="approved_by", null=True, blank=True) created_at = models.DateTimeField(auto_now=True, blank=True, null=True) updated_at = models.DateTimeField(auto_now_add=True, blank=True, null=True) history = HistoricalRecords() Full error message File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/asad/PycharmProjects/amarschool/venv/lib/python3.6/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/home/asad/PycharmProjects/amarschool/venv/lib/python3.6/site-packages/django/core/management/__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/asad/PycharmProjects/amarschool/venv/lib/python3.6/site-packages/django/core/management/base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "/home/asad/PycharmProjects/amarschool/venv/lib/python3.6/site-packages/django/core/management/base.py", … -
How to open and render and Excel file in django?
I am getting an error in Excel say: excel cannot open the file because the file format or file extension is not valid Hi I have a excel file that is being generated each morning. I want the user to be able to download the Excel file. def export_daily_report(request): output = pd.read_excel('crontab_files/daily.xlsx') response = HttpResponse(content_type='application/vnd.ms-excel') # tell the browser what the file is named response['Content-Disposition'] = 'attachment;filename="daiy_export.xlsx"' # put the spreadsheet data into the response response.write(output) # return the response return response I want to open the excel and then render the file so that the user can download it. -
Is there any API for value the vehicles in India [closed]
I'm a self-learning web developer. I'm working on an app that is for sells and buys used vehicles. Now I searching for an A API to value the vehicles as per the vehicle details that the user has given. So please help me for finding one. -
the time in DateTimeField is not correct
Hello I am creating a website and trying to save the clock in time to the database every time a person clicks the clock in button but the time saved in the database is off by 8 hours. How do I fix this? code where I use the DateTimeField: from django.db import models from datetime import datetime, date #Create your models here. class Name(models.Model): name = models.CharField(max_length=200) timeIn = models.DateTimeField(auto_now_add=True, auto_now=False, blank=True) def __str__(self): return self.name -
Django Template _set.all
I have this model: class CustomerAddresses(models.Model): ID = models.AutoField(primary_key=True) ... CustomerID = models.ForeignKey('Customers', on_delete=models.CASCADE) I render the Address Data in my Template: % for address in customer_default_shipping_address %} {% if address.Address_Company %} <h5>{{ address.Address_Company }}<br/> {{ address.Address_Firstname }} {{ address.Address_Lastname }}</h5> {% else %} <h5>{{ address.Address_Firstname }} {{ address.Address_Lastname }}</h5> {% endif %} <address class="mb-0 font-14 address-lg"> {{ address.Street}}<br> {{ address.Zip}} {{ address.City}}<br> {% for customer in customer_default_shipping_address.customers_set.all %} <abbr title="Telefon">P:</abbr> {{ customer.PhoneNumber }} <br/> <abbr title="E-Mail">M:</abbr> {{ customer.Email }} {% endfor %} </address> {% endfor %} but the E-Mail and Phone Field will not be rendered, are I'm doing something wrong? -
django - how to nested admin objects create?
I've got a set of models that look like this: class User(AbstractBaseUser, PermissionsMixin): user_nm = models.CharField(max_length=10) user_email = models.EmailField(unique=True) user_tel = models.CharField(max_length=11, validators=[validate_user_tel]) class GolferUser(User): class Meta: proxy = True verbose_name = "Golfer User" app_label = "users" class GolferProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True, blank=True) user_birth = models.DateField( null=True, blank=True) user_gender = models.CharField( max_length=8, null=True, blank=True) class GolferPhoto(models.Model): golfer_profile = models.ForeignKey( GolferProfile, on_delete=models.CASCADE, related_name="GolferPhoto", null=True ) photo = models.ImageField( null=True, blank=True) and an admin.py that looks like this: class GolferPhotoInline(NestedStackedInline): model = GolferPhoto extra = 1 class GolferProfileInline(NestedStackedInline): readonly_fields = ("user_gender",) model = GolferProfile extra = 1 inlines = (GolferPhotoInline,) @admin.register(GolferUser) class GolferUserAdmin(NestedModelAdmin): inlines = (GolferProfileInline,) fields = ["user_nm","user_email"] list_display = [ "id", "user_nm", "user_birth", "user_email", ] The problem is that when I add [golferphoto] on the Admin site, the image file is not entered into the DB. An object is created in the DB, but the image file column is empty. views.py class GolferPhotoViewSet( mixins.CreateModelMixin, mixins.RetrieveModelMixin, mixins.UpdateModelMixin, mixins.DestroyModelMixin, mixins.ListModelMixin, GenericViewSet, ): queryset = GolferPhoto.objects.all() serializer_class = GolferPhotoSerializer permission_classes = (permissions.IsAuthenticatedOrReadOnly, GolferPhotoPermission) def create(self, request, *args, **kwargs): golfer_photo = super().create(request, *args, **kwargs) golfer_photo_instance = GolferPhoto.objects.get(id=golfer_photo.data["id"]) if request.FILES: image_file = request.FILES["image"] resize_image( image_file, "GOLFER" + str(golfer_photo_instance.id), "/main_photo/", "MAIN", ) resize_image( image_file, … -
Use of Subquery on django's update
I'm currently getting this error Joined field references are not permitted in this query Any idea why it happens if I do this? (models recreated for a simpler view) class Foo(models.Model): bar = models.ForeignKey( Bar, related_name='foos', on_delete=models.CASCADE) baz = models.ForeignKey( Baz, related_name='foos', null=True, blank=True, on_delete=models.SET_NULL) class Bar(models.Model): name = models.CharField(max_length=255) class Baz(models.Model): name = models.CharField(max_length=255) Foo.objects.update( baz=Subquery( Baz.objects.filter( name=OuterRef('bar__name') ).values('pk')[:1] ) ) -
Show error message in HTTP response Django [closed]
I am using http response to handle exception in my website. I want to show proper message / validation during create and update data. But It shows HTTP responses like Bad Request , Internel server error. Here is my code: try: // Some code except Exception as e: logger.error(e) return http.HttpResponseBadRequest(content=e) In pop up message it shows ,"Bad Request" Instead of "Bad Request" in pop up message I want to show another message. -
Python manage.py runserver does not return anything
I am new to Python and trying to execute "python manage.py runserver" from the command line shell but nothing happens and it just goes to the next line without any error message. -
How to save created csv into cloudinary cloud?
I am developing a data science project, I scrape specific site data, created a dataframe and saved in csv format. Now, i want to save that file to my cloudinary account as a file storage. class NepseApi(APIView): authentication_classes = [] permission_classes = [] def get(self, request, format=None): level2=[] rng=get_range(request, 8) table_Datas=get_url(request) level1= pd.Series(table_Datas).drop_duplicates().tolist() for k in level1: if len(k)> 35: level2.append(k) else: pass d=[] for l in range(1, len(level2)): c= level2[l].split('\n') d.append(c) df= pd.DataFrame(d[1:], columns=d[0]) date= pd.Timestamp.today().strftime('%Y-%m-%d') df['date']= date df_csv = df.to_csv(date +'.csv', index=True) df.rename(columns={'Traded Companies': 'company_name','No. Of Transaction': 'no_of_transaction', 'Max Price':'max_price','Min Price':'min_price','Closing Price':'closing_price','Traded Shares':'traded_shares','Previous Closing':'previous_closing','Difference Rs.':'difference_rs'}, inplace=True) jsn = json.loads(df.to_json(orient='records')) return Response(jsn) df_csv = df.to_csv(date +'.csv', index=True) # How to create path to save file? -
CurrentUserDefault doesn't work using Django Rest
I'm working with Django / Django Rest Framework and I'm looking for a solution to insert the logged user id automatically. i tried to use, user = serializers.HiddenField(default=serializers.CurrentUserDefault()) : But i doesn't work This is my serializer class from rest_framework import serializers from contact.models import Contact class ContactSerializer(serializers.ModelSerializer): user = serializers.HiddenField(default=serializers.CurrentUserDefault()) class Meta: model = Contact fields = '__all__' -
How to Open/Edit/Save Ofifce files( Excel, Word) in browser using Python, Django?
I'm working on CMS project where I want to let users open excel sheets, word files to open in the browser, edit the file and after that save the file like this website : https://products.aspose.app/cells/editor. File would be saved to database. I have tried to find way by googling but unfortunately couldn't get one. Please help with the same. Thanks in advance. -
fetching data to return foreign key related fields django ajax
I have created a project and the project includes invoices , invoice items and items, sometimes during creating the invoice the admin doesn't remember the price of the item,we have inserted the price before, so I have decided to show the price when the admin selects an item (ForeignKey) in a drop down ! is it possible, please? my models.py class Item(models.Model): items = models.CharField(max_length=50) price = models.DecimalField(max_digits=10,decimal_places=3)#i have to return this price def __str__(self): return self.items class Invoice(models.Model): admin = models.ForeignKey(User,on_delete=models.CASCADE) customer = models.CharField(max_length=50) items = models.ManyToManyField(Item,through='ItemsInvoice') class ItemsInvoice(models.Model): invoice_no = models.ForeignKey(Invoice,on_delete=models.CASCADE) item = models.ForeignKey(Item,on_delete=models.CASCADE) quantity = models.IntegerField() price = models.DecimalField(max_digits=10,decimal_places=3)#when selecting an item , the price return back and write in the price field I have to display the price of the selects Item before submitting the form, then the admin know how much the price !? i returned back the price but i dont know how to give the returned value to the price field!? i have used inlineformset @login_required def check_price(request): item = request.GET.get('invoice-0-item',None) price = Item.objects.get(id=item).price print(price) data = { 'price':price, } return JsonResponse(data) and how to iterate through the number of dynamic forms ? in order to change make the 0 dynamic 'invoice-[0]-item' ! … -
How to verify the JWT using JWK without x5c?
I have a JWT security token that I need to verify via the jwks endpoint. Data in jwks looks like this: { "keys": [ { "alg": "RS256", "kty": "RSA", "use": "sig", "n": "xkAku1RWRycD0Fw49bIkdSy1O5rMTK4gyavBAxs9lkEPMCldrtBFWteXTw4bvdkDY62EOMjFN3QdqtJD9kRLcOxS9OwlLRBCVEEgPE3AyOazzovmVSVnrrwCcclU87iG8qMMx3ZK4qbaANpVETDRm-nU5L38la4i6yeNdJm0uX91003G07Ihq9LzWaIsT8pK1dirvq8d3ElUfZ-wBVz4imKnLrRgtTiZIa8eQvGVuWiBtp4I2rijDfzaYHKyAAh55UHNXCHde9yefQnSE_SHmunkCTLiQRbA7HorAOZBK0fiR9qidLMPwNBft01spufotp7UBseO7xusHezJ9VgIew", "e": "AQAB", "kid": "764edc29-9da0-43e0-97f3-2e140cc9152a", "x5t": "bisb-ais" } ] } I have tried one third party api but it looks like it is dependent on the x5c key which isn't present in my case. My code is: def verify_token(token): api_response = api_client(route='AUTH_KEY',query = {}) response = jwks_key(data=api_response) response.is_valid(raise_exception=True) public_keys = {} for jwk in response.data['keys']: kid = jwk['kid'] alg = jwk['alg'] public_keys[kid] = jwt.algorithms.RSAAlgorithm.from_jwk(json.dumps(jwk)) kid = jwt.get_unverified_header(token)['kid'] key = public_keys[kid] payload = jwt.decode(token, key=key, algorithms=alg,verify = True) How can I validate a JWT via jwks without x5c in python? -
Double Slash is Appearing in URL | Django Sitemap
Double slashes are appearing in Sitemap.xml enter image description here Code of models.py class Category(models.Model): name = models.CharField(max_length=100) class Meta: verbose_name = "Category" verbose_name_plural = "Categories" def __str__(self): return self.name def get_absolute_url(self): return reverse("category_items", kwargs={"category": self.name}) Code of urls.py from django.contrib.sitemaps.views import sitemap from core.sitemaps import BlogSitemap, CategorySitemap sitemaps = { "blogs": BlogSitemap(), "categories": CategorySitemap(), } urlpatterns = [ path('admin/', admin.site.urls), path('', include('core.urls')), path('sitemap.xml', sitemap, {'sitemaps': sitemaps}, name='django.contrib.sitemaps.views.sitemap'), ] Code of sitemap.py class CategorySitemap(Sitemap): changeFreq = "weekly" priority = 0.5 def items(self): return Category.objects.all() what is the possible soultion -
How to see if user is connected to internet or NOT?
I am building a BlogApp and I am stuck on a Problem. What i am trying to do I am trying to implement a feature that ,`If user is connected to internet then everything works fine BUT if user is not connected to internet then show a message like "You're not Connected to Internet". What have i tried I also tried channels but then i think internet connection are far away from Django-channels. I also tried this : url = "http://127.0.0.1:8000/" timeout = 5 try: request = requests.get(url, timeout=timeout) print("Connected to the Internet") except (requests.ConnectionError, requests.Timeout) as exception: print("No INTERNET") But it is keep showing me : 'Response' object has no attribute 'META' I don't know what to do. Any help would be Appreciated. Thank You in Advance -
What's the best way to get many items from a big table with specific IDs
I need to make a query with Django to a Postgres table with millions of rows and I need to select a few hundred items with specific IDs (or another field which has an index). Right now I'm doing it like this: A_query_filter = Q(item_id=None) for batch_id in batch_ids: A_query_filter = A_query_filter | Q(item_id=batch_id) A = Item.objects.filter(A_query_filter).order_by('-added') The query is pretty slow, even though I have an index on "item_id". Is there a more efficient way to do this? -
window.open opens multiple tabs instead of one in google chrome
I have created a dyanmic input field with search button.At first only on tab is opened when i click on Button. But after saving if I click on it again then it opens multiple tabs for the same url. No of tabs is equal to the no of dyanmic input field created and this happens only in google chorme. <button type="button" id='btn[]' name="btn" class='btn btn-default' ><i class="fa fa-search"></i></button> <script> $(document).on('click', '[id^=btn]', function(f){ f.preventDefault() console.log('vendor side'); console.log(this.id); window.inputid = $(this).closest("tr").find("td input").attr("id"); console.log(window.inputid); var myWin = window.open("/vendorlist/", "", "width=500,height=500"); }); </script> How can I stop window.open to open multiple tabs after dyanmic fields are created.Please help.