Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
python manage.py createsuperuser works on Mac, but does not work on windows
I have been going through the Django tutorial in the following link. I have completed this on a Mac, however I am hitting problems on windows 10: djangoproject In Tutorial part 2, when it comes to creating a new superuser, it fails. If I run the following on a Mac, I can create a new superuser. It fails when I run a similar command on windows. I have tried running both of the following on windows: ``` source venv/bin/activate python manage.py createsuperuser ``` ``` .\venv\Scripts\activate py manage.py createsuperuser ``` Package (pip list): ``` Package Version ----------- ------- Django 2.2.6 docutils 0.15.2 pip 19.3.1 pycodestyle 2.5.0 pytz 2019.3 setuptools 41.4.0 sqlparse 0.3.0 wheel 0.33.6 ``` The db.sqlite3 database is present, and as far as I can tell has a reasonable structure (there are lots of Django specific tables). I expect to create a new superuser, but instead get this output: Traceback (most recent call last): File "C:\Users\Mark\Documents\Development\Python\PYTHON---DJANGO---TUTORIAL\venv\lib\site-packages\django\contrib\auth\password_validation.py", line 26, in get_password_validators klass = import_string(validator['NAME']) File "C:\Users\Mark\Documents\Development\Python\PYTHON---DJANGO---TUTORIAL\venv\lib\site-packages\django\utils\module_loading.py", line 17, in import_string module = import_module(module_path) File "C:\Users\Mark\Documents\Development\Python\PYTHON---DJANGO---TUTORIAL\venv\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line … -
Is there a way to get only specific fields in a queryset after serialization data, without create a different serializer in drf?
i need to do a query where i want to get specific fields, then serializate it and keep only the specific fields which I got in the query. models.py class Search(models.Model): NEUTRAL = 'None' POSITIVE = 'P' NEGATIVE = 'N' POLARITY_CHOICES = [ (NEUTRAL, 'Neutral'), (POSITIVE, 'Positive'), (NEGATIVE, 'Negative'), ] user = models.ForeignKey(User,related_name='searched_user_id',on_delete=models.CASCADE) word = models.CharField( max_length = 100) social_network = models.ForeignKey(SocialNetwork,related_name='search_social_network_id',on_delete=models.CASCADE) polarity = models.CharField( max_length=4, choices=POLARITY_CHOICES, default=NEUTRAL, ) sentiment_analysis_percentage = models.FloatField(default=0) topic = models.ForeignKey(Topic,related_name='search_topic_id',on_delete=models.CASCADE) liked = models.IntegerField(default=0) shared = models.IntegerField(default=0) is_active = models.BooleanField(default=True) is_deleted = models.BooleanField(default=False) updated_date=models.DateTimeField(auto_now=True) searched_date = models.DateTimeField(auto_now_add=True) serializers.py class SearchSerializer(serializers.ModelSerializer): searched_date = serializers.DateTimeField(format="%d-%m-%Y") class Meta: model = Search fields = ('__all__') class RecentSearchSerializer(serializers.ModelSerializer): searched_date = serializers.DateTimeField(format="%d-%m-%Y") class Meta: model = Search fields = ('user','social_network','word','searched_date') class SentimentAnalysisSerializer(serializers.ModelSerializer): searched_date = serializers.DateTimeField(format="%d-%m-%Y") class Meta: model = Search fields = ('polarity','searched_date','sentiment_analysis_percentage') SearchSerializer is the main serializer for search, RecentSearchSerializer is the serializer to pass data and filtering in the DRF api view, and finally I created SentimentAnalysisSerializer to keep the specific fields that I need: api.py class SearchViewSet(viewsets.ModelViewSet): queryset = Search.objects.filter( is_active=True, is_deleted=False ).order_by('id') permission_classes = [ permissions.AllowAny ] serializer_class = SearchSerializer pagination_class = StandardResultsSetPagination def __init__(self,*args, **kwargs): self.response_data = {'error': [], 'data': {}} self.code = 0 def get_serializer_class(self): if … -
Django 2.2 i18n urlpatterns not being translated
I'm curious as if someone have tested using the i18n functionality of Django in the latest Django version? I'm trying to internationalize my urlpatterns as following: urlpatterns = [ path('i18n/', include('django.conf.urls.i18n')) ] urlpatterns += i18n_patterns( path('', include('apps.frontpage.urls', namespace='frontpage')), path(_('journal/'), include('apps.journal.urls', namespace='journal')), path(_('projects/'), include('apps.projects.urls', namespace='projects')), path(_('software/'), include('apps.software.urls', namespace='software')), path('administration/', admin.site.urls), ) using this .po file: #: core/urls.py:22 msgid "journal/" msgstr "dagbok/" #: core/urls.py:23 msgid "projects/" msgstr "prosjekter/" #: core/urls.py:24 msgid "software/" msgstr "programvare/" The .po and .mo files are being generated and detected as the HTML menu gets translated: <li><a href="{% url 'frontpage:index' %}"><i class="fas fa-home fa-fw"></i> {% trans "Home" %}</a></li> <li><a href="{% url 'journal:index' %}"><i class="fas fa-book fa-fw"></i> {% trans "Journal" %}</a></li> <li><a href="{% url 'projects:index' %}"><i class="fas fa-project-diagram fa-fw"></i> {% trans "Projects" %}</a></li> <li><a href="{% url 'software:index' %}"><i class="fas fa-hdd fa-fw"></i> {% trans "Software" %}</a></li> However, my urls are still not being translated. I'm not quite sure if I have done something wrong, or if this functionality is actually bugged in the latest Django version. Do I need to configure anything else than LOCALE_PATHS = [ os.path.join(BASE_DIR, 'shared/locale') ] for it to detect locale directories within applications? or is this done automatically by Django? -
ERRO DE EDITAR UN ID con Fk en DJANGO 2.2
Tengo un pequeño problema cuando yo quiero editar mi modelo con un relación fk django me lanza esto: enter image description here Este es mi funcion editar enter image description here Este es mi templete donde muestro la el id a editar enter image description here -
How to fix ‘ModuleNotFoundError: No module named 'pkgutil' error in pipenv
Im want creating virtual environment in my project Failed to create virtual environment. PS C:\Users\андрей\Desktop\Project> pipenv install Creating a virtualenv for this project… Pipfile: C:\Users\андрей\Pipfile Using c:\users\андрей\appdata\local\programs\python\python38-32\python.exe (3.8.0) to create virtualenv… [ ] Creating virtual environment...Already using interpreter c:\users\андрей\appdata\local\programs\python\python38-32\python.exe Using base prefix 'c:\users\андрей\appdata\local\programs\python\python38-32' New python executable in C:\Users\андрей.virtualenvs\андрей-TUBSFJkQ\Scripts\python.exe Command C:\Users\андрей.vir...Q\Scripts\python.exe -m pip config list had error code 1 Installing setuptools, pip, wheel... Complete output from command C:\Users\андрей.vir...Q\Scripts\python.exe - setuptools pip wheel: Traceback (most recent call last): File "", line 3, in return _run_code(code, main_globals, None, File "c:\users\андрей\appdata\local\programs\python\python38-32\lib\runpy.py", line 85, in _run_code exec(code, run_globals) File "c:\users\андрей\appdata\local\programs\python\python38-32\lib\site-packages\virtualenv.py", line 2628, in main() File "c:\users\андрей\appdata\local\programs\python\python38-32\lib\site-packages\virtualenv.py", line 860, in main create_environment( File "c:\users\андрей\appdata\local\programs\python\python38-32\lib\site-packages\virtualenv.py", line 1173, in create_environment install_wheel(to_install, py_executable, search_dirs, download=download) File "c:\users\андрей\appdata\local\programs\python\python38-32\lib\site-packages\virtualenv.py", line 1019, in install_wheel _install_wheel_with_search_dir(download, project_names, py_executable, search_dirs) File "c:\users\андрей\appdata\local\programs\python\python38-32\lib\site-packages\virtualenv.py", line 1110, in _install_wheel_with_search_dir call_subprocess(cmd, show_stdout=False, extra_env=env, stdin=script) File "c:\users\андрей\appdata\local\programs\python\python38-32\lib\site-packages\virtualenv.py", line 963, in call_subprocess raise OSError("Command {} failed with error code {}".format(cmd_desc, proc.returncode)) OSError: Command C:\Users\андрей.vir...Q\Scripts\python.exe - setuptools pip wheel failed with error code 1 -
I am getting the following error when open the admin panel of the project Note : OperationalError at /admin/app/contact/
OperationalError at /admin/app/contact/ no such table: app_contact Request Method: GET Request URL: http://127.0.0.1:8000/admin/app/contact/ Django Version: 2.2.6 Exception Type: OperationalError Exception Value: no such table: app_contact Exception Location: C:\Users\cvm\Desktop\CNumber\env\lib\site-packages\django\db\backends\sqlite3\base.py in execute, line 383 Python Executable: C:\Users\cvm\Desktop\CNumber\env\Scripts\python.exe Python Version: 3.8.0 Python Path: ['C:\Users\cvm\Desktop\CNumber', 'C:\Users\cvm\AppData\Local\Programs\Python\Python38-32\python38.zip', 'C:\Users\cvm\AppData\Local\Programs\Python\Python38-32\DLLs', 'C:\Users\cvm\AppData\Local\Programs\Python\Python38-32\lib', 'C:\Users\cvm\AppData\Local\Programs\Python\Python38-32', 'C:\Users\cvm\Desktop\CNumber\env', 'C:\Users\cvm\Desktop\CNumber\env\lib\site-packages'] Server time: Sun, 27 Oct 2019 16:43:09 +0000 -
Destroying file after HTTP response in Django
I'm now making website that downloads certain images from other website, zip files, and let users download the zip file. Everything works great, but I have no way to delete zip file from server, which has to be deleted after users download it. I tried deleting temp directory that contains zip file with shutil.rmtree, but I couldn't find way to run it after HTTPResponse. Here is my code in views.py. zipdir = condown(idx)#condown creates zip file in zipdir logging.info(os.path.basename(zipdir)) if os.path.exists(zipdir): with open(zipdir, 'rb') as fh: response = HttpResponse(fh.read(), content_type="multipart/form-data") response['Content-Disposition'] = 'inline; filename=download.zip' return response raise Http404 Thanks in advance. -
How to get input values from Django dynamically generated inline forms
I have a parent / child scenario (something like order/order items) wherein I have the child forms generated dynamically (with option to add form rows at runtime). I tried to get the values input in the fields using jQuery. I am able to do this for the header (parent) forms using the element's "id". But I am unable to do so with the inline (child) formset fields. The child forms are being generated by looping thru' formset object in management_form in the template (can't find the "id"s for the child fields). My question is: How do I assign "id"s to the child forms (so that then I may query them to get the value assigned to them Or is there any other way/s I can get the input values I have scoured thru' this site (including those suggested as I was typing out this query) as well as various others, but for the life of me unable to get a lead. Any possible lead? -
How can i add fields in my CustomUserCreationForm?
Forms.py class CustomUserCreationForm(UserCreationForm): #phone_number = forms.CharField(max_length = 100) class Meta: model = CustomUser fields = ('username', 'email','first_name','last_name', 'phone_number', 'middle_name') Admin.py class CustomUserAdmin(UserAdmin): model = CustomUser add_form = CustomUserCreationForm form = CustomUserChangeForm fieldsets = ( (('User'), {'fields': ('username', 'email', 'phone_number', 'first_name', 'last_name', 'middle_name', 'is_staff', 'is_superuser', 'is_active', 'is_parent', 'is_teacher')}), ) Models.py (All the fields in Admin.py are declared here without errors) class CustomUser(AbstractUser): phone_number = models.CharField(max_length = 100, blank=True, null = True) first_name = models.CharField(max_length = 100, default = '') last_name = models.CharField(max_length = 100, default = '') AddNewUser Image Here As you can see, I tried adding a Charfield directly in CustomUserCreationForm and I also tried adding fields but it just would not appear whenever I add new user. -
my apache config is not working getting error '500 Internal server error'
I am trying to deploy my django project on apache2 but its giving me an error '500 internal server error'. Here is my configuration file myproject.conf <VirtualHost *:80> ServerAdmin amol@myfirstdjango.localhost ServerName myfirstdjango.localhost ServerAlias www.myfirstdjango.localhost DocumentRoot /var/www/lms_project/Django-CRM ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined Alias /static /var/www/lms_project/static <Directory /var/www/lms_project/static> Require all granted </Directory> Alias /static /var/www/lms_project/media <Directory /var/www/lms_project/media> Require all granted </Directory> <Directory /var/www/lms_project/Django-CRM/crm> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess lms_project python-path=/var/www/lms_project python-home=/var/www/lms_project/env WSGIProcessGroup lms_project WSGIScriptAlias / /var/www/lms_project/Django-CRM/crm/wsgi.py </VirtualHost> my project is in /var/www/lms_project/Django-CRM #this folder contains manage.py virtual environment is in /var/www/lms_project my apache logs [Sun Oct 27 21:00:36.472014 2019] [wsgi:error] [pid 3409:tid 139766507882240] [remote ::1:43628] wtforms.validators.ValidationError: The CSRF session token is missing. [Sun Oct 27 21:00:36.472022 2019] [wsgi:error] [pid 3409:tid 139766507882240] [remote ::1:43628] [Sun Oct 27 21:00:36.472030 2019] [wsgi:error] [pid 3409:tid 139766507882240] [remote ::1:43628] During handling of the above exception, another exception occurred: [Sun Oct 27 21:00:36.472038 2019] [wsgi:error] [pid 3409:tid 139766507882240] [remote ::1:43628] [Sun Oct 27 21:00:36.472046 2019] [wsgi:error] [pid 3409:tid 139766507882240] [remote ::1:43628] Traceback (most recent call last): [Sun Oct 27 21:00:36.472054 2019] [wsgi:error] [pid 3409:tid 139766507882240] [remote ::1:43628] File "/usr/local/lib/python3.6/dist-packages/flask/app.py", line 1947, in full_dispatch_request [Sun Oct 27 21:00:36.472062 2019] [wsgi:error] [pid 3409:tid 139766507882240] [remote ::1:43628] rv … -
Django MPESA integration with C2B Till Number Payment and STK Push
I would like to be able to integrate MPESA API C2B Till Number Payment capabilities with STK push into a Django Web app I am working on such that the user of the platform gets an STK Push notification to pay to the till number and the transaction is stored in the database through a model. I have seen some frameworks people have developed online but most seem to cater for paybill and not till. any help with frameworks that can help me do this will be appreciated. I am finding the official documentation bulky and kind of difficult to work with from django. -
NoReverseMatch at /post/1/log/ Reverse for 'log-create' with keyword arguments '{'post_id': ''}' not found
I have a Post model with a whole bunch of posts. I also have a log model which has a foreign key field to the Post model. Essentially the Log model stores log entries for the Posts in the Post model (basically Post comments). Everything was going great. I have been using CBV for my post models and I used a CBV to List my log entries. I then added a link to redirect me to the Log CreateView using the following anchor tag: <a class="btn" href="{% url 'log-create' post_id=log.post_id %}">Add Entry</a> When the NoReverse errors started occuring. When I change the log.post_id to 1, the page loads correctly. This leads me to believe that the log.post_id is not returning any value. Another thought that I had was that because this anchor tag was on the LogListView there were multiple log entries so it didn't know which post_id to use. But I used the get_queryset function on this view to make sure that only logs related to a single post are returned. In my mind the log.post_id should work. My models are: class Post(models.Model): title = models.CharField(max_length=100, blank=True) date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) overview = models.TextField(blank=True) def get_absolute_url(self): … -
django, supervisor and gunicorn FATAL exited too quickly
*Note: Yes, I know there are several threads with about the same issue but none of them helps. Problem: this is about the conf file of supervisor getting to read the data from gunicorn_start file to launch the server. When I do: sudo supervisorctl reread sudo supervisorctl update All goes well. When I do supervisorctl status I get the answer: FATAL exited too quickly (process log may have details) Error I get: As I have looked in the logs it complains about not being able to find a file /home/videos/gunicorn_start: line 19: /home/videos/languagetech/../entornovirtual/bin/gunicorn: No such file or directory The strange thing is that if I modify the gunicorn_start file by adding extra lines, and I run again sudo supervisorctl status videos I get again the mention to line 19 although it should be another line. This is the gunicorn_start file. After having created it, I did a python manage.py test and all was well. #!/bin/bash NAME="django-videos" DIR=/home/videos/languagetech USER=videos GROUP=videos WORKERS=3 BIND=unix:/home/videos/run/gunicorn.sock DJANGO_SETTINGS_MODULE=tutoriales.settings DJANGO_WSGI_MODULE=tutoriales.wsgi LOG_LEVEL=error export DJANGO_SETTINGS_MODULE=$DJANGO_SETTINGS_MODULE export PYTHONPATH=$DIR:$PYTHONPATH exec ../entornovirtual/bin/gunicorn ${DJANGO_WSGI_MODULE}:application \ --name $NAME \ --workers $WORKERS \ --user=$USER \ --group=$GROUP \ --bind=$BIND \ --log-level=$LOG_LEVEL \ --log-file=- ===================================================================== SUPERVISOR FILE [program:videos] command=/home/videos/gunicorn_start directory = /home/videos/languagetech user=videos autostart=true autorestart=true redirect_stderr=true stdout_logfile=/home/videos/logs/gunicorn.log … -
How to render template after failed form validation?
urls.py: urlpatterns = [ path('employee/add_employee/', views.add_employee, name='add-employee'), path('employee/add_employee/add/', views.add_employee_action, name='add-employee-action'), ] I have add-employee page and some forms to fill there. views.py: def add_employee(request): personal_form = PersonalEmployeeForm() history_form = EmployeeHistoryForm() return render( request, 'sections/add_employee.html', context={ 'personal_form': personal_form, 'history_form': history_form, } ) def add_employee_action(request): if request.method == "POST": personal_form = PersonalEmployeeForm(request.POST) history_form = EmployeeHistoryForm(request.POST) if personal_form.is_valid() and history_form.is_valid(): # here is some logic with models return redirect('add-employee') else: personal_form = PersonalEmployeeForm() history_form = EmployeeHistoryForm() return render( request, 'sections/add_employee.html', context={ 'personal_form': personal_form, 'history_form': history_form, } ) The problem is after submitting invalid forms I have a page with blah-blah/employee/add_employee/add/ URL. And if I try to submit forms again I have a page with blah-blah/employee/add_employee/add/add/ URL, wich is incorrect. How can I render the page with blah-blah/employee/add_employee/ URL and show all error messages? -
How can I store possible values of a dropdown-box in a model and use them in a form
I am trying to create a dropdown box where a list of possible values is taken from the model, in such a way that when instanciating a model in the admins view for example, multiple options can be given to the model for use as the variables in the dropdown-box. I have tried googling around and can't find a clear awnser, or I am not understanding them at least. I also found django-collectionfield is this what I need? Just to be clear, I want the variables displayed to be dynamic on a model level. I want the give the administrator option to define a list of variables which then are used on the appropriate form in a dropdown-box. Thanks in advance! -
Active Tag in for extended templates
I'm a newbie to Django and want some help on template inheritance. I want to set "class="active" for the current active page but how do I do with template inheritance,as it generalizes it for all the pages but the active should change on changing current active page. I know this question might be silly but I don't know the answer still. I have no idea what to do for this case. <nav class="navbar navbar-expand-lg navbar-dark bg-dark"> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse " id="navbarSupportedContent"> <ul class="navbar-nav mr-auto"> <li class="nav-item mx-3"> <a class="nav-link" href="/Homepage/">Home <span class="sr-only">(current)</span></a> </li> <li class="nav-item mx-3"> <a class="nav-link" href="/booking/">Make a Booking</a> </li> <li class="nav-item mx-3 active"> <a class="nav-link" href="/History/">History</a> </li> <li class="nav-item mx-3"> <a class="nav-link" href="/pending/">Pending requests</a> </li> </ul> <ul class="nav navbar-nav navbar-right"> <li class="nav-item "> <form method="POST" action="{% url 'logout'%}"> {% csrf_token %} <a class="navbar-brand text-capitalize navbar-brand text-white">{{ user }}</a> <button type="submit" class="btn btn-danger mx-3">Logout</button> </form> </li> </ul> </div> </nav> I expect the active class might get applied to only current active pages. -
How to render elements depends on select value in react
i'm newbie in react and i wanted to render different HTML Elements depends on Selected value And if its possible POST datas in selected html to django model here is my react js code : class Resepy extends React.Component { constructor(props){ super(props); this.state = { selected : 'default' }; } setSelected = (event) => { let select = document.getElementById("id_field1"); document.getElementById("test").innerHTML = select.value; } render() { return ( <div className="Resepy"> <h1>Something</h1> <form> <select id="id_field1" name="field1" onChange={this.setSelected}> <option value="default">Food type not selected</option> <option value="burger">Burger</option> <option value="pizza">Pizza</option> </select> <div id="test"></div> <div className="food">{ this.state.selected == "default" ? <div className="default">Default</div> : this.state.selected == "Burger" ? <div className="burger">Burger</div> : <div className="pizza">Pizza</div> }</div> <button type="submit">Add to tray</button> </form> </div> ); } } <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script> -
How to know in a middleware which type of url entered?
Recently I started a new simple project in Django. I wrote some middleware. but in one of the middlewares, I want to know which URL is called because I have to make a decision which is related to URL. I used this code: import os path = os.environ['PATH_INFO'] but it makes an error which is described below: raise KeyError(key) from None KeyError: 'PATH_INFO' so how I can know the URL in my middleware? -
main view keeps redirecting to login page even for logged-in user in django
my main view is, def main(request): if request.user.is_authenticated: return render(request,'main/main.html',{'use':use,'query':query,'noter':noter,'theme':request.user.profile.theme}) else: return redirect('home') the home page is responsible for serving login form is def home(request): if request.user.is_authenticated: return redirect('main') else: return render(request,'home.html') the "home.html" uses ajax to submit login page $(document).ready(function(){ $('#form2').submit(function(event){ event.preventDefault(); $('#username_error').empty(); $("#password_error").empty(); var csrftoken = $("[name=csrfmiddlewaretoken]").val(); var formdata={ 'username':$('input[name=username2]').val(), 'password':$('input[name=loginpassword]').val(), }; $.ajax({ type:'POST', url:'/Submit/logging', data:formdata, dataType:'json', encode:true, headers:{ "X-CSRFToken": csrftoken }, }) .done(function(data){ if(!data.success){//we will handle error if (data.password){ $('#password_error').text(data.password); } if(data.Message){ $('#password_error').text("You can't login via pc"); } blocker(); return false; } else{ window.location='/'; } }); event.preventDefault(); }); this configuration is working fine but main page keeps redirecting to home.html even when though user is already logged in. I'm using nginx server whose configuration is server { server_name host.me www.host.me; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/username/projectname; } location /media/ { root /home/username/projectname/appname; } location / { include proxy_params; proxy_pass http://unix:/home/username/projectname/projectname.sock; } listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/www.host.me/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/www.host.me/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 = www.host.me) { return 301 https://$host$request_uri; } # managed by Certbot if ($host … -
Django Design: Store Extracted File Contents Automatically to DB
In my application, I have a scraper that kicks off every morning, generates the daily Islamic prayer times and saves them in a text file. I need to extract the contents from this file and save them to a db. I would like to have Django/Python automatically do this for me, check the file if it exists and slurps up the contents. The contents in the text file looks something like this: {"sunrise": "6:30AM", "noon": "12PM", "afternoon" : "5:30PM"} How do I go about writing the Model class? Should I go with a variable for each entry, meaning: pSunrise, tSunrise, pNoon, tNoon...etc (p = prayer, t = time) Or does it get stored differently? Secondly, how do I initiate Django to automate this for me? This has been bugging me for quite a while and I greatly appreciate all the help I can get. Thank you! -
3 questions about the web development
i am trying to go into the web development path and trying to React+Django Combination to get started. But i am having some doubts related to this. i. we can build a webpage both with Django and react. Then why are we categorized them as frontend and backend ? Though i know frontend means what user sees and backend means the logic behind the scene that helps the frontend to thrive. Can't we just use just one Django or React ? ii. Suppose i followed a tutorial to build 2 projects using react and Django separately. Then we will deploy . What are next things to learn to make it happen? i am asking long questions as am a noob here. Hoping for a detailed explanation. -
How to get coordinates correctly from django to leaflet with geojson
I loaded some Shapefile multipolygons into Geodjango to show them as a layer on a Leaflet map. But on the website, no layer appears, just the map itself. The geometry data are stored in the Geodjango database like so: from django.contrib.gis.db import models class wgo(models.Model): (some more variables) poly = models.MultiPolygonField(srid=4326) I pass the multipolygons with geojson and serialize like so: wcrds = wgo.objects.filter(id=wid) gridone = serialize('geojson', wcrds.all()) return render(request, 'result.html', {'gridone': gridone}) And when I inspect the page I can see that the geojson data indeed makes it to the html: var Hlayer = new L.GeoJSON( {"type": "FeatureCollection", "crs": {"type": "name", "properties": {"name": "EPSG:4326"}}, "features": [{"type": "Feature", "properties": {"wijkcode": "WK036356", "wijknaam": "Middenmeer", "poly": "SRID=4326;MULTIPOLYGON (((4.93714288723798 52.3576900936898, 4.93742729807085 52.3577390397678,)))", "pk": "909"}, "geometry": null}]} , { style: Hstyle } ); var mymap = L.map('mapid').setView([52.3701, 4.8967], 13); var OpenStreetMap_Mapnik = L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { maxZoom: 19, attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors' }).addTo(mymap); (I took out most of the coordinates for brevity's sake). It looks like geojson did not pick up on the fact that the poly variable is the one with the geometry. I see geojson coordinates with square brackets around them on example sites, as opposed to the round ones on mine. I … -
How to render element depends on selected option?
i'm new in React, and i want to render Different Elements depends on user selection via select and option tags. how can i do this? this is my wrong code : class Resepy extends Component { state = { Resepy : 'default' } render() { let Resepy = ( <div className="Resepy"> <form> <select id="id_field1" name="field1" onChange={(e) => this.state.Resepy = "Burger"}> <option value="default">Food type not selected</option> <option value="burger" onClick={(e) => this.setState({ Resepy: 'Burger' })}>Burger</option> <option value="pizza" onClick={(e) => this.setState({ Resepy: 'Pizza' })}>Pizza</option> </select> <div className="food"> <div className="default" Resepy={this.state.Resepy === 'default'}></div> <div className="burger" Resepy={this.state.Resepy === 'burger'}></div> <div className="pizza" Resepy={this.state.Resepy === 'pizza'}></div> </div> </form> </div> ); -
field of a model is disabled in admin panel
I have a model which name is article and each article has a title. I want to create a new article via admin but I've encountered that just the title field is suddenly disabled and I can't enter the title. my article model is such below: class Article(models.Model): title=models.CharField(max_length=100) body=models.TextField() view=models.IntegerField(default=0) created_at=models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now = True) published_at = models.DateTimeField(default=timezone.now) show=models.BooleanField( default=1) def __str__(self): return self.title user = models.ForeignKey(User,on_delete=models.SET_NULL, null = True) categories = models.ManyToManyField(Category) class Meta: permissions=( ('private_section_article','Private Section Article'), ) and the admin file corresponds to this model is: @admin.register(Article) class ArticleAdmin(ModelAdminJalaliMixin,admin.ModelAdmin): def published_fa(self,model): return datetime2jalali(model.published_at).strftime('%y/%m/%d _ %H:%M:%S') list_display=('title','view','published_fa','created_at','updated_at','show') list_display_links=('published_fa',) search_fields = ['title','body','created_at'] list_filter=('published_at','title') date_hierarchy='updated_at' ordering=['-created_at'] readonly_fields = ('title',) actions=['make_hide','make_show'] fieldsets = ( (None, { "fields": ( 'title','categories','body','published_at' ), }), ('Advanced Options',{ 'classes':('wide', 'extrapretty','collapse'), 'fields':('view','show','user') }) ) def make_hide(self,request,queryset): # queryset oonayi hastan ke tik khordan row_updated = queryset.update(show=0) message='1 article was' if row_updated is not 1: message="%s articles were" % row_updated self.message_user(request,"%s marked as hide" % message)# to show a message after this action have done make_hide.short_description='make selected articles as hide' def make_show(self , request , queryset): row_updated = queryset.update(show = 1) message='1 article was' if row_updated is not 1: message="%s articles were" % row_updated self.message_user(request,"%s marked … -
Django - Displaying Prices on elasticsearch results
I am making a booking website, and I have implemented elasticsearch. I got the search working just fine, but now I am kind of stuck on a problem. What I'm trying to do is display the lowest price for the apartment the user has searched for, in the search results. The prices are stored in the "ApartmentPrices" model : class ApartmentPrices(models.Model): apartment = models.ForeignKey(Apartment, on_delete="models.CASCADE", related_name="price") price_start_date = models.DateField(blank=True, null=True) price_end_date = models.DateField(blank=True, null=True) price = models.IntegerField() def __str__(self): return self.apartment.title This is my document and view for the actual search : search view : def search(request): apartments = Apartment.objects.all() q = request.GET.get('q') if q: apartments = ApartmentDocument.search().query("match", title=q) else: apartments = '' return render(request, 'search/search_elastic.html', {'apartments': apartments, "q": q, }) document: apartments = Index('apartments') @apartments.document class ApartmentDocument(Document): class Django: model = Apartment fields = [ 'title', 'id', 'bedrooms', 'list_date', ] I have tried passing in apartment_id to the search view, but I cannot get it to work. Can anyone point me in the right direction please ?