Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I pass these extra parameters to my form from my view
I currently have something like this class MainLoginForm(forms.Form): user_name = forms.CharField(widget=forms.TextInput(attrs={"class" : "login-form-group"}),required=True) user_password = forms.CharField(widget=forms.PasswordInput(attrs={'class' : 'myfieldclass'}),required=True) and I am using it like this def login(request): context = {} LoginForm = MainLoginForm() if request.method == "POST": LoginForm = MainLoginForm(request.POST) if LoginForm.is_valid(): pass else: return render(request, 'login.html', {"form": LoginForm, "error": "Invalid Username/Password"}) return render(request, 'login.html', {"form": LoginForm}) Now I created another form that basically has an init method like so class DynamicQuizForm(forms.Form): def __init__(self, user, *args, **kwargs): super(DynamicQuizForm, self).__init__(*args, **kwargs) ...... My question is in my view how do I pass it request.POST along with a dictionary for kwargs ? -
Django Sending HTML Table to Python
Hello Guys I'm working with Django and I have a big doubt, i have 3 HTML tables and i need save this data in mysql, that table is filled by users and im not sure how can i sending the tables to python. i tried using Ajax, but, really I'm not user how to use it. HTML CODE from one of my 3 tables: custom.html <table id="idTable" name="table" class="table table-striped table-bordered"> <thead> <tr> <th>FIRST</th> <th>Second</th> <tr> </thead> <tbody> </tbody> </table> <button class="btn btn-primary" onclick="ajaxFunction()" id="IDButton">Touch me!</button> The tbody rows are added with javascript Ajax code: <script type="text/javascript"> function ajaxFunction(){ var request = $.ajax({ url: window.location.href, type: 'get', data: {data1: "hello"}, contentType: 'application/json; charset=utf-8' }); request.done(function(data)){ console.log("works") }); </script> When i click the button in the console i can see "works" but in python is not working Python code: crm/views.py def custom(request, op_id): if request.method == "GET": IF request.is_ajax(): message ="Yes" else: message="No" return render(request, "custom.html") I don't know why function is_ajax does not works. I only wanna find a way to do this, i will be glad !!!! Thank you! -
Configuring gunicorn without virtualenv
I'm setting up a django site without virtualenv and I'm following digital ocean's guide to setup which has been going fine till I had to setup gunicorn service instance which has a field ExecStart which I've had to remove also while trying to test. When I try to start gunicorn I get the following error root@samuel-pc:~/revamp# systemctl start gunicorn Failed to start gunicorn.service: Unit gunicorn.service is not loaded properly: Invalid argument. See system logs and 'systemctl status gunicorn.service' for details. root@samuel-pc:~/revamp# My gunicorn service code is as follows: [Unit] Description=gunicorn daemon After=network.target [Service] User=root Group=www-data WorkingDirectory=/root/revamp #ExecStart=gunicorn --access-logfile - --workers 3 --bind unix:/root/revamp/rev$ [Install] WantedBy=multi-user.target the way I've setup the site is I login via root and I copied the folder directly into root. The django application is called revamp and if you run pwd from inside the folder you get the result /root/revamp -
How to Allow users to add a choice not in django Choices list
When giving users a choice of things to choose in choices list for a model, if they do not find the choice they are looking for, how can you make them add a new one, and store their choice as the value they added. -
In model __unicode__ accessing a many to many field property giving an error
I am getting the error AttributeError: 'ManyRelatedManager' object has no attribute 'choice' I am not sure why I am getting this error when I try to add an entry into modelQuizAnswer through the admin interface class modelQuizChoice(models.Model): question = models.ManyToManyField(modelQuizQuestion,default=None,blank=True) choice = models.CharField(max_length=200, unique=False) def __unicode__(self): return "choice : " +self.choice class modelQuizAnswer(models.Model): question = models.ForeignKey(modelQuizQuestion,null=True,default=None,blank=True) answer = models.ManyToManyField(modelQuizChoice, default=None, blank=True) def __unicode__(self): return "Answer : " +self.answer.choice #------>This is the problem Any suggestions on how I can fix this ? -
Connection issues implementing Django Custom Storage backend with Box Cloud Storage API
I am working on a legacy Django application that has a lot of third party dependencies, one of which is the storage backend for file uploads. I was recently tasked with replacing our legacy third party cloud storage vendor with a newer cloud storage vendor (Box). The cloud storage is implemented as a custom storage backend and used as the "storage" parameter in FileFields in models throughout the app. I'm basically trying to figure out what exactly happens in storage if you have a FileField in a model and you create a ModelForm based on that model, then you call "save" on the form. It seems that a lot of stuff is going on and some of it is causing connection problems with the cloud storage API. I tried reading the Django source to follow it and got all the way down to where the model is deciding if it should do an update (by doing an "exists" check in storage) or an insert. Once it decides to do an insert, I noticed a call to my cloud storage backend occurs to upload the file (presumably non blocking?) as the insert sql is being generated. Somewhere in here, connections to … -
Pagination in Django TemplateView
I have a template where I want to display a large list of data, (received from external API rather than DB). Although I'm aware this is easily done is ListView, however as I'm not pulling data from the database, TemplateView seems the best choice but what would the best way to display the list of data and paginate it? Currently I have: View class QuotesResultsView(TemplateView): template_name = 'site/quotes.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['quotes'] = self.request.session['quotes']['data'] return context Template: .... <div class="about"> {% for quote in quotes %} <h3>Supplier:{{ quote.supplierName }}</h3> <div> <p>Annual Cost: {{ quote.newSpend }}</p> <p>Savings: {{ quote.newSavings }}</p> </div> <button class="btn btn-cta-primary">Proceed</button> {% endfor %} </div><!--//about--> -
how to make form view with user is foreign key and one model has foreign key relationship with another model?
my model.py is from django.db import models from django.contrib.auth.models import User class Question(models.Model): asker = models.ForeignKey(User, related_name='questions') question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) forms.py from django.forms import ModelForm from django.forms import inlineformset_factory from .models import Question,Choice class PollForm(ModelForm): class Meta: model = Choice exclude = () postinline=inlineformset_factory(Question, Choice, form=PollForm, extra=1) how should i edit the view tomake the maximum amount of choices to be three and make the authenticated user is asker of the question thanks in advance -
DJANGO cannot import name _compare_digest
hello i have python 7.13 DJANGO 1.11.2 version django-crypto 0.20 version on windows 10. i want to create a DJANGO app but anytime to try to migrate i take that error : from django.utils.crypto import get_random_string File "C:\Python27\lib\site-packages\django\utils\crypto.py", line 8, in <module> import hmac File "C:\Python27\Lib\hmac.py", line 8, in <module> from operator import _compare_digest as compare_digest ImportError: cannot import name _compare_digest how to fix it ? -
Django {% trans %} tag not displaying any text
None of the {% trans %} tags in my templates show anything besides the msgid given to it. I am able to create the .po file correctly with makemessages and compile it successfully with compilemessages but when I run the server and bring up a page it doesn't show either language's translation, just the msgid. For example: {% trans "about-me-text" %} This only displays "about-me-text" on the page instead of either the English or French translation. My settings: LOCALE_PATHS = ( '/path/to/project/locale', ) MIDDLEWARE_CLASSES = ( 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.gzip.GZipMiddleware', ) LANGUAGE_CODE = 'en' LANGUAGES = ( ('en','English'), ('fr','French'), ) This project is Django 1.3.1 and Python 2.7 -
django-allauth caching login and signup pages
is there a way to set up Django Redis caching for login and signup views from django-allauth? I looked at docu and found nothing. I don't want whole site caching but only some views and these two are part of it. -
403 error for new files posted through django admin
I'm running a Django server with Gunicorn and Nginx hosted on DigitalOcean. I've run into a problem where adding a new file through the administrator interface produces a 403 forbidden error. Specifically, the file in question works fine if I summon a query of it (e.g. Object.objects.all())but can't be rendered in my templates. I've previously fixed the problem by doing chmod/chown, but the fix only applies to existing files, not new ones. Does anyone know how to permanently apply the fix once? -
Making a proper search function in Django
I'm trying to make a search function that allows me to enter the value of an object in an instance so I can display that instance and several of it's objects on the same page as the search page. Here's what I have so far: #models.py class Student(models.Model): # STEP 1 BASIC INFO student_id = models.CharField(max_length=128, unique=True) first_name = models.CharField(max_length=128) last_name = models.CharField(max_length=128) ssn = USSocialSecurityNumberField(null=False) gender = models.CharField(max_length=128, choices=GENDER_CHOICES) dob = models.DateField(auto_now=False, auto_now_add=False, db_column="date of birth") contact_number = models.CharField(max_length=128) address = models.CharField(max_length=128) city = models.CharField(max_length=128) state = USStateField(choices=STATE_CHOICES, default='NJ') zipcode = USZipCodeField(blank=True) country = CountryField(default='US', blank=True) home_phone = models.CharField(max_length=128) cell_phone = models.CharField(max_length=128) email = models.EmailField(max_length=254, validators=[validate_email]) def __str__(self): return self.first_name + self.last_name #views.py def search_Student(request): context_dict = {} context_dict['results'] = None if request.method == 'POST': query = request.POST['last_name_search'] if query: results = Student.objects.filter(last_name=query) context_dict['results'] = results return render(request, "students/search_student.html", context_dict) #search_student.html {% block main_content %} <form method="post" action="/students/search_student/"> {% csrf_token %} <label for="last_name_search">Last Name:</label> <input type="text" name="last_name_search" id="last_name_search"> <input type="submit" name="submit"> </form> <div id="result_panel"> {% for result in results %} {{ result.last_name }} {% endfor %} </div> {% endblock %} Basically, if I type in a last name in the input, I want it to be able to grab … -
how to write multiple management commands in one file? django
I have been reading how to write a django management command by reading http://janetriley.net/2014/11/quick-how-to-custom-django-management-commands.html I did also read the django documentation but I am wondering if it's possible to write few commands to run using only one file? instead of writing a few different files. -
Option to add extra choices in django form
I am trying to create a model via a form that has multiple other models related to it. Say I have a model Publisher, then another model Article with a foreign key to Publisher. When creating a Publisher via a form, I want to create An article at the same time. I know how to do this via formsets. However, I don't know how to add a button that says and extra article at the same view, without having to be redirected to a new page and losing the old data since the form was not saved. What I want is when someone clicks add new article, for a new form for article to appear and for the user to add a new Article. Is this possible to be done in the same view in django, if so can someone give me and idea how to approach this? I would show code or my attempts but, I am not sure how to even approach it. -
FileNotFoundError: [WinError 2] The system cannot find the file specified: 'manage.py' IN PYTHON/DJANGO
I have used below code in a thread running background. os.chdir("MEDIA/" + str(email) + "/" + str(id) + "/") os.system("rscript DataSet.R " + str(filename) + " >>logfile.log") os.chdir(settings.BASE_DIR) This Error comes sometimes whenever I run my server. I have no clue whats the issue here. Most of the time the code works. I have to use chdir to run my R scripts. Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "C:\Users\MEXSON~1\Desktop\PROJEC~1\TOX2020\MAINWE~1\TOX202~1\lib\site-packages\django\core\management\__init__.py", line 363, in execute_from_command_line utility.execute() File "C:\Users\MEXSON~1\Desktop\PROJEC~1\TOX2020\MAINWE~1\TOX202~1\lib\site-packages\django\core\management\__init__.py", line 355, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\MEXSON~1\Desktop\PROJEC~1\TOX2020\MAINWE~1\TOX202~1\lib\site-packages\django\core\management\base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\MEXSON~1\Desktop\PROJEC~1\TOX2020\MAINWE~1\TOX202~1\lib\site-packages\django\core\management\commands\runserver.py", line 62, in execute super(Command, self).execute(*args, **options) File "C:\Users\MEXSON~1\Desktop\PROJEC~1\TOX2020\MAINWE~1\TOX202~1\lib\site-packages\django\core\management\base.py", line 330, in execute output = self.handle(*args, **options) File "C:\Users\MEXSON~1\Desktop\PROJEC~1\TOX2020\MAINWE~1\TOX202~1\lib\site-packages\django\core\management\commands\runserver.py", line 101, in handle self.run(**options) File "C:\Users\MEXSON~1\Desktop\PROJEC~1\TOX2020\MAINWE~1\TOX202~1\lib\site-packages\django\core\management\commands\runserver.py", line 110, in run autoreload.main(self.inner_run, None, options) File "C:\Users\MEXSON~1\Desktop\PROJEC~1\TOX2020\MAINWE~1\TOX202~1\lib\site-packages\django\utils\autoreload.py", line 332, in main reloader(wrapped_main_func, args, kwargs) File "C:\Users\MEXSON~1\Desktop\PROJEC~1\TOX2020\MAINWE~1\TOX202~1\lib\site-packages\django\utils\autoreload.py", line 298, in python_reloader reloader_thread() File "C:\Users\MEXSON~1\Desktop\PROJEC~1\TOX2020\MAINWE~1\TOX202~1\lib\site-packages\django\utils\autoreload.py", line 276, in reloader_thread change = fn() File "C:\Users\MEXSON~1\Desktop\PROJEC~1\TOX2020\MAINWE~1\TOX202~1\lib\site-packages\django\utils\autoreload.py", line 206, in code_changed stat = os.stat(filename) FileNotFoundError: [WinError 2] The system cannot find the file specified: 'manage.py' -
Form required field in django model forms
i have a model form however I'm struggling to set one field as required without changing the model itself. Is there a way of making the location field mandatory without changing models.py when the user submits the form? modelys.py class Profile(models.Model): user = models.OneToOneField(User) location = models.CharField(max_length=120, null=True, blank=True) picture = models.ImageField(upload_to=upload_location, null=True, blank=True) gender = models.CharField(max_length=120, null=True, choices=GENDER, blank=True) bio = models.CharField(max_length=1000, null=True, blank=True) home_university = models.CharField(max_length=50, null=True, blank=True) my forms.py class ProfileForm(forms.ModelForm): class Meta: model = Profile fields = [ "location", "picture", "bio", "gender", "home_university", ] and my views.py @login_required def profile_complete(request): profile, created = Profile.objects.get_or_create(user=request.user) form = ProfileForm(request.POST or None, request.FILES or None, instance=profile) if form.is_valid(): instance = form.save(commit=False) instance.user = request.user instance.save() return redirect("home") context = { "form": form, } return render(request, "profiles/profile_complete.html", context) -
Django auth.models User One-To-Many (1048, "Column 'user_id' cannot be null")
I'm new to django and my task is to make user able to create a lot profiles after registration when he's logged in. This is my models.py: class Profile(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(blank=False, max_length=100) lastname = models.CharField( blank=False, max_length=100) city = models.CharField( blank=True, max_length=100) country = models.CharField( blank=True, max_length=100) phonenumber = models.CharField(blank=False, null=True, max_length=20) email = models.EmailField(blank=False, max_length=100) date_of_birth = models.DateField( blank=True, null=True) date_of_addition = models.DateField(auto_now=True, editable=False, null=True) When I create my user, do login and press create profile button I get : django.db.utils.IntegrityError: (1048, "Column 'user_id' cannot be null") This is my views.py: @login_required def profile_create(request): data = dict() if request.method == 'POST': form = ProfileForm(request.POST) if form.is_valid(): form.save() data['form_is_valid'] = True profiles = Profile.objects.all() data['html_profile_list'] = render_to_string('basic_app/users_list_1_10.html', {'profiles': profiles}) else: data['form_is_valid'] = False else: form = ProfileForm() context = {'form': form} data['html_form'] = render_to_string('basic_app/partial_profile_create.html', context, request=request) return JsonResponse(data) def register(request): registered = False if request.method == "POST": user_form = UserForm(data=request.POST) if user_form.is_valid(): user = user_form.save() user.set_password(user.password) user.save() registered = True else: print(user_form.errors) else: user_form = UserForm() return render(request,'basic_app/registration.html',{'user_form':user_form,'registered':registered}) This is my forms.py: from django import forms from django.forms import ModelForm from django.contrib.auth.models import User from .models import Profile class ProfileForm(ModelForm): class Meta: model = Profile … -
Using django-allauth and getting stuck on Facebook login page
I've registered a new app and I get to the FB login page, put in my password, but it just stays there and says: The page you are trying to visit on myapp requires that you re-enter your password. It doesn't want to re-direct to my site (on localhost). -
Django's URL Dispatcher not extracting kwargs
I have configured url patterns a ton of times in Django before. Suddenly it's not working and I have no idea why... I'm using Django REST Framework, and I'm testing the API using Django's RequestFactory. This is my URL pattern: url(r'^samples/(?P<sha256>\w+)/?$', endpoints.SampleAPI.as_view()) These are the GET request URLs I've tried: /samples/somehashhere /samples/somehashhere/ This is what I'm trying to do: class SampleAPI(APIView): def get(self, request: Request, *args, **kwargs) -> Response: sha256 = self.kwargs.get('sha256', None) The URL gets resolved and I go into the method, but for some reason, sha256 is always None (The kwargs dictionary is always empty!). Weird thing is that I did the exact same thing in 2 of the other services I'm developing (only another name for the keyword argument), and they work. Do you guys see anything I'm missing here? -
How to use react-router and Django templates
Folks, I am pretty sure I am not the first one to stumble on this problem. But somehow I am unable to find any relevant resources out there. Here is my issue, I have a backend in Django and my front completely written in Reactjs- React Router - Redux (nice combo right). when entering the url webhost.com/, django provides me with a page with links to a bundle that is my whole react application and different stylesheets The problem arise when I want to refresh a page, the browser still tries to query the server even though a route exists in my react-router configuration. I had a look at the answer here (catch-all option) React-router urls don't work when refreshing or writting manually , but I don't quite understand it and I am afraid to have a new redux state everytime Django will provide the user with a new page. -
django auto requery from influxdb
I wrote a page in django such that it queries all the information from influxdb and output the result as an html table. The problem is information keeps coming in to influxdb, and I would like to write a python script such that the page automatically queries from influxdb every 10 seconds. I tried code like this: def view_table(request): while 1: publish_page(request) time.sleep(10) def publish_page(request): # pull the query and publish into the page return render(request, 'table_template.html', context) But it's not working. Django just loads forever and never give me the webpage. Does anyone know what's wrong and how to fix it? -
Why is my CSS class not being used in chrome but in Safari and Firefox?
I am having trouble with a css class which is used in Safari and Firefox but not in Chrome. Here is the code: main.css .stylized_button_red { background-color: red !important; color: white; } .stylized_button_red:hover { background-color: #cc0000 !important; } .stylized_button_orange { background-color: #FFA500 !important; color: white; } .stylized_button_orange:hover { background-color: #FF8C00 !important; } template.html <td class="action_buttons"> <input type="button" id="orange_button_{{ button.id }}" class="stylized_button stylized_button_smaller stylized_button_tight stylized_button_orange" data-role="none" value="{% trans 'orange button' %}" /> <input type="button" id="red_button_{{ button.id }}" class="stylized_button stylized_button_smaller stylized_button_tight stylized_button_red" data-role="none" value="{% trans 'red button' %}" /> </td> The styling for the red and orange button are in the same file. The red button works on all browsers. The orange button only works on Safari and Firefox. If I change the orange button to a red button in the template it works on all browsers. If I change the color in the css file from orange to a different color it does not work on chrome. The other button classes such as stylized_button_tight work on all browsers and are also defined in the same main.css. I have reloaded the page multiple times, restarted chrome and restarted the development server there was no difference. I tried to research this and found … -
Permission hierarchy system for SaaS based B2B
We are working on a B2B solution While our MVP is being tested with clients, we now need to work on the hierarchy system. It would be great if I could be shown some direction, as in how to proceed with it, like for A we need to do B and for X we need to do Y. While this is a very open-ended question, it would be great if some generic approaches are suggested. -
Django session cookie expiry date
I am running a django (1.10) site. In settings, I have defined SESSION_COOKIE_AGE = 60*60*24*365 and it was setting the cookie expiry 1 year from creation. Recently, the session is expiring at session end. Simply put, perhaps the session expiry is not being set although it is still defined in settings as earlier. What can be the problem. Why the default behaviour is not being followed. I am facing the same problem in local server, testing server and production. I understand that the question is not clear as I have no idea what is the root of the problem. What I want is setting sessionid cookie's expiry date to be one year from creation. Any pointers would be helpful.