Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
saving anonymous user session key get None in django
I have an app where user comes select item and add to cart it work perfectly for login user but i want it for anonymous user . So i am trying to get session key and save in models and after user login map it with user and get details. views.py def AddToCart(request): if request.method == 'POST': cart = AddCart() cart.session_key = request.session.session_key cart.user = request.user cart.testselected = request.POST['selectedTests'] cart.save() models.py class AddCart(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE,null=True) session_key = models.CharField(max_length=32, null=True) testselected = models.TextField() Now, i have trouble to save session key for anonymous user it saves none but if user is login it save session key . is something missing in my code ? and if anonymous user session key gets save how can i use that after user login or register and should i remove user field from model once i have added session key as new to django no idea to proceed. -
How to map flask and Django to same database model?
I want to have a database model which is written in Django ORM and the same database is used to read data by flask using SQLAlchemy for microservices. What is the right way to do this so that I don't have to write model in both django ORM and flask separately? The django model is required as there is a need of admin functionality and flask will be used to serve data to UI which is written in Angular. -
Python: isinstance on Abstract Inherited Classes?
New to Python here– I'm trying to see if isinstance(obj, Class) works on abstract inherited classes. Specifically I'm working on a Django project and I want to check if one type of object is inherited from a set of shared base classes. class AbstractClass(models.Model): class Meta: abstract=True class ClassA(AbstractClass): ... class ClassB(AbstractClass): ... obj = ClassB() if isinstance(obj, AbstractClass): ... Does this work? -
Change inheritance to OnToOne relation in Django models
I have models that have a inheritance relationship. I want to turn this relationship into a OneToOne relationship, without removing anything data in project. This is structure of models: class BaseFieldsModel(models.Model): create_date = DateTimeField(auto_now_add=True,) update_date = DateTimeField(auto_now=True,) created_by = ForeignKey('UserManager.User', related_name='created_%(class)ss') updated_by = ForeignKey('UserManager.User', related_name='updated_%(class)ss') class User(AbstractBaseUser,BaseFieldsModel): # Some fields class Teacher(User): # Some fields class Student(User): # Some fields All things was good until I want to resructure my database because of this problem that I had in this design. In new DB model, I want to have something like this: (OneToOne Relation) class User(AbstractBaseUser,BaseFieldsModel): # Some fields class Teacher(BaseFieldsModel): user_ptr = OneToOneField('UserManager.User', primary_key=True,related_name='student_user') # Some fields class Student(BaseFieldsModel): user_ptr = OneToOneField('UserManager.User', primary_key=True,related_name='teacher_user') # Some fields So I did run makemigrations: Migrations for 'UserManager': UserManager/migrations/0022_auto_20200425_1233.py - Change managers on student - Change managers on teacher - Add field create_date to student - Add field created_by to student - Add field update_date to student - Add field updated_by to student - Add field create_date to teacher - Add field created_by to teacher - Add field update_date to teacher - Add field updated_by to teacher - Alter field user_ptr on student - Alter field user_ptr on teacher and then run migrate … -
How to set date without year using Date Field on Python?
I want to set dates without year using Date Field on Python, the solution was to set year 2000, but I am not interested on the year, is it possible to modify Date Field to set it not to require year data? -
Django app on Apache2 Forbidden 403 Response
I have been battling with this for about an hour and I am not sure how to fix the issue. It seems my Apache server is running fine but anytime I try to access the website I get a Forbidden 403 Error. Here Is what added to the default .conf file <Directory "/home/mredwin/website\ v1.0/marketingvideosclub"> <Files wsgi.py> Require all granted </Files> </Directory> WSGIScriptAlias / "/home/mredwin/website\ v1.0/marketingvideosclub/wsgi.py" WSGIDaemonProcess marketingvideosclub python-home="/home/mredwin/website\ v1.0/venv" python-path="/home/mredwin/website\ v1.0" WSGIProcessGroup marketingvideosclub And I checked the logs and there is nothing useful in there except that it is getting a GET and it is returning a 403 error code. Any help is appreciated thanks! -
Div not being found when Ajax loaded
I have a Django template that looks like this: page.html {% extends 'core/base.html' %} {% block content %} <div class="example"> ..some..content.. </div> {% endblock %} Inside base.html contains a wrapper div that wraps everything up. I'm trying to retrieve this page like so in Ajax: $.ajax({ url: '/page/', method: 'GET', success: function (data) { console.log($(data).find(".wrapper")); } }); However, the log says that .wrapper does not exist for some reason, even though if I do console.log(data); it shows the wrapper and all the HTML. Is it because the tag hasn't loaded yet? If so, how can I make it show? -
django admin list filter?
Actually, my models has foreign key to User table. And I want to make admin list show only what I made. # models.py class Store(models.Model): name = models.CharField(max_length=20) address = models.CharField(max_length=50) city = models.CharField(max_length=20) state = models.CharField(max_length=2) phone = models.CharField(max_length=25) user_id = models.ForeignKey(User, on_delete=models.DO_NOTHING) # admin.py class StoreAdmin(admin.ModelAdmin): list_display = ('name', 'address', 'city', 'state') list_filter = ['name'] search_fields = ['name'] But this shows all of list. -
UTF-8 is not saving txt file correctly - Python
My django application reads a file, and saves some report in other txt file. Everything works fine except my language letters. I mean, encoding="utf-8" can not read some letters. Here are my codes and example of report file: views.py: def result(request): #region variables # Gets the last uploaded document last_uploaded = OriginalDocument.objects.latest('id') # Opens the las uploaded document original = open(str(last_uploaded.document), 'r') # Reads the last uploaded document after opening it original_words = original.read().lower().split() # Shows up number of WORDS in document words_count = len(original_words) # Opens the original document, reads it, and returns number of characters open_original = open(str(last_uploaded.document), "r") read_original = open_original.read() characters_count = len(read_original) # Makes report about result report_fives = open("static/report_documents/" + str(last_uploaded.student_name) + "-" + str(last_uploaded.document_title) + "-5.txt", 'w', encoding="utf-8") report_twenties = open("static/report_documents/" + str(last_uploaded.student_name) + "-" + str(last_uploaded.document_title) + "-20.txt", 'w', encoding="utf-8") # Path to the documents with which original doc is comparing path = 'static/other_documents/doc*.txt' files = glob.glob(path) #endregion rows, found_count, fives_count, rounded_percentage_five, percentage_for_chart_five, fives_for_report, founded_docs_for_report = search_by_five(last_uploaded, 5, original_words, report_fives, files) context = { ... } return render(request, 'result.html', context) report file: ['universitetindé™', 'té™hsili', 'alä±ram.', 'mé™n'] was found in static/other_documents\doc1.txt. ... -
cannot send large text using POST request in Django
I am making an app in reaact native and backend is in django. I am sending POST request from the app to the api, when the text is small it is working fine but when I try to send long text like about 3 paragraphs, only 1.5 paragraph comes in request the other half is not coming. Please help me on this. -
django gunicorn workers vs theads vs other possibilities
My app in django with gunicorn and I am kinda new to gunicorn. My app is heavy on IO, not so much on memory and CPU, essentially a thread has to save a or serve a big file (from few MB to few GB) from storage. Currently because of this the workers run out while there is no load on CPU or memory or even the HDD. By default has a config file for gunicorn that looks like this: import os daemon = True workers = 5 # default localhost:8000 bind = "127.0.0.1:8000" # Pid pids_dir = '/opt/pids' pidfile = os.path.join(pids_dir, 'app.pid') # for file upload, we need a longer timeout value (default is only 30s, too short) timeout = 7200 limit_request_line = 8190 I am not sure about how to configure the workers and threads etc for my work load. let me provide more details: We run "a few VMs" of 2 CPUs/8GB RAM. python is 2.7 we are on the way to upgrade to 3.7, but for now is 2.7 I already tried adding threads with different values (1 to 6), but it does not seem to work. Can someone please help explain what I can do? -
Getting id of an item instead of value, django forms
I have created a form and I wanted to create a field that is for display only, after adding that line, the form started returning id instead of the value. class AmendLoan(ModelForm): borrower = forms.CharField(disabled=True) class Meta: model = BikeInstance fields = ( 'borrower', 'due_back', 'status' ) Any ideas, how to display value of borrower, instead of id? -
Django: adding excluded fields after ModelForm submission
I have a ModelForm where I excluded the selected_season field. The model looks like this (showing relevant part): class Registration(models.Model): student_name = models.CharField(max_length=50) selected_season = models.ForeignKey(Season, on_delete=models.CASCADE) ... before saving the form I have tried adding that field in: if form.is_valid(): form.save(commit=False) form.selected_season = '21' form.save() But it shows null value in column "selected_season_id" violates not-null constraint I added the 21 because there are 2 objects in my Season table, '21' and '22'. How do I fix this? -
Django: Change the HTML button when user joins a event with ManyToMany field
I am designing a event management system using django. I have a problem in changing the button of html page. The problem is: 1.If user is not authenticated then the button should have the value "Login to join" 2. After login, if the user clicks the "join" button(which is earlier "login to join") then the same button changes to "Joined". 3. If the The number of joiners is exceeds to the given limit then the same button should replace with "Full" or "Not Available". {% if user.is_authenticated %} <a href="{{ event.increase_join }}"><button>Join Now</button></a> {% else %} <a href="{% url 'login' %}">Login to Join match</a> {% endif %} I tried the above one but it is not capable to handle my problem the views.py is given below: @login_required def event_joined(request,id): event = get_object_or_404(Event,id=id,available=True) current_joiner = User.objects.get(username=request.user) event.joiners.add(current_joiner) event.joined+=1 event.available_slot-=1 event.save() return render(request,'events/event/detail.html',{'event': event}) -
Error while running '$ python manage.py collectstatic --noinput'.even with static configuration from heroku docs
After trying to upload my django-project to heroku i get the following error, even though I tried to configure setting.py in accordance with heroku documentation. Tried to fix it myself for couple of days but I clearly got no idea about what is wrong. -----> $ python manage.py collectstatic --noinput Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/base.py", line 328, in run_from_argv self.execute(*args, **cmd_options) File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/base.py", line 369, in execute output = self.handle(*args, **options) File "/app/.heroku/python/lib/python3.7/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 187, in handle collected = self.collect() File "/app/.heroku/python/lib/python3.7/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 104, in collect for path, storage in finder.list(self.ignore_patterns): File "/app/.heroku/python/lib/python3.7/site-packages/django/contrib/staticfiles/finders.py", line 130, in list for path in utils.get_files(storage, ignore_patterns): File "/app/.heroku/python/lib/python3.7/site-packages/django/contrib/staticfiles/utils.py", line 23, in get_files directories, files = storage.listdir(location) File "/app/.heroku/python/lib/python3.7/site-packages/django/core/files/storage.py", line 316, in listdir for entry in os.scandir(path): FileNotFoundError: [Errno 2] No such file or directory: '/tmp/build_3daca1eccd4631486a8597ada28d44da/static' ! Error while running '$ python manage.py collectstatic --noinput'. See traceback above for details. You may need to update application code to resolve this error. Or, you can disable collectstatic for this application: $ heroku config:set DISABLE_COLLECTSTATIC=1 https://devcenter.heroku.com/articles/django-assets ! … -
How to identify which anchor tag submitted form in django?
I have created test.html. I have two anchor tag as shown below.I want to submit form and print name of anchor tag. <div class="collapse navbar-collapse" id="navbarNavDropdown" > <ul class="navbar-nav" > <li class="nav-item" name="lang" > <a class="nav-link" id ='id' value="home" onclick="design.submit();">Home</a> </li> <li class="nav-item"> <a class="nav-link" id ='id1' value="latest_news" onclick="design.submit();">latest news </a> </li> </ul> </div> In view.py i have test func associated with test.html. def test(request): login_data = request.POST.dict() print("succeed") print(login_data) return render(request,'test.html') My aim is when one click the link it will submit form,I will identify which link is clicked and call further code according to it. But, I do not know how to do it.Please Help. -
Saving image of <image> tag in django
I want to save image of tag of html to database using Django. <form method="post" name="data" enctype="multipart/form-data"><br>{% csrf_token %} <image id="theimage" name="theimage"></image> <input class="btn btn-outline-secondary btn-md " type="submit" name="submit" id="submit" value="Upload"> </form> -
in django how to display all videos in static folder in a single page
I want to built a page which will display all the videos in static folder and able to play them (not just listing the video file name). -
Possible permission issue with upstart script/uwsgi
I'm trying to configure an Apache/uwsgi/Django app on a Centos 7. I've been able to set apache to proxy requests to uwsgi. I also set an ini file to link uwsgi with my Django app. The point is that I'm missing something with the systemd service to start the uwsgi server. I suspect is some permissions issue. if I manually run the server with uwsgi --ini /home/foo/env/app/uwsgi.ini then everything works like a charm but when I start the server with systemctl start uwsgi that corresponds to a configured service, the server starts with no errors but certain views on my app just fail. Watching logs I see many errors like these ones During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/foo/env/lib/python3.6/site-packages/django/template/base.py", line 903, in _resolve_lookup (bit, current)) # missing attribute Traceback (most recent call last): File "/home/foo/env/lib/python3.6/site-packages/django/template/base.py", line 882, in _resolve_lookup current = current[bit] File "/home/foo/env/lib/python3.6/site-packages/django/template/context.py", line 87, in __getitem__ raise KeyError(key) KeyError: 'form' During handling of the above exception, another exception occurred: File "/usr/lib64/python3.6/traceback.py", line 105, in print_exception print(line, file=file, end="") UnicodeEncodeError: 'ascii' codec can't encode character '\xf8' in position 18057: ordinal not in range(128) This same views work perfectly when starting … -
How can i copy the current row of a model to other in Django?
After I create a blog I have two submit buttons one to post an article in my profile which only I can see and other to post it in homepage as well as in my profile where all users can see but I can't figure out how to make second submit button work properly #Model MyLane in mylane/models.py class MyLane(models.Model): id = models.IntegerField(primary_key=True) title = models.CharField(max_length=25) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.title def get_absolute_url(self): return reverse('my-lane') # Model Home in home/models.py class Home(models.Model): title = models.ForeignKey(MyLane, on_delete=models.CASCADE) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.title #Createview in mylane/views.py class MyLaneCreateView(LoginRequiredMixin, CreateView): model = MyLane fields = ['title', 'content'] def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) def get_success_url(self): if 'homepost' in self.request.POST: mylane = MyLane.objects.get("??") home = Home(title=mylane.title, content=mylane.content, author=self.request.user) home.save() url = reverse('home') else: url = reverse('my-lane') return url -
no such table: form1_user
I have tried all previous solutions such as syncdb, migrate, makemigrations etc. I am still not getting the program to work. My models.py class Role(models.Model): ROLE_CHOICES = ( (1,'ADMIN'), (2,'HR'), (3,'MGR'), (4,'EMP'), ) id = models.PositiveSmallIntegerField(choices=ROLE_CHOICES,primary_key=True) def ___str___ (self): return self.get_id_display() class User(AbstractUser): roles = models.ManyToManyField(Role) class Admins(models.Model): user = models.PositiveSmallIntegerField(choices=Role.ROLE_CHOICES) first_name = models.CharField(max_length=256) last_name = models.CharField(max_length=256) class HRs(models.Model): user = models.PositiveSmallIntegerField(choices=Role.ROLE_CHOICES) first_name = models.CharField(max_length=256) last_name = models.CharField(max_length=256) Then here is my views.py class AdminSignUpView(CreateView): model = User form_class = AdminSignUpForm template_name = 'form1/signup_form.html' def get_context_data(self, **kwargs): kwargs['user_type'] = 'ADMIN' return super().get_context_data(**kwargs) def form_valid(self, form): user = form.save() login(self.request, user) return redirect('/form1/forms/') class HRSignUpView(CreateView): model = User form_class = HRSignUpForm template_name = 'form1/signup_form.html' def get_context_data(self, **kwargs): kwargs['user_type'] = 'HR' return super().get_context_data(**kwargs) def form_valid(self,form): user = form.save() login(self.request, user) return redirect('/form1/forms') Here is my forms.py class AdminSignUpForm(UserCreationForm): class Meta(UserCreationForm.Meta): model = User fname = forms.CharField(max_length=256) lname = forms.CharField(max_length=256) @transaction.atomic def save(self): user = super().save(commit=False) user.roles = 1 user.save() admin1 = Admins.objects.create(user=user) admin1.first_name.add(*self.cleaned_data.get('fname')) admin1.last_name.add(*self.cleaned_data.get('lname')) return user class HRSignUpForm(UserCreationForm): class Meta(UserCreationForm.Meta): model = User @transaction.atomic() def save(self, commit=True): user = super().save(commit=False) user.roles = 2 user.save() hr1 = HRs.objects.create(user=user) hr1.first_name.add(*self.cleaned_data.get('fname')) hr1.last_name.add(*self.cleaned_data.get('lname')) return user Finally, here is my error - OperationalError at /accounts/signup/hr/ no such … -
Unable to import Django Project onto additional computers
For the final project in my software class, my group has decided to use Django to build a web app. I created a Django project with a working Virtual Environment and have it sitting in GitHub for my teammates to be able to access and collaborate. So far, I have been able to run the website and create new apps with ease. That being said, when my teammates first pull from VCS into Pycharm Professional and configure the interpreter, they are met with this error: Cannot set up a python SDK at Python 3.8 (DeliverMe) (/Users/taylorschissel/PycharmProjects/DeliverMe/venv/bin/python) The SDK seems invalid. I have read through many posts but cannot seem to find anyone with a similar issue, so I am at a loss for causes/solutions. Here is the link to the repo: https://github.com/isaacfc4/DeliverMe -
Difficulty adding widget to django project
Firstly I apologize for the very basic question but I am currently learning to develop and have read a lot of documentation and searched a lot but still cannot get this working. I'm building a website using Django framework am trying to add the django-bootstrap-datepicker-plus widget. I am having a lot of difficulty figuring out exactly where the different parts of code should go. I have included snippets from my model.py and forms.py files below. The forms work as they are now, but I encounter lots of problems when I try to add the datePicker widget. class PersonalInformation(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) GENDERS = ( ('M', 'Male'), ('F', 'Female'), ) first_name = models.CharField(max_length=200, default='') surname = models.CharField(max_length=200, default='') gender = models.CharField(max_length=1, choices=GENDERS) class PersonalInformationForm(forms.ModelForm): class Meta: model = PersonalInformation fields = ['first_name', 'surname', 'gender'] Thank you very much and I apologize for the very basic question but I have spent hours trying to figure it out and am just going around in circles. -
Does enabling HTTP/2 in Daphne preclude Daphne's server pushed events feature from working?
The HTTP/2 Support section of the Daphne GitHub page (https://github.com/django/daphne#http2-support) says: Daphne only supports "normal" requests over HTTP/2 at this time; there is not yet support for extended features like Server Push. I plan on using Daphne for its server push feature. Does the above statement imply I should not even try to enable HTTP/2 because it would prevent the server push feature from working at all? -
Apache configuration for serving Django app is not working
I have installed my Django Project on the server, and it is running locally with no problem. I can make migrations and runserver works with no error. I am following this tutorial in order to use Apache to serve the project on Ubuntu, but I am having problems. The first one is where you start Django's development server and allow remote connections (./manage.py runserver 0.0.0.0:8000). When I connect from a remote browser, I get this error: Esta página no funciona 189.172.218.174 envió una respuesta no válida. ERR_INVALID_HTTP_RESPONSE I have also made al configurations to serve the app with Apache, but when a try to connect to the server from a browser, I just get a blank page. No error or anything. This is my 000-default.conf file: <VirtualHost *:80> # The ServerName directive sets the request scheme, hostname and port that # the server uses to identify itself. This is used when creating # redirection URLs. In the context of virtual hosts, the ServerName # specifies what hostname must appear in the request's Host: header to # match this virtual host. For the default virtual host (this file) this # value is not decisive as it is used as a last …