Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
virtual environment activation error in python [closed]
when I was trying to activate virtual environment, I faced this error. how can I fix this? I search on the link that error returned, but I didn't find out how to fix it! enter image description here -
How to capture picture or generate thumbnail from video in python django restframework?
Actually, I am trying to capture to make a thumbnail from an uploaded video in python Django. And then I have to save this thumbnail in a separate model field for later use. class Post(models.Model): user= models.ForeignKey(Profile, on_delete=models.CASCADE) video = models.FileField(upload_to='post_videos/%Y/%m', null=True) thumbnail = models.ImageField(upload_to='post_images/%Y/%m', null=True) I just want to upload a video, capture a thumbnail at any timestamp and then save it to the thumbnail field. Please, Let me know if anyone can help me out. I tried using FFmpeg and moviepy but unable to resolve the issue. waiting for help. Thanks -
Why we need to have the full Django project folder in the celery worker container?
I am new to Celery and Django. When I tried to build Django, Celery in different containers, the Examples always have the whole Django project folder in both Celery and Django Containers as a share volume. And these two containers share the same Dockerfile. Consider we only need the task module in the Celery worker. And I don't really want to install the same amount of "requirements" in the celery image. Is there a way we can build the celery image without putting the whole django project folder in the celery container? Thanks. -
Is there a way to tag and display the reception number and MCO number in 1 cell
I have created a website where user will enter the reception number(Verify if the reception number is same as the database, if different, they cannot be redirected to the success page) and MCO number as shown below: When it is redirected to my table page which is my success page, it created a new column show below, the 234 reception number should be tag to 13873827 the mco number and not a new column, how do I do that?: When I enter the 234 and a different MCO number it will show an error message: UNIQUE constraint failed: account_photo.reception when i enter 234 and 13873827, it will show this error message: UNIQUE constraint failed: account_photo.mcoNum, so I assume that it is tag? views.py @login_required() def verifydetails(request): if request.method == 'POST': form = verifyForm(request.POST) if form.is_valid(): Datetime = datetime.now() mcoNum = form.cleaned_data['mcoNum'] if Photo.objects.filter(reception=form.cleaned_data['reception']): form = Photo(Datetime=Datetime, mcoNum=mcoNum) form.save() return redirect('gallery') else: messages.success(request, 'The reception number you have enter is incorrect') return redirect('verifydetails') else: form = verifyForm() return render(request, 'verifydetails.html', {'form': form, }) forms.py class verifyForm(forms.Form): reception = forms.CharField(label='', widget=forms.TextInput( attrs={"class": 'form-control', 'placeholder': 'Enter Reception number'})) mcoNum = forms.CharField(label='', widget=forms.TextInput(attrs={"class": 'form-control', 'Placeholder': 'Enter MCO NUMBER'})) class Meta: model = Photo fields … -
Can't solve django templatedoesnotexist error
I know this question has been asked many times before yet I either can't find an answer that isn't outdated or that generally works. I keep getting this error even though my server is running correctly Environment: Request Method: GET Request URL: http://localhost:8000/subscribe/ Django Version: 3.1.4 Python Version: 3.8.10 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'app', 'subscribe'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Template loader postmortem Django tried loading these templates, in this order: Using engine django: * django.template.loaders.app_directories.Loader: /usr/local/lib/python3.8/dist-packages/django/contrib/admin/templates/subscribe/index.html (Source does not exist) * django.template.loaders.app_directories.Loader: /usr/local/lib/python3.8/dist-packages/django/contrib/auth/templates/subscribe/index.html (Source does not exist) * django.template.loaders.app_directories.Loader: /root/project/subscribe/templates/subscribe/index.html (Source does not exist) Traceback (most recent call last): File "/usr/local/lib/python3.8/dist-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/usr/local/lib/python3.8/dist-packages/django/core/handlers/base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/root/project/subscribe/views.py", line 16, in subscribe return render(request, 'subscribe/index.html', {'form':sub}) File "/usr/local/lib/python3.8/dist-packages/django/shortcuts.py", line 19, in render content = loader.render_to_string(template_name, context, request, using=using) File "/usr/local/lib/python3.8/dist-packages/django/template/loader.py", line 61, in render_to_string template = get_template(template_name, using=using) File "/usr/local/lib/python3.8/dist-packages/django/template/loader.py", line 19, in get_template raise TemplateDoesNotExist(template_name, chain=chain) Exception Type: TemplateDoesNotExist at /subscribe/ Exception Value: subscribe/index.html these are my template settings TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', … -
Django (uwsgi) + nginx throws 504 Gateway timeout after 120 seconds
Is there is any default setting that would return this timeout after 2 minutes when waiting response from a Django view (even if view contains just a simple time.sleep(200)) no matter my nginx configuration. I set all timeouts that I could think of to 300s. Excerpt from nginx config: http { ## # Basic Settings ## sendfile on; tcp_nopush on; tcp_nodelay on; keepalive_timeout 65; types_hash_max_size 2048; proxy_send_timeout 300s; proxy_read_timeout 300s; proxy_connect_timeout 75s; ## # Virtual Host Configs ## upstream uwsgi_upstream { server localhost:8000; } server { listen 80; server_name {{ 'SERVER_NAME' | env }}; location / { include uwsgi_params; uwsgi_pass uwsgi_upstream; uwsgi_read_timeout 300s; uwsgi_send_timeout 300s; # Match the upstream header buffer size to http setting uwsgi_buffer_size 64k; uwsgi_buffers 8 64k; uwsgi_param HTTP_Host $http_host; uwsgi_param HTTP_X_Real_IP $remote_addr; uwsgi_param HTTP_X_Forwarded_For $proxy_add_x_forwarded_for; uwsgi_param HTTP_X_Forwarded_Proto $scheme; client_max_body_size 200M; } } } -
Minimize Number of Queries in Django Model Admin
Suppose I have two models ModelA, ModelB, class Model1(models.Model): # multple model fields, also contains foreign key class Model2(models.Model): model1_id = models.ForeignKey(Model1, models.DO_NOTHING) # other model fields field1 = models.IntegerField() field2 = models.ForeignKey() field3 = models.CharField(max_length=50) field4 = models.DateTimeField(blank=True, null=True) admin file for Model1 like, @admin.register(Model1) class Model1Admin(admin.ModelAdmin): list_per_page = 10 list_display = ['some_model1_fields', 'get_field1','get_field2', 'get_field3', 'get_field4'] def get_field1(self, obj): return obj.model2_set.last().field1 def get_field2(self, obj): return obj.model2_set.last().field2 def get_field3(self, obj): return obj.model2_set.last().field3 def get_field4(self, obj): return obj.model2_set.last().field4 when I get related model fields using method in list_display, it repeats same query multiple time (list_per_page * no_of_fields_by_method which is 40 in current case). I don't want to join model1 with model2 because model1 already join with other models and we know Count() query will takes time if we have large tables. My question is , Is any other way to get releted model objects without repeat the same query? (means only 10 times query instead of 40 times same query in current case.) -
How to get list of tags related to any Blogpost in model - Django
So I have two models: class Tag(models.Model): name = models.CharField(max_length=15) def __str__(self): return str(self.name) and class BlogPost(models.Model): title = models.CharField(max_length=255) slug = models.SlugField(max_length=255, unique=True, blank=True, null=True) author = models.CharField(max_length=255) tags = models.ManyToManyField(Tag) body = models.TextField(blank=True, null=True) snippet = models.TextField(max_length=255) status = models.CharField( max_length=10, choices=STATUS_CHOICES, default='draft') created_on = models.DateTimeField(auto_now_add=True) updated_on = models.DateTimeField(auto_now=True) class Meta: ordering = ('-created_on',) def __str__(self): return str(self.title) I am trying to get a list of tags that have been used in any BlogPost model object i.e. if there are tags stored in database are ['movie','entertainment','games','documentary'] and BlogPost A has tags with m2m relation: ['movie','documentary'] and BlogPost B has tags with m2m relation:['games'] then I want to get a list of tags that has been used in any object BlogPost model as ['movie','documentary','games']. I couldn't find the answer to this.Is there a way to query for this? -
How to loop multiple urls in javascript
The chkArray list contains numbers. If the condition is satisfied, I want the function to work by adding the values of the list to the url parameter one by one through the for statement. This is because the function defined in views.py is returned only when the url below is returned. However, window.location.href seems to only work once. Is there any way to make the url work multiple times? Please help. [student_list.html] <table id="student-list" class="maintable"> <thead> <tr> <th>Name</th> <th>Age</th> <th>Register date</th> <th>Select</th> </tr> </thead> <tbody> {% for student in student %} <tr> <td>{{ student.name }}</td> <td>{{ student.age }}</td> <td>{{ student.register_date }}</td> <td><input type="checkbox" class="Checked" id="{{ student.id }}"></td> </tr> {% endfor %} </tbody> </table> <button type="button" class="btn btn-secondary addteacher">Update Teacher</button> [student_list.js] $('button.addteacher').on('click',function () { $checkbox = $('.Checked'); var chkArray = []; var updateTeacher = confirm("Will you update?"); chkArray = $.map($checkbox, function(el){ if(el.checked) { return el.id }; }); console.log(chkArray); for (let x = 0; x < chkArray.length; x++) { if (updateTeacher && chkArray.length > 0) { window.location.href = '/student/add_teacher/' + chkArray[x] + '/'; } else { alert('At least one checkbox must be checked.'); } } }); [urls.py] path('student/add_teacher/<int:id>/', views.add_teacher, name='add_teacher'), [views.py] def add_teacher(request, id): student= Student.objects.get(pk=id) student.teachcer = request.user.name student.save() return HttpResponseRedirect(f'/student_list/') -
Effect of periodic page refresh on server in a django web application
i'm refreshing a web page at interval of every 10 sec using meta refresh tag in a django application.I want to know that how much it effects the server. Is it best practice to refresh a web page. -
saving image URL using django shell
I want to save the url of images in my database using django shell here is my model class Album(models.Model): reference = models.IntegerField(null = True) created_at = models.DateTimeField(auto_now_add=True) available = models.BooleanField(default=True) title = models.CharField(max_length=200) picture = models.URLField() artists = models.ManyToManyField(Artist, related_name='albums', blank=True) here is what i did in the shell album = Album.objects.create(title="Funambule", picture="/home/MyUbuntu/Images/moi.png") the url is correctly save in the database but it's impossible to load it in the view here is the view <div class="col-sm-4 text-center"> <a href="/"> <img class="img-responsive" src="{{ album.picture }}" alt="{{ album.title }}"> </a> <h3><a href="/">{{ album.title }}</a></h3> {% for artist in album.artists.all %} <p>{{ artist.name }}</p> {% endfor %} </div> thank you -
Set initial (default) instances in django admin
I am building a Blog App and I am trying to add inbuilt initial instances in django admin so when user clone the repo , then user will see several initial blogs every time even after reset the database. I didn't find anywhere to set the initial data. I also tried How to set initial data for Django admin model add instance form? But it was not what i am trying to do. models.py class BlogPost(models.Model): title = models.CharField(max_length=1000) body = models.CharField(max_length=1000) I tried to use Providing data with fixtures But I have no idea , How can I store in. Any help would be much Appreciated. Thank You. -
GDAL configuration for Django in mac GDAL_LIBRARY_PATH exception
I tried to install GDAL in macos by the command for django brew install django and it successfully installed and I have also used pip install GDAL command and it also installed successfully. But, When I tried to run the django server it throw a error set a path for GDAL library. django.core.exceptions.ImproperlyConfigured: Could not find the GDAL library (tried "gdal", "GDAL", "gdal3.2.0", "gdal3.1.0", "gdal3.0.0", "gdal2.4.0", "gdal2.3.0", "gdal2.2.0", "gdal2.1.0", "gdal2.0.0"). Is GDAL installed? If it is, try setting GDAL_LIBRARY_PATH in your settings. -
Django app working locally but throws 'NotSupportedError at /accounts/login/' on Elastic Beanstalk
I don't understand why my django app works locally but throws a NotSupportedError error upon elastic beanstalk deploy using the awsebcli. I follow the normal password flow for logging in and redirecting to a certain app, however when I'm doing this via the deployment it throws the following error: NotSupportedError at /accounts/login/ deterministic=True requires SQLite 3.8.3 or higher Additional info Django Version: 3.2.7 Exception Type: NotSupportedError Exception Value: deterministic=True requires SQLite 3.8.3 or higher Exception Location: /var/app/venv/staging-LQM1lest/lib/python3.8/site-packages/django/db/backends/sqlite3/base.py, line 217, in get_new_connection Python Executable: /var/app/venv/staging-LQM1lest/bin/python Python Version: 3.8.5 Python Path: ['/var/app/current', '/var/app/venv/staging-LQM1lest/bin', '/var/app/venv/staging-LQM1lest/bin', '/usr/lib64/python38.zip', '/usr/lib64/python3.8', '/usr/lib64/python3.8/lib-dynload', '/var/app/venv/staging-LQM1lest/lib64/python3.8/site-packages', '/var/app/venv/staging-LQM1lest/lib/python3.8/site-packages'] Server time: Thu, 30 Sep 2021 06:32:23 +0000 I've roughly followed this tutorial for deploying a Django app via eb, albeit with python 3.8 changes login/logout setup followed this tutorial this post has a similar issue with a different deployment method Thanks for reading! Any help is appreciated. -
RotatingFileHandler is not creating file on crossing maxBytes value
I am working on rotating file handler. I need another file to be created once the file size crosses the given maxBytes value. but the code does not seems to working fine import logging from logging.handlers import RotatingFileHandler logging.basicConfig(format='%(asctime)s - %(message)s', handlers=[RotatingFileHandler("/app.log", maxBytes=100, backupCount=5)]) logger = logging.getLogger('DemoLogger') @router.get('/demo_api/v1') def default_rd(db: Session = Depends(get_db)): try: Category_data = db.query(models.table_new.id, models.table_new.Label).filter(models.table_new.classCode=='Category').all() except Exception: logger.exception("Database Error") else: logger.warning("Fetched Category data") -
how can my django form grab current username and email and submit them into another database table?
In my django project I have a form VisitorRegForm which collects scanned_id and body_temp and submits data to my database table ClinicalData, since the current user is already logged in, how can I make this form to also be able grab current logged in user's username and email (Note: username and email were both created from the built-in django User model) and submit these four items: 'scanned_id', 'body_temp', 'username', 'email' into the database table ClinicalData? Don't mind the missing details and inports, the form works and am able to submit 'scanned_id', 'body_temp'. Help me on the easiest way I will be able to submit these four items: 'scanned_id', 'body_temp', 'username', 'email' looking at the details shown in the files below: Where should it be easier to achieve this; in the views.py or the template file? forms.py class VisitorRegForm(UserCreationForm): class Meta: model = User fields = ['username', 'email', 'password1', 'password2'] class ScannerForm(ModelForm): class Meta: model = ClinicalData fields = ['scanned_id', 'body_temp', 'username', 'email'] models.py class ClinicalData(models.Model): ... scanned_id = models.CharField(verbose_name="Scanned ID", max_length=50, null=True) body_temp = models.DecimalField(verbose_name="Body Temperature", max_digits=3, decimal_places=1, null=True) username = models.CharField(verbose_name="Facility Name", max_length=200, null=True) email = models.EmailField(verbose_name="Visitor Email", max_length=200, null=True) ... views.py Am assuming I might need like two … -
Plotly Dash: How to save/cache Dash DataTable without making an external file?
I am looking for a set of functions or a library that could allow me to do the following operations: There is a Dash DataTable displayed in my web app. I select specific rows in the table and click the save button. Then the selected rows transform into a pd.dataframe object then it's changed to a json object using df.to_json('records'). The created json file stays in the web browser or server(like heroku) without making an external json or excel file on the local server(aka my laptop). And this saved file stays permanently in the storage (server or wherever) unless I do something on it. When I click another button on my web app, Dash DataTable object is displayed sourcing from that json file. When I click again another button on my web app, the file is deleted permanently. This series of operations is beyond my knowledge as I have never touched server-side caching or whatsoever in my life... (sorry I am a newb :( ). Hope my question was clear! Thank you! -
why django shows NoReverseMatch at /articles/3/ Reverse for 'article_edit' with arguments '('',)' not found. 1 pattern(s) tried: []
Whenever I try to Link Edit (article_edit.html) and Delete(article_detail.html) Django shows this error. NoReverseMatch at /articles/3/ Reverse for 'article_edit' with arguments '('',)' not found. 1 pattern(s) tried: ['articles/(?P<pk>[0-9]+)/edit/$'] Request Method: GET Request URL: http://127.0.0.1:8000/articles/3/ Django Version: 3.2.7 Exception Type: NoReverseMatch Exception Value: Reverse for 'article_edit' with arguments '('',)' not found. 1 pattern(s) tried: ['articles/(?P<pk>[0-9]+)/edit/$'] I tried without Linking these tags (Edit and Delete), the app runs absolutely fine but whenever I add these lines of codes the app stop working. here's my article_detail.html template {% extends 'base.html' %} {% block content %} <div class="article-entry"> <h2>{{object.title}}</h2> <p>by {{object.author}} | {{object.date}}</p> <p>{{object.body}}</p> </div> <p> <a href="{% url 'article_edit' article.pk %}">Edit</a> | <a href="{% url 'article_delete' article.pk %}">Delete</a> </p> <p>back to <a href="{% url 'article_list' %}"></a>All Articles</p> {% endblock content %} here are models.py , urls.py and views.py for 'articles' app from django.db import models from django.contrib.auth import get_user_model from django.urls import reverse class Articles(models.Model): title = models.CharField(max_length=250) body = models.TextField() date = models.DateTimeField(auto_now_add=True) author = models.ForeignKey(get_user_model(), on_delete=models.CASCADE) def __str__(self): return self.title def get_absolute_url(self): return reverse("article_detail", args=[str(self.id)]) from django.urls import reverse_lazy from django.urls.base import reverse from django.views.generic import ListView, DetailView from django.views.generic.edit import UpdateView, DeleteView from .models import Articles class ArticleListView(ListView): model = … -
Django Email Template Different styling in gmail and in mailhog
I have an html email template in Django and trying to align the footer items in 1 column, it is aligned properly in mailhog and when I open the html template in browser, but when it is sent using gmail smtp, the alignment looks different. Please help me with the correct styling that works in Gmail. Attached below are the images Incorrect alignment in gmail: Correct alignment: <tr> <td align="center" bgcolor="#ffffff" class="footer"> <p style="margin: 0; color:#2B4C4C">6th Floor, 259 CLMC Building, EDSA, Mandaluyong City<br> <a href="mailto:admin@folaglobal.com" style="color:#0563c1">admin@folaglobal.com</a><br> </p> <div style="display:flex; flex-direction: row; justify-content: center; margin-top: 5px; margin-bottom: 5px;"> <a href="https://www.instagram.com/folaglobalinc/" target="_blank" style="margin-right: 15px; height: 20px; width: 20px;"> <img src="https://folaglobal-production-bucket.s3.ap-southeast-1.amazonaws.com/logo/instagram-square-brands.png" alt="instagram" title="instagram" width="20px" height="20px" style="display:block" /> </a> <a href="https://www.facebook.com/FolaGlobalInc/" target="_blank" style="margin-right: 15px; height: 20px; width: 20px;"> <img src="https://folaglobal-production-bucket.s3.ap-southeast-1.amazonaws.com/logo/facebook-square-brands.png" alt="facebook" title="facebook" width="20px" height="20px" style="display:block" /> </a> <a href="https://www.tiktok.com/@folaglobal?lang=en" target="_blank" style="height: 20px; width: 20px;"> <img src="https://folaglobal-production-bucket.s3.ap-southeast-1.amazonaws.com/logo/tiktok-brands.png" alt="tiktok" title="tiktok" width="20px" height="20px" style="display:block" /> </a> </div> <p style="margin: 0; color:#2B4C4C; font-size: 8pt;">This is a system generated message. Please do not reply to this email</p> <!-- <img src="https://folaglobal-production-bucket.s3.ap-southeast-1.amazonaws.com/logo/letter-head.png" style="width: 100%; margin-top: 10px;" alt="tiktok" /> --> </td> </tr> -
How to take input of ManyToManyField of django?
I have 2 models - Rooms and Modules. A module can contain many rooms and a room can be contained by many different modules. below are the models - Rooms model - class Rooms(models.Model): room_id = models.AutoField(primary_key=True) title = models.CharField(max_length=100) desc = models.TextField() level = models.CharField(max_length=100) Module model - class Module(models.Model): module_id = models.AutoField(primary_key=True) title = models.CharField(max_length=100) desc = models.TextField() is_deleted = models.BooleanField(default=False) rooms = models.ManyToManyField(Rooms) Module serializer - class ModuleSerializer(serializers.ModelSerializer): rooms = RoomSerializer(read_only=True, many=True) class Meta: model = Module fields = "__all__" Module view.py file - class add_module(APIView): def post(self, request, format=None): module_serializer = ModuleSerializer(data=request.data) if module_serializer.is_valid(): module_serializer.save() return Response(module_serializer.data['module_id'], status = status.HTTP_201_CREATED) return Response("response":module_serializer.errors, status = status.HTTP_400_BAD_REQUEST) How do I take multiple rooms as input in views.py file while creating my module object. Also if i want to test my API in postman, then how can i take multiple inputs in postman. -
'AddForm' object has no attribute 'reception'
I have a page where it allow the user to enter the reception number, so when the user enter the reception number, it should verify with the database if the reception number exist, but i am having this error: 'AddForm' object has no attribute 'reception'. How do I solve this error? views.py @login_required() def verifydetails(request): if request.method == 'POST': #Customername = request.GET['Customername'] form = AddForm(request.POST or None) if form.reception == Photo.reception: messages.success(request, 'Both Reception and customer name match') return redirect('AddMCO') else: messages.success(request, 'Both Reception and customer do not match') return redirect('verifydetails') else: form = AddForm() return render(request, 'verifydetails.html', {'form': form, }) forms.py class verifyForm(forms.Form): reception = forms.CharField(label='', widget=forms.TextInput( attrs={"class": 'form-control', 'placeholder': 'Enter Reception number'})) class meta: model = Photo fields = ('reception') verifydetails.html <!DOCTYPE html> <html> <head> <script> $(function () { $("#datetimepicker1").datetimepicker(); }); </script> <meta charset='utf-8'> <meta http-equiv='X-UA-Compatible' content='IE=edge'> <title>SCS verify details</title> <meta name='viewport' content='width=device-width, initial-scale=1'> <!-- CSS only --> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous"> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js" integrity="sha384-wHAiFfRlMFy6i5SRaxvfOCifBUQy1xHdJ/yoi7FRNXMRBu5WHdZYu1hA6ZOblgut" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js" integrity="sha384-B0UglyR+jN6CkvvICOB2joaf5I4l3gm9GU6Hc1og6Ls7i6U/mkkaduKaBhlAXv9k" crossorigin="anonymous"></script> <!-- Font Awesome --> <link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous"> <!-- Moment.js --> <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.23.0/moment.min.js" integrity="sha256-VBLiveTKyUZMEzJd6z2mhfxIqz3ZATCuVMawPZGzIfA=" crossorigin="anonymous"></script> <!-- Tempus Dominus Bootstrap 4 --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/tempusdominus-bootstrap-4/5.1.2/css/tempusdominus-bootstrap-4.min.css" integrity="sha256-XPTBwC3SBoWHSmKasAk01c08M6sIA5gF5+sRxqak2Qs=" crossorigin="anonymous" /> … -
django migrations: django.db.utils.ProgrammingError: relation does not exist
I started working on an existing project that is being developed by others as well. When I cloned it from git I could not makemigrations and every time I try to migrate I got this "django.db.utils.ProgrammingError: relation does not exist" error. If I can make only migrations I think the problem will be solved. Can anyone help me here to do that or if you know any other solution for it please let me know. Traceback (most recent call last): File "/Users/ss/projects/backend/.venv/lib/python3.9/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) psycopg2.errors.UndefinedTable: relation "app_customer" does not exist LINE 1: ...LECT "app_customer"."customer_mobile_number" FROM "app_custo... ^ The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/Users/ss/projects/backend/manage.py", line 21, in <module> main() File "/Users/ss/projects/backend/manage.py", line 17, in main execute_from_command_line(sys.argv) File "/Users/ss/projects/backend/.venv/lib/python3.9/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/Users/ss/projects/backend/.venv/lib/python3.9/site-packages/django/core/management/__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/ss/projects/backend/.venv/lib/python3.9/site-packages/django/core/management/base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "/Users/ss/projects/backend/.venv/lib/python3.9/site-packages/django/core/management/base.py", line 393, in execute self.check() File "/Users/ss/projects/backend/.venv/lib/python3.9/site-packages/django/core/management/base.py", line 419, in check all_issues = checks.run_checks( File "/Users/ss/projects/backend/.venv/lib/python3.9/site-packages/django/core/checks/registry.py", line 76, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "/Users/ss/projects/backend/.venv/lib/python3.9/site-packages/django/core/checks/urls.py", line 13, in check_url_config return check_resolver(resolver) File "/Users/ss/projects/backend/.venv/lib/python3.9/site-packages/django/core/checks/urls.py", line 23, in check_resolver return check_method() File "/Users/ss/projects/backend/.venv/lib/python3.9/site-packages/django/urls/resolvers.py", line 412, … -
Polynomial coefficients in Python without numpy
Write a program that first receives the number m from the user and then the number n, and then receives the polynomial coefficients P (x) of the order m from the user and prints the polynomial coefficients P (x) ^ n in the output. As an example of the calculation of P (x) ^ n, suppose. P (x) = x ^ 2 + 2x + 3 and n = 2: P (x) ^ n = (x ^ 2 + 2x + 3) (x ^ 2 + 2x + 3) = x ^ 4 + 4x ^ 3 + 10x ^ 2 + 12x + 9 Input sample 3 2 1 2 3 4 Sample output 1 4 10 20 25 24 16 -
In Django filter posts in between two specific times
I want to filter the posts which was added in between last 2 or 3 hours.. i have already used timedelta etc but the filter keyword always want to get exact date, whereas dt = timezone.now() - timedelta(hours=2) never give exact datetime.. how can i achieve that?? models.py from django.db import models from datetime import datetime # Create your models here. class addPost(models.Model): date = models.DateTimeField(auto_now_add=True) postId = models.AutoField(primary_key=True) title = models.CharField(max_length=100) category = models.CharField(max_length=60) image = models.ImageField(upload_to="blog/images", default="") content = models.TextField(default="") views.py def index(request): dt = timezone.now() - timedelta(minutes=23) obj = addPost.objects.filter(date=dt) print(obj[0].date) return render(request, "blog\home.html", {"obj":obj}) -
How to Migrate only required models table if using Multiple DB in django
I have tried migrating models when using Multiple DB in django. It is creating all table in both the DB by default, Can we customize it so unnecessary table can't be made in the DB.