Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django 2.0.4 urls not working
Django suddenly does not seem to be processing urls correctly. I followed part 3 of "Writing your first Django app" again with just a polls view and the urlsconf. It isn't working. What am I missing? Here is my views.py: from django.http import HttpResponse def index(request): return HttpResponse("Hello, world. You're at the polls index.") Here is my polls\urls.py: from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.index, name='index'), ] whyitsnotworking\urls.py: from django.conf.urls import include, url from django.contrib import admin urlpatterns = [ url(r'^polls/', include('polls.urls')), url(r'^admin/', include(admin.site.urls)), ] whyitsnotworking\settings.py: INSTALLED_APPS = [ 'polls', Here is the directory for my polls app: migrations admin.py apps.py models.py tests.py urls.py views.py init.py I can run the test server: Run 'python manage.py migrate' to apply them. April 08, 2018 - 16:25:27 Django version 2.0.4, using settings 'whyitsnotworking.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. [08/Apr/2018 16:25:33] "GET / HTTP/1.1" 200 16348 Not Found: /polls [08/Apr/2018 16:25:39] "GET /polls HTTP/1.1" 404 1964 But get the following error message: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/polls Using the URLconf defined in whyitsnotworking.urls, Django tried these URL patterns, in this order: admin/ The current path, polls, didn't match … -
how to renumber id when the row deleted in django
I would like to set a limit of the number of rows in certain models. to implement this, when I add a new row to the database in django, I would like to delete the old row and renumber id(pk). By referring to the following links about the above issue, I was able to set the number of lines limit and delete old lines. Limit the number of rows in a Django table However, this solution, when the old row deleted, id(pk) is also deleted. if I set limit number of rows is 100, the row id after deletion database is starting at 101. To solve this issue, I would like to renumber id as starting 1 when deleting old id. Could you tell me how to implement it? class History(models.Model): history = models.IntegerField(default=0) def save(self): objects = History.objects.all() print(id) if objects.count() > 100: objects[0].delete() self.save() class Player(models.Model): user = models.CharField(max_length=255) game_count = models.IntegerField(default=0) medal = models.IntegerField(default=100, verbose_name='medal') game_history = models.ForeignKey(History, on_delete=models.CASCADE, verbose_name='game_history', null=True) def __str__(self): return self.user -
Simple Web app:Django or Django Rest Framework?
If I want to create a web app using Vue.js for frontend, what should I use, Django or Django Rest Framework? -
Django tutorial NoReverseMatch error
I was following the tutorial for Django, however, I encounter an error when I reach part 5. NoReverseMatch at /polls/ Reverse for 'detail' with arguments '('',)' not found. 1 pattern(s) tried: ['polls\\/(?P<pk>[0-9]+)\\/$'] Request Method: GET Request URL: http://127.0.0.1:8000/polls/ Django Version: 2.0.2 Exception Type: NoReverseMatch Exception Value: Reverse for 'detail' with arguments '('',)' not found. 1 pattern(s) tried: ['polls\\/(?P<pk>[0-9]+)\\/$'] Error during template rendering In template /media/shawn/New Volume/tests/django/mysite/polls/templates/polls/index.html, error at line 5 <li><a href="{% url 'polls:detail' question.id %}">{{ question.question_text }}</a></li> polls/urls.py: from django.urls import path from . import views app_name = 'polls' urlpatterns = [ path('', views.IndexView.as_view(), name='index'), path('<int:pk>/', views.DetailView.as_view(), name='detail'), path('<int:pk>/results/', views.ResultsView.as_view(), name='results'), path('<int:question_id>/vote/', views.vote, name='vote'), ] polls/template/polls/index.html: {% load static %} <link rel="stylesheet" type="text/css" href="{% static 'polls/style.css' %}" /> <li><a href="{% url 'polls:detail' question.id %}">{{ question.question_text }}</a></li> polls/views.py: from django.utils import timezone from django.shortcuts import get_object_or_404, render from django.http import HttpResponseRedirect from django.urls import reverse from django.views import generic from .models import Choice, Question class IndexView(generic.ListView): template_name = 'polls/index.html' context_object_name = 'latest_question_list' def get_queryset(self): """ Return the last five published questions (not including those set to be published in the future). """ return Question.objects.filter( pub_date__lte=timezone.now() ).order_by('-pub_date')[:5] class DetailView(generic.DetailView): model = Question template_name = 'polls/detail.html' def get_queryset(self): """ Excludes any questions … -
celery supervisor returns "no such file or directory" error
I'm using supervisor to daemonize my django project. If I don't start celery from supervisor but start from shell (celery -A proj worker --app=proj.celery:app --loglevel=INFO) everything works fine. When I daemonize the celery program, task logs No such file or directory and finishes immediately. There isn't any other problem, workers are alive, supervisorctl status celery is RUNNING etc. Whats the problem? My celery_err.log file content: [2018-04-08 15:24:01,121: INFO/MainProcess] Connected to redis://localhost:6379// [2018-04-08 15:24:01,131: INFO/MainProcess] mingle: searching for neighbors [2018-04-08 15:24:02,135: INFO/MainProcess] mingle: all alone [2018-04-08 15:24:02,143: WARNING/MainProcess] /home/ali/Desktop/proj/projenv/local/lib/python2.7/site-packages/celery/fixups/django.py:265: UserWarning: Using settings.DEBUG leads to a memory leak, never use this setting in production environments! warnings.warn('Using settings.DEBUG leads to a memory leak, never ' [2018-04-08 15:24:02,143: WARNING/MainProcess] celery@debian ready. [2018-04-08 15:24:32,789: INFO/MainProcess] Received task: task_proj[441f7326-c847-4a29-a65d-543b8794e7a3] [2018-04-08 15:24:32,797: INFO/Worker-2] task_proj[441f7326-c847-4a29-a65d-543b8794e7a3]: Sent scan request successfully [2018-04-08 15:24:32,831: WARNING/Worker-2] [Errno 2] No such file or directory [2018-04-08 15:24:32,843: WARNING/Worker-2] [Errno 2] No such file or directory my supervisord.conf file content: [program:proj] environment=LANG=en_US.UTF-8,LC_ALL=en_US.UTF-8 ,PATH="/var/www/proj/projenv/bin", PROJ_ENV_FILE="/var/www/proj/proj.env",VIRTUAL_ENV="/var/www/proj/projenv",PYTHONPATH="/var/www/proj/projenv/lib/python:/var/www/proj/projenv/lib/python/site-packages" command = /var/www/proj/bin/gunicorn_start user = root redirect_stderr = true stdout_logfile=/var/www/proj/logs/django.log stderr_logfile=/var/www/proj/logs/django_err.log [program:redis] command = /etc/redis-4.0.2/src/redis-server [program:celery] environment=LANG=en_US.UTF-8,LC_ALL=en_US.UTF-8 ,PATH="/var/www/proj/projenv/bin", PROJ_ENV_FILE="/var/www/proj/proj.env",VIRTUAL_ENV="/var/www/proj/projenv",PYTHONPATH="/var/www/proj/projenv/lib/python:/var/www/proj/projenv/lib/python/site-packages" directory=/var/www/proj/proj command = /var/www/proj/projenv/bin/celery -A proj worker --app=proj.celery:app --loglevel=INFO user = root redirect_stderr = true stdout_logfile = /var/www/proj/logs/celery.log … -
Django error: local variable 'image' referenced before assignment . Please help me with it
I have an error in django code. And,here is the Traceback: File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in get_response 149. response = self.process_exception_by_middleware(e, request) File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in get_response 147. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\dell\Desktop\BlrCityPolice\fir\views.py" in create_image 123. file_type = image.image_file.url.split('.')[-1] Exception Type: UnboundLocalError at /fir/2/create_image/ Exception Value: local variable 'image' referenced before assignment: views.py: def create_image(request, evidence_id): form = ImageForm(request.POST or None, request.FILES or None) evidence = get_object_or_404(Evidence, pk=evidence_id) if form.is_valid(): evidences_images = evidence.image_set.all() for s in evidences_images: if s.image_title == form.cleaned_data.get("image_title"): context = { 'evidence': evidence, 'form': form, 'error_message': 'You already added that image', } return render(request, 'fir/create_image.html', context) image = form.save(commit=False) image.evidence = evidence image.image_file = request.FILES['image_file'] file_type = image.image_file.url.split('.')[-1] file_type = file_type.lower() if file_type not in IMAGE_FILE_TYPES: context = { 'evidence': evidence, 'form': form, 'error_message': 'Image file must be JPG, JPEG, or PNG', } return render(request, 'fir/create_image.html', context) image.save() return render(request, 'fir/detail.html', {'evidence': evidence}) context = { 'evidence': evidence, 'form': form, } return render(request, 'fir/create_image.html', context) create_image.html: {% extends 'fir/base.html' %} {% block title %}Add a New Image{% endblock %} {% block evidences_active %}active{% endblock %} {% block body %} <div class="container-fluid"> <div class="row"> <!-- Left Evidence Info --> <div class="col-sm-4 col-md-3"> <div class="panel panel-default"> <div class="panel-body"> <a href="{% … -
How did Django find Bootstrap files under this folder "/usr/local/lib/python3.6/site-packages"?
I recently started to work on a Django Bootstrap project and it started to become confusing. I installed the Django and created a project. Normally, it works as it should be and I'm able to display the app from my browser. However, I wanted to personalise the template and decided to go with bootstrap4, which is a really cool framework. I installed bootstrap with this command "pip install django-bootstrap-static". I'm aware that I should include my static files in to the STATIC folder and specify it on to the settings.py, which I did, but I couldn't find the bootstrap4 files on the machine at the first place. The thing is, I included the library references on the the html file like this; <link rel="stylesheet" href="{% static 'bootstrap/css/bootstrap.min.css' %}"> <script src="{% static 'bootstrap/js/jquery.min.js' %}"></script> <script src="{% static 'bootstrap/js/bootstrap.min.js' %}"></script> and suddenly, it started to work with bootstrap, which means my bootstrap elements are there! But as I said, I didn't specify the bootstrap files, only thing I specified is my STATIC folder under the app. The bootstrap files which I found later on is under this folder "/usr/local/lib/python3.6/site-packages". I want to include SASS to personalise even more my site but I … -
How to submit Form using Ajax in Django
I am trying to submit a HTML Form using Ajax, But I am not getting any alert success or failure. index.html <form method="post" class="needs-validation" enctype="multipart/form-data" action="/upload/" id="fupload"> <div class="custom-file"> <input type="file" class="custom-file-input" id="data_files" name="data_files" multiple required> <label class="custom-file-label" for="data_files">Choose files</label> </div> <button type="submit">Upload files</button> </form> <script type="text/javascript"> var frm = $('#fupload'); frm.submit(function () { $.ajax({ type: frm.attr('method'), url: frm.attr('action'), data: frm.serialize(), success: function (data) { alert('Form Submitted'); }, error: function(data) { alert('Form submission failed'); } }); return false; }); views.py @csrf_exempt def upload(request): if request.method == 'POST': return HttpResponse() Any guesses why it doesn't work -
Create mysql database with Django using Docker
I am stuck with deploying my Django project which uses mySQL database using docker containers. I am able to create the two containers but the web container exits with code 1 as soon as it is created with the error -- Not able to find tg_db database. My understanding is that when I run docker-compose up -d to start both the containers, it uses MYSQL_DATABASE=tg_db environment variable to create the database named tg_db, which is used and identified by django settings. Or, I can run command docker-compose run web python3 manage.py migrate to run docker-compose which will create database and migrations on it. Please let me know, if this is not true. Below are the files used: settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'tg_db', 'USER': 'root', 'PASSWORD': 'password', 'HOST': 'db', 'PORT': '3306', 'OPTIONS': {'init_command': 'SET default_storage_engine=INNODB;'} },} Dockerfile: # Start with a python image FROM python:3 # Some stuff that everyone has been copy-pasting # since the dawn of time. ENV PYTHONUNBUFFERED 1 # Install things RUN apt-get update # Make folders and locations for project RUN mkdir /code COPY . /code WORKDIR /code/project/t_backend # Install requirements RUN pip install -U pip RUN pip install -Ur requirements.txt … -
Django button changes the year
I've only been using Django for a short time. My new project should display data from a database, depending on the year. I need a button to change the year (see picture). Button How can I do this? The display of the data for the current year already works. Hope you can help me. -
Django 2.0 login error after setting it up in browser
I am using this code to login and its not working.... def user_login (request): if request.method=='POST': username = request.POST.get('username') password = request.POST.get('password') user = authenticate(username=username,password=password) if user : Maybe the is_active is not True and if its not what should i do if user.is_active: login(request,user) return HttpResponseRedirect(reverse('index')) else: return HttpResponse('Account Not Active') else: print("Someone tried to login and failed!") print("username:{},password:{}".format(username,password)) return HttpResponse("Invalid Login Details Supplied") else: return render (request,'basictwo/login.html',{}) -
template can't find objects
this is my views.py def index(request): all_albums = Album.objects.all() context = {'all_albums': all_albums} return render(request, 'music/index.html', context) and this is index.htlm {% if all_albums %} <h3>Here are my ALL Albums</h3> <ul> {% for album in all_albums %} <li><a href="/music/{{album.id}}/">{{album.album_title}}</a></li> {% endfor %} </ul> {% else %} <h3>you don‘t have any album</h3> {% endif %} it keeps showing you don't have any album at the webI learn it from youtube by thenewbobson. I write all the tutorial has told .but now I got this problem . hope there is someone helps me thanks. -
How to add code blocks to Mezzanine blog posts?
How to allow users to insert code blocks (formatted code for reading only)? That is, not to run the users code, only allow users to store and display their code. Similar to: How Stack Overflow allows users to format code in posts. -
Django: null=False does not work
Here is my User class: class User(AbstractUser): email = models.EmailField(_('email address'), blank=False, null=False) Why can I do the following? new_user3 = User.objects.create_user("test45447", None, "password") -
How to use a select widget in django forms
I tried to make a select form using Django forms, but instead of the form, only the names of the fields are being displayed (category, subcategory and certificate). The forms.py file: class LeadForm(forms.Form): CHOICE = ((1,'Student Professional Societies (IEEE,IET, ASME, SAE,NASA etc.)'), (2,'College Association Chapters (Mechanical, Civil,Electrical etc.)'), (3,'Festival & Technical Events(College approved)'),` (4,'Hobby Clubs'), (5,'Special Initiatives(Approval from College and University is mandatory)'), ) CHOICE1 = ((1,'Core coordinator'), (2,'Sub coordinator'), (3,'Volunteer')) CHOICE2 = ((1,'(a) Certificate'), (2,'(b) Letter from Authorities'), (3,'(c) Appreciation recognition letter'), (4,'(d)Documentary evidence'), (5,'(e) Legal Proof'), (6,'Others') ) category = forms.ChoiceField(widget=forms.Select, choices=CHOICE) subcategory = forms.ChoiceField(widget=forms.Select, choices=CHOICE1) certificate = forms.ChoiceField(widget=forms.Select, choices=CHOICE2) The Template: {% block body %} <div class="container"> <h2>Certificate</h2> <!--surround the select box with a "custom-select" DIV element. Remember to set the width:--> <div class="custom-select" style="width:200px;"> <form method="post"> {% csrf_token %} {{ form }} <input type="submit"> </form> <br> </br> </select> </div> </div> {% endblock %} The views.py file: class Leadership_management(LoginRequiredMixin, TemplateView): template_name = 'accounts/Leadership_management.html' def get(self, request): form = LeadForm() return render(request, self.template_name, {'form': form}) def post(self, request): form = LeadForm(request.POST) if form.is_valid(): catagory = form.cleaned_data['catagory'] subcatagory = form.cleaned_data['subcatagory'] certificate = form.cleaned_data['certificate'] form = LeadForm() args = {'form': form, 'catagory': catagory, 'subcatagory': subcatagory, 'certificate': certificate} return render(request, self.template_name, … -
Django queryset annotation mutated by randomization
I've been working on a project where I need to perform a fairly involved filter & sort operation on a reasonably large dataset in Django, then serialize the result out to be consumed by some frontend application. Here's the goal: Filter StoreItem results by some criteria. Let's just assume this is already done. Sort these StoreItem instances by their respective number of Discounts, in descending order. For collisions (i.e. when two StoreItems have the same number of Discounts), randomize that subset of results. Paginate the sorted results and return a subset of data. We have a couple of oversimplified models: class StoreItem(models.Model): # Model Fields name = models.CharField(max_length=128) price = models.DecimalField(max_digits=4, decimal_places=2) class Discount(models.Model): # Model Fields name = models.CharField(max_length=128) is_active = models.BooleanField(default=True) client_verified = models.BooleanField(default=False) value = models.DecimalField(max_digits=4, decimal_places=2) # Relationships store_item = models.ForeignKey(StoreItem, on_delete=models.CASCADE, related_name='discounts') Pretty straightforward: we have a bunch of StoreItem records, each of which can have N Discounts. === Attempt One === To solve item #2, we'll use a queryset annotation to calculate the number of Discounts for each StoreItem. For #3, we'll use order_by with the randomization flag. Let's skip forward and pretend we already have serializers and a StoreItem viewset via Django Rest … -
In Chart.js and django, add data by clicking the button
I am trying to make a simple program that drawing line graph using Chart.js(ver2.7) and ajax. This program is that when user click button, it can get new data from saved in the database, and then advance labels and data in graph one by one in real time. I understand that I write as follows, but I tried many times what to write inside the function, but I could not implement it. $("#id").click(function() { }); Currently, I can display properly the chart before implementing function above. $( document ).ready(function() { var endpoint ='/api/chart/data'; var defaultData = []; var labels = []; $.ajax({ method: "GET", url: endpoint, success: function (data) { labels = data.labels; defaultData = data.defaults; setChart(); }, error: function (error_data) { console.log("error"); console.log(error_data) } }); function setChart() { var ctx = document.getElementById("myChart"); var myChart = new Chart(ctx, { type: 'line', data: { labels: labels, datasets: [{ label: '# of medals', data: defaultData, backgroundColor: [ 'rgba(255, 99, 132, 0.2)', ...etc ], borderColor: [ 'rgba(255,99,132,1)', ...etc ], borderWidth: 1 }] }, options: { scales: { yAxes: [{ ticks: { beginAtZero: true } }] } } }); } graph.html <div class="col-sm-6"> <canvas id="myChart" width="400" height="400"></canvas> </div> How should this be implemented? -
Serializing a dictionary that is not a model in Django restframework
I have read a few answers and posts about serializing an dictionary . But I still can't get it to work. Here is the problem. I do some data processing in django app , and it returns this dictioary (It has information about a quiz): {101: {'subject': 'General-Intelligence', 'topics': ['Coding Decoding', 'Dice & Boxes', 'Statement & Conclusion', 'Venn Diagram', 'Mirror and Water Image', 'Paper Cutting and Folding', 'Clock/Time', 'Matrix', 'Direction', 'Blood Relation', 'Series Test', 'Ranking', 'Mathematical Operations', 'Alphabet Test', 'Odd one out', 'Analogy'], 'num_questions': 25, 'creator': 'Rajesh K Swami'}} I want to serialize this dictionary. So what I have done is created a class for this dictionary. ie. class PsudoTests: def __init__(self,body): self.body = body Also a serializer: class PsudoTestSerializer(serializers.Serializer): body = serializers.DictField() Now in api view : class TestListView(generics.ListAPIView): def get_serializer_class(self): serializer = PsudoTestSerializer def get_queryset(self): me = Studs(self.request.user) tests = me.toTake_Tests(1) # this method brings in the above dictionary that i want to serialize p_test = PsudoTests(tests) #this creates an instance of class created above return p_test Now when i go to the url there is a key error: "Got KeyError when attempting to get a value for field body on serializer PsudoTestSerializer.\nThe serializer field might be named … -
Celery and Rabbitmq: How to get an external worker to consume tasks from a queue
I have 2 servers A (producer) & B (Consumer). Server A has a celery_beat task that runs every 30 seconds. Server A is using Rabbitmq 3.5.7 and celery 4.1.0. Server B is using celery 4.1.0 Server A can send jobs to the tasks queue however Server B's celery_worker does not pick them up. It returns the follwoing warning and deletes all jobs. When running the tasks from either servers shell, they work fine I think the issue is with my celery worker config. This is the error I am getting from server B's celery_worker.logs [2018-04-08 10:07:01,083: WARNING/MainProcess] Received and deleted unknown message. Wrong destination?!? The full contents of the message body was: body: '{"user": "Lewis", "status": "submitted", "start": "21-10-2017T21:08:04Z+00:00", "end": "21-10-2017T21:08:04Z+00:00", "profile_data": {"delivery_method": "ftp", "transcode_settings": "test", "delivery_settings": {"test": "test"}, "name": "Amazon", "contact_details": "test"}, "id": 78, "video_data": {"segment_data": {"segment_data": {"segment_4": {"end": "00:00:05:00", "start": "00:00:00:00"}, "segment_3": {"end": "00:00:05:00", "start": "00:15:00:00"}, "segment_1": {"end": "00:00:05:00", "start": "00:10:00:00"}, "segment_2": {"end": "00:00:05:00", "start": "00:05:00:00"}}}, "material_id": "LB000002", "total_duration": "00:00:20:00", "audio_tracks": {"en": [1, 2]}, "resolution": "SD169", "number_of_segments": 4}}' (720b) {content_type:None content_encoding:None delivery_info:{'redelivered': False, 'routing_key': 'tasks', 'consumer_tag': 'None8', 'exchange': '', 'delivery_tag': 46} headers={}} I have gone through both Celery & Rabbitmq's docs and I am stumped any help would … -
python3 manage.py runserver error
When I try to start (python3 manage.py runserver) my django2.0 webapp on my PC I have this message: Performing system checks... Unhandled exception in thread started by .wrapper at 0x7fc889c36510> Traceback (most recent call last): File "/home/neo/.local/lib/python3.5/site-packages/django/urls/resolvers.py", line 538, in url_patterns iter(patterns) TypeError: 'module' object is not iterable During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/neo/.local/lib/python3.5/site-packages/django/utils/autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "/home/neo/.local/lib/python3.5/site-packages/django/core/management/commands/runserver.py", line 120, in inner_run self.check(display_num_errors=True) File "/home/neo/.local/lib/python3.5/site-packages/django/core/management/base.py", line 364, in check include_deployment_checks=include_deployment_checks, File "/home/neo/.local/lib/python3.5/site-packages/django/core/management/base.py", line 351, in _run_checks return checks.run_checks(**kwargs) File "/home/neo/.local/lib/python3.5/site-packages/django/core/checks/registry.py", line 73, in run_checks new_errors = check(app_configs=app_configs) File "/home/neo/.local/lib/python3.5/site-packages/django/core/checks/urls.py", line 13, in check_url_config return check_resolver(resolver) File "/home/neo/.local/lib/python3.5/site-packages/django/core/checks/urls.py", line 23, in check_resolver return check_method() File "/home/neo/.local/lib/python3.5/site-packages/django/urls/resolvers.py", line 398, in check warnings.extend(check_resolver(pattern)) File "/home/neo/.local/lib/python3.5/site-packages/django/core/checks/urls.py", line 23, in check_resolver return check_method() File "/home/neo/.local/lib/python3.5/site-packages/django/urls/resolvers.py", line 397, in check for pattern in self.url_patterns: File "/home/neo/.local/lib/python3.5/site-packages/django/utils/functional.py", line 36, in get res = instance.dict[self.name] = self.func(instance) File "/home/neo/.local/lib/python3.5/site-packages/django/urls/resolvers.py", line 545, in url_patterns raise ImproperlyConfigured(msg.format(name=self.urlconf_name)) django.core.exceptions.ImproperlyConfigured: The included URLconf '' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import. my app's code : (/django-examples/mysite): (Setting.py) INSTALLED_APPS … -
404 error , Get Object or 404 django
Hey guys i have made a blog website in which if i type in the number beside like this: blog/1, I should get the first blog or i should get a 404 error! but i only get the 404 error whereas i have the blogs! My project name is portfolio-project and the urls.py for it look like: from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static import blog.views urlpatterns = [ path('admin/', admin.site.urls), path('', blog.views.home, name='home'), path('blog/', include('blog.urls')), ]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) And then it goes to blog.urls, and it looks like: from django.urls import path from . import views urlpatterns = [ path('', views.home, name='allblogs'), path('<int:blog_id>/', views.detail, name='detail'), ] as i put blog/1 It goes to the views.detail file which looks like this: from django.shortcuts import render, get_object_or_404 from .models import Blog def home(request): blogs = Blog.objects return render(request, 'blog/home.html', {'blogs':blogs}) def detail(request, blog_id): detailblog = get_object_or_404(Blog, pk=blog_id) return render(request, 'blog/detail.html', {'blog':detailblog}) Ok, So according to this i should go to the details.html and it has {{ blog.title }} But i dont see anything but an 404 error! -
How to retrieve data from database sqlite3 and then show to django view?
I want to show my csv data into my django views.In this case i used pandas.I pushed data in database using pandas.to_sql method.like this way `db_name='db.sqlite3' engine = sqlalchemy.create_engine("sqlite:///%s" % db_name) df2.to_sql('xCompany', engine)` This works fine.If i checked my database it will show tables like this(xCompany_data).here,you see index,0,1...etc as a column name. In normal way we fast create manually our model in django then retrieve it and show the view.In my case it will create automatically based on pandas data frame.how can see my model 'xCompany' which was created to_sql() method .How can i retrieve data from this model and how to deal with django views. -
Your WSGIPath refers to a file that does not exist for django application
I have deployed Django application in AWS Elastic Beanstalk server. I have .extensions folder and there I have wrote django.config file. In django.config file have following code. option_settings: aws:elasticbeanstalk:container:python: WSGIPath: ebdjango/wsgi.py When I deploy django application then showing Your WSGIPath refers to a file that does not exist. -
django modelform submission
I am working on a django project, The model CaseRegister i am trying to submit values using model form. My model class belo - model.py from django.db import models from core.models import ProviderMaster,FacilityMaster,ProviderMaster,CaseMaster,CasestatusMaster from patient.models import PatientMaster from django.contrib.auth.models import User from django.forms import ModelForm from account.models import Profile def update_id(func): def decorated_function(*args): data_object = args[0] sequence_name = 'seq_%s' % data_object._meta.db_table from django.db import connection cursor = connection.cursor() cursor.execute("SELECT nextval(%s)", [sequence_name]) row = cursor.fetchone() data_object.caseid = row[0] return func(*args) return decorated_function class CaseRegister(models.Model): caseid = models.DecimalField(primary_key=True, max_digits=8, decimal_places=0) patient = models.ForeignKey(PatientMaster, on_delete=models.CASCADE, db_column='patientid') case_startdate = models.DateField() case_enddate = models.DateField(blank=True, null=True) providerid = models.ForeignKey(ProviderMaster, models.DO_NOTHING, db_column='providerid', blank=True, null=True) facilityid = models.ForeignKey(FacilityMaster, models.DO_NOTHING, db_column='facilityid', blank=True, null=True) casetypeid = models.ForeignKey(CaseMaster, models.DO_NOTHING, db_column='casetypeid', blank=True, null=True) casestatus = models.ForeignKey(CasestatusMaster, models.DO_NOTHING, db_column='casestatus', blank=True, null=True) approved_date = models.DateField(blank=True, null=True) last_modifieduser = models.ForeignKey(Profile,on_delete=models.CASCADE, db_column='last_modifieduser') class Meta: managed = False db_table = 'case_register' def __str__(self): return self.caseid @update_id def save(self): # Now actually save the object. super(CaseRegister, self).save() The form is created as below and mapped query set for all FK fields - The form.py from django import forms from .models import CaseRegister from patient.models import PatientMaster from django.contrib.auth.models import User from account.models import Profile,ProfileFaciltiyMembership from core.models import FacilityMaster,CasestatusMaster,ProviderMaster,ProviderCategory,RoleMaster … -
Django REST Framework - CSRF token missing in Login API view
I made Login API in Django REST framework and I'm getting this error CSRF Failed: CSRF token missing or incorrect. Everything works perfectly in a browser but in Postman I'm getting above error. Here is my code: api/views.py class UserLoginAPI(views.APIView): # authentication_classes = (SessionAuthentication, BasicAuthentication) serializer_class = UserLoginSerializer def post(self, request, *args, **kwargs): data = request.data # request.POST serializer = UserLoginSerializer(data=data) if serializer.is_valid(raise_exception=True): new_data = serializer.data user = authenticate( username=new_data['username'], password=new_data['password']) login(request, user) return Response(new_data, status=HTTP_200_OK) new_data = { 'test': 10 } return Response(new_data) api/serializers.py class UserLoginSerializer(serializers.ModelSerializer): username = serializers.CharField(required=False, allow_blank=True) status = serializers.CharField(allow_blank=True, read_only=True) class Meta: model = User fields = [ 'username', 'password', 'status' ] def validate(self, data): user_obj = None username = data.get("username", None) password = data["password"] if not username: raise ValidationError("Musisz podac nazwe uzytkownika.") user = User.objects.filter( Q(username=username) ).distinct() if user.exists() and user.count() == 1: user_obj = user.first() else: raise ValidationError("Zła nazwa użytkownika.") if user_obj: if not user_obj.check_password(password): raise ValidationError("Podano złe dane") data['status'] = "Logged in" return data I don't know what I'm doing wrong. Thanks in advance for the help!