Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - Get URL from DB and use it as src in in iframe
I have simple requirement. There is a URL that is stored in DB. I need to retrieve this URL from the DB and in my template use this URL as SRC value in an iframe. Model.py: from django.db import models # Create your models here. class DashboardLink(models.Model): dashboard_url = models.CharField(max_length=255, unique=True) Views.py from django.shortcuts import render from .models import DashboardLink def index(request): dashboard_url = DashboardLink.objects.all() return render(request, 'index.html') In Index.html I have the following code, in which I want to use the url retrieved from the DB. index.html <p>{{ dashboard_url.dashboard_url }}</p> ### This is to just check if the data is being fetched or not.. This too results in blank. #### <section> <iframe width="100%" height="700" src="{% for item in dashboard_url %} {{ item }} {% endfor %}" frameborder="0" allowfullscreen></iframe> </section> <br><br> </div> In urls.py I have the following code: *urls.py* path('index/', logged_in_views.index, name='index'), When I use Inspect, I see the following [![enter image description here][1]][1] Can someone please help me in understanding what am I missing? [1]: https://i.stack.imgur.com/C7Oek.png -
Updating User details in UserDetail Table using One-To-One Relation Django Rest API
I am new to Django. I am trying to update User details in another table using One-To-One relation by following Django document but is giving me an error. Creating a new user is working fine Models.py class UserDetails(models.Model): user=models.OneToOneField(User,on_delete=models.CASCADE) phone=models.CharField(max_length=10) address=models.CharField(max_length=200,default="") created=models.DateTimeField(auto_now_add=True) updated=models.DateTimeField(auto_now_add=True) objects=models.Manager() def __str__(self): return self.user.username Serializer.py class UserDetailsSerializer(serializers.ModelSerializer): class Meta: model = UserDetails fields= ['phone','address'] class CreateUserSerializer(serializers.ModelSerializer): userdetails=UserDetailsSerializer() class Meta: model = User fields=['id','url','username','email','password','userdetails'] def create(self,validated_data): user_data=validated_data.pop('userdetails') user=User.objects.create_user(**validated_data) UserDetails.objects.create(user=user,**user_data) user.save() return user def update(self,instance,validated_data): user_data=validated_data.pop('userdetails') user=User.objects.update(**validated_data) UserDetails.objects.update(user=user,**user_data) user.save() return user The error I get - (1062, "Duplicate entry 'admin' for key 'auth_user.username'") I know we can update it column by column but I want to update all columns at once as I have a lot of columns. I want a method similar to create. One more question is that can I combine these create and update as they are doing the same thing? -
transaction in ethereum ropsten net
I'm trying to make a transaction in a ethereum ropsten testnet, and I receive the ether from ropsten ethereum faucet, but when I try to send the transaction raise this error: ValueError: {'code': -32000, 'message': 'insufficient funds for gas * price + value'}. How can i do? This is my code: from web3 import Web3 def sendTransaction(message): w3 = Web3(Web3.HTTPProvider('https://ropsten.infura.io/v3/af2c9d3063c34f29aed833341a7a0b90')) address = '' #address of wallet privateKey = '' #privatekey nonce = w3.eth.getTransactionCount(address) gasPrice = w3.eth.gasPrice value = w3.toWei(0, 'ether') signedTx = w3.eth.account.signTransaction(dict( nonce=nonce, gasPrice=gasPrice, gas=100000, to='0x0000000000000000000000000000000000000000', value=value, data=message.encode('utf-8') ), privateKey) tx = w3.eth.sendRawTransaction(signedTx.rawTransaction) txId = w3.toHex(tx) return txId -
Trying to get value of a subprocess
I am creating a function to test connection and to get value but it is not working. I'm using a grep to get only received value. def testConnection(ip): TIMEOUT = 10 args = ('sudo', 'ping', '-c', '1', '-q', ip, '|', 'grep -E -o', '"[0-9]+ received"', '|', 'cut', '-f1', '-d') try: popen = subprocess.Popen(args, stdout=subprocess.PIPE) popen.wait(timeout=TIMEOUT) if (popen == 1): print(ip + " is up") else: print(ip + " is down") except subprocess.TimeoutExpired as e: print(e) return False if(popen.returncode != 0): raise ServiceException() -
while I am hovering on main category then I am getting a drop down of sub category. but it hiding behind another div. How to prevent
while I am hovering to an main category I am getting fine sub category drop down but the sub category drop down is hiding behind the image as you can see in the image I have attached.So here I have use "z-index:1" but it is not working so how to solve this issue please let me know <div class="dropdownCategory"> <a class="dropbtnCat" href="{% url 'coupons' Categories.cat_name %}">{{Categories.cat_name}}<i class="arrow-indicator fa fa-angle-right" aria-hidden="true"></i></br></a> <div class="dropdown-contentCat"> {% for subCategories in SubCategoriesBar %} {% if Categories.cat_id == subCategories.parent_id %} <a href="{% url 'coupons' subCategories.cat_name %}">{{subCategories.cat_name}}</a> {% endif %} {% endfor %} </div> </div> css .dropdown-contentCat { display: none; position: absolute; background-color: #f1f1f1; min-width: 160px; box-shadow: 0px 8px 16px 0px rgb(0 0 0 / 20%); z-index: 1; left: 101%; top: -2px; border-top: 2px solid #DB0038; font-size: 14px; } -
How to save data in both (user and profile) tables using django signals in a single request?
I have a register form with fields(firstname, lastname, username, email, dateofbirth, phoneno.) I have used signals to create a record in userprofile. whenever a new userdata is added to the user table what i want is whenever user post the request. the data should get saved in user table and then the signal creates a record in profile table and then the remaining data should also get populated in there respected fields. As I'm receiving all the data from user at the registration time. views.py def register(request): if request.method == "POST": print(request.POST) first_name = request.POST.get('first-name') <-----user table last_name = request.POST.get('last-name') <-----user table username = request.POST.get('username') <-----user table email = request.POST.get('email') <-----user table gender = request.POST.get('gender') <-----profile table date_of_birth = request.POST.get('date-of-birth') <-----profile table address = request.POST.get('address') <-----profile table phone_number = request.POST.get('mob-number') <-----profile table ans_1 = request.POST.get('ans-1') <-----profile table ans_2 = request.POST.get('ans-2') <-----profile table User.objects.create_user(first_name=first_name, last_name=last_name, email=email, username=username, last_login=timezone.now()) return render(request, 'authentication/register.html') signals.py @receiver(post_save, sender=User) def create_user_info(sender, instance, created, **kwargs): if created: UserInformation.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_info(sender, instance, **kwargs): instance.userinfo.save() -
Django-cron check running proceses
Is there any way to get the crons that are runging and wich one? if any. I'm usign the library Django-Cron: https://django-cron.readthedocs.io/en/latest/index.html ¿Why? I want to allow the user to start a process with an action from Admin site. But if the process is running I will skip the order and deliver the message that there's a process already running. Thank you. -
Django change temporary path while uploading files
By default Django stores all its temp files in "/tmp" when files are uploaded. I tried to change the FILE_UPLOAD_TEMP_DIR in settings.py to give a custom path. But Django fails to take the new path. Tried the following properties in settings.py FILE_UPLOAD_HANDLERS = ( 'django.core.files.uploadhandler.MemoryFileUploadHandler', 'django.core.files.uploadhandler.TemporaryFileUploadHandler', ) FILE_UPLOAD_MAX_MEMORY_SIZE = 2621440 FILE_UPLOAD_TEMP_DIR = "/datadrive/test" MEDIA_ROOT = '/datadrive/test' SESSION_FILE_PATH = '/datadrive/test' FILE_UPLOAD_DIRECTORY_PERMISSIONS = 0o644 FILE_UPLOAD_PERMISSION = 0o644 -
I can't view my template with render in django
My template with called hello.html <h1>Hello World</h1> My views.py from django.shortcuts import render from django.http import HttpResponse def say_hello(request): return render(request,'hello.html') Also if i try return HttpResponse('Hello World') it is working. But rander is not working. -
HTML Modal not functioning in Django application
I am trying to implement this codepen into my Django program. I don't know why, but I just can't get it to work. I have all of the classes and everything names correctly, but my program does not do anything. I want the user to be able to click on the view button and have an HTML overlay exactly like the one in the codepen come up, but for some reason nothing is happening when I click on the button. Can someone please take a look and tell me what I am doing wrong? Thank you. HTML: {% extends 'suppliesbase.html' %} {% load static %} {% block content %} <div class="row"> {% for donation in donations %} <div class="col-lg-4"> <img class="thumbnail" src="{{donation.imageURL}}"> <div class="box-element product"> <h6><strong>{{donation.title}}</strong></h6> <hr> <button class="btn btn-outline-success" id="openModalBtn" href="#">View</button> <h4 style="display: inline-block; float: right"><strong>Free!</strong></h4> </div> </div> {% endfor %} </div> <!--Modal Overlay Content --> <div id="modal-overlay"> <div id="modal"> <div class="head"> <a id="close-modal-button" href="javascript:;"></a> </div> <div class="content">Modal content</div> </div> </div> <script> var openModalButton = document.getElementById("open-modal-button"); var closeModalButton = document.getElementById("close-modal-button"); var modalOverlay = document.getElementById("modal-overlay"); var modal = document.getElementById("modal"); // function that open modal and display the overlay openModalButton.addEventListener("click", event => { modalOverlay.classList.add("modal-overlay-visible"); modal.classList.add("modal-visible"); }); // function that closes the … -
Django: Ignore transaction for given update
I have a long-running process that should be atomic (Larger update of an application's data). However, during the update, I'd like to let the user know about the progress. How can I update a model from within the transactioned code, such that it is not part of said transaction? One potential solution would be to use non-DB storage, such as files, or a second DB connection with the same credentials. Both don't feel like the "right" way to do it... -
Django-selenium How to make download button work on a webclient of another website
I am building a website with Django. It displays the content of another website by scraping parts of its HTML with selenium and incorporating that code in my webpage to make it look better. For example, in one page, a table is passed to my website through the context and it's incorporated this way {% extends 'home.html' %} {% block content %} {{ table_name|safe }} {% endblock %} This table also has a download button in each row, and the number of rows changes over time (I don't know if that matters but anyway). In the table the download button is displayed but it doesn't work. Is there any way I can make it work? You should also know that the download button does not redirect to a link. -
Try, Except is not giving required result in django serializers create method. the getobject statements gives required result if put is outside try:
class BeneficiarySerializer(serializers.Serializer): class Meta: model = Beneficiary fields ='__all__' def create(self, validated_data): try: available = Beneficiary.objects.get(coupon_code=validated_data['coupan_code']) raise serializers.ValidationError("The provided coupon code is already utilized") except: return super().create(validated_data) class Coupon(models.Model): sl_no = models.CharField(max_length=50, primary_key=True) c_code = models.CharField(max_length=50, blank=True) def __str__(self): return self.c_code class Beneficiary(models.Model): name = models.CharField(max_length=50) coupon_code = models.ForeignKey(Coupon, on_delete=models.CASCADE) def __str__(self): return self.name purpose is to issue a coupon to only one person, if the same coupon code is issued to another in that case Serializers should raise and error that the key is issued to someone. if i put the code in try and except every time the verification fails, the same coupon code is allotted to many, if use objects.get outside try: statement is return result is found. please let me know if i am not using try: except in proper way or any other way to deal with this situation -
Why Python String auto convert into Date in microsoft excel
I am writing data into a CSV file. file contains data related to student marks like 6/10, which means 6 out of 10. issues are when I open this file with Microsoft excel 6/10 becomes 6-Oct. here is anyone have an idea how can we stop to converting a string to date. need solution from code side not an excel side -
NameError: name 'StudentsSubscription' is not defined IN DJANGO SAVE METHOD
I am trying to filter entries from the child model in parent model save method to show in admin pannel,But getting this error class StudentsSubscription(models.Model): student = models.ForeignKey('student.Student', on_delete=models.CASCADE,blank=True,null=True,help_text = "This Field Is Mandatory") enrolled_activity = models.ForeignKey('student.EnrolledActivity', on_delete=models.CASCADE,blank=True,null=True,help_text = "This Field Is Mandatory") teachers_class = models.ForeignKey('teacher.TeachersClass',on_delete=models.CASCADE,blank=True,null=True,related_name='subscription_name') demo_class = models.BooleanField(default=False,blank=True,null=True) is_finished = models.BooleanField(default=False,blank=True,null=True) channel_name = models.CharField(max_length=250,blank=True,null=True) count = models.IntegerField(default=0,blank=True,null=True) room_id = models.IntegerField(blank=True,null=True) is_active = models.BooleanField(default=False,blank=True,null=True) class TeachersClass(models.Model): class_name = models.CharField(max_length=250,blank=True,null=True) description = models.TextField(blank=True,null=True) batch_size = models.IntegerField(default=0) seats_left=models.IntegerField(default=0) image = models.ImageField(upload_to='teacher/class',blank=True,null=True) teacher = models.ForeignKey(Teacher,on_delete=models.CASCADE,blank=True,null=True,help_text = "This Field Is Mandatory") grade = models.ForeignKey(Grade,on_delete=models.CASCADE,blank=True,null=True,help_text = "This Field Is Mandatory") activity = models.ForeignKey(Activity,on_delete=models.CASCADE,blank=True,null=True,help_text = "This Field Is Mandatory") days = models.ManyToManyField(DaysOfWeek,blank=True) date = models.DateField(blank=True,null=True,help_text = "This Field Is Mandatory") start_time = models.TimeField(blank=True,null=True,help_text = "This Field Is Mandatory") end_time = models.TimeField(blank=True,null=True,help_text = "This Field Is Mandatory") is_active = models.BooleanField(default=False,blank=True,null=True) agora_token = models.CharField(max_length=250,blank=True,null=True) free_trial = models.BooleanField(default=False,blank=True,null=True) background1 = models.CharField(max_length=250,blank=True,null=True) background2 = models.CharField(max_length=250,blank=True,null=True) button_color1 = models.CharField(max_length=250,blank=True,null=True) button_color2 = models.CharField(max_length=250,blank=True,null=True) image = models.ImageField(upload_to='class/image',blank=True,null=True) def save(self, *args, **kwargs): all_admissions=StudentsSubscription.objects.filter(teachers_class__class_name=self.class_name).count() print(all_admissions) super(TeachersClass, self).save(*args, **kwargs) I am unable to figure out the issue -
How to access a file outside from a docker container?
I am using django as my framework. To manage the server we are using docker. When I try to run: docker-compose exec -T web python3 manage.py shell < /data01/ipse/litework/second_level_controller/load.py to load some data I get the following Error: File "/code/second_level_controller/DataBaseLoader.py", line 53, in load_filenames with open(os.path.join(self.data_directory, 'manifest.txt')) as f: FileNotFoundError: [Errno 2] No such file or directory: '/data01/ipse/rawdata/manifest.txt' But the file /data01/ipse/rawdata/manifest.text exists and I can acces the file normally with: nano /data01/ipse/rawdata/manifest.txt How can I access the file correctly? -
Looking for guidance on creating a search engine using a django web framework [closed]
Hi i would like to look for guidance on creating a search engine using a django web framework. I am not to sure how to proceed as I do not really have an experience on this. I would like to create a search engine on the website that I am building, whereby it will search from a shortlisted list of websites. -
Django - when user submits a form, tables are created, but the connection between the tables is not
i am working on a small project where a customer can go to my website and register phone numbers associated to their name. it is a connection-wise registration (where number1 <--> number2 is one connection), so only two phone numbers are ever registered per session. when viewing a particular phone number (in admins panel, for instance), i want to see the id of the user it belongs to and the id of the connection it is part of. When i view a connection the same way, i want to see who registered that particular connection, and the two phone numbers that were registered in the same session. my problem: all of the foreign keys give a "django.db.utils.IntegrityError: NOT NULL constraint failed" error. I had to set null=True for all of the foreign keys for the customer's data to be submitted at all. the ManyToManyField doesn't give any bugs - but it doesn't limit each Connection to only the two phone numbers registered in the session like it should. and so, this kind of structured connection outlined above isn't made when the data is added. it's like each phone number and each connection and each user becomes its own little island, … -
Add Task doesnot working in django in ToDo List
this is task_list.html <!--if we didnt create this tasklis.html we get error becoz as said in views .py it looks for tempate we diidnt cdreated any list on template et--> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>To Do List By Manasi</title> </head> <body> {% if request.user.is_authenticated %} <p>{{ request.user }}</p> <a href="{% url 'logout' %}">Logout</a> {% else %} <a href="{% url 'login' %}">Login</a> {% endif %} <hr> <h2>WELCOME To My To List! </h2> <a href="{% url 'create-task' %}">Add task</a> <table bgcolor="yellow" align="center" border="2px"> <tr> <th>Task Name</th><th> Task Details</th><th>Edit Task</th><th align="center">Delete Task</th> </tr> {% for task in tasks %} <!--for task in object_list %}this is when we havent created objet context list yet in view.pywhen view.py only contains model=Task--> <tr><td align="center">{{task.title}}</td><td align="center"><a href=" {% url 'task' task.id %}">View</a></td><td align="center"><a href=" {% url 'update-task' task.id %}">Edit</a></td> <td align="center"><a href=" {% url 'delete-task' task.id %}">Delete Task</a></td></tr> <!--i think this 'task' in url is context_objct_name in views.py but its false--> {% empty %} <!--this is django template format for empty condition likewise ele etc.--> <tr><td>No item</td></tr> {% endfor %} </table> </body> </html> **this is task_form.html for add task ie.create task** <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Create task Form</title> </head> <body> <h1>Create … -
Django style.css is not found
Error :Not Found: /{ % static 'css/style.css' % } "GET /%7B%20%%20static%20'css/style.css'%20%%20%7D HTTP/1.1" 404 2378 When i want to link my style.css to django project it throws an error. html : <!DOCTYPE html> {% load static %} <html> <head> <meta charset="utf-8"> <title>Have a Good Day</title> <link rel="stylesheet" href="{ % static 'css/style.css' % }" > </head> <body> <h1 class="ok">Great it works</h1> </body> </html> settings.py: STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] Note : DEBUG=True Folder structure : newproject : app1: migrations static css style.css templates init.py admin.py apps.py models.py tests.py urls.py views.py It is only for development . not deployment. -
How to import python code like a interface or service like in Laravel
I have this code in python for generating statistics, how can I optimize and make as many classes as possible to import this code https://gyazo.com/6aaca72d6c27595f619f026a40ece496 My code https://gyazo.com/440f5f25f8643245479ab29ab8e079c3 My structure -
Nested query in Django ORM
i'm try to remove duplicated row with distinct or annotate then measure count of something.(mysql:8 ,django:2.2) sql select t1.cp_id, count(*) from ( SELECT user_id, product_id, cp_id, count(*) as cnt FROM A where created_at between '2021-07-12' and '2021-07-13' group by user_id, product_id, cp_id ) as t1 group by t1.cp_id my queryset A.objects.filter( created_at__gte='2021-07-12', created_at__lt='2021-07-13' ).values('cp_id', 'user_id', 'product_id').annotate(cnt=Count('cp_id')).values('cp_id').annotate(count=Count('cp_id')) this queryset sql SELECT A.cp_id, COUNT(cp_id`) AS count FROM A WHERE ( created_at >= 2021-07-11 19:30:00 AND created_at < 2021-07-12 19:30:00 AND ) GROUP BY cp_id, created_at ORDER BY created_at ASC I'm confused why Django ignores the order of my commands and executes the last query commands on the original table (not the table where the duplicate data is deleted) Thanks if you have a solution or idea to remove the rows that have the same 'cp_id', 'user_id', 'product_id' (not from the database), then count the number of cp_ids -
URL automatically changes & it gives me the error of Page not found
"127.0.0.1:8000/adminpanel/edit_gallary/29" So this is the main problem when I first edit it works properly. But when I want to edit the second time URL automatically changes & it changes this way. "127.0.0.1:8000/adminpanel/edit_gallary/edit_gallary/29" This is my views.py file: def edit_gallary(request,gallaryid): table = gallary.objects.get(id=gallaryid) gallary_form = gallaryform(instance=table) if request.method=='POST': form = gallaryform(data=request.POST, files=request.FILES, instance=table) if form.is_valid(): form.save() table=gallary.objects.all() return render(request,"gallary1.html",{'table':table}) context = {'gallary_form':gallary_form} return render(request,'edit_gallary.html',context) This is my URLS.py file: path('edit_gallary/<int:gallaryid>',views.edit_gallary,name="edit gallery"), This is my edit_gallary.html file: {% extends 'index.html' %} {% block content %} <body> <div class="main-wrapper"> <div class="app" id="app"> <header class="header"> <div class="header-block header-block-collapse d-lg-none d-xl-none"> <button class="collapse-btn" id="sidebar-collapse-btn"> <i class="fa fa-bars"></i> </button> </div> <div class="header-block header-block-nav"> <ul class="nav-profile"> <li class="profile dropdown"> <a class="nav-link dropdown-toggle" data-toggle="dropdown" href="#" role="button" aria-haspopup="true" aria-expanded="false"> <div class="img" style="background-image: url('https://avatars3.githubusercontent.com/u/3959008?v=3&amp;s=40')"> </div> <span class="name">Admin</span> </a> <div class="dropdown-menu profile-dropdown-menu" aria-labelledby="dropdownMenu1"> <div class="dropdown-divider"></div> <a class="dropdown-item" href="#"> <i class="fa fa-power-off icon"></i> Logout </a> </div> </li> </ul> </div> </header> <aside class="sidebar"> <div class="sidebar-container"> <div class="sidebar-header"> <div class="brand"> <div class="logo"> <span class="l l1"></span> <span class="l l2"></span> <span class="l l3"></span> <span class="l l4"></span> <span class="l l5"></span> </div> Compare school </div> </div> <nav class="menu"> <ul class="sidebar-menu metismenu" id="sidebar-menu"> <li> <a href="insert_school"> <i class="fa fa-home"></i>Back</a> </li> </ul> </nav> </div> </aside> <div class="sidebar-overlay" id="sidebar-overlay"></div> <div class="sidebar-mobile-menu-handle" … -
How to sync a large CSV file with Django model
I want to process item report every hour for multiple accounts in my system. There are around 150k+ records in each csv. I want to sync report with database in the following way. Create record if it does not exists Update if it is present I want to do this in bulk (in one database query) Currently I am doing get or create for each record. I am using Postgres=13.2, Django=3.2.5 and python=3.9 -
Passing a URL into render_as_string
Is there a way to pass a URL instead of a template name in render_as_string. If not what can we use? # something like this def my_view_(request): if request.POST.get == 'POST': is_ajax = request.META.get('HTTP_X_REQUESTED_WITH') == 'XMLHttpRequest' if is_ajax: return JsonResponse(data={ 'string_template': render_as_string('a url here'), # or we have something other than render_as_string which takes URLS })