Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Continuous cycling through all objects in a table with django
As a learner of the django framework, I face the challenge of looping through all primary keys of a table, beginning with the first, and at the end of the sequence, to start all over again. The id field is an auto-incrementing serial field in postgres. A very basic breakdown of the project is as follows: models.py ... class Event(models.Model): id = models.BigAutoField(primary_key=True) event_name = models.BigIntegerField(blank=True, null=False) timestamp = models.DateTimeField(blank=True, null=True) viewed = models.BooleanField(default=False) views.py def home(request, id=None): from .models import Event first_obj = Event.objects.order_by('id').first() my_json = serialize('json', first_obj, fields=('event_name', 'timestamp')) return render(request, 'home.html', {'items': my_json}) def confirm(request): #set viewed=True on current object .save() return redirect('home') #move to next object home.html ... <form method="POST" action="{% url 'confirm' %}"> <button>confirm</button> </form> ... The idea is to send the my_json object to an html template. A user clicks a button, which should then mark the current object as viewed (sets viewed from False to True), then the next object should be fetched (by incremental primary key), and so on. If it has reached the last object, the first object (pk=1) should be fetched next, and the cycle continues. I would like to avoid making ajax requests and think a second url would … -
Is it possible to list out a range of values in the database?
Let's say I have a form that has 2 fields, First and Last. For example, the input for First: 1 and Last : 5. Upon saving: It saves the range: 1, 2, 3, 4, 5 and stored under a single field (Num) in a database table called (Numbers), row 1 - 1, row 2 - 2, row 3 - 3, row 4 - 4, row 5 - 5 It saves the First and Last values in a table called Range. Using a view (Django) and somehow uses the numbers of 1 & 5 and derive the range of 1, 2, 3, 4, 5 and stored in another table (Numbers) where under the field (Num), row 1 - 1, row 2 - 2, row 3 - 3, row 4 - 4, row 5 - 5 Which is possible? And how do i do it? Appreciate it for any help provided -
How to use Django rest framework query parameters
I'm trying to create an API with Django and I'm having a hard time understanding how query string parameters work: So far I created an endpoint which gives out a list of products and know I want to be able to filter those products by name like /api/Products/name=guitar or any equivalent of /api/Products?name=guitar I created this view and serializer: serializer_class = ProductSerializer def get_queryset(self): queryset = ProductJoinShop.objects.raw(f'select * from Product join Shop using (id_shop) limit 12') name = self.request.query_params.get('name') if name is not None: queryset = ProductJoinShop.objects.raw(f'select * from Product join Shop using (id_shop) where name like \'%{name}%\' limit 12') return queryset And this is my urls.py: router = routers.DefaultRouter() router.register(r'Products', views.ProductView, 'Products') router.register(r'Products/(?P<name>.+)/$', views.ProductView, 'ProductsSearch') urlpatterns = [ path('admin/', admin.site.urls), path('api/', include(router.urls)) ] This doesn't crash but for /api/Products/guitar/ I get nothing back. I also tried /api/Products/?name=guitar/ and that throws an error. Thanks! -
django unable to save req body to sqlitedb
I have a nitpicky problem with my Django rest api, I'm using postman to POST in some basic information as raw json then make an instance of the model 'Planet' then store it in the sqlite db that comes with django as standard, I'm getting a 200 response but it is failing the try block for some weird reason?, I have tried changing the param values and also the model data types but it doesn't seem to fix it, there are no errors server side either hoping someone can point out my logic error here :) Model class class Planet(models.Model): name = models.CharField(max_length=20) temp = models.CharField(max_length=20) hrs = models.CharField(max_length=20) mass = models.CharField(max_length=20) diameter = models.CharField(max_length=20) circumference = models.CharField(max_length=20) def add_planet(request): if request.method == 'POST': payload = json.loads(request.body) planet_name = payload['name'] avg_temp = payload['temp'] day_hrs = payload['hrs'] planet_mass = payload['mass'] planet_diameter = payload['diameter'] planet_circumference = payload['circumference'] //data prints out correctly here print(planet_name,avg_temp,day_hrs,planet_mass,planet_diameter,planet_circumference) planet = Planet(name=planet_name,temp=avg_temp,hrs=day_hrs,mass=planet_mass, diameter=planet_diameter, circumference=planet_circumference) try: planet.save() response = json.dumps([{ 'Success': 'Planet added successfully!'}]) except: response = json.dumps([{ 'Error': 'Planet could not be added!'}]) return HttpResponse(response, content_type='text/json') here is my json body being sent in postman, I'm using POST and raw json as my option as I don't have … -
Unable to verify email while using simple JWT in django
The register and login sections are functioning properly in my django application. When someone registers he receives a confirmation email, but on clicking the email confirmation link the account is not verified. I'm using try and except, it's the except that is being executed each time and try never executes. models.py username = models.CharField(max_length=255, unique=True, db_index=True) email = models.EmailField(max_length=255, unique=True, db_index=True) is_verified = models.BooleanField(default=False) views.py serializer_class = EmailVerificationSerializer def get(self, request): token = request.GET.get('token') try: key = jwt.decode(token, settings.SECRET_KEY) user = User.objects.get(id=key['user_id']) if not user.is_verified: user.is_verified = True user.save() return Response({'email': 'Your email has been activated'}, status=status.HTTP_200_OK) except jwt.exceptions.DecodeError as identifier: return Response({'error': 'token not valid'}, status=status.HTTP_400_BAD_REQUEST) Please I want to know why the the code in the try section never gets executed even when the token is intact and has not expired. -
How to implement only one user session to perform specific task in my django application
I have a application, in that one page has form submit operation which writes a data to data base, I want this submit operation to perform by only one user session at a time, if other user submitted it must show , please wait some user is performing operation like that, please suggest here. -
Can't access django admin anymore
I can no longer access my admin page after the last migration I made. All I did was add a foreign field connecting two models (Listing and User). I am getting the message: “C:... Django\commerce\media\admin” does not exist I did a lot of searching but all I came up with was to delete 'django.contrib.sites', or to add it instead while setting SITE_ID equal to 1. There was also the suggestion to put: from django.contrib.sites.models import Site Site.objects.create(pk=1, domain='localhost', name='localhost') into python shell. None of these things worked for me. For some reason django seems to be searching in my media folder but I have no idea why it would do that. My settings: """ Django settings for commerce project. Generated by 'django-admin startproject' using Django 3.0.2. For more information on this file, see https://docs.djangoproject.com/en/3.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.0/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '6ps8j!crjgrxt34cqbqn7x&b3y%(fny8k8nh21+qa)%ws3fh!q' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True … -
Disable image-cleanup in Django
I create a few badge for users. I using django-CleanUp for delete other media objects. When user's score high enough I want change old badge to new badge. But when change images, old image(badge) is deleted. I dont want this. I want keep old badge because is still used other users My Views: def liked_post(request, pk): user_update = get_object_or_404(UserRanks, user = post.username) if user_update.score < 50: user_update.rank_image = "guard.gif" elif user_update.score < 100: user_update.rank_image = "captain1.gif" elif user_update.score < 300: user_update.rank_image = "knight1.gif" user_update.save() my Models: class UserRanks(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) rank_image = models.ImageField( verbose_name="Rank Gif", default="guard.gif", null=True, blank=True) score = models.IntegerField( null=True, blank=True, verbose_name="Score", default=0) def save(self, *args, **kwargs): super(UserRanks, self).save(*args, **kwargs) is there a way to do keep old image without remove the django-clean-up? -
Django email verification link redirect to last page rather than set url
I have a django website where a user can select "sign up" from many different pages with many different urls. I want the authorization link they receive to return them to the page they were at, rather than some set page. My set up is as follows: *** using default Abstract User class urls.py urlpatterns = [ path('signup/', SignUpView.as_view(), name='signup'), path('activate/<uid>/<token>/', ActivateAccount.as_view(), name='activate'), ] ***using default django login/registration with custom templates registration/signup.html {% extends 'gitrepo/base.html' %} {% block title %}Sign Up{% endblock %} {% block content %} <h2>Sign Up</h2> <p>Register using your username. <br> You will be asked to verify your email.</p> <form method="post"> {% csrf_token %} {{ form.as_p }} {% if request.GET.next %} <input type="hidden" name="next" value="{{ request.GET.next}}"> {% endif %} <button type="submit">Sign Up</button> </form> <p><b> {% if messages %} {% for message in messages %} <div class="alert {% if message.tags %}alert-{{ message.tags }}{% endif %}" role="alert">{{ message }}</div> {% endfor %} {% endif %} </b></p> {% endblock %} *** this queries an ldap to get the user's email in the following views.py User = get_user_model() class SignUpView(View): form_class = UserCreationForm template_name = 'registration/signup.html' def get(self, request, *args, **kwargs): form = self.form_class() return render(request, self.template_name, {'form': form}) def post(self, … -
how do I get my altair plot from views to render on my html page in Django?
I am trying to get my Altair plot to render from my views to my html page. I have tried everything from stack overflow to get this to work, but every time I try I don't get my plot. This is my code in the different sections. Views.py: def search_site(request): if request.method == "POST": inputSite = request.POST.get('Site') SITES = Ericsson_LTE_1D_Version_Sectir_ID_HOUR.objects.filter(SITE__contains = inputSite).values() data = pd.DataFrame(SITES) chart = alt.Chart(data).mark_line().encode( y ='Avg_Nr_Of_RRC_Connected_Users:Q', x ='PERIOD_START_TIME:T', ).to_json(indent=None) return render(request,'VenueReporting/searchSite.html', {'site':inputSite,'Predictions':SITES,'chart':chart}) else: return render(request, 'VenueReporting/searchSite.html',{}) HTML Page: <head> <script src="https://cdn.jsdelivr.net/npm/vega@[VERSION]"></script> <script src="https://cdn.jsdelivr.net/npm/vega-lite@[VERSION]"></script> <script src="https://cdn.jsdelivr.net/npm/vega-embed@[VERSION]"></script> </head> <body> <script type="text/javascript"> var chart = "{{chart}}"; vegaEmbed('#vis1', chart).then(result => console.log(result)) .catch(console.warn); </script> {% if Predictions %} <h2>You Searched for:</h2> <h3>{{site}}</h3> <h2>The activity was:</h2> <div id="vis1"></div> {% else %} <h1>That Venue does not exist or you put the wrong information</h1> {% endif %} </body> -
How to add the valid css class for form field?
Is there an opposite equivalent for error_css_class in forms class/template? I cannot find a way to add a valid class only after validation. -
Django forms retrieve unique list
just wanted to know how to reference a unique list from a models field. Here is the forms: Defect_Area_Associate = forms.ChoiceField(choices=[("%s" % dv['pk'], "%s" % dv['Defect_Area_dv']) for dv in dv_model.objects.all().values('pk', 'Defect_Area_dv')], widget=forms.Select) I want to be able to get only the unique list of "Defect_Area_dv". I tried calling .unique() but cant figure what change to make... Hope someone can help me with that. -
Get Fatal Python error: Module Not Found: No module named encoding
I am trying to get my Apache Web Server to run my Django page using wsgi.py. My virtual environment is at /var/www/myapp/myapp_root/myapp. When I activate the virtual environment I see my user home directory being used. I tried the following wsgi.py changes: """ WSGI config for trackx project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/3.1/howto/deployment/wsgi/ """ import os,sys sys.path.append('/home/myuserid/.local/share/virtualenvs/lib/python3.9/site-packages') from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'trackx.settings') application = get_wsgi_application() When I try to start the server - it gives me the following repeating error (over and over): Python path configuration: PYTHONHOME = '/home/myuser/.local/share/virtualenvs/myapp-nygxcPTP/lib/python3.9' PYTHONPATH = (not set) program name = 'python3' isolated = 0 environment = 1 user site = 1 import site = 1 sys._base_executable = '/usr/local/bin/python3' sys.base_prefix = '/home/myuser/.local/share/virtualenvs/myapp-nygxcPTP/lib/python3.9' sys.base_exec_prefix = '/home/myuser/.local/share/virtualenvs/myapp-nygxcPTP/lib/python3.9' sys.executable = '/usr/local/bin/python3' sys.prefix = '/home/myuser/.local/share/virtualenvs/myapp-nygxcPTP/lib/python3.9' sys.exec_prefix = '/home/myuser/.local/share/virtualenvs/myapp-nygxcPTP/lib/python3.9' sys.path = [ '/home/my-user/.local/share/virtualenvs/myapp-nygxcPTP/lib/python3.9/lib64/python38.zip', '/home/myuser/.local/share/virtualenvs/myapp-nygxcPTP/lib/python3.9/lib64/python3.8', '/home/myuser/.local/share/virtualenvs/myapp-nygxcPTP/lib/python3.9/lib64/python3.8/lib-dynload', ] Fatal Python error: init_fs_encoding: failed to get the Python codec of the filesystem encoding Python runtime state: core initialized ModuleNotFoundError: No module named 'encodings' Current thread 0x00007f52bfd07880 (most recent call first): <no Python frame> My WSGI settings in the http.conf file look like this... WSGIPythonHome /var/www/myapp/myapp_root/venv WSGIPythonPath /var/www/myapp/myapp_root/venv/lib/python3.9/site-packages WSGIDaemonProcess … -
'NoneType' object has no attribute 'id'. Django Admin
Here is my model and my admin code. Whenever I create a group without a headman I've got this error when Im reaching Groups page in admin -'NoneType' object has no attribute 'id'. What should I change? @admin.register(Group) class GroupAdmin(admin.ModelAdmin): list_display = ("descipline", "hours_to_take", 'link_to_curator', "link_to_headman") list_filter = ("descipline", "hours_to_take") search_fields = ("descipline__startswith", ) list_display_links = ['link_to_curator', 'link_to_headman'] def link_to_headman(self, obj): link = reverse("admin:students_student_change", args=[obj.headman.id]) return format_html(u'<a href="%s">%s<a/>' % (link,obj.headman.last_name)) class Group(models.Model): descipline = models.CharField(max_length=200) hours_to_take = models.IntegerField(default=32) headman = models.ForeignKey('students.Student',blank=True, null=True, unique=False, on_delete=models.CASCADE, related_name="headed_group") curator = models.ForeignKey(Teacher, on_delete=models.CASCADE, null=True, blank=True,) -
I have an error in importing django debug toolbar
I am writing a project with django and I am trying to install the debug toolbar. I have done everything in the installation page like the command and also the things in the different files. In the urls.py file when do "import debug_toolbar" there's a yellow line under it and the error says "Import debug_toolbar could not be resolved". BTW I am following the tutorial by code with mosh and here's my code if that helps. Thanks for any help. urls.py from django.contrib import admin from django.urls import path, include import debug_toolbar urlpatterns = [ path('admin/', admin.site.urls), path('playground/', include('playground.urls')), path('__debug__/', include(debug_toolbar.urls)), ] settings.py """ Django settings for storefront project. Generated by 'django-admin startproject' using Django 3.2.6. For more information on this file, see https://docs.djangoproject.com/en/3.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.2/ref/settings/ """ from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-%unxe*h6tbm-+e3wx60wl0ce%q@!uw-csq64o^x#&o*g#7936p' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS … -
Sort a tsv by date with python
I've downloaded some files using python-edgar and it's all tsv. However when I tried using it, the rows are not arranged according to dates. Here is the format: param1 | param2 | param3 | date | param5 | param6 | Sample content: 1000045|sample 1|10-Q|2021-02-11|edgar/data/1000045/0001564590-21-005399.txt|edgar/data/1000045/0001564590-21-005399-index.html 1000045|sample 1|4/A|2021-02-12|edgar/data/1000045/0001398344-21-003309.txt|edgar/data/1000045/0001398344-21-003309-index.html 1000045|sample 1|4|2021-02-08|edgar/data/1000045/0001496701-21-000001.txt|edgar/data/1000045/0001496701-21-000001-index.html 1000045|sample 1|4|2021-02-09|edgar/data/1000045/0001398344-21-002769.txt|edgar/data/1000045/0001398344-21-002769-index.html 1000045|sample 1|8-K|2021-01-25|edgar/data/1000045/0001564590-21-002004.txt|edgar/data/1000045/0001564590-21-002004-index.html 1000045|sample 1|8-K|2021-02-03|edgar/data/1000045/0001564590-21-003940.txt|edgar/data/1000045/0001564590-21-003940-index.html 1000045|sample 1|8-K|2021-03-08|edgar/data/1000045/0001564590-21-011365.txt|edgar/data/1000045/0001564590-21-011365-index.html 1000045|sample 1|SC 13G/A|2021-02-08|edgar/data/1000045/0001104659-21-013485.txt|edgar/data/1000045/0001104659-21-013485-index.html 1000045|sample 1|SC 13G/A|2021-02-11|edgar/data/1000045/0001037389-21-000122.txt|edgar/data/1000045/0001037389-21-000122-index.html 1000045|sample 1|SC 13G/A|2021-02-12|edgar/data/1000045/0000354204-21-000071.txt|edgar/data/1000045/0000354204-21-000071-index.html 1000097|sample 2|13F-HR|2021-02-16|edgar/data/1000097/0001000097-21-000004.txt|edgar/data/1000097/0001000097-21-000004-index.html 1000097|sample 2|SC 13G|2021-01-11|edgar/data/1000097/0000919574-21-000165.txt|edgar/data/1000097/0000919574-21-000165-index.html 1000177|sample 3|SC 13G/A|2021-01-29|edgar/data/1000177/0000834237-21-004594.txt|edgar/data/1000177/0000834237-21-004594-index.html Currently its sorted by param1. I need to sort it by date. I tried to use this answer to sort using the fourth column: sort -t $'\t' -k 4,4 2021-QTR1.tsv but it did not do anything. I need it sorted by date so I can use my script here: def edgar_filings_download(date): try: with open(edgar_path + filename, 'r') as file: tsv_file = list(csv.reader(file, delimiter='|')) _CHECK = datetime.datetime.strptime(date, "%Y-%m-%d") start_date = datetime.datetime.strptime(tsv_file[len(tsv_file) - 1][3], "%Y-%m-%d") end_date = datetime.datetime.strptime(tsv_file[0][3], "%Y-%m-%d") if start_date <= _CHECK <= end_date: logger.debug('pass') else: logger.debug('no pass') except Exception as e: logger.error(e) Any help would be appreciated. -
How to (easily) put python variables from Django into html?
In one of my Django projects in views.py I've got some code: from django.shortcuts import render from django.http import HttpResponse from .models import * # Create your views here. products = Product.objects.all() product_list = list(products) def displayhome(request): return render(request, 'bootstrap/index.html', {'title': product_list[0].title}, {'link': product_list[0].official_path_name}) Now using this (very clunky) method, I am able to put the string version of variables into html using: {{title}} for example. However this does not let me operate on the variables, e.g. if I sent through product_list I couldn't get product_list[0]. I vaguely know of using {% %} tags instead of {{ }} but I am (a) not completely sure how they work and (b) don't know how powerful they are e.g. if you could use it like a normal python file. If there is no easy way to execute python in html, is there a way to instead put my python variables into javascript and then somehow use those in the html instead? -
Bad Gateway on Geonode Advanced installation Ubuntu 20.04
I am going through the installation process, and when i reach the step 6.3 Update OAuth2 configuration in order to hit the new hostname. sudo PYTHONWARNINGS=ignore VIRTUAL_ENV=$VIRTUAL_ENV DJANGO_SETTINGS_MODULE=geonode.settings GEONODE_ETC=/opt/geonode/geonode GEOSERVER_DATA_DIR=/opt/data/geoserver_data TOMCAT_SERVICE="service tomcat" APACHE_SERVICE="service nginx" geonode_updateip -l localhost -p csdc.immap.org I got this errors related to database: Traceback (most recent call last): File "/home/geonode/.virtualenvs/geonode/bin/django-admin", line 8, in <module> sys.exit(execute_from_command_line()) File "/home/geonode/.virtualenvs/geonode/lib/python3.8/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/home/geonode/.virtualenvs/geonode/lib/python3.8/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/geonode/.virtualenvs/geonode/lib/python3.8/site-packages/django/core/management/base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "/home/geonode/.virtualenvs/geonode/lib/python3.8/site-packages/django/core/management/base.py", line 364, in execute output = self.handle(*args, **options) File "/opt/geonode/geonode/base/management/commands/fixsitename.py", line 39, in handle site = Site.objects.get_current() File "/home/geonode/.virtualenvs/geonode/lib/python3.8/site-packages/django/contrib/sites/models.py", line 58, in get_current return self._get_site_by_id(site_id) File "/home/geonode/.virtualenvs/geonode/lib/python3.8/site-packages/django/contrib/sites/models.py", line 30, in _get_site_by_id site = self.get(pk=site_id) File "/home/geonode/.virtualenvs/geonode/lib/python3.8/site-packages/django/db/models/manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/home/geonode/.virtualenvs/geonode/lib/python3.8/site-packages/django/db/models/query.py", line 402, in get num = len(clone) File "/home/geonode/.virtualenvs/geonode/lib/python3.8/site-packages/django/db/models/query.py", line 256, in __len__ self._fetch_all() File "/home/geonode/.virtualenvs/geonode/lib/python3.8/site-packages/django/db/models/query.py", line 1242, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "/home/geonode/.virtualenvs/geonode/lib/python3.8/site-packages/django/db/models/query.py", line 55, in __iter__ results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size) File "/home/geonode/.virtualenvs/geonode/lib/python3.8/site-packages/django/db/models/sql/compiler.py", line 1142, in execute_sql cursor.execute(sql, params) File "/home/geonode/.virtualenvs/geonode/lib/python3.8/site-packages/django/db/backends/utils.py", line 99, in execute return super().execute(sql, params) File "/home/geonode/.virtualenvs/geonode/lib/python3.8/site-packages/django/db/backends/utils.py", line 67, in execute return self._execute_with_wrappers(sql, params, many=False, executor=self._execute) File "/home/geonode/.virtualenvs/geonode/lib/python3.8/site-packages/django/db/backends/utils.py", line 76, in _execute_with_wrappers return executor(sql, params, many, context) … -
Django and React realtime app architecture
In a nutshell, I'm designing an app similar to https://www.tradingview.com/. So I need previous data to get the OHLC (Open, High, Low, Close) for the previous 1 minute or 5 minutes or 1-hour, interval here can change, also other than that I need real-time data to populate the candlestick chart. I'm using Binance's services for both getting the previous data, by API calls, and the current real-time data, via connection to their WebSocket server. And the problem is I don't know to properly manage those data, I wrote all the scenarios that came to my mind: 1- Make the backend serves the previous data and let the frontend connect to the WebSocket and continue appending data. 2- Make the backend serves both the previous data and also set up a WebSocket server for the client to connect to 3- Make the frontend get both the previous data and connect to Binance's WebSocket server Which way shall I go, the third option for me is the easiest, but I'm afraid that it may put a huge load on the browser, and finally, the project will be hosted on AWS if there is any service that may help. -
Changing db schema django based heroku
I am adding a field to my existing Django model and when I push it to Heroku the new field didn't add and it shows an error : column [new field] does not exist. What did I miss? I did migrate it and the new field added in local Django but it's not changing in Heroku column quizTest_responden.nohp does not exist LINE 1: ...st_responden"."job", "quizTest_responden"."jobg", "quizTest_... -
Unable to install mod_wsgi package
I am trying to install mod_wsgi package using pip , in amazon linux 2 instance, but I keep facing an error: Command: python3 -m pip install mod_wsgi OUTPUT/ERROR: Defaulting to user installation because normal site-packages is not writeable Collecting mod_wsgi Using cached mod_wsgi-4.9.0.tar.gz (497 kB) ERROR: Command errored out with exit status 1: command: /usr/bin/python3 -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-2sfljsxd/mod-wsgi/setup.py'"'"'; __file__='"'"'/tmp/pip-install-2sfljsxd/mod-wsgi/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base /tmp/pip-pip-egg-info-54w0mlq7 cwd: /tmp/pip-install-2sfljsxd/mod-wsgi/ Complete output (5 lines): Traceback (most recent call last): File "<string>", line 1, in <module> File "/tmp/pip-install-2sfljsxd/mod-wsgi/setup.py", line 91, in <module> 'missing Apache httpd server packages.' % APXS) RuntimeError: The 'apxs' command appears not to be installed or is not executable. Please check the list of prerequisites in the documentation for this package and install any missing Apache httpd server packages. ---------------------------------------- ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output. Steps taken trying to resolve the error: 1.I tried running python setup.py egg_info, but kept getting the error setup.py doesnt exist 2.I tried finding setup.py , using the command find . -name setup.py, but nothing was returned How do I solve this? PS: I know you … -
Django Foreign Key to Multiple Models
Is there a way to make one model be able to foreignkey to more than one model? For example class Tshirt(models.Model): ..... class Jeans(models.Model): ..... class Clothes(models.Model): item = ForeignKey(Tshirt and Jeans, on_delete = models.CASCADE) -
How to create a matrix type table with one form field where field name attribute will be different (like as matrix a_1_1, a_1_2, ...) in Django?
My form: class DatainputForm(forms.Form): def __init__(self, request, *args, **kwargs): super().__init__(*args, **kwargs) for i in range(3): for j in range(3): self.fields['costtp_sd%s%s' % (i, j)] = forms.DecimalField() In HTML template: {% for form in datatp_from %} # datatp_from is the name of the form in views.py {{ form }} {% endform %} Form shows in HTML page: Form shows in HTML page: But I want it in a matrix form like below: But I want it in a matrix form like below: -
How to upload an image temporarily on Heroku?
I am facing the following issue: I have deployed a Django-app to the Heroku and want to upload an image using file input. But it should not be storing there, it could be deleted after I reload the page, but I want to have URL to this image for that time. So, I have no idea how to do this at all, can someone help me? -
Django PostUpdateView isn't saving image ValueError thrown
In models.py I have: class Post(models.Model): title = models.CharField(max_length=100) post_content = models.TextField(max_length=10000) date_posted= models.DateTimeField(auto_now_add=True) image = models.ImageField(upload_to='blog-post-images/', blank=True, null=True) author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail', kwargs={'pk': self.pk}) def save(self, *args, **kwargs): super().save(*args, **kwargs) img = Image.open(self.image.path) if img.height > 500 or img.width > 500: if img.height > img.width: factor=500/img.height nH=500 nW=img.width*factor output_size= (nH,nW) if img.width > img.height: factor=500/img.width nW=500 nH=img.height*factor output_size= (nH,nW) else: output_size=(500,500) img = ImageOps.exif_transpose(img) img.thumbnail(output_size) img.save(self.image.path) And then in views I have: class PostUpdateView(LoginRequiredMixin, UserPassesTestMixin, UpdateView): model = Post fields = ['title', 'post_content', 'image'] def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) def test_func(self): post=self.get_object() if self.request.user == post.author: return True return False Upon runserver, page renders html with form fields just fine, allows me to select image path, but then the error I get thrown when actually submitting image path is: "ValueError at /home/post/10/update/ The 'image' attribute has no file associated with it." And image doesn't save. However, when I do it through admin it does save image. I have image blank and null bc I want image to be optional attribute. Is this the reason I'm getting issues? Does something extra need to be added to PostUpdateView class? Thank …