Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why do I get 'MySQL server has gone away' after running a Telegram bot for some hours?
I'm building a Django (ver. 3.0.5) app that uses mysqlclient (ver. 2.0.3) as the DB backend. Additionally, I've written a Django command that runs a bot written using the python-telegram-bot API. Problem is that approximately 24hrs. after running the bot (not necessarily being idle all the time), I get a django.db.utils.OperationalError: (2006, 'MySQL server has gone away') exception after running any command. I'm absolutely sure the MySQL server has been running all the time and is still running at the time I get this exception. My assumption is that some MySQL threads get aged out and get closed, so after reusing them they won't get renewed. Has anyone bumped into this situation and knows how to solve it? Traceback (most recent call last): File "/opt/django/gip/venv/lib/python3.6/site-packages/telegram/ext/dispatcher.py", line 555, in process_update handler.handle_update(update, self, check, context) File "/opt/django/gip/venv/lib/python3.6/site-packages/telegram/ext/handler.py", line 198, in handle_update return self.callback(update, context) File "/opt/django/gip/gip/hospital/gipcrbot.py", line 114, in ayuda perfil = get_permiso_efectivo(update.message.from_user.id) File "/opt/django/gip/gip/hospital/telegram/funciones.py", line 33, in get_permiso_efectivo u = Telegram.objects.get(idtelegram=userid) File "/opt/django/gip/venv/lib/python3.6/site-packages/django/db/models/manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/opt/django/gip/venv/lib/python3.6/site-packages/django/db/models/query.py", line 411, in get num = len(clone) File "/opt/django/gip/venv/lib/python3.6/site-packages/django/db/models/query.py", line 258, in __len__ self._fetch_all() File "/opt/django/gip/venv/lib/python3.6/site-packages/django/db/models/query.py", line 1261, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "/opt/django/gip/venv/lib/python3.6/site-packages/django/db/models/query.py", line 57, in … -
Django - settings seem to get cached in unknown location; how and where to clear python/django?
I can't run my Django server after restructuring the project into different subfolders. Error: "No module named..." for an app name that is just wrong in the error message, but not wrong in the settings file. I tried to remove all apps except the default apps from "INSTALLED_APPS" in settings. Nothing changed. So I modified the files of the Django package itself like following: in django/apps/registry.py I added print(installed_apps) in django/__init__.py I added print(settings) With surprising results. Settings printed out as expected: it showed to correct "path" to my settings file. installed_apps variable however returned a list of installed apps that was an old list of installed apps. When I add or remove entries from my settings file and rerun the server the output here doesn't change. Django somehow seems to have "cached" the INSTALLED_APPS somewhere - and I can't find where or why. Interestingly, I investigated further: I am not using a single settings file anymore. After restructuring the project I created a folder "settings" including the files _base.py with all main settings, prod.py, dev.py, and __init__.py. prod.py and dev.py currently just include from _base import * and that's it. __init__.py just contains from .prod import *. In my … -
how to check if a user is in a default django group? in the admin panel (admin.py)
My logic is that when a user with is_stuff privilege went to the admin panel and tried to create, for example, news, then the program checked him, in which group he is, if this group exists, then it should issue fieldsets with limited capabilities, or other fields... I checked this link (In Django, how do I check if a user is in a certain group?), but it does not work for my situation, since I have to check in the admin panel not return it to api or templates. i tried to do the following: in admin.py (a) def get_fieldsets(self, request, obj=None): group = Group(name="OutSource") if request.user.groups(name=group): # first_fields = {...} else: # second_fields = {...} callback: TypeError: 'NoneType' object is not callable admin.py (b): if request.user.groups.all()[0].name == "OutSource": callback: IndexError: list index out of range admin.py (c): if request.user.groups.filter(name='OutSource').exists(): callback: unhashable type: 'dict' -
How to fill table rows using context of views.py on page load?
I am working on a django project and I ran into a bit of a problem and not able to figure out what I am doing wrong. Problem The user clicks on a cell on a page "userlist/". I save the value of username in localstorage in Javascript and take user to another page "maclists". On "maclists" I run POST using fetch of javascript and POST the stored username to views.py. I am able to retrieve the values as I want. Though they are as queryset objects like this: <QuerySet [(1, '828234y8y', 'hn', 'hbhb', 'bhjh', 'hbj'), (2, '9299338uu8u', 'hbhb', 'hbhb', 'bhb', 'bhbh')]> I convert them to list of dictionaries and I finally have something like this: [{'machineid': '828234y8y', 'machinename': 'hn', 'protocol': 'hbhb', 'port': 'bhjh', 'targetip': 'hbj'}, {'machineid': '9299338uu8u', 'machinename': 'hbhb', 'protocol': 'hbhb', 'port': 'bhb', 'targetip': 'bhbh'}] Then I try to send it to the "maclists" page using : return render(request, "users/maclists.html", {'machines': listsofmac}) listsofmac stores the above list of dictionaries. The issue is I don't see the data in table of HTML using the context I passed. I don't know if it is due to the thing that I used POST at windows.load(). Help required Any suggestion or alternative to … -
How to get other attribute except from 'value' request.POST.get("") ? Django
I'm usuing request.POST.get("") with the name of the HTML tag and get the Value of the HTML tag. However I want to get id/text .. how can I do it ? -
Where am i suppose to clone Heroku python-getting-started repo
Am i suppose to clone https://github.com/heroku/python-getting-started.git? if yes where? -
How can I link (connect) two dropdowns in django admin
Like: There are three dropdowns: Country, Province, and District. Country: When I click on Country dropdown it'll display all the countries. And I'll choose one. Province: When I choose a Country, the Province gets filtered according to country and displays all the provinces on that chose country. And I'll choose a province. District: After choosing a province, the district gets filtered according to the districts inside that province. I hope you got me. I want this to be possible in Django admin -
How do I get route params in a custom middleware?
I have this route: re_path(r'ws/(?P<room_name>\w+)$' And I can get a param from the route like this in the consumer: self.scope['url_route']['kwargs']['room_name'] But how do I get the same param in a custom auth middleware (BaseMiddleware)? -
Media files are not visible after deploying the django project on heroku
I have deployed my website (build in django) on heroku, all the static files are visible but media files are not showing. -
How to hide inline title when no related objects
My solution, but it seems to me that there is a more elegant solution class ModelInline(StackedInline): model = Model @register(AnotherModel) class AnotherModelAdmin(ModelAdmin): inlines = [ModelInline] def get_inlines(self, request, obj): inlines = super().get_inlines(request, obj) if not another_model_instance.<related_name>.exists(): inlines.remove(ModelInline) return inlines -
Ajax in Django is creating duplicate elements
I have a form which when submitted creates a graph using Plotly. I am trying to use Ajax to submit the form without page refresh. While the form is submitted successfully, the form div is duplicated on the screen. I am not sure how to rectify this problem. I am using the Django web framework. Here is my code. template <form action="{% url 'home' %}" method='post' id='year-form'> {% csrf_token %} <select class="form-select form-select-lg mb-3 dropdown-btn" aria-label="Default select example" name="year"> <option selected>Select Year</option> <option value="2017">2017</option> <option value="2018">2018</option> <option value="2019">2019</option> <option value="2020">2020</option> </select> <div class="d-grid gap-2"> <button class="btn btn-primary btn-lg" type="submit">Button</button> </div> </form> <div id="message"></div> <div class="graph center" id='graph'> {% if graph %} {{ graph.0|safe }} {% else %} <p>No graph was provided.</p> {% endif %} </div> ajax jQuery <script type="text/javascript"> var frm = $('#year-form'); frm.submit(function () { $.ajax({ type: frm.attr('method'), url: frm.attr('action'), data: $(this).serialize(), success: function (data) { $("#graph").html(data); }, error: function (data) { $("#message").html("Something went wrong!"); } }); return false; }); </script> This is what the page looks like before the form submit this is what it looks like after the form is submitted I think I am not feeding the correct data in the success part of the Ajax … -
Can't upload large file from django admin panel
I have a django application. I want to upload files from admin panel of this application. After the files are uploaded, they are uploaded to google cloud storage and deleted from the application. I am getting DATA_UPLOAD_MAX_MEMORY_SIZE error because my file size is about 1GB. Can you help me? Models.py: class Document(AbstractBasicFTPSupportModel): category = models.ForeignKey( to="SupportCategory", related_name="documents", on_delete=models.CASCADE, verbose_name=_("category"), ) related_products = models.ManyToManyField( "product.Product", blank=True, related_name="documents", verbose_name=_("related products") ) document_file = models.FileField( upload_to=save_support_file, verbose_name=_("document file"), null=True, blank=True, max_length=255, ) class Meta: verbose_name = _("document") verbose_name_plural = _("documents") ordering = ["-created_at"] def save(self, *args, **kwargs): category_name = self.category.name file_base_path = os.path.join(MEDIA_ROOT, str(self.document_file)) file_basename, file_extension = os.path.splitext(os.path.basename(file_base_path)) file_name = category_name+"/"+slugify(urlify(file_basename))+file_extension file_path = file_name.replace(category_name, "media") self.ftp_url = "https://files.example.com/"+file_name super().save(*args, **kwargs) upload_to_cloud(file_name, file_path, "test-data") upload_to_cloud func: def upload_to_cloud(blob_name, file_path, bucket_name): try: bucket = client.get_bucket(bucket_name) blob = bucket.blob(blob_name) blob.upload_from_filename(file_path) # upload by file path logger.info("{} uploaded to {} successfully!".format(blob_name, bucket_name)) delete_uploaded_file(file_path, blob_name) return True except Exception as e: logger.error(e) return False def delete_uploaded_file(file_path, blob_name): if os.path.isfile(file_path): os.remove(file_path) logging.info("{} is deleted from media folder.".format(blob_name)) -
Post Method not allowed in CBV dispatch method when form is invalid
When creating a view using FormView class and using dispatch method to fetch some data during class initialization, Error is received when the form gets invalid {'detail': ErrorDetail(string='Method "POST" not allowed.', code='method_not_allowed')} here is the code :- class TestView(LoginRequiredMixin,FormView): form_class = TestForm template_name = 'test.html' def dispatch(self, request, *args, **kwargs): self.data = TestViewSet.as_view({'get': 'list'})(self.request).data return super(TestView, self).dispatch(request, *args, **kwargs) def get_context_data(self, **kwargs): context = super(CredentialsView, self).get_context_data(**kwargs) if self.request.user.is_authenticated: context['username'] = self.data['username'] context['firstname'] = self.data['firstname'] context['lastname'] = self.data['lastname'] return context def form_valid(self, form): password = form.cleaned_data['password'] if form.is_valid(): return self.query_api(password) else: return super(TestView, self).form_valid(form) Here is the trace :- django: {'detail': ErrorDetail(string='Method "POST" not allowed.', code='method_not_allowed')} Traceback (most recent call last): File "/usr/local/lib/python3.6/dist-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/usr/local/lib/python3.6/dist-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/usr/local/lib/python3.6/dist-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/local/lib/python3.6/dist-packages/django/views/generic/base.py", line 71, in view return self.dispatch(request, *args, **kwargs) File "/usr/local/lib/python3.6/dist-packages/django/contrib/auth/mixins.py", line 52, in dispatch return super().dispatch(request, *args, **kwargs) File "/usr/local/lib/python3.6/dist-packages/django/views/generic/base.py", line 97, in dispatch return handler(request, *args, **kwargs) File "./ssh/views.py", line 91, in post return self.form_invalid(form, **kwargs) File "./ssh/views.py", line 77, in form_invalid context = self.get_context_data(**kwargs) File "./ssh/views.py", line 97, in get_context_data kwargs['username'] = data['username'] KeyError: 'username' How … -
fromtimestamp returns me Invalid argument
I'm trying to convert an int variable (timestamp) to datetime but django returns me fromtimestamp Invalid argument date_time = datetime.fromtimestamp(int(request.data["time"])) Exception Type: OSError Exception Value: [Errno 22] Invalid argument How to solve this problem ? -
Nested for loop string equivalent in separate Django model Tables
I have a nested for loop to see where a field from Table Clock equals the field from table Employee, and when this happens run some condition. This seems extremely intuitive however i seem to be making a fundamental error. My if statement does not execute. I have printed out the each tables values and confirmed that some are equal I have also confirmed that both fields types are strong. Please help. ''' queryClock = Clock.objects.all() queryEmployee = Employees.objects.all() if queryClock.count() > 0 : for x in queryClock: for y in queryEmployee: # print(type(x.EmployeeNoC),type(y.EmployeeNo)) # print(x.EmployeeNoC, y.EmployeeNo) if x.EmployeeNoC == y.EmployeeNo: print("yay") x.hourlyRate = y.rate x.save(update_fields=['hourlyRate']) break ''' -
How to convert '2021-08-24T11:00:19Z' to datetime and find days between it and the current time in django
I get the following publishedAt string '2021-08-24T11:00:19Z' from youtube's api for the video object. But I don;t understand how to convert it into a datetime object and find the hours between it and current. I tried the below code but it didn't work view.py from django.utils import timezone from datetime import datetime today = timezone.now() publish_date = datetime.fromtimestamp('2021-08-24T11:00:19Z') diff = today - publish_date But I am getting the below error at this line publish_date = datetime.fromtimestamp('2021-08-24T11:00:19Z') TypeError: an integer is required (got type str) I don't understand how to convert the string to datetime object and get the difference. -
how can I create json data structure in mongodb like this?
I am having a problem to create this structure inside my mongodb. I'm using django. Djongo is the model i used to try and create this but I cant seem to find a way. I've tried using Arrayfield and embeddedfield as well but I'm stuck. Kindly help me if anyone of you know how. Thank you. -
Django nginx gunicorn how they connect together?
I want to deploy my django app on a linux server. For this I use gunicorn (version 20.1.0) nginx/1.18.0 Django==3.0.5 sites-available/bunn_nginx.conf upstream django { server unix:///home/app/bunn/auth/auth.sock; } server { server_name example.com www.example.com; # max upload size client_max_body_size 75M; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/app/bunn/auth/static/; } location / { include proxy_params; proxy_read_timeout 300; proxy_connect_timeout 300; proxy_pass http://unix:/home/app/bunn/auth/auth.sock; } listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/thermal.d-d-s.dk/privkey.pem; # managed by Certbot include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot } server { if ($host = example.com) { return 301 https://$host$request_uri; } # managed by Certbot listen 80; server_name example.com; return 404; # managed by Certbot } uwsgi.ini [uwsgi] # full path to Django project's root directory chdir = /home/app/bunny/auth/ # Django's wsgi file module = auth.wsgi # full path to python virtual env home = /home/app/bunny/env/ # enable uwsgi master process master = true # buffer size buffer-size = 72000 # maximum number of worker processes processes = 10 # the socket (use the full path to be safe socket = /home/app/bunny/auth/auth.sock # socket permissions chmod-socket = 666 # clear environment on exit … -
json.dumps takes too much time to convert the data
I am using json.dumps to make some reports from my Django model. start = time.process_time() items = Allotment.objects.all().order_by('dispatch_date') print("allotments", len(items)) serializer = AReportSerializer(items, many=True) items_json = json.dumps(serializer.data) print("allot time", time.process_time() - start) I have checked the time of query and serialization and it comes too small to even notice but json.dumps takes too much time, sometimes it's even in the minutes. What should I do to reduce this processing time? -
How do I get all for-looped values from a Django template
I am new to django. I want to use this django form to get number_of_days for all {{ name }} values <div> <form action="change_number_of_days" method="post"> {% csrf_token %} {% for name in filenames %} <input type="number" name="number_of_days" id="number_of_days" value=200> <label for="number_of_days"> {{ name }} </label> <input type="hidden" value="{{ name }}" name="name_of_file"><br><br> {% endfor %} <button type="submit"> Gem </button> </form> </div> Currently Im only getting the values of the LAST loop(Pizzaria, 200), but I want to get all looped inputs as a POST request This is my VIEW.py def change_number_of_days(request): if request.method == 'POST': days = request.POST['number_of_days'] print(cleaning_days) filename = request.POST['name_of_file'] print(filename) return render(request, 'price_calculation_complete.html') return HttpResponse("error") -
How to get the 'id' of PATCH request in django?
The PATCH request looks something like this "PATCH /api/details/43/ HTTP/1.1". I want to get the id from that request viz. 43. I am using ModelViewSet and overriding partial_update. I tried to MyModel.objects.get() inside partial_update but its returning more than one objects. -
django mongodb connections by using djongo and pymongo
Can I use djongo to connect with Mongodb database and for complex queries i want to use Pymongo in my django project. please let me now if it is possible. As I wanted to do fulltext search in my project which is possible by pymongo. ''' details = collection_name.find({"$text": {"$search": "python"}},{"score": {"$meta": "textScore"}}).sort([("score",{"$meta":"textScore"})]) ''' -
User foreign key in same model getting updated together in sql database
models.py class test(models.Model): a_names = models.ForeignKey(User, related_name='a_names', on_delete=models.DO_NOTHING, blank=True, null=True) b_names = models.ForeignKey(User, related_name='b_names', on_delete=models.DO_NOTHING, blank=True, null=True) forms.py class Test1ModelForm(forms.ModelForm): class Meta: model = Test1 fields = ('id', 'a_names') views.py def Testing(request, pk): form = Test1ModelForm(instance=pk) if form.is_valid(): form.save() the problem is, when the data is getting updated in the database, both a_names and b_names is getting updated. -
'int' object has no attribute 'encode' error while sending mail in django
[this error i get while sending email][1] def registration(request): if request.method == 'POST': username = request.POST['username'] first_name = request.POST['first_name'] last_name = request.POST['last_name'] email = request.POST['email'] password = request.POST['password'] if User.objects.filter(username = username).exists(): messages.info(request,'Username taken') return redirect('registration') elif User.objects.filter(email = email).exists(): messages.info(request,'Email id is already registered') return redirect('registration') else: user = User.objects.create_user(username=username, password= password, email= email, first_name = first_name,last_name = last_name) user.save() auth_token = str(uuid.uuid4()) print('done') print(auth_token , email) send_mail_after_registration(auth_token , email) profile_obj = Profile.objects.create(user=user , auth_token = auth_token ) profile_obj.save() return render(request, 'token_check.html') else: return render(request, 'registration.html') def send_mail_after_registration(ctoken , email): print("hiii") subject = 'Your account need to verified- MyTrip' message = 'Hello, \n We are excited to have you get started. First, you need to confirm your account. Just press the Link below. \n Or paste the link in browser to verify `your account http://127.0.0.1:8000/verify/'+ctoken + '\n \n If you have any questions, just reply to this email—we are always happy to help out. \n Cheers, \n The MyTrip Team' email_from = settings.EMAIL_HOST_USER recipient_list = [email] print("hii") #msg=EmailMessage(subject,message,to=recipient_list) #msg.send() send_mail(subject, message, email_from, recipient_list) error discription: AttributeError at /registration/ 'int' object has no attribute 'encode' Request Method: POST Request URL: http://127.0.0.1:8000/registration/ Django Version: 3.2.6 Exception Type: AttributeError Exception Value: 'int' … -
How to fetch specific data from database using react hooks
I'm trying to make it so that I can just fetch a specific title for the page from the database and have it displayed on the webpage. Here is what I have so far. It fetches the entire list of the titles. const GettingStarted = () => { const classes = useStyles(); const [title, setTitle] = useState([]); const [paragraph, setParagraph] = useState([]); useEffect(() => { const fetchData = async () => { try { const res = await axios.get(`http://localhost:8000/api/text/`); setTitle(res.data); } catch (err) { } } fetchData(); }, []); const getTitle = () => { let result = []; title.map(titledata => { console.log(titledata.title) return result.push( <h1>{titledata.title}</h1> ) }) } return ( <main className={classes.content}> <Helmet> <title>Getting Started</title> </Helmet> <div className={classes.toolbar} /> {getTitle()} </main> ) } For this page, I just want to fetch 'Getting Started' from the list of titles stored in the database. How do I do this?