Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Openstack Horzion install -> AttributeError: module 'django.contrib.auth.views' has no attribute 'login'
I'm following OpenStack installation guide to install Train. Trying to install Horizon but stuck in an error when I try to login via dashboard. My apache2 error log: [Mon Mar 09 15:24:34.678452 2020] [wsgi:error] [pid 17044:tid 140208455399168] [remote 127.0.0.1:60994] ERROR django.request Internal Server Error: /horizon/auth/login/ [Mon Mar 09 15:24:34.678593 2020] [wsgi:error] [pid 17044:tid 140208455399168] [remote 127.0.0.1:60994] Traceback (most recent call last): [Mon Mar 09 15:24:34.678636 2020] [wsgi:error] [pid 17044:tid 140208455399168] [remote 127.0.0.1:60994] File "/usr/local/lib/python3.6/dist-packages/django/core/handlers/exception.py", line 34, in inner [Mon Mar 09 15:24:34.678681 2020] [wsgi:error] [pid 17044:tid 140208455399168] [remote 127.0.0.1:60994] response = get_response(request) [Mon Mar 09 15:24:34.678713 2020] [wsgi:error] [pid 17044:tid 140208455399168] [remote 127.0.0.1:60994] File "/usr/local/lib/python3.6/dist-packages/django/core/handlers/base.py", line 115, in _get_response [Mon Mar 09 15:24:34.678744 2020] [wsgi:error] [pid 17044:tid 140208455399168] [remote 127.0.0.1:60994] response = self.process_exception_by_middleware(e, request) [Mon Mar 09 15:24:34.678775 2020] [wsgi:error] [pid 17044:tid 140208455399168] [remote 127.0.0.1:60994] File "/usr/local/lib/python3.6/dist-packages/django/core/handlers/base.py", line 113, in _get_response [Mon Mar 09 15:24:34.678806 2020] [wsgi:error] [pid 17044:tid 140208455399168] [remote 127.0.0.1:60994] response = wrapped_callback(request, *callback_args, **callback_kwargs) [Mon Mar 09 15:24:34.678837 2020] [wsgi:error] [pid 17044:tid 140208455399168] [remote 127.0.0.1:60994] File "/usr/local/lib/python3.6/dist-packages/django/views/decorators/debug.py", line 76, in sensitive_post_parameters_wrapper [Mon Mar 09 15:24:34.678869 2020] [wsgi:error] [pid 17044:tid 140208455399168] [remote 127.0.0.1:60994] return view(request, *args, **kwargs) [Mon Mar 09 15:24:34.678899 2020] [wsgi:error] [pid 17044:tid 140208455399168] [remote 127.0.0.1:60994] … -
Trouble implementing an already developed Django App
Hello fellow programmers, I'm having trouble and also have several questions about the implementation of this app in Django. https://github.com/voxy/django-audio-recorder It has a 'quick start' section that I have tried to follow several times but with no success. My questions are: -What is really happening when I run this line in terminal pip install git+https://github.com/voxy/django-audio-recorder.git#egg=django-audio-recorder -When the developer refers to 'create your models, views and forms' should i already have a project setup django-admin startproject X and change lines of code in that folder specifically? -I also used the git clone https://github.com/voxy/django-audio-recorder.git to get the folders and see what is really going on in this app, unfortunately I can't get it to work. Would apreciate some insight on this matter, thank you in advance. -
django template form target with dynamic data
i'm new at django template. i have a search field in header and i want to send searched keyword in this format search/q/{{keyword}}/ my html code is this <form action="{% url 'content.search' q=searched_key %}" class="search-input"> <input type="text" name="searched_key"> <button type="submit"><i data-feather="search"></i></button> </form> i want to get input value and send but result url is this http://127.0.0.1:8000/contents/search/q//?searched_key=test how can i do it in right way? -
stefanfoulis/django-phonenumber-field display format of phone number in template
I'm trying to figure out how to display a phone number using stefanfoulis/django-phonenumber-field. I have stefanfoulis/django-phonenumber-field[phonenumberslite] installed. In my settings file I have: PHONENUMBER_DB_FORMAT = "NATIONAL" PHONENUMBER_DEFAULT_REGION = "US" In my model I have: phone_number = PhoneNumberField(blank=True) In my form I have: phone_number = PhoneNumberField(max_length=25,required=False) And in my template I have: {{ myform.phone_number }} I am able to enter a phone number in a variety of formats (831-555-5555, 831-555-5555, 831.555.5555) and it stores properly in the database as +18315555555. But when I use the form field in a template it always displays as +18315555555. I would like it to display as either 831-555-5555 or (831) 555-5555. How do I make the phone number display in one of these formats in my template? Is there a tag modifier? -
Django ORM - update ForeignKey field with model's ManyToManyField
I have a model: class User(AbstractUser): name = models.CharField(max_length=255) organizations = models.ManyToManyField(Organization) active_organization = models.ForeignKey(Organization) Now I want to update active_organization with one of the organizations within the model, so I want to do something like this: User.objects.filter(active_organization=q).update(active_organization=F('organizations__pk')[0]) sadly F is not subscriptable, I've also tried, User.objects.filter(active_organization=q)\ .update(active_organization=Subquery( Organization.objects.filter(pk=OuterRef('organizations').objects.first().pk))) But in this case it tells me the OuterRef should be inside a SubQuery which it is, so I'm completely at a loss here how this should be approached. -
Django CSRF and axios post 403 Forbidden
I use Django with graphene for back-end and Nuxt for front-end. The problem appears when I try post requests from nuxt to django. In postman everything works great, in nuxt I receive a 403 error. Django # url.py urlpatterns = [ path('admin/', admin.site.urls), path('api/', GraphQLView.as_view(graphiql=settings.DEBUG, schema=schema)), ] # settings.py CORS_ORIGIN_WHITELIST = 'http://localhost:3000' CORS_ALLOW_CREDENTIALS = True CSRF_USE_SESIONS = False CSRF_COOKIE_HTTPONLY = False CSRF_COOKIE_SAMESITE = None NuxtJs # nuxt.config.js axios: { baseURL: 'http://127.0.0.1:8000/', debug: false, progress: true, credentials: true }, # plugins/axios.js await $axios.onRequest((config) => { config.headers.common['Content-Type'] = 'application/json' config.xsrfCookieName = 'csrftoken' config.xsrfHeaderName = 'X-CSRFToken' const csrfCookie = app.$cookies.get('csrftoken') config.headers.common['X-CSRFToken'] = csrfCookie console.log(config) # store/contact.js import { AddMessage } from '../queries/contact.js' export const actions = { async send() { const message = await this.$axios({ url: 'api/', method: 'POST', data: AddMessage }) } } # queries/contact.js export const AddMessage = { query: ` mutation AddContact($input: AddMessageInput!){ addMessage(input: $input){ message{ name email body terms } } } `, variables: ` { "input":{ "name": "test", "email": "test@test.com", "body": "test", "terms": true, } } `, operationName: 'AddMessage' } Somethig that Here are request headers from axios post. Something strange for me is the cookie with a wrong value. The good value of token is present in … -
django authentication in signup page error : 'str' object has no attribute '_meta'
this is my signup authentication views.py def , when i add username and password and hit signup it says this error : AttributeError at /accounts/signup 'str' object has no attribute '_meta' views.py def : def signup(request): if request.method == 'POST': if request.POST['password1'] == request.POST['password2']: try: user = User.objects.get(username = request.POST['username']) return render(request, 'accounts/signup.html', {'error':'try another username'}) except User.DoesNotExist: User.objects.create_user(request.POST['username'], password = request.POST['password1']) auth.login(request, request.POST['username']) return redirect('home') else: return render(request, 'accounts/signup.html', {'error':'password error'}) -
Django simple_history "missing 1 required positional argument: 'on_delete'"
I've tried to install simple_history to my existing Django app- but have encountered a few errors including the below. I've encountered these errors when attempting to run "makemigrations". I could fix this by adding the on_delete to the package models file- though because of the other issues I encountered before this one, it seems like there might be a deeper issue. My django version is: (2, 2, 7, 'final', 0) Python version is 3.7.3 'history_user': CurrentUserField(related_name=rel_nm), File "appname/lib/python3.7/site-packages/simple_history/models.py", line 26, in __init__ super(CurrentUserField, self).__init__(User, null=True, **kwargs) TypeError: __init__() missing 1 required positional argument: 'on_delete' Thanks! -
Call Postgresql procedure from Django
I am using Postgresql in Django and Python,and I do all the CRUD operation successfully but I don't know how can I call Postgresql procedure from Django and show the result in my web application!! -
Django jumping model id number (AutoField)
Today my django app jumped from id 126 to 1125 in one of my models, 999 ids! Does anybody knows what could cause it? See below the screenshot of my admin area, from my MSSQL database and also my model code: I appreciate any feedback that might help me to understand why django did it... DJANGO ADMIN: MSSQL: MY MODEL: (which is working for many months without issues... Also, as you can see, the id is an AutoField, it is not in my class, only on the migrations file.) class New_ticket(models.Model): process_expert = models.ForeignKey(Team_Structure, on_delete=models.SET_NULL, limit_choices_to={'available':True}, blank=True, null=True) status = models.ForeignKey(Status_table, on_delete=models.CASCADE, limit_choices_to={'available':True}, blank=True, null=True) created_by = models.CharField(max_length=20) created_on = models.DateTimeField() option = models.ForeignKey(Options_table, on_delete=models.CASCADE, limit_choices_to={'available':True}, verbose_name="Where is the issue?") priority_level = models.ForeignKey(Priority_level, on_delete=models.CASCADE, limit_choices_to={'available':True}) department = models.ForeignKey(Department, on_delete=models.CASCADE, limit_choices_to={'available':True}) transaction = models.CharField(max_length=50, blank=True) zone = ChainedForeignKey(Zone,chained_field="option",chained_model_field="option", show_all=False, auto_choose=True, sort=True, blank=True, null=True) duration_of_error = models.CharField(max_length=50, blank=True) error_message = models.TextField(max_length=250) comments = models.TextField(blank=True) upload_1 = models.FileField(upload_to='uploads/', blank=True, validators=[file_size]) upload_2 = models.FileField(upload_to='uploads/', blank=True, validators=[file_size]) upload_3 = models.FileField(upload_to='uploads/', blank=True, validators=[file_size]) history = HistoricalRecords() def __str__(self): return str(self.id) class Meta: verbose_name_plural = "Tickets" -
generate unique id in each loop of for loop django template
I need to generate unique id in each loop instead of ````city-selected``` {% for form in formset.forms %} <tr> {% for field in form %} <td class="input_td{% if field.errors %} error_td{% endif %}"> <select name="city-select" id="city-select"></select> </td> {% endfor %} <td class="delete_formset_td"></td> </tr> {% endfor %} How can I generate it here? -
One To Many and models
i am trying to build my first project, a CRM website to handle orders and inventory. and i got stuck, i was able to link orders to customer. but when i try to build order that contain multi items. for some reason i didn't find a way to do it. hope you can assist me. so I have User>>Order>>Multi Items. questions: 1) does the best practice here is just use ForeignKey ? this my model's code: from django.db import models class Customer(models.Model): name = models.CharField(max_length=200, null=True) phone = models.CharField(max_length=200, null=True) email = models.CharField(max_length=200, null=True) date_created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.name def date_createdview(self): return self.date_created.strftime('%B %d %Y') class Product(models.Model): CATEGORY = ( ('General', 'General'), ('SmartHome', 'SmartHome'), ('Software', 'Software'), ('Mobile', 'Mobile'), ) name = models.CharField(verbose_name='שם', max_length=200, null=True) price = models.FloatField(verbose_name='מחיר', null=True) category = models.CharField(max_length=200, null=True, choices=CATEGORY, verbose_name='קטגוריה') description = models.CharField(max_length=200, null=True, verbose_name='מלל חופשי') date_created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.name class Order(models.Model): STATUS = ( ('New', 'New'), ('Work in progress', 'Work in progress'), ('completed', 'completed'), ) customer = models.ForeignKey(Customer, null=True, on_delete=models.CASCADE) date_created = models.DateTimeField(auto_now_add=True, null=True) status = models.CharField(max_length=200, null=True, choices=STATUS) def date_createdview(self): return self.date_created.strftime('%d/%m/%Y') class OrderItem(models.Model): product = models.ForeignKey(Product, null=True, on_delete=models.CASCADE) order = models.ForeignKey(Order, null=True, on_delete=models.CASCADE) quantity = models.IntegerField(null=True) 2)how should … -
Execute a Python file via PHP Script
I have a Python script ready which completes some tasks. to initiate the task I need to manually start the Index.py Now I want a web page (php / html or anything) which will execute the index.py located on ec2 and the python code will execute. (no issues if it does not shows output) Also required that the terminal shall not be on every time thus we need to run services in background. Thanks +91 9033024545 -
Django-bootstrap-modal-forms on datatable row click
So, I have datatable, and I need to open modal form whenever a row is clicked. My table is defined like this <table id="tabledata" class="datatable display"> Using django-bootstrap-modal-forms, I've done this: $('.datatable').modalForm({ formURL: "{% url 'myapp:modelform-url' %}" }).on('click', 'tbody tr', function(){ // other code here }) It sort of works, except the modal pops up wherever I click on the table. I tried something like this but doesn't seem to work: $('.tabledata tbody tr').modalForm({}) Any ideas? -
What is the right way to load different js file for each template in Django?
I want to load different .js, .css files (static files) for each template, but also to load same group of files for each of them. Example: first.html - Here I want to load jquery.js, jquery.css, maps.js second.html - Here I want to load jquery.js, jquery.css without maps.js third.html - Here I want to load test.js, maps.js Right now I add all files in footer.html (.js files), or header.html (.css files) and include all of them, via {% include 'footer.html' %} -
Average for ratings in Django
I working on an app using django and python at school. It an app for writing reviews and rating movies. I would like to implement a rating system, so I can display the average rating for a film based on the rating given in the reviews. At the moment this code gives the rating in descending order for all reviews, and not the average. Like if I got two reviews for a movie, with score 1 and 5, I get both, but not one that says 3. Please help! In models.py: class Film(models.Model): title = models.CharField(max_length=100) title_short = models.CharField(max_length=17, default=None, null=True) plot = models.TextField() poster = models.ImageField(default="default.png", upload_to="posters") release_date = models.DateField(blank=True, null=True) date_posted = models.DateTimeField(default=timezone.now) class Review(models.Model): writer = models.ForeignKey(User, on_delete=models.CASCADE) reviewed_film = models.ForeignKey(Film, on_delete=models.CASCADE) title = models.CharField(max_length=100) content = models.TextField() rating = models.IntegerField( default=1, validators=[MinValueValidator(1), MaxValueValidator(5)] ) In views.py: class ToplistListView(LoginRequiredMixin, ListView): model = Review template_name = "board/toplist.html" context_object_name = "films" def get_queryset(self): return Review.objects.annotate(avg_rating=Avg('rating')).order_by('-avg_rating') -
Celery after_task_publish signal fire but other signals do not?
I have the following three signal handlers: @after_task_publish.connect def task_sent_handler(sender=None, headers=None, body=None, **kwargs): info = headers if 'task' in headers else body logger.info('task_sent_handler for task id {info[id]}'.format( info=info, )) @task_success.connect def task_success_handler(*args, **kwargs): logger.info('task_success_handler') @task_failure.connect def task_failure_handler(*args, **kwargs): logger.info('task_failure_handler') The three handlers are registered in django app ready method: def ready(self): import app.signals Celery broker (redis) run locally, and the tasks are applied async using delay. I can only see in the log file the task_sent_handler handler, but the other handlers does not log, any idea why? I also tried task_prerun, but it did not fire also. -
Every task failing to execute on Google Cloud Tasks
I need to run some asynchronous tasks in a Django app, and I started to look into Google Cloud Tasks. I think I have followed all the instructions - and every possible variation I could think of, without success so far. The problem is that all created tasks go to the queue, but fail to execute. The console and the logs report only a http code 301 (permanent redirection). For the sake of simplicity, I deployed the same code to two services of an App Engine (standard), and routed the tasks request to only one of them. It looks like the code itself is working fine. When I go to "https://[proj].appspot.com/api/v1/tasks", the routine executes nicely and there's no redirection according to DevTools/Network. When Cloud Tasks try to call "/api/v1/tasks", it fails every time. If anyone could take a look at the code below and point out what may be causing this failure, I'd appreciate very much. Thank you. #-------------------------------- # [proj]/.../urls.py #-------------------------------- from [proj].api import tasks urlpatterns += [ # tasks api path('api/v1/tasks', tasks, name='tasks'), ] #-------------------------------- # [proj]/api.py: #-------------------------------- from django.views.decorators.csrf import csrf_exempt @csrf_exempt def tasks(request): print('Start api') payload = request.body.decode("utf-8") print (payload) print('End api') return HttpResponse('OK') #-------------------------------- # … -
Django how to create multiple model objects at once - sharing all values but one
I have been making an app for tracking user wages and issues that they are working on. I would like to have a view from which I could specify payment details and select mutliple Users to whom the payment will be made. I have a User model and Payment model. In the Payment model there is a FK to Users. Is there a way to have a view where I'll select multiple Users, fill the other shared vlaues (such as date, value etc.) in the form and then hit submit. I'm looking for a way to override class based functions so that it iterates through the multiple select field (bunch of User ids) and then creates and saves Payment model object with the FK and shared fields. Thank you very much. -
Django button that updates text from database with each press
I am trying to make a basic quizz type app in Django and I'm having a problem with understanding how Django works and where to find instructions to this specific problem. Below is the functionality that I am looking for: -A view that has a quizz question text that comes from a database -An answer text field to that quizz -Pressing enter after typing or pressing a submit button changes the quizz question to the next question from the database Any help on this would be much appreciated. -
get students in a course in django
i'm pretty new to django and i'm struggling with models and database but i managed to get some stuff right but this here isnt working out for me. so basically what i want to do is when i click on a course it shows me a table with the students who are registered to this course but i keep getting an empty table models.py from django.db import models from django.contrib.auth import get_user_model from django.urls import reverse from django.utils.text import slugify User = get_user_model() # Create your models here class student (models.Model): S_id = models.IntegerField(unique=True) S_fname = models.CharField(max_length=255) S_lname = models.CharField(max_length=255) def __str__(self): return self.S_id class classes(models.Model): C_id = models.CharField(max_length=255,unique=True) C_name = models.CharField(max_length=255) C_room = models.CharField(max_length=255) Start_time = models.CharField(max_length=255) Instructs = models.ManyToManyField(User, through='Teaches') Registered = models.ManyToManyField(student, through='Registered') slug = models.SlugField(allow_unicode=True, unique=True) def __str__(self): return self.C_id def save(self,*args,**kwargs): self.slug = slugify(self.C_id) super().save(*args,**kwargs) def get_absolute_url(self): return reverse('classes:single',kwargs={'slug':self.slug}) class Meta: ordering = ['C_name'] class Teaches(models.Model): Instructor = models.ForeignKey(User, related_name='St_id', on_delete=models.CASCADE) Course = models.ForeignKey(classes, related_name='Co_id', on_delete=models.CASCADE) class Registered(models.Model): Student = models.ForeignKey(student, related_name='Stu_id', on_delete=models.CASCADE) Course = models.ForeignKey(classes, related_name='Cou_id', on_delete=models.CASCADE) classes_detail.html {% extends "classes/classes_base.html" %} {% block pregroup %} <div class="container"> <h1>{{classes.C_name}}</h1> <div class="table-responsive"> <table class="table"> <thead> <tr> <th>Student ID</th> <th>Student First Name</th> <th>Student Last Name</th> <th>attendance</th> … -
how to identified two login that this is loader and other is driver in django project
I am working on a Django project where a user post a load and driver take that load and to deliver to the destination . My point is how I can differentiate both of them in my project like when someone login whether is loader or driver because when driver login the all the post created by multiple users will display and on the other hands the loader will see his own post after login just like in the uber app -
Python Django- How to download file on client machine in django project
I am new to python, I have created a small Django application to download data into excel format. it downloads in a project folder or given path(on the server). but when I hit the URL from the client machine then it should download on the client machine but it downloads on my server only. Please suggest a suitable method(code) to download an excel file on the client machine only. Thanks in advance. -------code------- try: cursor = connection.cursor() cursor.execute("""select * from table""") columns = [desc[0] for desc in cursor.description] data = cursor.fetchall() result = len(data) print("No of records :" ,len(data)) df = pd.DataFrame(list(data), columns=columns) home = os.path.expanduser("~") print('Home path------------',home) download_location = os.path.join(home,'Downloads') print('download path------------',download_location) filename = 'django_simple.xlsx' writer = pd.ExcelWriter(download_location+'/'+ filename) df.to_excel(writer, sheet_name='Hundai') writer.save() print("File saved successfully!") cursor.close() except: print("There is an error") finally: if (connection): connection.close() cursor.close() print("The MSSQL connection is closed") return render(request,'result.html',{'result': result}) -
where are the pages are stored which I created through Django CMS and how can I seperately copy and run it to other PC?
I need to seperately know where are actually the pages are stored which I created through Django CMS. In which directory of venv/site packages/ where it is stored ?. please anyone knows . -
pdfkit image not embedded using Django
I'm converting a protected webpage into pdf using Django and this solution. The solution works great except the part that the webpage contains images which do not show up in the pdf and i get an error Warning: Failed to load file:///media/images/main/logo.jpg (ignore) I'm currently using from_string method as follows pdfkit.from_string(msg_html, 'testing123.pdf') #msg_html contains html string with images