Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Not displaying my navbar {% extends 'base.html' %} when I use django {% block content %}
When I use {% extends 'base.html' %} my navbar displays correctly but when I use {% block content %} Hello World{% endblock content %} my navbar disappears and I only see the text "Hello World". I dont really know what to try it appeared to be straight forward but apparently it isn't until you actually know. {% extends "base.html" %} {% block content %}<h1>Hello World</h1>{% endblock content %} My 'base.html' file {% load static %} <!DOCTYPE html> <html lang="en"> <head> {% block head %} <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- Latest compiled and minified CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"> <link rel="stylesheet" type="text/css" href="{% static "css/style.css" %}"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script> <meta charset="UTF-8"> <title>my title goes here</title> {% endblock %} </head> <body> {% block content %} <div class="container-fluid"> <div class="row"> <div class="col"> <nav class="navbar custom-navbar"> <h1>World Truthers</h1> <div class="col navbar-buttons"> <button class="btn custom-button"><p><b>Contact</b></p></button> <button class="btn custom-button"><p><b>About</b></p></button> <button class="btn custom-button"><p><b>Returns</b></p></button> <button class="btn custom-button"><p><b>Payment</b></p></button> <button class="btn custom-button"><p><b>Delivery</b></p></button> <button class="btn custom-button"><p><b>Store</b></p></button> </div> </nav> </div> </div> </div> {% endblock %} </body> -
send multiple files Json file django rest framework
Hi I am submitting data like this as raw data with Content-Type : application/json in header. { "myData": { "name": "name", "title": "journalist", "type": "Media", } } Now I want to send multiple files with this . how I can achieve in this scenario ? -
pikepdf - how to return in memory pdf object from django view
I currently have the following code: pdf = Pdf.open(f"cover.pdf") page = pdf.pages[0] for i, a in enumerate(page.Annots): print(a.T) a.V = str(i) pdf.save("output_test.pdf") I can't find anywhere online that describes how to return the in-memory pdf object from a django view. This is diving me nuts, can anyone help? -
Filter DateTimeField by rounded time ( 10 minutes for examples ) using only the ORM?
I came up with a solution but it's using a model method ( as far as i understand it cannot be used with X.objects.filter() ) and then use the python method sorted. I've read that it's way faster to use django ORM than direct python so I'm searching for a solution. I precise that adding fields to my model is not possible as the database is already well populated. Basically I've an Articles model : class Articles(models.Model): title = models.CharField(max_length=200, null=False, blank=False) image = models.URLField(null=False, blank=False) summary = models.TextField() link = models.URLField(null=False, blank=False) pub_date = models.DateTimeField(default=timezone.now) source = models.ForeignKey( Sources, on_delete=models.CASCADE, related_name="souurce") category = models.ManyToManyField(Categories) and what I want to do is filtering result by approximate publication date ( for example an article published at 5:34 and an another one published a 5:31 are both considered published at the same time ), then I can perform other filters like per category, source or even by title. Here is my class method to do that (by closest 10 minutes ): def get_approximate_date(self): pub_date = self.pub_date def timeround10(dt): """timertound closets 10 minutes""" a, b = divmod(round(dt.minute, -1), 60) h = (dt.hour + a) % 24 m = b new = dt.replace(hour=h, minute=m, … -
Problems with installing psycopg2 in Django [duplicate]
In my Django project, I tried to add this line to requiements.txt, and pip install -r requirements.txt, I had problems with install. psycopg2==2.7.1 Here's the error: ERROR: Could not install packages due to an EnvironmentError: [Errno 13] Permission denied: '/Library/Python/2.7/site-packages/psycopg2-2.7.1.dist-info' Consider using the --user option or check the permissions. Than I tried installing manually: pip install psycopg2 I had the following error: ld: library not found for -lssl clang: error: linker command failed with exit code 1 (use -v to see invocation) error: command 'cc' failed with exit status 1 Than I tried to install with --user: pip install psycopg2 --user ...but it's still the same error. Edit: I already set virtualenv in the project directory. UPDATE When I look to the first error, I see that it has a warning for Python2.7, but I'm working with Python3. This might be source of problems. -
How to make a `FileHandler` strip terminal escape sequences (colors) from a log message?
I have a single Logger with two Handlers: StreamHandler and FileHandler. I want to log colored output to the terminal using escape sequences (see Logger usage) via the StreamHandler. However, I don't want to log such escape sequences via the FileHandler: Log to StreamHandler: \033[39m{}\033[0m\033[91m{}\033[0m\033[39m{}\033[0m Log to FileHandler: {}{}{} In order words, the FileHandler should strip the terminal escape sequences. Is there any solution besides creating two Loggers configured with a StreamHandler and FileHandler, respectively? I really don't want to carry two separate Loggers around in the code, if it can be avoided. Logger usage: fmt = 'Match: {} ({}/v{}): \033[39m{}\033[0m\033[91m{}\033[0m\033[39m{}\033[0m ({}) {}' self.logger.info( fmt, o.type.lower(), o.id, o.version, remove_control_chars(match.left), remove_control_chars(match.text), remove_control_chars(match.right), match.regex, suffix ) Logger configuration: def init(log, level, no_console): formatter = logging.Formatter( '{asctime:s} -- {levelname:<5s} -- {name:s} -- {process:d} -- {funcName:s} -- {message:s}', datefmt='%m/%d/%Y %I:%M:%S %p', style='{' ) logger = logging.getLogger('watchdog') if getattr(logging, level.upper()) is None: raise common.exc.WatchdogException(f'Failed to set level for logger: {level.upper()}') logger.setLevel(getattr(logging, level.upper())) if not no_console: handler = logging.StreamHandler() handler.setFormatter(formatter) logger.addHandler(handler) try: handler = logging.FileHandler(log, mode='w+') handler.setFormatter(formatter) logger.addHandler(handler) except Exception as exc: raise common.exc.WatchdogException(f'Failed to initialize file handler: {log}') from exc -
how to call and use my pk given in urls in a class based view?
I have this code in urls from .views import testview urlpatterns = [ path('test/<pk>', testview.as_view(), name='test') ] And this is my view : class testview(FormView): template_name = 'test/test.html' form_class = ExampleForm def form_valid(self, form): cl = form.cleaned_data book= Book(user_id='pk', book = cl['book'], price = book.price ) return create_book(self.request, book) So how can I take that pk in the urls and use it inside the view? -
Display data according to users as in Facebook,Amazon [closed]
I have built the ecommerce website.How can I display the content according to their username and password as like in facebook,Amazon -
How to automatically change a Django Model field after a specific amount of time?
I'm working on an e-commerce website that includes an auction process. For this I have created an Auction Model with different status options: (e.g.: active, closed, canceled, completed, etc.). I want to give users a fixed amount of time (say 5 hours) to partake in the auction and add their bids, after which the auction status will automatically be change from "active" to say "completed" and the users won't be able to submit bids anymore and a winner will be determined. What is the best way to achieve this in Django? I have read about using background tasks like django-backgound-tasks or Celery. But this would require me to check every minute to see if the task if the 5 hours have passed or not. The other things option I cam across are using some type of timer or Django signals. I'm not sure which would be the best strategy here and therefore am asking the community for their opinion, thank you! -
How to recognize urls with get parameters un django?
I am learning Django, usually I use urls like www.mysite.com/post/1, and I have understood them because they are well described in the documentation. Now I need to create a url like: www.mysite.com/calendar/?day=21&?month=12&year=2020, I don't understand what should I write in my ulrpatterns list. I have tried something like this: url(r'^search/(?P<parameter>\w+)', views.calendar, name='calendar') but it doesn't work. What should I write as regex expression? Thanks -
Django - middleware inserting code in template
I need middleware just like contib.messages, but to insert specific JS code to page from views instead of message. Is there a ready-made solutions or any ideas how to do this? -
How to show data according to heading in Table (Django Template)
I am having a following model class Project(models.Model): project = models.CharField(max_length=255, blank=True, null= True) user = models.ForeignKey(User, on_delete=models.CASCADE) start_time = models.TimeField() end_time = models.TimeField() start_date = models.DateField() I need to print the details in an html table format Here is my query set in views.py table_heading = Project.objects.values_list( "start_date", flat=True).distinct() heading = ['project']+list(table_heading) q = Project.objects.values('start_date').filter(user=request.user).annotate( total_hours=Sum((F('end_time') - F('start_time')),project =F('project')) context{ 'heading': heading, 'query : q } In my html <table class="table"> <thead> <tr> {% for value in heading %} <th>{{value}}</th> {% endfor %} </tr> </thead> <tbody> {% for value in query %} <tr> <td>{{value.project}}</td> <td>{{value.total_hours}}</td> </tr> {% endfor %} </tbody> </table> But it's coming as all the total hours are printing in the first column..... But what I need is if the date is today total_hour need to print down to that heading ...... if the date in heading is yesterday it need to print down to that date But now all the values are printing only in the first column Thanks -
what is this main this error "TypeError: expected str, bytes or os.PathLike object, not NoneType django 3 [closed]
hi how are you i have problem : what is this main this error "TypeError: expected str, bytes or os.PathLike object, not NoneType [26/Aug/2020 16:58:02] "GET /static/images/favicon.png HTTP/1.1" 500 84143" and admin page have no style -
Handle event.preventDefault inside fetch
I have this piece of code. I'm only using the fetch to validate email field on my database, in my form I have a lot of more fields. I have a problem here. Exactly as this code is written, it wont be submitted if result.exists == undefined and will be submitted if that is not the case (the form will be submitted on the else part). The problem is that I want all of the previous form fields to be sumitted on the this.submit() function. I realized that this.submit() only submits the email, not all the others I have in my form. If I cut the event.preventDefault(), put it only under the if condition, and delete the else statement, If the if condition is not true, the form submits all the previous form fields successfully, not only email. But if I put event.preventDefault() under that if, it's too late for the function to preventDefault in case the if condition is true. So i'm struggling to make the form submit all the form fields in the case of the else part of the code. And also making the form to be prevented from submit under that if condition (in case it's … -
Django Google cloud store: error 400 failed to upload image file
I'm writing a django rest project and recently deployed my project to google cloud. However, I'm having trouble uploading files. Here is the response that I get: 400 POST https://storage.googleapis.com/upload/storage/v1/b/project-id/o?uploadType=multipart&predefinedAcl=publicRead: ('Request failed with status code', 400, 'Expected one of', <HTTPStatus.OK: 200>) I have a pretty generic model and viewset as follows: class EndUser(models.Model): id = models.AutoField(primary_key=True) image = models.ImageField(upload_to="users/", blank=True) name = models.CharField('Name', max_length=256) location = models.PointField() device = models.ForeignKey(FCMDevice, on_delete=models.CASCADE) current_task = models.ForeignKey('tasks.Task', on_delete=models.CASCADE, blank=True, null=True) def __str__(self): return self.name class EndUserViewSet(viewsets.ModelViewSet): parser_classes = (MultiPartParser, FormParser) queryset = EndUser.objects.all() def get_serializer_class(self): if self.request.method == "GET": return EndUserSerializer return CreateUpdateEndUserSerializer I believe my settings.py are prefect. But I'll add them here for reference: MEDIA_ROOT = "https://storage.googleapis.com/my-project-id/media/" STATIC_ROOT = "https://storage.googleapis.com/my-project-id/static/" DEFAULT_FILE_STORAGE = "storages.backends.gcloud.GoogleCloudStorage" STATICFILES_STORAGE = "storages.backends.gcloud.GoogleCloudStorage" GS_BUCKET_NAME = "my-bucked-name" GS_CREDENTIALS = service_account.Credentials.from_service_account_file( "credentials.json" ) how do I solve this error? -
Django - Saving generated PDF in a model with xhtml2pdf
I am trying to save a generated PDF using xhtml2pdf app. I want it to save the pdf to the model. The pdf is created perfectly and the browser downloads the file, but instead of download, I would like to save it to the model, which in my models.py I've told it to save to a folder in the media folder. Models.py: class purchase(models.Model): purchase_id = models.AutoField(primary_key=True) transaction_date = models.DateTimeField() method_payment = models.CharField(max_length = 20) cmr_name = models.CharField(max_length = 60) cmr_address = models.CharField(max_length = 90) cmr_postcode = models.CharField(max_length = 10) cmr_tel = models.CharField(max_length = 14) cmr_email = models.CharField(max_length = 40) cmr_pod = models.FileField(upload_to='customers_id') cmr_signature = JSignatureField() receipt = models.FileField(upload_to='receipts', null=True, blank=True) added_by = models.CharField(max_length = 30) item_brand = models.CharField(max_length = 50) product = models.CharField(max_length = 100) model = models.CharField(max_length = 100) serial = models.CharField(max_length = 50) item_brand2 = models.CharField(max_length = 50) product2 = models.CharField(max_length = 100) model2 = models.CharField(max_length = 100) serial2 = models.CharField(max_length = 50) item_brand3 = models.CharField(max_length = 50) product3 = models.CharField(max_length = 100) model3 = models.CharField(max_length = 100) serial3 = models.CharField(max_length = 50) def __str__(self): return '{}'.format(self.cmr_name) Utils.py: from io import BytesIO from django.http import HttpResponse from django.template.loader import get_template from xhtml2pdf import pisa def render_to_pdf(template_src, context_dict={}): … -
How to load the latest record on top Django New User
I am trying to load the latest record on top based on the time and date added. I have already assigned the following values in MODELS.PY date_posted = models.DateTimeField(default=timezone.now) I also try to add this in my view function but it didn't work def client_list(request): context = {'client_list':Client.objects.all()} ordering = ['-date_posted'] return render(request, 'client_register/client_list.html', context) -
socket.gaierror: [Errno 10109] getaddrinfo failed
I am getting this error when i try to send an email from django using the gmail smtp. I have already tried to use a different gmail address and also a different smtp server but it gives me the same error. File "c:\users\user\appdata\local\programs\python\python38-32\lib\socket.py", line 918, in getaddrinfo for res in _socket.getaddrinfo(host, port, family, type, proto, flags): socket.gaierror: [Errno 10109] getaddrinfo failed -
objects.all() is not returning all items from DB
I am following an online course about Django and I am encountering a strange problem: When I am referring to my db entry and when I am expecting to get all entries, I only receive the field that I designated to be returned as a string when I defined the class. My files are as follow: models.py from django.db import models class About_me(models.Model): name = models.CharField(max_length=100) position = models.CharField(max_length=100) about = models.TextField(max_length=5000) location = models.CharField(max_length=100) email = models.CharField(max_length=100) linked_in = models.CharField(max_length=100) github = models.CharField(max_length=100) def __str__(self): return self.name views.py from django.shortcuts import render from .models import About_me # Create your views here. def cv(requests): cv = About_me.objects.all() return render(requests, 'cv/cv.html', {'cv': cv}) cv.html template <!DOCTYPE html> <head> <meta charset="utf-8"> <title>About me</title> </head> <body> <h1>CV</h1> {% for item in cv %} <p>{{item}}</p> {% endfor %} </body> </html> I am expecting to get a list with all fields: name, position, about, etc... but I am getting only the Name and to be honest I don't understand why. Since I am in a learning project, I would better like to know why is this happening rather than just fix it. Thank you all in advance -
how can i authenticate in django with GET method?
how can i login/authenticate in django using GET method? my login_user function: def user_login(request): if request.method == 'POST': form = UserLoginForm(request.POST) if form.is_valid(): cd = form.cleaned_data user = authenticate(request,tag=cd['tag'],password=cd['password']) find = User.objects.filter(tag=cd['tag']) if user is not None: login(request,user) messages.success(request,'You logged successfully.','success') return redirect('roleplay:index') else: messages.error(request,'Your Username Or Password does not correct.','danger') else: form = UserLoginForm() return render(request,'account/login.html',{'form':form}) -
Ask again. i want django datbase update
Contanier.js ... deletePatient = ({ key, test }) => { const { deletePatient } = this.props; deletePatient({ key, test }); console.log(test) }; render() { const { deletePatient } = this; const handleDelete = (rowData) => { deletePatient({ key: rowData.key, test: rowData.delete }); } ... render: (text,rowData) => ( <IconButton color="primary" aria-label="delete" size="small" onClick={() => { handleDelete(rowData) }}> <DeleteForever fontSize="small" style={{ color: "#00ffff" }} /> </IconButton> ... const mapDispatchToProps = dispatch => { return { deletePatient: ({ key, test }) => { dispatch(patientActions.deletePatient({ key, test })); } }; }; Module.js ... export const deletePatient = ({ key, test }) => ({ type: DELETE_PATIENT, payload: { key, test } }); export const deletePatientSuccess = ({ user, token, key, test }) => ({ type: DELETE_PATIENT_SUCCESS, payload: { user, token, key, test } }); ... const deletePatientEpic = (action$, state$) => { return action$.pipe( ofType(DELETE_PATIENT), withLatestFrom(state$), mergeMap(([action, state]) => { // const token = localStorage.getItem("userInfo") ? JSON.parse(localStorage.getItem("userInfo")).token : null; return ajax .patch(`/api/patient/${action.payload.key}` // , {"Content-Type": "application/json", Authorization: `token ${token}`} // , {'X-CSRFToken': state.CSRFToken.props.value} , { test : action.payload.test } ) .pipe( map(response => { const patient = response.response; return deletePatientSuccess({ patient }); }), catchError(error => of({ type: DELETE_PATIENT_FAILURE, payload: error, error: true }) ) … -
can't convert string to datetime python
how to convert '2020-08-26T12:09:14+0000' to datetime using python from datetime import datetime s = '2020-08-26T12:09:14+0000' f = '%Y-%m-%dT%H:%M:%S.%f%z' date_time_obj = datetime.strptime(s, f) but I got this error: time data '2020-08-26T12:09:14+0000' does not match format '%Y-%m-%dT%H:%M:%S.%f%z' what's the correct format ? -
image is not showing in django
all the data from models is visible except images..tried everthing .. pillow is preinstalled.. static url and root are right.. but cant figure out whats wrong with images.. html.. <div class="col-sm-6"> <div class="profile-image"> <img src="{{About.imsge}}" alt="profile photo"> </div><!-- end profile-image --> </div><!-- end col --> <div class="col-sm-6"> <div class="about-text"> <p> {{ About.first.desc}}</p> models.py from django.db import models import datetime # Create your models here. class About(models.Model): image = models.ImageField(upload_to = 'pics') desc = models.TextField() settings.py STATIC_URL = '/static/' STATICFILES_DIRS =[ os.path.join(BASE_DIR,'portfolio/static') ] STATIC_ROOT = os.path.join(BASE_DIR,'assets') MEDIA_URL ='/media/' MEDIA_ROOT = os.path.join(BASE_DIR,'media') -
Django urls. Why aren't urls.py included with new app?
Just curious, especially since Django is all about the DRY principle, why doesn't it include urls.py with creation of new app? Maybe it's just my case(I'm relatively new to Django), but at least 90% of the time, I need to create a urls.py file, which seems quite repetitive to me. There are other actions while doing a web project/app that I've found repetitive, but the URLs seems fundamental to the structure, so don't see what the harm would be for it to be included with the new app creation. Any thoughts, insights? -
How do I force Django 1.11 to create `migrations` folder automatically at custom location?
Disclaimer: the project is legacy, and we have no resource to migrate to Python 3. Originally, we had an application APP with its migrations in APP/migrations folder. The APP/migrations was .gitignored; the server could be launched easily by python manage.py runserver and produced no errors, while the APP/migrations folder remained absent. However, we needed to test our app APP on several different sets of data (indeed, they just represent different stages of a particular process). To do so, we created a symlink APP2 to APP folder (and a couple of similar symlinks like static/APP). However, the migrations in APP/migrations and APP2/migrations ran into a conflict; thus, we had to separate the migrations folders. The following code was added to settings.py: MIGRATION_MODULES = dict([(app, app + '.migrations.' + app) for app in INSTALLED_CUSTOM_APPS]) (INSTALLED_CUSTOM_APPS is concatenated to standard INSTALLED_APPS). Since that, Django refuses to start without the folders APP/migrations/APP and APP2/migrations/APP2: Performing system checks... System check identified no issues (0 silenced). Unhandled exception in thread started by <function wrapper at 0x7f3e7edaa230> Traceback (most recent call last): File "/usr/local/lib/python2.7/dist-packages/django/utils/autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/django/core/management/commands/runserver.py", line 127, in inner_run self.check_migrations() File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 422, in check_migrations executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS]) File …