Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Filtering django model using date
I need to filter some data from models using the date. I see some posts that speaks about ranges but I just want to see for example the rows of my table from the 22/04/2020, in other words, just one day. Reading the documentation, I understood that I have to do the following, import datetime prueba = DevData.objects.order_by('-data_timestamp').filter(data_timestamp=datetime.date(2020, 4, 22)) prueba = loads(serializers.serialize('json', prueba)) for p in prueba: print(p) But appears the following warning: RuntimeWarning: DateTimeField DevData.data_timestamp received a naive datetime (2020-04-22 00:00:00) while time zone support is active. And the list appears empty. I think the problem is that is just filtering using 2020-04-22 00:00:00 and not all the day. How can I fix this? Between two dates is working but just one day I don't know how to do it. import datetime start_date = datetime.date(2020, 4, 22) end_date = datetime.date(2020, 4, 23) prueba = DevData.objects.order_by('-data_timestamp').filter(data_timestamp__range= (start_date,end_date)) PD: I have info rows in this day. Thank you very much. -
Class view default view location defaults to wrong folder
I have the following class in my views.py file: class PostDetailView(DetailView): model = Product Which correctly displays view, stored at products/product_detail.html However, i also have the following class in views file: class OfferDetailView(DetailView): model = Offer I have created offer directory with offer_detail view. However, Django still tries to get products/offer_details.html Of course i can manually set template name, but I want Django to search in offers folder. Why does it search in products? -
I AM THINKING THERE IS SOMETHING WRONG IN MY VIEW RELATED TO FOREIGN KEY. PLEASE HELP ME OUT
This is my model class addteacher(models.Model): Teacher_Name=models.CharField(max_length=50) Teacher_Subjects=models.ForeignKey("subjects",related_name="+", on_delete=models.CASCADE) //here foreign key use Teacher_Subjects_Code=models.CharField(max_length=50) Teacher_Username=models.CharField(max_length=50) Teacher_Password=models.CharField(max_length=50) class subjects(models.Model): Subject_Name=models.CharField(max_length=50) ** form related to model** class addstudent_form(forms.ModelForm): Student_Registration_no=forms.CharField(widget=forms.TextInput()) Student_Name=forms.CharField(widget=forms.TextInput()) Student_roll_no=forms.CharField(widget=forms.TextInput()) Student_mobile_no=forms.CharField(widget=forms.TextInput()) class Meta(): model = addstudent fields = ['Student_Registration_no','Student_Name','Student_roll_no','Student_mobile_no'] class addsubject_form(forms.ModelForm): Subject_Name=forms.CharField(widget=forms.TextInput(),required=True) class Meta(): model=subjects fields = ['Subject_Name'] ----------------------below is view-------------- def addteacher1(request): if request.method == 'POST': Teacher_Name = request.POST['Teacher_Name'] Teacher_Subjects = request.POST['Teacher_Subjects'] Teacher_Subjects_Code = request.POST['Teacher_Subjects_Code'] Teacher_Username = request.POST['Teacher_Username'] Teacher_Password = request.POST['Teacher_Password'] Teacher_Password2 = request.POST['Teacher_Password2'] if Teacher_Password == Teacher_Password2 : if login_teacher.objects.filter(user_name_teacher = Teacher_Username).exists(): messages.info(request, 'username exists') return render(request, 'createteacher.html') else: add_teacher = addteacher.objects.create(Teacher_Name=Teacher_Name, Teacher_Subjects=Teacher_Subjects, Teacher_Subjects_Code=Teacher_Subjects_Code, Teacher_Username=Teacher_Username, Teacher_Password=Teacher_Password) add_teacher.save() return render(request, 'createteacher.html') else: return render(request, 'principlehome.html') below is the error I am receiving while is am giving input using HTML ValueError at /principle/addteacher Cannot assign "'c'": "addteacher.Teacher_Subjects" must be a "subjects" instance. Request Method: POST Request URL: http://127.0.0.1:8000/principle/addteacher Django Version: 3.0.2 Exception Type: ValueError Exception Value: Cannot assign "'c'": "addteacher.Teacher_Subjects" must be a "subjects" instance. I am 19-year student I tried hard to this but I can't. please help me out if you can I though I am using foreign key wrong. 1 There is "c " stored in the database in the subject table 2 I am thinking if I … -
insert to mysql database by reading text file in python
I have a text file with delimiter "|" ,below is the file structure. Each row should be considered as each row in database table and each filed is separated by "|" symbol. 1585035601212|asd.OTHER|3|ww1|7.14.2| 15850356012323|asd.OTHER|3|ww1|7.14.2| 158503560113132|asd.OTHER|3|ww1|7.14.2| am using below code, import mysql.connector, csv, sys with open('externaldatabase.txt') as textfile: csvreader = csv.reader(textfile, delimiter='\t') csvdata = [] for row in csvreader: csvdata.append(row) conn = mysql.connector.connect( host="localhost", user="root", passwd="root", database="mydjangoapp", port=3307, ) c=conn.cursor() for row in csvdata: # Insert a row of data c.execute("INSERT INTO externaldatabase (release_date, version, download_url, name, description) VALUES ('%s', '%s', '%s', '%s', '%s')" % (row)) conn.commit() c.close() but I got following error c.execute("INSERT INTO externaldatabase (release_date, version, download_url, name, description) VALUES ('%s', '%s', '%s', '%s', '%s')" % (row)) TypeError: not enough arguments for format string also it will be helpful if i can read files in a particular destination with out mentioning the file name and remove the file after inserting to DB(Type of file to be read is FILE) -
How do i build my react front end and django backend application for a 32 bit system?
I am working on an application for a 32 bit PC. i have almost completed the front end and backend. now i want to build executable for my application (if that's even possible in case of react and django). I want to run the application on a 32 bit PC. I myself have a 64 bit machine. Please guide me how do i do that. For django application i can create a virtual environment? but would that require me to install python on the system i want to install the app. and in case of react how can i build it from my PC to work on 32 bit PC. Thanks in advance. -
how to combine quires in django
i am creating a website where user will download videos , now i want to query the artist and it's videos, i already have one to many field but i have no idea how to do in views.py this is my models from django.db import models from embed_video.fields import EmbedVideoField # Create your models here. class Video(models.Model): video_author = models.CharField(default='Bongo Media', max_length=20) video_title = models.CharField(max_length=100) video_file = models.FileField(blank=True) video_image = models.ImageField(default='image.png') video_embed_link = EmbedVideoField(blank=True) video_descriptions = models.TextField(max_length=100, blank=True) video_pubdate = models.DateTimeField(auto_now=True) is_recommended = models.BooleanField(default=False) def __str__(self): return self.video_title class Artist(models.Model): artist_picture = models.ImageField(upload_to='media') artist_name = models.CharField(max_length=100) artist_songs = models.ForeignKey(Video, on_delete=models.CASCADE) def __str__(self): return self.artist_name and this is my views.py from django.shortcuts import render, get_object_or_404 from .models import Video, Artist # Create your views here. def home(request): artist = Artist.objects.all() videos = Video.objects.all().order_by('-video_pubdate') context = { 'videos': videos, 'artist': artist } return render(request, 'index.html', context) def detail(request, pk): video_detail = get_object_or_404(Video, pk=pk) context = { 'video_detail': video_detail } return render(request, 'detail.html', context) -
Adding django auth token to ajax call for external api
I have a django app (called Client) that makes an API call to another django app api (Master) and I'm logging in the users using OpenID Connect (via django-keycloak). My question is how to securely add the users access token to the header of an ajax call on the Client site to the Master site. The obvious solution is to have in my template something like:: "beforeSend": function (xhr) { xhr.setRequestHeader('Authorization', "Bearer {{ user.token }}"); }, But exposing the token seems like a bad idea. I could also create an api in the Client system that called the API in the Master system and added the token behind the scenes, but this is going to double the time for each round trip and also seems a bad idea. What is the best solution to this problem? -
How to unit test a file upload in Django?
I want to test a view that accepts .zip file as request. So far, I tried this: def test_upload_zip(self): with open('zip_file.zip', 'rb') as file: response = self.client.post(reverse(self.url), {'zip_file': file}, format='multipart') The data I am getting at the view when I do print(request.data) is: <QueryDict: {'zip_file': [<InMemoryUploadedFile: zip_file.zip (application/zip)>]}> But, for my actual request I want data in multipart like this: <QueryDict: {'zip_file': ['data:application/zip;base64,UEsDBBQAAAAIAK1xmF................AAAA=']}> In real request, I am not sending any content-type from my frontend. When I tried to put content_type='multipart/form-data in my test like this: def test_upload_zip(self): with open('zip_file.zip', 'rb') as file: response = self.client.post( reverse(self.url), {'zip_file': file}, content_type='multipart/form-data' ) I got this error: django.http.multipartparser.MultiPartParserError: Invalid boundary in multipart: None What am I doing wrong, and how can I get the desired data in my request.data? -
How do i load css file into html in Django
I'm trying to create a Django app and i have made all the static settings like Settings.py STATICFILES_DIRS = [ os.path.join(BASE_DIR,'CricketTeamManagement/static') ] STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' URLS.py from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('', include('Management.urls')) ] + static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT) I have also created a static folder in Main project folder and ran python manage.py collectstatic it created a new static folder outside and it has admin folder in it and sub folders like js,css,font,images and collectstatic collects the images and stores in this folder. I see static files are clearly working. All the models.py imagefields are uploaded to media folders and even that works. The Problem comes here My css files are not taking its styles and not altering my html elements. If I have the below code in html file the styling works and if i separate it to a css folder and create a css file by removing style tag it is not working. <style> body { background-color: powderblue; } h1 { color: blue; } p { color: red; } </style> when i saw the css file Not Found … -
Obtaining user's timezone
I'm making a website and need to know the user's timezone. I know I could simply ask them for it, but think some users may not know their timezone and feel there must be a more user-friendly kinda way to get it (rather that having users Google their timezone or something if they dont know it). Maybe there is a way to grab their timezone without having to specifically ask them? Or maybe there is a Django widget which displays a list of citys which the user can select theirs from and that will give me their timezone? Or maybe there's simply no user-friendlier way than simply asking them for it. Thank you. -
Django Choice Field rename first option
Django 3 Enum like field generates an addition option like <option value="" selected="">---------</option> How to Rename this like <option value="" selected="">Select an option</option> class Student(models.Model): class YearInSchool(models.IntegerChoices): FRESHMAN = 1, 'Freshman' SOPHOMORE = 2, 'Sophomore' year_in_school = models.IntegerField( choices=YearInSchool.choices, default=YearInSchool.FRESHMAN, ) -
while filtering datatable server side Cannot resolve keyword 'priority' into field. Choices are: eventname, id, key, timestamp
I'm using django-rest-framework-datatables to filtering/pagination/sorting datatable when using rest-framework, it's working correctly with all fields except one, it's show error "Cannot resolve keyword 'priority' into field. Choices are: eventname, id, key" i think that the problem is: this field not appear in database table model class CachedEvent(models.Model): key = models.CharField(max_length=255) timestamp = models.DateTimeField() eventname = models.CharField(max_length=255) @property def priority(self): eventtype, created = EventType.objects.get_or_create( eventname=self.eventname ) return eventtype.priority viewSet: class EventViewSet(viewsets.ReadOnlyModelViewSet): queryset = CachedEvent.objects.all() serializer_class = CachedEventSerializer serializer: class CachedEventSerializer(serializers.ModelSerializer): id = serializers.CharField(source='original_id') class Meta: model = CachedEvent fields = ['key', 'timestamp', 'id', 'eventname', 'priority'] can help me please -
Import statements not being recognized in Django [closed]
I am using Django = 2.1 Python = 3.6 Pycharm Community Edition Import statements in one of my apps are not being recognized but the same import statements in other apps are working properly. Image of apps import staements not being recognized Image of import statements being recognized in other app of same project I have tried deleting .idea and I have also made sure that I have init.py in my apps and I have also deleted and reinstalled pycharm. -
Django monthly sums for a specific filter
I have the following models structure: Conto | Sottocategoria | Price | Quantity | Total* | Date of purchase Conto 1 | Product_a | 10 | 1 | 10 | 1/01/2020 Conto 1 | Product_a | 15 | 1 | 15 | 1/01/2020 Conto 2 | Product_b | 10 | 2 | 20 | 1/02/2020 I want to have the monthly sum for each "conto". Something like this: Conto | Gen | Feb | Mar | Apr | May | Jun | .... Conto 1 | 25 | 0 | 0 | 0 | 0 | 0 | .... Conto 2 | 0 | 20 | 0 | 0 | 0 | 0 | .... This one my models.py: class Tipologia(models.Model): nome= models.CharField('Categoria', max_length=30) class Sottocategoria(models.Model): tipologia = models.ForeignKey(Tipologia, on_delete=models.CASCADE) name = models.CharField() class Conto(models.Model): nome=models.CharField() class Materiale(models.Model): conto = models.ForeignKey(Conto, on_delete=models.CASCADE, null=True) tipologia = models.ForeignKey(Tipologia, on_delete=models.CASCADE, null=True) sottocategoria = models.ForeignKey(Sottocategoria, on_delete=models.CASCADE, null=True) quantita=models.DecimalField() prezzo=models.DecimalField() data=models.DateField(default="GG/MM/YYYY") -
How to implement alive and readyness with django-health-check
We are using kuberntes and need two different endpoints one for health and one for alive. For some reasons we chosse https://github.com/KristianOellegaard/django-health-check. Its easy to implement a second view for alive which is loaded, but - this view is empty - I do not understand how I could configure the plugings which should be used for the view. class AliveCheck(MainView): # template_name = 'myapp/health_check_dashboard.html' # customize the used templates def __init__(self): self.plugins.clear() self.plugins.append(DiskUsage()) def get(self, request, *args, **kwargs): errors = super(MainView, self).run_check() return super(MainView, self).get(request, args, kwargs) Any ideas? -
Django - Correct Use of Mixins with CBVs
I just started to shift from function-based views to class-based views, as I realize more and more the benefits of the latter, especially regarding the modularity that you can achieve via mixins. However, as CBVs and Mixins are still quite new to me, I wanted to check, if I understand the basic concepts correctly: Example: class ReportingMixin1(object): def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['reportingmixin1_context'] = 'test1' return context class ReportingMixin2(object): def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['reportingmixin2_context'] = 'test2' return context class MyTemplateView(ReportingMixin1, ReportingMixin2, TemplateView): template_name = 'test4.html' My questions are the following: With function based views I would do context = {'reportingmixin1': 'test1} but I see that with class based views this is always done via context['reportingmixin1'] = 'test1 . Why is this the case? I assume one reason is that when combining multiple mixins in a TemplateView (as in the code in my example) but with context = {'reportingmixin1': 'test1} and context = {'reportingmixin2': 'test2} I would initiate or redefine the context dictionary in each mixin, so you would have only access to the context keys I defined in my mixin that is called last? What is context = super().get_context_data(**kwargs) doing exactly? I read that it is "calling … -
How to solve "Blocked:CSP" error Passit (Django)
I'm not sure if this is the right stack exchange but i think this one fits my question the most. I was searching for an Free Opensource web based password manager to manage passwords for me and our team and found Passit (passit.io). I wanted to test this tool so installed an ubuntu 18 server with docker, postgreSQL and nginx and followed the installation instructions to run passit docker: https://passit.io/install/ I configured Passit via the web based installation wizard and now i can see the passit web interface. When i try to create an account the application does not respond. When i check the Google dev-tools i see that the http://passit.axx/account/register request gets an blocked:CSP response. During an attempt to solve this issue, i found that i can "enable" the Django admin interface by logging in into the container and set the ENABLE_DJANGO_ADMIN setting in the passit>settings.py to True. I tried to login here with just some random credentials and got this error: Forbidden (403) CSRF verification failed. Request aborted. You are seeing this message because this site requires a CSRF cookie when submitting forms. This cookie is required for security reasons, to ensure that your browser is not being … -
Django - how to change email field error measge
I have a django email field when email is entered wrongly it shows custom error message please include an @ in email address how can i change the error message class confirmmail(forms.Form): emailid = forms.EmailField(max_length=100,widget=forms.TextInput(attrs={'class': 'form-control user_name_textbox_style', 'placeholder':'Email Address', 'type':'email','required':'true','ng-model': 'email_from_forgotpassword'})) -
trying to createsuperuser on heroku but it throws me a typeError
i tried this command to createsuperuser using this command "heroku run python manage.py createsuperuser" but it always throws me this error Running python manage.py createsuperuser on ⬢ django-blog-web-app... up, run.4727 (Free)enter code here Username (leave blank to use 'u10279'): ###################### Email address: ####################### Password: Password (again): 'Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.8/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.8/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/app/.heroku/python/lib/python3.8/site-packages/django/core/management/base.py", line 328, in run_from_argv self.execute(*args, **cmd_options) File "/app/.heroku/python/lib/python3.8/site-packages/django/contrib/auth/management/commands/createsuperuser.py", line 79, in execute return super().execute(*args, **options) File "/app/.heroku/python/lib/python3.8/site-packages/django/core/management/base.py", line 369, in execute output = self.handle(*args, **options) File "/app/.heroku/python/lib/python3.8/site-packages/django/contrib/auth/management/commands/createsuperuser.py", line 189, in handle self.UserModel._default_manager.db_manager(database).create_superuser(**user_data) File "/app/.heroku/python/lib/python3.8/site-packages/django/contrib/auth/models.py", line 158, in create_superuser return self._create_user(username, email, password, **extra_fields) File "/app/.heroku/python/lib/python3.8/site-packages/django/contrib/auth/models.py", line 141, in _create_user user.save(using=self._db) File "/app/.heroku/python/lib/python3.8/site-packages/django/contrib/auth/base_user.py", line 66, in save super().save(*args, **kwargs) File "/app/.heroku/python/lib/python3.8/site-packages/django/db/models/base.py", line 745, in save self.save_base(using=using, force_insert=force_insert, File "/app/.heroku/python/lib/python3.8/site-packages/django/db/models/base.py", line 793, in save_base post_save.send( File "/app/.heroku/python/lib/python3.8/site-packages/django/dispatch/dispatcher.py", line 173, in send return [ File "/app/.heroku/python/lib/python3.8/site-packages/django/dispatch/dispatcher.py", line 174, in <listcomp> (receiver, receiver(signal=self, sender=sender, **named)) File "/app/Users/signals.py", line 10, in create_profile Profile.objects.create(user=instance) File "/app/.heroku/python/lib/python3.8/site-packages/django/db/models/manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/app/.heroku/python/lib/python3.8/site-packages/django/db/models/query.py", line 433, in create obj.save(force_insert=True, using=self.db) TypeError: save() got … -
TemplateDoesNotExist error due to a comment
I'm in the process of making a website with Django and have yet to create order_snippet.html. When I add {% include "order_snippet.html" %} I expect a TemplateDoesNotExist error, but I put this in the payment.html and commented it out like this: <!-- {% include "order_snippet.html" %} --> yet I still have a TemplateDoesNotExist error. I thought comments weren't read by html? How come this raises an error? -
using python & django for new huge human resources system... which is better react js or angular?
using python & django for new huge human resources system... which is better react js or angular? we are developing new human resources system with huge data... we will use python as a back end... which is better to use as a front end reactjs or angular? we need fast & stable system... and which is better to serve single page request? class HelloMessage extends React.Component { render() { return ( <div> Hello {this.props.name} </div> ); } } ReactDOM.render( <HelloMessage name="Taylor" />, document.getElementById('hello-example') ); -
my pipenv doesnt create a pipfile and pipfile.lock in any of my projects folders anymore
It used to automatically create these files in the folder I was working in, in the command line. If I were to say install django... C:\Users\Admin\Desktop\Djangoproj>pipenv install django Installing django… Adding django to Pipfile's [packages]… Installation Succeeded Installing dependencies from Pipfile.lock (536933)… ================================ 9/9 - 00:00:02 To activate this project's virtualenv, run pipenv shell. Alternatively, run a command inside the virtualenv with pipenv run. This is what I get. I have an empty folder. I dont get the pipfile or pipfile.lock like I am supposed to. Has anyone encountered this before? Is there a solution to this? I have already uninstalled pipenv and reinstalled the package a few times already. Same thing goes for installing requests package. C:\Users\Admin\Desktop\Djangoproj>pipenv install requests Installing requests… Adding requests to Pipfile's [packages]… Installation Succeeded Installing dependencies from Pipfile.lock (536933)… ================================ 9/9 - 00:00:02 To activate this project's virtualenv, run pipenv shell. Alternatively, run a command inside the virtualenv with pipenv run. C:\Users\Admin\Desktop\Djangoproj>ls 'ls' is not recognized as an internal or external command, operable program or batch file. C:\Users\Admin\Desktop\Djangoproj> -
how to make icons <i class="fas fa-minus mr-2"></i> display in template
I am trying to add some icons to my project template. I think i am putting them in the right place but they are not displaying when i look at the template. I have even tried placing the icons in other places but it still doesn't display. here is the place where the icons are on the template <td> <i class="fas fa-minus mr-2"></i> {{ equipment_order_item.quantity }} <i class="fas fa-plus ml-2"></i> </td> -
Web Development Learning Guidance [closed]
Can anyone acqauint me with basic Web Development if I'm a complete beginner? And guide me as to how to learn it? I know C++ and Python but want to start to learn web dev. What courses do you suggest? (Prefarably Free) Please endow me with all the knowledge you have! -
How to apply ManyToManyField to non primary key field?
I have a model A which has name and server_permission attributes. I would like to use both of these fields in my model B, but so far with no luck. Could you please help me? class A(models.Model): name = models.CharField(primary_key=True, max_length=50, unique=True) server_permission = ArrayField(models.CharField(max_length=10, blank=True),size=8) class B(models.Model): zuya_server = models.ForeignKey(A, on_delete=models.CASCADE, default='None',related_name='zuya_server') account_permission = models.ManyToManyField(A,db_column="server_permission",related_name='account_permission')