Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
two-stage submission of django forms
I have a django model that looks something like this: class MyModel(models.Model): a = models.BooleanField(default=False) b = models.CharField(max_length=33, blank=False) c = models.CharField(max_length=40, blank=True) and a corresponding form class MyForm(ModelForm): class Meta: model = MyModel Asking the user to fill in the form is a two phase process. First I ask whether a is True or False. After a submit (would be better maybe with ajax, but keep it simple at first) I can fill in a dropdown list with choices for b and decide whether or not to show c as an option. No need to show a as a choice any more, it's descriptive text. So I want to present a form twice, and the same model is behind it, slowly being filled in. First choose a, then be reminded that a is True and be asked about b and c. Or that a is False and be asked about only b. After submitting this second form, I save the object. I'm not clear how best to do this in django. One way is to make two separate form classes, one of which has hidden fields. But if the same model is behind both and the model has required … -
Django : TypeError: Object of type 'ProgrammingError' is not JSON serializable
I have these Serializer on my Django Project class CashbackDetailSerializer(serializers.ModelSerializer): id = serializers.SerializerMethodField() class Meta: model = Cashback fields = ['id'] def get_id(self, obj): return obj.transaction_id and then on the view i have this data that will be returned when the POST success returned_Data = { 'data': CashbackDetailSerializer(cashback).data } if cashback_code is not None: cashback = Cashback.objects.get(cashback_code__iexact=cashback_code) cashback_amount = cashback.amount return_value.update({ 'amount_cashback':cashback_amount }) but i keep getting these error TypeError: Object of type 'ProgrammingError' is not JSON serializable where did i go wrong ? -
Django and sites: reloading staging db
Loading production snapshots of my django database on staging used to be easy: python manage dumpdata / python manage loaddata or even pg_dump / pg_restore. We're now using the Sites module and detecting site based on http request. (Setting by primary key in the Sites table is fragile.) So if I do the dump/restore above, I'll overwrite Sites hostnames. Production is expecting site names like 'www.example.com' while staging is expecting names like 'staging.example.com'. One way around this is to write some wrapper around the dump/restore so that the site data is modified on restore. Another solution (which I believe would fail, see next sentence) is just to enter the staging site data in production so that it is present on staging. A problem with this last approach is site equivalence: some features activate if site is example.com but not example.de, say, and the models that do this key on site.id, which is different between www and staging. Are there common idioms for approaching this that I've missed? I'm sure I can get this to work, but I'm merely concerned that I haven't seen "best practice" advice on this, which makes me think I've missed something. Thanks for any tips. -
Why the data from the database is not displayed in the Frontend?
I'm trying to fetch data from my database to the frontend and display with datatables. This is what my view function looks like: (I tried both the comment part too but without success) def displayPatientsToFrontend(request): patients = Patient.objects.all() #patients_json = serializers.serialize('json', patients) #return JsonResponse({'patients_json': patients_json}) return JsonResponse({'patients': patients}) my jQuery script: $(document).ready(function() { var data; fetch("http://192.168.1.32:8000/displayPatientsToFrontend/") //.then(response => response.text()) //.then(text => console.log("text is: " + text)) .then(response => response.json()) .then(json => data = json) .then(() => {console.log(data); $('#datatable').DataTable( { data: data.patients, deferRender: true, scrollY: false, scrollX: false, scrollCollapse: true, scroller: true, columns: [ { data: "id" }, { data: "first_name" }, { data: "last_name" }, { data: "email" }, { data: "date1" }, { data: "date2" }, ] } ) }) } ); The problem is that the data doesn't want to display in the datatables. I believe there is a mistake in the promise in the jQuery script. The error I got is: Failed to load resource: the server responded with a status of 404 (Not Found) and Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0 this is from DevTool and from django terminal I got: ** Not Found: /displayPatientsToFrontend/ ** Of course I define … -
Django - get newest entry from each related set
I have the following Django models : class SearchQuery(models.Model): query = models.CharField(max_length = 512) ...etc class Crawl(models.Model): query = models.ForeignKey('SearchQuery', on_delete = models.CASCADE) status = models.CharField(max_length = 512) date = models.DateTimeField(default = timezone.now) ...etc I have the following entries in SearchQuery : id | query | Other columns 1 | cars are cool | 2 | how to cook | 3 | how to cook | There may be search query objects with similar queries (like 2 and 3 in the example) but different other parameters (they are distinguished based on ID) I have the following entries in Crawl : id | query | status | date | Other columns 1 | cars are cool (1) | Found | 2021-01-01 03:15 | 2 | how to cook (2) | Not Found | 2021-01-01 03:23 | 3 | how to cook (3) | Found | 2021-01-01 03:25 | 4 | how to cook (2) | Blocked | 2021-01-01 03:29 | I would like to get each search query with its latest crawl. (i want to get the date of the latest crawl and its status) So something like this id (SearchQuery) | query (SearchQuery) | latest_crawl_status | latest_crawl_date 1 | cars … -
How hide text 'next' in infinity pagination (waypoint Django spinner)
I made infinity pagination with spinner. I used jquery waypoints. Everything works fine but there is one inconvenience. Before spinner is showing up it shows text "Next" from 'infinite-more-link' class How fix this? I want show only spinner without text "Next" When I deleted 'Next' infinity pagination doesn't work. {% block body %} <div class="infinite-container"> <div class="infinite-item"> {% for post in all_posts %} {{ post.title }} {% endfor %} </div> </div> <div class="loading"> <div class="d-flex justify-content-center"> <div class="spinner-border" role="status"> <span class="sr-only">Loading...</span> </div> </div> </div> {% if page_obj.has_next %} <a class="infinite-more-link" href="?page={{ page_obj.next_page_number }} ">Next</a> {% endif %} {% endblock %} {% block scripts %} <script src="{% static "js/jquery.waypoints.min.js" %}"></script> <script src="{% static "js/infinite.min.js" %}"></script> <script> var infinite = new Waypoint.Infinite({ element: $('.infinite-container')[0], offset: 'bottom-in-view', onBeforePageLoad() { $('.loading').show(); }, onAfterPageLoad: function () { $(`.loading`).hide(); } }); </script> {% endblock %} And this is base.html {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" name="viewport" content="width=device-width, initial-scale=1.0"> {% block css %}{% endblock %} <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous"> <script src="https://kit.fontawesome.com/f558545230.js" crossorigin="anonymous"></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <title>{% block title %}{% endblock %}</title> </head> <body> {% block body %}{% endblock %} <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script> {% block scripts %}{% endblock … -
why my datatable pagination doesn't work after updating tbody html contents by ajax request?
Here datatable pagination doesnot work when the table tbody html contents gets updated with ajax call. I am updating html content on ajax success but after updating the datatable pagination doesn't work properly. How can I solve this issue ? datatable $('#results').dataTable({ "autoWidth": false, "lengthChange": false, "pageLength": 3, searching: false, "bSort" : false,,, ajax <script> $('#id').on('change', function(e) { e.preventDefault(); $.ajax({ type: "GET", url: "{% url 'sort-results' %}", data: { 'query' : $('#id').val(), }, success: sortSuccess, dataType: 'html' }); }); function sortSuccess(data, textStatus, jqXHR){ $('#results tbody').html(data); } </script> results.html {% for res in results %} .. {% endfor %} main_template <table id="results"> <thead> <tr> <th></th> </tr> </thead> <tbody> {% include 'results.html' %} </tbody> </table> django view class SortResults(View): def get(self, request, *args, **kwargs): query = request.GET.get('query') results_qs = Model.objects.all() if query == 'recent': results = results_qs.order_by('-date') return render(request, 'results.html', {'results': results}) -
Google Analytics Account implementation in Python Django
Write now i am fetching the details of the users from Google Analytics Account. They are: 1: sessions 2: Bounce Rate 3: Average session Duration 4: New users 5: page view 6: Session Per user 7: page view per session from googleapiclient.discovery import build from oauth2client.service_account import ServiceAccountCredentials SCOPES = ['https://www.googleapis.com/auth/analytics.readonly'] KEY_FILE_LOCATION = 'samplet.json' VIEW_ID = '216282641' def initialize_analyticsreporting(): """Initializes an Analytics Reporting API V4 service object. Returns: An authorized Analytics Reporting API V4 service object. """ credentials = ServiceAccountCredentials.from_json_keyfile_name( KEY_FILE_LOCATION, SCOPES) # Build the service object. analytics = build('analyticsreporting', 'v4', credentials=credentials) return analytics def get_report(analytics, from_date, to_date): """Queries the Analytics Reporting API V4. Args: analytics: An authorized Analytics Reporting API V4 service object. Returns: The Analytics Reporting API V4 response. """ metrics_value = analytics.reports().batchGet( body={ 'reportRequests': [ { 'viewId': VIEW_ID, 'dateRanges': [{'startDate': from_date, 'endDate': to_date}], 'metrics': [{'expression': 'ga:sessions'}, {'expression': 'ga:bounceRate'}, {'expression': 'ga:avgSessionDuration'}, {'expression':ga:users'}, {'expression': 'ga:newUsers'}, {'expression': 'ga:pageviews'}, {'expression': 'ga:pageviewsPerSession'}, {'expression':'ga:sessionsPerUser'}], }] } ).execute() dimensions_value = analytics.reports().batchGet( body={ 'reportRequests': [ { 'viewId': VIEW_ID, 'dateRanges': [{'startDate': from_date, 'endDate': to_date}], 'metrics': {'expression': 'ga:users'}, "dimensions": {"name": "ga:day"} }] } ).execute() metric_value = '' for report in metrics_value.get('reports'): for row in report.get('data').get('rows'): dateRangeValues = row.get('metrics') metrics_value = dateRangeValues[0].values() for each in metrics_value: metric_value = … -
I want to sum values of two cells and display them in another cell in django
models.py class Report(models.Model):<br> msp = models.IntegerField(blank=True, null=True) msp2 = models.IntegerField(blank=True, null=True) ago = models.IntegerField(blank=True, null=True) total = models.IntegerField(blank=True, null=True) date_posted = models.DateTimeField(auto_now=True) def __str__(self): return 'Report{}'.format(self.id) class Meta: verbose_name_plural = 'Reports' views.py def view(request):<br> open_stock = Report.objects.all() msp = Report.objects.get(msp) context = {'open_stock': open_stock} return render(request, 'Strt/view.html', context) -
Django Difficult! : 'Account' object has no attribute 'has_perms'
AttributeError at /HomeFeed/blog/1/testuser1-2/member-list/ 'Account' object has no attribute 'has_perms' Hi, tbh I'm not even sure whats causing the error. After some research I realised it might have something to do with AbstractBaseUser, but I'm unsure of what exactly is causing it. Basically I'm trying to direct to a list of members in the blog post. Theres should be nothing wrong with my template. The error is either with my views or my models. Let me know if you need additional information... views.py class DetailBlogPostView(BlogPostMixin,DetailView): template_name = 'HomeFeed/detail_blog.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) blog_post=self.get_object() blog_post.save() context['blog_post'] = blog_post return context class MemberListView(LoginRequiredMixin,PermissionRequiredMixin,BlogPostMixin, DetailView): template_name = "HomeFeed/membersof_yourpost.html" permission_required = ('blogpost.view_all_blogpost_members',) detail_blog.html: <h3><a href='{% url "HomeFeed:member_list" blog_post.pk blog_post.slug %}'>View my blog's members list</a></h3> models.py class Account(AbstractBaseUser): email = models.EmailField(verbose_name="email", max_length=60, unique=True) username = models.CharField(max_length=30, unique=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) objects = MyAccountManager() #For checking permissions. to keep it simple all admin have ALL permissons def has_perm(self, perm, obj=None): return self.is_admin class BlogPost(models.Model): chief_title = models.CharField(max_length=50, null=False, blank=False, unique=True) brief_description = models.TextField(max_length=300, null=False, blank=False) body = models.TextField(max_length=5000, null=False, blank=False) members = models.ManyToManyField(settings.AUTH_USER_MODEL, blank=True, related_name="members") urls.py path("blog/<pk>/<slug>/member-list/", MemberListView.as_view(), name="member_list"), path('<slug>/detail/', DetailBlogPostView.as_view(), name= "detail"), path('<user_id>/', account_view, name="view"), … -
NoReverseMatch: Reverse for 'view' with keyword arguments '{'user_id': ''}' not found. 1 pattern(s) tried: ['account/(?P<user_id>[^/]+)/$']
I am trying to query the list of people that liked my blogpost, however i am receiving an error that says no reverse match. Is there any way to get rid of the error without changing my url. I believe there is something that i can specify on my template like the user_id to solve this error. I have tried user_id=user_id but it didnt work. Any help is appreciated with thanks! detail_blog.html <p>Users that has liked your post:</p> {% for user in blog_post.likes.all %} <a class="dropdown-item" href="{% url 'account:view' user.pk %}"> {{ user.username }} </a> {% endfor %} urls.py path('<user_id>/', account_view, name="view"), models.py class Account(AbstractBaseUser): email = models.EmailField(verbose_name="email", max_length=60, unique=True) username = models.CharField(max_length=30, unique=True) view.py class DetailBlogPostView(BlogPostMixin,DetailView): template_name = 'HomeFeed/detail_blog.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) blog_post=self.get_object() context['liked'] = True if blog_post.likes.filter(id=self.request.user.id).exists() else False blog_post.save() context['blog_post'] = blog_post return context TraceBack: Traceback (most recent call last): File "lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "lib/python3.8/site-packages/django/core/handlers/base.py", line 145, in _get_response response = self.process_exception_by_middleware(e, request) File "lib/python3.8/site-packages/django/core/handlers/base.py", line 143, in _get_response response = response.render() File "/lib/python3.8/site-packages/django/template/response.py", line 106, in render self.content = self.rendered_content File "/lib/python3.8/site-packages/django/template/response.py", line 83, in rendered_content content = template.render(context, self._request) File "/lib/python3.8/site-packages/django/template/backends/django.py", line 61, in render return … -
Too many redirect error with nginx and django
I had my website up and running, I made some changes to html templates and restart gunicorn with kill -HUP <pid> reading the official documentation. After that I'm facing this ERR_TOO_MANY_REDIRECTS on browser. What could be wrong in my nginx conf file for this to happen and how can I avoid the same making changes to HTML files in future? I also tried changing SECURE_SSL_REDIRECT = True. to False in my project settings but that didn't help either. upstream capngo_server { server unix:/home/uday/website/cap_env/run/gunicorn.sock fail_timeout=0; } server { server_name capfoundationindia.com www.capfoundationindia.com; client_max_body_size 4G; access_log /home/uday/logs/nginx-access.log; error_log /home/uday/logs/nginx-access.log; location / { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_hedaer X-Forwarded-Proto https; proxy_set_header Host $https_host; proxy_redirect off; if (!-f $request_filename) { proxy_pass http://capngo_server; break; } } listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/capfoundationindia.com/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/capfoundation.com/privkey.pem; # managed by Certbot include /etc/letsencrypt/options-ssl--nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencypt/ssl-dhparrams.pem; # managed by Certbot server { if ($host = capfoundationindia.com) { return 301 https://$host$request_uri; } # managed by Certbot listen 80; server_name capfoundation.com www.capfoundation.com; retrun 404; # managed by Certbot } -
'str' object has no attribute 'get' when redirect to login page
i have a link and when i click on it i need to redirect to the login page if the user is not logged in. this is my link: <a href="{{ request.scheme }}://{{ request.get_host }}{% url 'join_miz_email' id=meeting.pk email=email %}" and this is my url : path('joinmizemail/<uuid:id>/<str:email>',join_miz, name="join_miz_email"), and this is my join_miz function: @login_required def join_miz(request,id,email=None): print(email) if request.user.email == email: logout(request) return('register_login_landing') else: meeting = get_object_or_404(Meeting,pk=id) try : meeting_member= get_object_or_404(MeetingMember,meeting=meeting) return redirect('index') except: member = MeetingMember(meeting = meeting, user = request.user,status="A") member.save() return redirect(reverse('meeting-info',args=(meeting.pk,))) and this this the login function: def register_login_landing(request): if request.user.is_authenticated: return redirect('index') return render(request, "../templates/templates_v2/register-login-landing.html",context={'next':request.GET.get('next')}) and input in html form: <input type="hidden" name="next" value="{{next}}"/> but i get this error : AttributeError at /meeting/joinmizemail/57e27cda-227f-4e60-a9c5-5493bf8e5961/niloofarharooni29@gmail.com 'str' object has no attribute 'get' what should i do? -
How can I pass multiple values for a single parameter into the API url in Django Rest Framework?
I have made a filter api like this. localhost/api/allpackages?price_min=700&price_max=900&destination=Spain&new_activity=Swimming&tour_type=Group%20Tour&featured=true&fix_departure=true But according to new changes, I should be able to filter like this localhost/api/allpackages?destination=Spain&destination=Japan&destination=Thailand....featured=true... There can be multiple values for a single parameter, beacause user can now clik the chekboxes on the frontend. How can I achieve this? My models: class Package(models.Model): operator = models.ForeignKey(UserProfile, on_delete=models.CASCADE) destination = models.ForeignKey(Destination, on_delete=models.CASCADE) package_name = models.CharField(max_length=255) featured = models.BooleanField(default=False) price = models.IntegerField() duration = models.IntegerField(default=5) discount = models.CharField(max_length=255, default="15% OFF") discounted_price = models.IntegerField(default=230) savings = models.IntegerField(default=230) tour_type = models.CharField(max_length=100, choices=TOUR_TYPE, default='Group Tour') new_activity = models.ManyToManyField(NewActivity) accommodation = models.CharField(max_length=255,default='Guest House & Hotel') transport = models.CharField(max_length=150, default='Flight') age_range = models.CharField(max_length=100, default='6 to 79 years old') fix_departure = models.BooleanField(default=False) .... ... My views: class AllPackageAPIView(ListAPIView): queryset = Package.objects.all() serializer_class = PackageSerializer filterset_class = PackageFilter def get_queryset(self): new_activity = self.request.query_params.get('new_activity', None) destination = self.request.query_params.get('destination', None) if new_activity is not None: if destination is not None: return Package.objects.filter(destination__name=destination, new_activity__title=new_activity) else: return Package.objects.filter(new_activity__title=new_activity) elif destination is not None: if new_activity is not None: return Package.objects.filter(destination__name=destination, new_activity__title=new_activity) else: return Package.objects.filter(destination__name=destination) else: return Package.objects.all() My filter: class PackageFilter(filters.FilterSet): price = filters.RangeFilter() class Meta: model = Package fields = ['price','featured', 'fix_departure', 'tour_type',] My serializers: class PackageSerializer(serializers.ModelSerializer): class Meta: model = Package fields = … -
Django : API Endpoint not created after creating a method in Viewset in Django
I have created a tags method in the Startup viewset and have used @action decorator to treat it as an API viewpoint but when I see all the urls of my project, the endpoint has not been created. All the urls are shown below Routers file is shown below - I want to create an api endpoint at the url - 'http://127.0.0.1:8000/api/v1/startup/startup-name/tags' -
How to group child as a nested list for each parent?
This is a survey system The question is "How to properly serialize data to get nested answers under every question" (group answers as a nested list for each question)? Models class Survey(models.Model): name = models.CharField(max_length=150) start_at = models.DateTimeField(db_index=True) finish_at = models.DateTimeField(db_index=True) class Question(models.Model): QUESTION_TYPE = ( ("text", "Text answer"), ("choice", "Choose one option"), ("choice_multiple", "Choose many options") ) text = models.TextField(max_length=300) type = models.CharField(max_length=15, choices=QUESTION_TYPE) order_num = models.IntegerField() survey = models.ForeignKey(Survey, related_name="questions", on_delete=models.CASCADE) class Choice(models.Model): text = models.CharField(max_length=300) question = models.ForeignKey(Question, related_name="choices", on_delete=models.CASCADE) class SurveyResult(models.Model): survey = models.ForeignKey(Survey, related_name="results", on_delete=models.CASCADE) user = models.ForeignKey(User, null=True, blank=True, related_name="surveys", on_delete=models.DO_NOTHING) class Answer(models.Model): survey_result = models.ForeignKey(SurveyResult, related_name="answers", on_delete=models.CASCADE) question = models.ForeignKey(Question, related_name="answers", on_delete=models.DO_NOTHING) choice = models.ForeignKey(Choice, related_name="answer_choices", null=True, blank=True, on_delete=models.DO_NOTHING, default=None) text = models.CharField(max_length=300, null=True, blank=True, default=None) Serializers class QuestionSerializer(serializers.ModelSerializer): class Meta: model = Question fields = ["id", "type", "order_num", "text", "choices"] class AnswerListSerializer(serializers.ModelSerializer): question = QuestionSerializer(read_only=True) class Meta: model = Answer fields = ["id", "question", "choice", "text", ] class SurveyListSerializer(serializers.ModelSerializer): answers = AnswerListSerializer(many=True) class Meta: model = SurveyResult fields = ["id", "survey", "user", "created_at", "answers", ] View class SurveyViewSet(CreateModelMixin, ListModelMixin, RetrieveModelMixin, GenericViewSet): queryset = SurveyResult.objects.all().prefetch_related( "answers", "answers__question", "answers__question__choices") pagination_class = PageNumberPagination permission_classes = [AllowAny] Result "id": 2, "survey": 1, "user": 18, "answers": [ … -
How to Enable iterative calculation in openpyxl?
is this way to enable iterative calculation Programmatically? -
Can't get data from ManyToMany relat in Django
I have two models like this: class Book(models.Model): name = models.CharField(blank=True, max_length=128) description = models.TextField(blank=True) count = models.IntegerField(default=10) authors = models.ManyToManyField(Author, related_name='books') and class Author(models.Model): name = models.CharField(blank=True, max_length=20) surname = models.CharField(blank=True, max_length=20) patronymic = models.CharField(blank=True, max_length=20) Now, question - how can I print name and surname of author of the certain book? -
Unable to communicate with postgres using docker and django
I don't achieve to communicate with my database postgres using Docker and Django. Here is my docker-compose.yml : version: '3' services: web: container_name: web build: context: ./web dockerfile: Dockerfile command: python manage.py runserver 0.0.0.0:8000 volumes: - ./web/:/usr/src/web/ ports: - 8000:8000 - 3000:3000 - 35729:35729 env_file: - database.env stdin_open: true depends_on: - database database: container_name: database image: postgres volumes: - database-data:/var/lib/postgresql/data/ ports: - 5432:5432 volumes: database-data: Here is my database.env : # database.env POSTGRES_USERNAME=admin POSTGRES_PASSWORD=pass POSTGRES_DBNAME=db POSTGRES_HOST=database POSTGRES_PORT=5432 PGUSER=admin PGPASSWORD=pass PGDATABASE=db PGHOST=database PGPORT=5432 DATABASE=db SQL_HOST=database SQL_PORT=5432 And here is my Dockerfile : # pull official base image FROM python:3.8.3-alpine # set work directory WORKDIR /usr/src/web # set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # install psycopg2 dependencies RUN apk update \ && apk add postgresql-dev gcc python3-dev musl-dev RUN apk add zlib-dev jpeg-dev gcc musl-dev # install nodejs RUN apk add --update nodejs nodejs-npm # copy project ADD . . # install dependencies RUN pip install --upgrade pip RUN pip install -r requirements.txt # run entrypoint.sh ENTRYPOINT ["sh", "/usr/src/web/entrypoint.sh"] And there my entrypoint.sh : #!/bin/sh if [ "$DATABASE" = "db" ] then echo "Waiting for postgres..." while ! nc -z $SQL_HOST $SQL_PORT; do sleep 10 done echo "PostgreSQL started" … -
when a user give information than it comes in admin how i can do this in django
When a user give a information in my site suppose user give when he needs a appointment, which doctor he need to appointment . So how i can see the data. -
How to delete a record through a button in django
I have created a model Announcement in models.py file class Announcement(models.Model): title = models.CharField(max_length=30) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) teacher = models.ForeignKey(Teacher, on_delete=models.CASCADE) def __str__(self): return self.title And for deleting a record of Announcement I have created the following view def AnnouncementDelete(request, pk): announcement = get_object_or_404(Announcement, pk=pk) if request.method=='POST': announcement.delete() return redirect('/') return render(request, 'classroom/announcement_confirm_delete.html', {'announcement': announcement}) The delete view of announcement (that is AnnouncementDelete) has the following url path("delete/<int:pk>/", view=views.AnnouncementDelete, name="AnnouncementDelete"), If i enter http://127.0.0.1:8000/classroom/delete/3 on browser it is deleting the Announcement having pk = 3 Now I want a button to directly delete my record without the need of typing http://127.0.0.1:8000/classroom/delete/3 on browser I have tried the following methods in my allannouncement.html file {% extends "classroom/base.html" %} {% block content %} <h1>Announcements</h1> {% for announcement in announcements %} <!-- starting loop (posts is keyword from view) --> <div style="border-style: solid;"> {% if announcement.teacher.user == request.user %} <div> <a href="{% url 'classroom:AnnouncementDelete' %}">Delete</a> </div> {% endif %} {{ announcement.pk }} <a class="mr-2">Posted by: {{ announcement.teacher }}</a> <h2><a class="article-title">{{ announcement.title }}</a></h2> <p class="article-content">{{ announcement.content}}</p> </div> {% endfor %} {% endblock content %} but it is giving the following error NoReverseMatch at /classroom/allannouncement/ Reverse for 'AnnouncementDelete' with no arguments not … -
check if POST request exist in database and return custom response in django rest framework
i am creating basic Coupon verification Django Rest framework APP, i just want to pass json parameter through Postman and get custom response if coupon code is valid or invalid. Here is my models.py File: from django.db import models # Create your models here. class Coupon(models.Model): code = models.CharField(primary_key=True, max_length=50, unique=True) def __str__(self): return self.code Here is my Serializers.py file: from rest_framework import serializers from .models import Coupon class CouponSerializer(serializers.ModelSerializer): class Meta: model = Coupon fields = '__all__' I like to write views for given serializer and get custom message as mentioned above. -
Datatable not working with filtered results from views?
Here datatable pagination doesnot work with the view SortResults. It filters the table but the pagination doesnot work. Initially results are sent to the main-template from another view like this MyModel.objects.all() in this case the pagination works. But applying filter and ajax, pagination doesnot work . ajax <script> $('#sort').on('change', function(e) { e.preventDefault(); $.ajax({ type: "GET", url: "{% url 'sort-results' %}", data: { 'query' : $('#id').val(), }, success: sortSuccess, dataType: 'html' }); }); function sortSuccess(data, textStatus, jqXHR) { $('#results').html(data) } </script> views class SortResults(View): def get(self, request, *args, **kwargs): query = request.GET.get('query', '') if query == 'recent': results =MyModel.objects.all().order_by('-date') return render(request, 'results.html', {'results': results}) results.html {% for res in results %} some data {% endfor %} main-template <table id="results"> <thead> <tr> <th></th> </tr> </thead> <tbody> {% include 'results.html' %} </tbody> </table> -
How to check user email address valid or not in django can anyone have idea to check user interring email address is valid or not
How we can know user email address is valid or not without sending a link is there any method to do this in django , i just try to check the user their email address is valid or not . -
Django : attribute not defined in the "models.py" file
My "models.py" file has the following code: from django.db import models # Create your models here. class Questions(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') class Choice (models.Model): choice_text = models.CharField(max_length=200) votes = models.IntegerFeild(default = 0 ) question = models.ForeignKey(Question, on_delete=models.CASCADE) The error I am getting while running the code is: votes = models.IntegerFeild(default = 0 ) AttributeError: module 'django.db.models' has no attribute 'IntegerFeild'