Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
unable to start uwsgi with encodings error in uwsgi 2.0.18 and python 3.6.9
I'm having serious trouble to start uwsgi in django project with nginx. I even tried to run plugins=python36 but still failed. I checked uWSGI Fails with No module named encoding Error but doesn't help me. I still have no idea how to fix the ModuleNotFoundError: No module named 'encodings'. Could you please advise and help me out? Thanks!! Here's the versions info: Python 3.6.9 uwsgi 2.0.18 nginx version: nginx/1.14.0 (Ubuntu) /usr/local/bin/uwsgi I got the following error when running sudo uwsgi --ini /usr/share/nginx/html/portal/portal_uwsgi.ini [uWSGI] getting INI configuration from /usr/share/nginx/html/portal/portal_uwsgi.ini open("./python3_plugin.so"): No such file or directory [core/utils.c line 3724] !!! UNABLE to load uWSGI plugin: ./python3_plugin.so: cannot open shared object file: No such file or directory !!! *** Starting uWSGI 2.0.18 (64bit) on [Thu Jun 18 22:51:54 2020] *** compiled with version: 7.5.0 on 11 June 2020 23:01:20 os: Linux-5.3.0-59-generic #53~18.04.1-Ubuntu SMP Thu Jun 4 14:58:26 UTC 2020 machine: x86_64 clock source: unix detected number of CPU cores: 4 detected binary path: /usr/local/bin/uwsgi !!! no internal routing support, rebuild with pcre support !!! uWSGI running as root, you can use --uid/--gid/--chroot options *** WARNING: you are running uWSGI as root !!! (use the --uid flag) *** chdir() to /usr/share/nginx/html/portal your processes number … -
Same Apis Giving different output on different servers in django
enter image description here This is output in my Local System , which is using python 3.6.9 with Django rest framework 3.11.0 And another image is below enter image description here This is the same Django view which is running on remote Machine with same code base but with Python version 3.6.10 with the same Django Rest Framework version 3.11.0 . I am confused and I searched about what can be a glitch , I see the output coming on remote is a Dictionary in which there is a "result" key But in My local Environment its simply returning the list of data . I don't think python version could cause that trouble , If anyone can let me know what can go wrong . View is using Generic class and its List enter image description here This is the View which is same on both the machines. ` class DoctorListApiView(generics.ListAPIView): serializer_class = DoctorListSerializer def get_queryset(self): valid_user = False # get data in header (patient's phone number) patient_username = self.request.META['HTTP_X_USERNAME'] try: user_obj = UserProfile.objects.get(phone = patient_username) hospital_code = user_obj.hospital_code if hospital_code == None : pass else: partner_code = PartnerDatabase.objects.get(hospital_code = hospital_code).partner_code # print('Hospital Code : ' + str(hospital_code)) # print('Partner … -
Set Django JSONField value to a JSON null singleton with the Django ORM
Using a Django JSONField on PostgreSQL, say I have the following model class Foo(models.Model): bar = models.JSONField(null=False) and I want to set a row to have bar=null where null is a single JSON null value (different to a database NULL value). I can achieve it through a raw SQL query: UPDATE "myapp_foo" SET "bar" = 'null'::jsonb WHERE "myapp_foo"."id" = <relevant_id> The closest things I can do in the ORM is Foo.objects.filter(id=<relevant_id>).update(bar=None) but Django is interpreting this as a database NULL and I get the following error: null value in column "bar" violates not-null constraint or Foo.objects.filter(id=<relevant_id>).update(bar="null") but Django (correctly) interprets this as the JSON string "null" Am I missing something or is this a gap in the ORM functionality? -
Model foreign key field empty
I have two models Order and a date model. The order model has a foreign key attribute of date model. I have made a form in which I can update the date fields of order, but when I click submit it creates a new date object in date model not in the order date field. I want my form to save values in the date field in order. models.py class Order(models.Model): date = models.ForeignKey('date', null=True, on_delete=models.CASCADE) user = models.ForeignKey(User, null=True, on_delete=models.CASCADE) quote_choices = ( ('Movie', 'Movie'), ('Inspiration', 'Inspiration'), ('Language', 'Language'), ) quote = models.CharField(max_length =100, choices = quote_choices) box_choices = (('Colors', 'Colors'), ('Crossover', 'Crossover'), ) box = models.CharField(max_length = 100, choices = box_choices) pill_choice = models.CharField(max_length=30) shipping_tracking = models.CharField(max_length=30) memo = models.CharField(max_length=100) status_choices = (('Received', 'Received'), ('Scheduled', 'Scheduled'), ('Processing/Manufacturing', 'Processing/Manufacturing'), ('In Progress','In Progress'), ) status = models.CharField(max_length = 100, choices = status_choices, default="In Progress") def __str__(self): return f"{self.user_id}-{self.pk}" class Date(models.Model): date_added = models.DateField(max_length=100) scheduled_date = models.DateField(max_length=100) service_period = models.DateField(max_length=100) modified_date = models.DateField(max_length=100) finish_date = models.DateField(max_length=100) view.py def dateDetailView(request, pk): order = Order.objects.get(pk=pk) date_instance = order.date form = DateForm(request.POST, request.FILES, instance=date_instance) if request.method == 'POST': if form.is_valid(): order = form.save(commit = False) order.date = date_instance order.save() context = { 'order':order,'form':form } … -
ReportLab : How to retrieve data from database
I'm new to Django and also this ReportLab things. Right now I have to use ReportLab to generate PDF. But I don't know how to retrieve data from database and insert it into the PDF. Can you guys help me on the way to do this ? I know how to do it in the html template but how can I do it in PDF ? I'm really lost right now :( views.py def empIncomeform(request): if request.method == "GET": b1 = Income1.objects.filter(Q(title='Salary')| Q(title='Bonus')).annotate(as_float=Cast('total_amount', FloatField())).aggregate(Sum('as_float')) b2 = Income2.objects.filter(Q(title='Overtime')).annotate(as_float=Cast('total_amount', FloatField())).aggregate(Sum('as_float')) context= { 'b1':b1, 'b2':b2 } return render (request, 'EmpIncome.html', context) empIncome.py (PDF) def drawMyRuler(pdf): from reportlab.pdfbase import pdfmetrics from reportlab.pdfbase.ttfonts import TTFont pdfmetrics.registerFont(TTFont('Arial-Bold', 'arialbd.ttf')) pdf.setFont("Arial-Bold", 11) pdf.drawString(10,100, b1) #this is where I want to put my db data pdf.drawString(20,200, b2) #this is where I want to put my db data fileName = 'Emp_Income.pdf' documentTitle = 'Employee Income Form' from reportlab.pdfgen import canvas pdf = canvas.Canvas(fileName) pdf.setTitle(documentTitle) pdf.save() EmpIncome.html <table> <tr> <th>#</th> <th>Details</th> <th>Amount</th> </tr> <tr> <td>1</td> <td>Salary and Bonus</td> <td>{{ b1.as_float__sum}}</td> </tr> <tr> <td>2</td> <td>Overtime</td> <td>{{ b2.as_float__sum}}</td> </tr> <tr> <td colspan="2">Total Amount</td> <td>{{ total.as_float__sum}}</td> </tr> </table> -
I am getting a 404 error when running Django admin on Chrome but works on Microsoft Edge
My Django admin was working fine, when I added the Allauth then the admin is not working on chrome and internet explorer but works fine on Microsoft edge. What could be the problem. -
Model Inheritance in Django Forms
How can I access the Child Model Data in Django Forms? Forms.py class CourseForm(ModelForm): class Meta: model = Course fields = '__all__' class SectionForm(ModelForm): class Meta: model = Section fields = '__all__' Models.py class Section(models.Model): SEM = ( ('1st', '1st'), ('2nd', '2nd'), ('Summer','Summer'), ) section_code = models.CharField(max_length=22) academic_year = models.CharField(max_length=22) semester = models.CharField(max_length=22, choices=SEM) course_fk = models.ForeignKey( Course, models.CASCADE, db_column='course_fk') course_staff_fk = models.ForeignKey( Course, models.CASCADE, db_column='course_staff', related_name='course_staff') schedule_fk = models.ForeignKey( Schedule, models.CASCADE, db_column='schedule_fk') scheduleClassroom_fk = models.ForeignKey( Schedule, models.CASCADE, db_column='schedule_classroom_fk', related_name='classroom_schedule') def __str__(self): return self.section_code Views.py def add_sections(request): form = SectionForm() if request.method == 'POST': form = SectionForm(request.POST) if form.is_valid(): user = form.save() messages.success(request, 'Section Created') return redirect('add_section') context = {'form':form} return render(request, 'app/add_section.html', context) HTML <div class="input-group mb-3"> <div class="input-group-append"> <label for="course-staff">Course Instructor</label> </div> {{form.course_staff_fk.staff_fk}} ### This is what i hope to do {{form.course_staff}} ####This is whats working but doesnt give me the right data </div> I was hoping to get the child data through the django forms. I have tried using __ to access the child model but with the same result. Any help and advice is appreciate. Im hoping that this community can help me in my problem. Thank you -
What is the difference between some_list=[a,b] and some_list=[a]+b?
In django, seems urlpatterns = [ path('admin/', admin.site.urls), path('catalog/', include('catalog.urls')), path('', RedirectView.as_view(url='/catalog/')), ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) and urlpatterns = [ path('admin/', admin.site.urls), path('catalog/', include('catalog.urls')), path('', RedirectView.as_view(url='/catalog/')), static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) ] are different. However, in my mindset it seems that some_list=[a,b] and some_list=[a]+b should be same object. Am I correct? -
Application error with Heroku after deployment of Django app
After having deployed my app with success I clicked on "Open app" and I see this error: An error occurred in the application and your page could not be served. If you are the application owner, check your logs for details. My log details: 2020-06-19T05:42:21.334962+00:00 app[api]: Release v6 created by user harshalsinha437@gmail.com 2020-06-19T05:42:21.542382+00:00 heroku[web.1]: State changed from crashed to starting 2020-06-19T05:42:26.249249+00:00 heroku[web.1]: Starting process with command : gunicorn mywebsite.wsgi --log-file - 2020-06-19T05:42:28.310063+00:00 heroku[web.1]: Process exited with status 0 2020-06-19T05:42:28.349024+00:00 heroku[web.1]: State changed from starting to crashed 2020-06-19T05:42:28.357811+00:00 heroku[web.1]: State changed from crashed to starting 2020-06-19T05:42:33.000000+00:00 app[api]: Build succeeded 2020-06-19T05:42:33.690668+00:00 heroku[web.1]: Starting process with command : gunicorn mywebsite.wsgi --log-file - 2020-06-19T05:42:36.303973+00:00 heroku[web.1]: Process exited with status 0 2020-06-19T05:42:36.338696+00:00 heroku[web.1]: State changed from starting to crashed 2020-06-19T05:42:38.907020+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=harshal-portfolio.herokuapp.com request_id=9bfded63-ac10-4a2a-b9af-491cb7a70c73 fwd="223.230.128.180" dyno= connect= service= status=503 bytes= protocol=https 2020-06-19T05:42:39.307963+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=harshal-portfolio.herokuapp.com request_id=18e4fab6-017a-4423-b23d-c3919da0d937 fwd="223.230.128.180" dyno= connect= service= status=503 bytes= protocol=https 2020-06-19T05:43:53.725469+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=harshal-portfolio.herokuapp.com request_id=8c0aaff8-1a6f-48f2-9a8c-4c231f6a450f fwd="223.230.128.180" dyno= connect= service= status=503 bytes= protocol=https 2020-06-19T05:43:54.171265+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=harshal-portfolio.herokuapp.com request_id=8a7448aa-3453-4fbe-bc6e-95f0a0dd572f fwd="223.230.128.180" dyno= connect= service= status=503 bytes= protocol=https 2020-06-19T05:44:30.900385+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" … -
How to check the data in a form with javascripts
Here I have a form which has 2 inputs. 1st input asks if it's a video or image. 2nd input takes in the file. Now I want the JavaScript function demo() to run only if the 1st input is video. Any help regarding this matter will truly be helpful. Thanks in advance. This is my form :- <form method="post" enctype="multipart/form-data"> <input type="radio" id="type" name="type" value="image" required /> <label class="text-black" for="subject">Image</label><br> <input type="radio" id="type" name="type" value="video" required /> <label class="text-black" for="subject">Video</label><br> <label class="text-black" for="subject">Upload the File</label> <input type="file" id="upload" name="file" accept="image/*, video/*" onchange="demo()" required /> <input type="submit" value="POST" class="btn btn-primary"/> </form> This is the JavaScript function :- <script type="text/javascript"> function demo() { var upload = document.getElementById('upload'); var type = document.getElementById('type').value; if (type == 'video') { if (upload.files[0].size > 5000000) { if (window.confirm('File size above 5mb. Want to reduce it ?')) { window.location.href='https://www.google.com'; } else { window.location = '/' } } } } </script> -
Django: Filtering not returning any results?
Here I am trying to filter the two models logs with some parameters but it is not returning any results. Is my view looks fine or I need to change logic since it is not returning any results. def get(self, request): crud_logs = LogEntry.objects.none() user_logs = UserActivity.objects.none() parameter = request.GET.get('param') today = datetime.datetime.today() current_month = today.month past_7_days = today - datetime.timedelta(days=7) if parameter == 0: return redirect('logs:activity_logs') elif parameter == 1: user_logs = UserActivity.objects.filter(action_time=today) crud_logs = LogEntry.objects.filter(action_time=today) elif parameter == 2: crud_logs = LogEntry.objects.filter(action__time__range=[past_7_days, today]) user_logs = UserActivity.objects.filter(action_time__range=[past_7_days, today]) elif parameter == 3: user_logs = UserActivity.objects.filter(action_time__month=current_month) crud_logs = LogEntry.objects.filter(action_time__month=current_month) logs = sorted(chain(crud_logs, user_logs), key=attrgetter('action_time'), reverse=True) return render(request, 'logs/show_activity_logs.html', {'logs': logs}) template <form action="{% url 'logs:filter_logs' %}"> <select name="param" id="" onchange="this.form.submit()"> <option value="0">Any date</option> <option value="1">Today</option> <option value="2">Past 7 days</option> <option value="3">This Month</option> </select> </form> -
How to search for the object of a foreign key django
I am creating an Task Completion Queue where people create Projects then add Posts to that specific Project, kind of like comments on a blog post. I am creating a detail view for the Project model, and I want to search all of the posts using the Project as a parameter because I only want posts that pertain to that specific Project. The problem is I cant figure out how to use the model currently being used as a search parameter in a Detail view Here's my models.py class MyProjects(models.Model): title = models.CharField(max_length=30) description = models.CharField(max_length=140) class Post(models.Model): title = models.CharField(max_length=50) content = models.TextField() project = models.ForeignKey(MyProjects, on_delete=models.CASCADE, null=True, default=None) And here is my views.py class ProjectView(DetailView): model = MyProjects def get_context_data(self, **kwargs): CurrentProject = get_object_or_404(MyProjects, title=self.kwargs['MyProjects']) completed = Post.objects.filter(status='Completed', project= CurrentProject) inProgress = Post.objects.filter(status='InProgress', project= CurrentProject) posts = Post.objects.filter(project= CurrentProject) Features = Post.objects.filter(ticket_type='Features', project= CurrentProject) context = super().get_context_data(**kwargs) context['posts '] = posts context['Features '] = Features context['completed '] = completed context['inProgress '] = inProgress context['projects'] = projects return context -
I want to change product name in Django/admin panel. So that it will show the product name instead of "Product object (number)" [duplicate]
How can I change the product name from Django pannel so that it will show me a particular product name instead of showing just a number as it shows in below attached screenshot. It will help a lot as same product name has been used in the 'Order_item' module as well. model.py from django.db import models from django.contrib.auth.models import User from phone_field import PhoneField # Create your models here. class Customer(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True, blank=True) name = models.CharField(max_length=200, null=True) email = models.CharField(max_length=200, null=True) phone = PhoneField(blank=True,E164_only=False, help_text='Contact phone number') def __self__(self): return self.name class Product(models.Model): name = models.CharField(max_length=200, null=True) price = models.FloatField() detail = models.CharField(max_length=500, null=True) digital = models.BooleanField(default=False, null=True, blank=False) image = models.ImageField(null= True, blank= True) def __self__(self): return self.name @property def imageURL(self): try: url = self.image.url except: url = "" return url class Order(models.Model): customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, blank=True, null=True) date_order = models.DateTimeField(auto_now_add = True) complete = models.BooleanField(default=False, null=True, blank=False) transaction_id = models.CharField(max_length=200, null=True) def __self__(self): return str(self.id) class OrderItem(models.Model): product = models.ForeignKey(Product, on_delete=models.SET_NULL, blank=True, null=True) order = models.ForeignKey(Order, on_delete=models.SET_NULL, blank=True, null=True) quantity = models.IntegerField(default=0, null=True, blank=True) date_added = models.DateTimeField(auto_now_add = True) class ShippingAddress(models.Model): customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, blank=True, null=True) order = models.ForeignKey(Order, on_delete=models.SET_NULL, blank=True, null=True) … -
Django App interacts with outside models.py
├── API #app │ ├── apps.py │ ├── models.py # models.py inside 'API' app, we aim to not use this. │ ├── serializer.py │ └── views.py ├── __init__.py ├── MY_PROJECT #Project │ ├── asgi.py │ ├── settings.py │ ├── SUB_FOLDER │ │ ├── conn │ │ │ ├── sqlDatabase.py │ │ │ └── static_data.py │ │ ├── MODELS_FODLER │ │ └── models.py # models.py inside the root project, USE THIS. │ ├── urls.py │ └── wsgi.py ├── manage.py Currently, we are doing a Django project called 'MY_PROJECT'. Somewhere in the root folder, we create a models.py to connect to our MySQL on Google Cloud (CloudSQL). We create an app called 'API' to, as the name suggests, expose our end for the world to interact with our database. However, I'm not really sure how to make the API interact with models.py in 'MY_PROJECT' instead of the models.py in 'API'. -
How to pass in value from a text box to this function and have it print the output out on html page?
So basically I have a text box and button and I want to be able to enter text into the textbox which will pass to the text to the WebOutput object and then I want to print those results from the function to the HTML page. Is this possible? Here is some code to get a better understanding. The function that I want to be able to pass in my text from the textbox to. As you can see the object takes user input which would be the text I enter into the textbox. DatabaseInteractor.py def match_tweet_for_website(self): output= WebOutput.WebOutput(input("Enter Tweet ")) print(output.impWords) info = ', '.join(output.impWords) self.cursor = self.connection.cursor(buffered=True) print(', '.join(output.impWords)) query= f"SELECT DISTINCT company_name FROM CompanyKeywords where keyword IN ({info})" self.cursor.execute(query,(info)) result = self.cursor.fetchall() print(result) index.html Code for basic text box and submit button <form action="/external/" method="post"> Input Text: <input type="text" name="param" required<br><br> <br><br> <input type="submit" value="Check tweet"> </form> url.py from django.contrib import admin from django.urls import path from . import views urlpatterns = [ path('admin/', admin.site.urls), path('', views.output), ] views.py from django.shortcuts import render from subprocess import run, PIPE import sys def output(request): return render(request,'index.html') -
code coverage is high for zero test cases
I have a simple Django app that doesn't contain any test cases and I tried to get the test coverage using coverage. The result was surprising, coverage run --omit '*.virtual_env/*' ./manage.py test && coverage report System check identified no issues (0 silenced). ---------------------------------------------------------------------- Ran 0 tests in 0.000s OK Name Stmts Miss Cover -------------------------------------------------- django2x/__init__.py 0 0 100% django2x/settings.py 20 0 100% django2x/urls.py 7 2 71% manage.py 12 2 83% music/__init__.py 0 0 100% music/admin/__init__.py 1 0 100% music/admin/actions.py 6 2 67% music/admin/filters.py 12 5 58% music/admin/model_admin.py 13 0 100% music/admin/register.py 7 0 100% music/filters.py 7 0 100% music/forms.py 6 0 100% music/migrations/__init__.py 0 0 100% music/models.py 28 4 86% music/pagination.py 3 0 100% music/serializers.py 54 18 67% music/tests.py 1 0 100% music/urls.py 9 0 100% music/views.py 30 1 97% -------------------------------------------------- TOTAL 216 34 84% Why I have got 84% test coverage from zero tests? -
Django appending %20 to URL causing 404 error
I am having an issue with pagination during filtering/ordering when I try to go to page 2. The URL Django is creating when going to page #2: https://example.com/accounts/?page=2%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20&q=%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20&ordering=-date_joined Pagination looks like this: <a class="btn btn-default mb-4 m-1" href="?page=1{% for key, value in request.GET.items %} {% if key != 'page' %}&{{ key }}={{ value }}{% endif %}{% endfor %}"> First</a> <a class="btn btn-default mb-4 m-1" href="?page={{ page_obj.previous_page_number }}{% for key, value in request.GET.items %} {% if key != 'page' %}&{{ key }}={{ value }}{% endif %}{% endfor %}"> Previous</a> View: class AccountStatusListView(AccountSearchMixin, ListView): model = Employee template_name = 'employees/account_list.html' paginate_by = 15 def get_ordering(self, *args, **kwargs): ordering = self.request.GET.get('ordering', '-is_active') return ordering def get_queryset(self, *args, **kwargs): queryset = super(AccountStatusListView, self).get_queryset() queryset = queryset.filter(Q( supervisor__exact=self.request.user)) | queryset.filter(Q( supervisor__isnull=False)) | queryset.filter(Q( is_active__exact=False)) ordering = self.get_ordering() if ordering and isinstance(ordering, str): ordering = (ordering,) queryset = queryset.order_by(*ordering) return queryset -
How to fix "object of type 'NewsletterUser' has no len()" error for a Newsletter app in Django
I have created a new Newsletter to send emails when status is Published but I keep getting TypeError at /control/newsletter/ object of type 'NewsletterUser' has no len() Because of this error probably I am not receiving the emails I don't know what is the reason for this error and how to fix it, I have selected an email but still Here is the models.py: class Newsletter(models.Model): EMAIL_STATUS_CHOICES = ( ('Draft', 'Draft'), ('Published', 'Published') ) subject = models.CharField(max_length=250) body = models.TextField() email = models.ManyToManyField(NewsletterUser) status = models.CharField(max_length=10, choices=EMAIL_STATUS_CHOICES) created = models.DateTimeField(default=timezone.now) updated = models.DateTimeField(default=timezone.now) def __str__(self): return self.subject Here is the views.py def control_newsletter(request): form = NewsletterCreationForm(request.POST or None) if form.is_valid(): instance = form.save() newsletter = Newsletter.objects.get(id=instance.id) if newsletter.status == "Published": subject = newsletter.subject body = newsletter.body from_email = settings.EMAIL_HOST_USER for email in newsletter.email.all(): send_mail(subject=subject, from_email=from_email, recipient_list=[ <----- error this line email], message=body, fail_silently=False) context = { "form": form, } template = 'control_newsletter.html' return render(request, template, context) here is the urls.py from newsletters.views import control_newsletter, control_newsletter_list, control_newsletter_detail, control_newsletter_edit, control_newsletter_delete app_name = 'newsletters' urlpatterns = [ path('newsletter/', control_newsletter, name="control_newsletter"), -
subprocess used in python django does not working when django was host in IIS
I have using the subprocess package in my django web, when i run local on server or publish using apache, it work without causeing any issue BUT when I host my django web on IIS, this subprocess does not work. Below is my subprocess code: files = subprocess.check_output("dir /b " + path, shell=True).decode() p_pcat=subprocess.Popen(['java', '-cp', str(PARSER_JAR), 'parsePCAT.ParsePCAT', str(pcat_file_name)],stdout=subprocess.PIPE, stderr=subprocess.PIPE,shell=True) This both function not working when hosting at IIS (version 10.0.14393.0), anyone have idea on this? -
Password expiry django-user-accounts not work
I have followed the instructions django user accounts. However I have a problem with the password expiry and password history. I have been setup to 60 seconds for password expiry but nothing happens for the new sign up user. Did I miss something ? Thanks -
access file from static folder with template tags inside javascript code
appreciate if anyone can help. I have a app which creates file location from submit button - json_path = os.path.join('json', request.POST['submit'], '.json' ) This gives the file location under \static\json\ folder. I am sending this using dictionary to template render_dict = { 'json_path':json_path, } Inside javascript, I have following - map.addSource('locationData', { type: 'geojson', data: "location of the json file needs to be provided here" }); can anybody suggest if this can be done through template taging? -
django + jquery Ajax + CORS = empty JSON response sent to server
I'm running my webapp on another domain via an iframe. This page can produce ajax POST called to the db. When these happen, the variables that I'm passing to the view that processes the ajax arrive empty (or not at all). When I run the ajax call, there are no errors. In other words, I don't beleive this is related to Csrf token as I'm passing that into the ajax view. I was previously getting errors related to the CSFR token, but I think I've resolved that. No, the ajax view just fails silently by not passing the required data back to the server. In trying to get this setup, I've done the following: 1) I'm including the csrf_token on the data I'm sending to my backend via ajax. 'csrfmiddlewaretoken': '{{ csrf_token }}', 2) I've installed django-cors-headers and set CORS_ORIGIN_ALLOW_ALL = True in settings.py 3) I've set CSRF_COOKIE_SAMESITE = None in settings.py 4) I've got the following standard code to support ajax requests $(document).ready(function(){ function getCookie(name) { var cookieValue = null; if (document.cookie && document.cookie !== '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = jQuery.trim(cookies[i]); // Does this cookie … -
How to setup Django every time you use it? (i.e. using **source bin/activate** and ** python manage.py runserver**)
I am a beginner with Django, and I am very confused as to how to consistently setup Django everytime you are opening a new terminal. Whenever I do so, I have to always restart and do the following: Change directory (cd) to my trydjango directory where I start the virtual environment (source bin/activate) After the terminal has the automatic (trydjango) at the furthest left of (trydjango) ismodes-MacBook-Air:trydjango ismodes$ I know that I have the virtual environment enabled. Then, I go to the src directory through the terminal where I enter python manage.py runserver I am running into consistent errors (e.g. AttributeError) whenever I enter the runserver step (step 3). Am I doing something wrong? The following is the full Traceback of the error (trydjango) ismodes-MacBook-Air:src ismodes$ python manage.py runserver Performing system checks... Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x10d5a6b90> Traceback (most recent call last): File "/Users/ismodes/Dev/trydjango/lib/python3.7/site-packages/django/utils/autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "/Users/ismodes/Dev/trydjango/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 120, in inner_run self.check(display_num_errors=True) File "/Users/ismodes/Dev/trydjango/lib/python3.7/site-packages/django/core/management/base.py", line 364, in check include_deployment_checks=include_deployment_checks, File "/Users/ismodes/Dev/trydjango/lib/python3.7/site-packages/django/core/management/base.py", line 351, in _run_checks return checks.run_checks(**kwargs) File "/Users/ismodes/Dev/trydjango/lib/python3.7/site-packages/django/core/checks/registry.py", line 73, in run_checks new_errors = check(app_configs=app_configs) File "/Users/ismodes/Dev/trydjango/lib/python3.7/site-packages/django/core/checks/urls.py", line 13, in check_url_config return check_resolver(resolver) File "/Users/ismodes/Dev/trydjango/lib/python3.7/site-packages/django/core/checks/urls.py", line 23, in check_resolver … -
Django Query Values from a List of names
Is it possible to do a query from a list (or string) of desired values in Django? v = ['a', 'b', 'c'] // or could be a sting like v = '"a","b","c" qs = Data.objects.all().values ( v ) I am getting errors like: AttributeError: 'list' object has no attribute 'split' Thank you. -
Django: add records to multiple tables via one ModelForm (or Form?)
When I update the data in the Project table using ProjectForm, I need to write the changes to the Log table. As I understand it, I need to use Form instead of ModelForm. How can I implement this?