Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Get Display CHOICE in a ForeignKey Django Model
My models: class Sell(models.Model): item = models.OneToOneField(Buy, related_name='sell', on_delete=models.CASCADE) date = models.DateField(default=timezone.now) code = models.ForeignKey(Order, related_name='order', on_delete=models.CASCADE, null=True, blank=True) class Order(models.Model): status_choice = ( ("W", "Aguardando aprovação do pagamento"), ("A", "Pagamento aprovado - produto em separação"), ) code = models.CharField(max_length=100) status = models.CharField(max_length=1, choices=status_choice, default='W') My template: {% for order in orders %} <tr> <td>{{ order.code__code }}</td> <td>{{ order.date }}</td> <td>{{ order.get_code__status_display }}</td> </tr> {% endfor %} The output I was expecting: "Aguardando aprovação do pagamento" but it's not printing this. Any help to display the full text instead the only word "W"? Thank you! -
Django unit tests - API calls slowing down testing greatly, optimize or rewrite?
I have an application that calls to OpenWeatherMap API and I decided to write a test for the purpose of verifying that the cities are listed on the url page context. I used the setUpTestData class method to populate the test DB, but when I run the tests the time taken goes from 0.0XX seconds without the test DB to like 5.7XX seconds with the test DB. I believe its the API calls to populate the DB that is causing the slow down (Which I assume also counts against my limit for calls per hour on the API key) and I am wondering what the proper way would be to test something like this? I.E something that relies on API data to work properly. Do I need to optimize my code, or is my approach wrong? I am relatively new to unit testing, so I appreciate any tips or advice you may have. views.py class WeatherHomeView(TemplateView): template_name='weather/home.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) url = 'API URL' cities = City.objects.all() weather_data = [] for city in cities: city_weather = requests.get(url.format(city)).json() weather = { 'city' : city, 'temperature' : city_weather['main']['temp'], 'description' : city_weather['weather'][0]['description'], 'icon' : city_weather['weather'][0]['icon'], } weather_data.append(weather) context = {'weather_data' … -
Mocking dataframe for testing in python
I am trying to mock a dataframe for unit testing in python. here is the form of the table: However, I am having trouble hard coding a dataframe to have a json within it. This is my attempt at mocking a record: test_strip = pd.DataFrame( [[1], "2020-09-21", [{'WTI': {'1604188800000': '40.25', '1606780800000': '40.51', '1609459200000': '40.81', '1612137600000': '41.13', '1614556800000': '41.45', '1617235200000': '41.74', '1619827200000': '42.00', '1622505600000': '42.22'} }], [1]], columns=['id','trade_date','prices','contract'] ) This yields the following error: ValueError: 4 columns passed, passed data had 10 columns So it appears it is interpreting my json as separate records. Appreciate any help anyone might have. -
Is there any other way to avoid duplicate data while scraping and avoid storing the same data in database?
I have a simple model. models.py class Content(models.Model): title = models.CharField(max_length = 300, unique = True) category = models.CharField(max_length = 50) def __str__(self): return self.title then I'm scrapping the data from some sources and want to store in this table. toi_r = requests.get("some source") toi_soup = BeautifulSoup(toi_r.content, 'html5lib') toi_headings = toi_soup.findAll("h2", {"class": "entry-title format-icon"})[0:9] toi_category = toi_soup.findAll("a", {"class": ""})[0:9] toi_news = [th.text for th in toi_headings] toi_cat = [tr.text for tr in toi_category] for th in toi_headings: toi_news.append(th.text) for tr in toi_category: toi_cat.append(tr.text) for title, category in zip(toi_news, toi_cat): n = Content.objects.create(title=title, category=category) So here, error is UNIQUE Constraint failed. So, If I remove the UNIQUE Constraint, then everything works but mulitple copies of data are stored as the page refreshes. Is there any other way to work with this? -
Can't login with new users, only old users (Django Rest Framework views.obtain_auth_token)
I first noticed this after I deployed my site, but I checked when running it locally and I get the same issue, so I guess this was happening before deployment without me noticing. Posting log in credentials for new users to obtain a token using DRF views.obtain_auth_token only works for users that I created early in the project, not new ones (trying to login with new users returns a bad request cant login in with user credentials). I don't understand why because new users are still created, and appear in the admin User panel along with the old users, and I can see tokens are still generated for new users created. I'm guessing it might be because I've done something wrong when changing the user model, but I'm fairly sure I created the first users after I changed it, so I'm not really sure. Here is my user model: class UserManager(BaseUserManager): use_in_migrations = True def _create_user(self, email, password, **extra_fields): '''Create and save a user with the given email, and password. ''' if not email: raise ValueError('The given email must be set') email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, password=None, **extra_fields): extra_fields.setdefault('is_staff', False) extra_fields.setdefault('is_superuser', … -
Deploying Multiple Django Websites with Apache & mod_wsgi Windows
I am using mod_wsgi in a virtualenv with Apache 2.4 and I want to serve multiple Django sites from the same server. httpd.config ### Configuration Site_1 LoadModule wsgi_module " S:/Site_1/VirtualEnvSite_1/Lib/site-packages/mod_wsgi/server/mod_wsgi.cp36-win_amd64.pyd" WSGIApplicationGroup %{GLOBAL} WSGIPythonHome "c:/users/mmyuser/appdata/local/programs/python/python36" WSGIScriptAlias / " S:/Site_1/site_1/site_1/wsgi_windows.py" WSGIPythonPath " S:/Site_1/VirtualEnvSite_1/Lib/site-packages" Alias /static " S:/Site_1/site_1/staticfiles" Alias /media " S:/Site_1/site_1/media" <Directory " S:/Site_1/site_1/staticfiles"> Require all granted </Directory> <Directory " S:/Site_1/site_1/media"> Require all granted </Directory> <Directory " S:/Site_1/site_1/PEQ"> <Files wsgi_windows.py> Require all granted </Files> </Directory> ####Configuration Site_2 LoadModule wsgi_module " S:/Site_2/VirtualEnvSite_2/lib/site-packages/mod_wsgi/server/mod_wsgi.cp36-win_amd64.pyd" WSGIApplicationGroup %{GLOBAL} WSGIPythonHome "c:/users/myuser/appdata/local/programs/python/python36" WSGIScriptAlias / " S:/Site_2/site_2/site_2/wsgi_windows.py" WSGIPythonPath " S:/Site_2/VirtualEnvSite_2/Lib/site-packages" Alias /static " S:/Site_2/site_2/staticfiles" Alias /media " S:/Site_2/site_2/media" <Directory " S:/Site_2/site_2/staticfiles"> Require all granted </Directory> <Directory " S:/Site_2/site_2/media"> Require all granted </Directory> <Directory " S:/Site_2/site_2/site_2"> <Files wsgi_windows.py> Require all granted </Files> </Directory> httpd-vhosts.config # Virtual Hosts # <VirtualHost *:8080> ServerAdmin webmaster@localhost DocumentRoot "c:/wamp/www" ServerName localhost ErrorLog "logs/localhost-error.log" CustomLog "logs/localhost-access.log" common </VirtualHost> I have reviewed these posts: Deploying multiple django apps on Apache with mod_wsgi multiple-django-sites-with-apache-mod-wsgi running-multiple-django-projects-on-one-apache-instance-with-mod_wsgi/ Múltiples direcciones, un solo proyecto how-to-use-mod-wsgi-for-hosting-multiple-django-projects-under-single-domain but they have not worked for me. The server is a Windows Server 2012R2 Please direct me what I should do to get both sites up and running. Note: The websites work perfectly separate -
Django unable to get model property Sum of objects in template
I want to get sum of all the prices available in my model. I have gone through this link Sum of objects' prices in Django template but I was not able to get my answer when I am running in a shell, I am getting the correct output, but from the template point unable to get the correct output **shell** >>> from tasks.models import Task >>> from django.db.models import Sum >>> Task.objects.all().aggregate(Sum('price')) {'price__sum': 2.0} Model: from django.db.models import Sum, Avg class Task(models.Model): title = models.CharField(max_length=200) complete = models.BooleanField(default=False) created = models.DateTimeField(auto_now_add=True) price = models.FloatField(max_length=5,default='0.00',editable=False) def __str__(self): return self.title @property def get_price_total(self): total=Task.objects.all().aggregate(Avg("price")) print(total) return total Views def query(request): tasks = Task.objects.all() form = TaskForm() if request.method =='POST': form=TaskForm(request.POST) if form.is_valid(): form.save() return redirect('/') print("Price",Task.get_price_total) context = {'tasks':tasks,'form':form,'Totalprice':Task.get_price_total} return render(request,'tasks/query.html',context) Output at the console is ( and same is getting printed in the template ) Django version 3.0.7, using settings 'todo.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. Price <property object at 0x000002D3301502C0> [29/Sep/2020 22:33:53] "GET /query/ HTTP/1.1" 200 2473 Can some help me where I am going wrong? -
VS Code | Django model error (doesn't recognize inheritance)
I have a model, "Post," and I'm calling it in views.py like this: def index(request): context = { 'posts': Post.objects.all() } return render(request, 'feed/index.html', context This was done, following this tutorial. It works just fine on the website itself, but VS Code is giving me an error stating, "Class 'Post' has no 'objects' member" from Pylint. But, where it's a Django model that was correctly setup in models.py; everything is working properly on the server. This class has inherited "objects" from pylint... why wouldn't this be recognized by pylint? -
Why am I getting this error "__str__ returned non-string" Django
I get this error in the admin page only when referencing the object (as foreign key when adding entries in another model) but when I create an entrie of that model it works well. I have this tuple of choices for a django field INSCRIPTION = 'INS' CROSSFIT = 'CRF' FUNCTIONAL = 'FUN' KICKBOXING = 'KBX' ALL_ACCESS = 'ALL' UNSPECIFIED = 'UNS' PAYMENT_CHOICES = ( (INSCRIPTION, 'Inscription'), (CROSSFIT, 'Crossfit'), (FUNCTIONAL, 'Functional'), (KICKBOXING, 'Kickboxing'), (ALL_ACCESS, 'All access'), (UNSPECIFIED, 'Unspecified') ) payment_code = models.CharField(max_length=3, choices=PAYMENT_CHOICES, default=UNSPECIFIED) amount = models.FloatField() def __str__(self): choice_index = 0 if self.payment_code == self.CROSSFIT: choice_index = 1 elif self.payment_code == self.FUNCTIONAL: choice_index = 2 elif self.payment_code == self.KICKBOXING: choice_index = 3 elif self.payment_code == self.ALL_ACCESS: choice_index = 4 payment_name = str(self.PAYMENT_CHOICES[choice_index][1]) return payment_name I get the error when I try to add an entry to this model class Payment(models.Model): payment_type = models.ForeignKey(PaymentType, on_delete=models.SET("UNS")) date = models.DateField(default=timezone.now) reference = models.IntegerField() athlete = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.payment_type -
Django forms initial value of ChoiceField when choices are dynamically set in __init__()
I have a Django form class: class FilterForm(forms.Form): number = forms.ChoiceField() def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # ... (logic for setting up available options) self.fields['number'].choices = number_choices When I instantiate this form with data={'number': -1} (and assuming that is a valid option's value), the form loads in the page with the last option in the select dropdown selected. I've attempted to set self.fields['number'].initial = kwargs['data']['number'], and I've tried self.initial['number'] = kwargs['data']['number'], both after the call to super(), and neither has worked to set the correct initially selected value in the dropdown. What am I missing here? -
Django CreateView does not saving and loading the success url after submit
Hello i have been working on django CreateVeiw. As i have add tags and save my post form. But the problem is after i click submit it just reload the page and when i check on my post it didnt add also. Did i miss something out? Can someone answer me? This is my view of creating post. class PostCreate(CreateView): template_name = 'add_post.html' model = Post form_class = PostForm def form_valid(self, form): form.instance.user = self.request.user form = form.save(commit=False) form.slug = slugify(form.title) form.save() form.save_m2m() return super(PostCreate, self).form_valid(form) def get_success_url(self): return reverse('article-list', args=self.object.id,) Thanks in advance :). -
How to submit data for the address and payment details after PayPal payment is made
I have recently integrated a PayPal payment option to my project and everything is working fine for the amounts of the items in the cart except that after a payment is made the items remain in the cart and there is no payment notified to the backend. My question is how to set a submit for the address and all the details made in the check out the template along with the paid amount to reflect in the backend. Here is the views.py class CheckoutView(View): def get(self, *args, **kwargs): try: order = Order.objects.get(user=self.request.user, ordered=False) form = CheckoutForm() context = { 'form': form, 'couponform': CouponForm(), 'order': order, 'DISPLAY_COUPON_FORM': True } shipping_address_qs = Address.objects.filter( user=self.request.user, address_type='S', default='True' ) if shipping_address_qs.exists(): context.update( {'default_shipping_address': shipping_address_qs[0]}) billing_address_qs = Address.objects.filter( user=self.request.user, address_type='B', default='True' ) if billing_address_qs.exists(): context.update( {'default_billing_address': billing_address_qs[0]}) return render(self.request, "checkout.html", context) except ObjectDoesNotExist: messages.info(self.request, "You do not have an active order") return redirect("core:checkout") def post(self, *args, **kwargs): form = CheckoutForm(self.request.POST or None) try: order = Order.objects.get(user=self.request.user, ordered=False) if form.is_valid(): use_default_shipping = form.cleaned_data.get( 'use_default_shipping') if use_default_shipping: print("Using the defualt shipping address") address_qs = Address.objects.filter( user=self.request.user, address_type='S', default=True ) if address_qs.exists(): shipping_address = address_qs[0] order.shipping_address = shipping_address order.save() else: messages.info( self.request, "No default shipping address available") … -
my webpage displays nothing at all. No html,css or images,just keeps on loading
I am trying to create a website with django but when i use load static files , it only loads but displays nothing.Aside from that , it also displays "Not Found" for all the css ,images and javascript files .Any help will be appreciated. The project layout is below. this is part of html code(full code is really long). <!DOCTYPE html> <html lang="en"> <head> <title>LERAMIZ - Landing Page Template</title> <meta charset="UTF-8"> <meta name="description" content="LERAMIZ Landing Page Template"> <meta name="keywords" content="LERAMIZ, unica, creative, html"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <!-- Favicon --> <link href="{% static 'Mainapp/img/favicon.ico'%}" rel="shortcut icon"/> <!-- Google Fonts --> <link href="https://fonts.googleapis.com/css?family=Source+Sans+Pro" rel="stylesheet"> <!-- Stylesheets --> <link rel="stylesheet" href="{% static 'Mainapp/css/bootstrap.min.css'%}" /> <link rel="stylesheet" href="{% static 'Mainapp/css/font-awesome.min.css'%}"/> <link rel="stylesheet" href="{% static 'Mainapp/css/animate.css'%}"/> <link rel="stylesheet" href="{% static 'Mainapp/css/owl.carousel.css'%}"/> <link rel="stylesheet" href="{% static 'Mainapp/css/style.css'%}"/> </body> </html> This is urls.py from django.conf.urls.static import static from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index.html'), ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) views.py from django.shortcuts import render def index(request): return render(request, 'Mainapp/index.html') settings.py import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'Mainapp', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', … -
Python3 Django3 Docker compose build issue on Windows machine - requirements.txt issue
Im trying to do a docker compose build, and I'm getting the same error. Ive tried removing and installing setuptools and cairocffi iwth pip 3 but have had not joy. Also tried going down a number of rabbit holes with finding out what gcc was but again no joy. Even tried copying to Ubuntu machine and that was couldnt even get python and pip installed there. Anyone have a clue what this error means or what I can try? requirements.txt appdirs==1.4.4 asgiref==3.2.10 asn1crypto==1.4.0 astroid==2.4.2 Babel==2.8.0 bleach==3.2.1 cairocffi==1.1.0 CairoSVG==2.4.2 certifi==2020.6.20 cffi==1.14.3 chardet==3.0.4 click==7.1.2 colorama==0.4.3 contextlib2==0.6.0.post1 coreapi==2.3.3 coreschema==0.0.4 cryptography==3.1.1 cssselect2==0.3.0 Cython==0.29.21 defusedxml==0.6.0 distlib==0.3.1 dj-database-url==0.5.0 Django==3.0.10 django-appconf==1.0.4 django-bootstrap3==14.1.0 django-classy-tags==2.0.0 django-cookie-law==2.0.3 django-countries==6.1.3 django-crispy-forms==1.9.2 django-enumfields==2.0.0 django-environ==0.4.5 django-filter==2.4.0 django-jinja==2.6.0 django-js-asset==1.2.2 django-mptt==0.11.0 django-parler==2.2 django-parler-rest==2.1 django-polymorphic==3.0.0 django-registration-redux==2.8 django-rest-swagger==2.2.0 django-reversion==3.0.8 django-timezone-field==4.0 djangorestframework==3.12.1 djangorestframework-jwt==1.11.0 easy-thumbnails==2.7 entrypoints==0.3 et-xmlfile==1.0.1 factory-boy==3.0.1 fake-factory==9999.9.9 Faker==4.1.3 filelock==3.0.12 html5lib==1.1 idna==2.10 isort==5.5.3 itypes==1.2.0 jdcal==1.4.1 Jinja2==2.11.2 jsonfield==3.1.0 keyring==21.4.0 keyrings.alt==3.5.2 lazy-object-proxy==1.4.3 lxml==4.5.2 Markdown==3.2.2 MarkupSafe==1.1.1 mccabe==0.6.1 openapi-codec==1.3.2 openpyxl==3.0.5 packaging==20.4 Pillow==7.2.0 pipenv==2020.8.13 pycparser==2.20 PyJWT==1.7.1 pylint==2.6.0 pylint-django==2.3.0 pylint-plugin-utils==0.6 pyparsing==2.4.7 pytest-runner==5.2 python-dateutil==2.8.1 pytz==2020.1 pywin32-ctypes==0.2.0 requests==2.24.0 setuptools==50.3.0 simplejson==3.17.2 six==1.15.0 spark-parser==1.8.9 sqlparse==0.3.1 text-unidecode==1.3 tinycss2==1.0.2 toml==0.10.1 typed-ast==1.4.1 uncompyle6==3.7.4 unicodecsv==0.14.1 Unidecode==1.1.1 uritemplate==3.0.1 urllib3==1.25.10 virtualenv==20.0.31 virtualenv-clone==0.5.4 webencodings==0.5.1 wrapt==1.12.1 xdis==5.0.4 xlrd==1.2.0 Error: Collecting cairocffi==1.1.0 Downloading cairocffi-1.1.0.tar.gz (68 kB) ERROR: Command errored out with exit status 1: command: /usr/local/bin/python -c 'import … -
Why are the changes to the database not part of the django migrations?
Database in a Django application can be modified using the admin panel or the shell or using the POST data from the user. But these modifications are not part of the migrations. Why it is so? It would be nice to have them because I can put them under source control. -
'User' object is not subscriptable
I created a form to set let the user changes their password, but I got this message: 'User' object is not subscriptable. I'd like to know how to change it properly. here's the part of my code. view.py def alterar_senha(request, user_username): if request.method == 'GET': form = AlterarSenha() context = { 'form': form, } return render(request, 'usuarios/administrativo/alterar_senha.html', context) elif request.method == 'POST': usuario = User.objects.get(username=user_username) form = AlterarSenha(request.POST) context = { 'form': form, } senha = request.POST.get('password') senha1 = request.POST.get('new_password1') senha2 = request.POST.get('new_password2') print(senha1, senha2) if not usuario.check_password(senha): form.add_error('password', 'Senha inválida!') id = usuario.id if form.is_valid(): user = usuario[id] user.set_password('senha') user.save() return redirect('logout') else: print(form.errors) return render(request, 'usuarios/administrativo/alterar_senha.html', context) forms.py class AlterarSenha(forms.Form): password = forms.CharField(label='Senha atual', widget=forms.PasswordInput( attrs={ 'class': 'form-control', 'placeholder': "Digite sua senha", 'name': 'senha1' } )) new_password1 = forms.CharField(label='Nova senha', widget=forms.PasswordInput( attrs={ 'class': 'form-control', 'placeholder': "Digite sua senha", 'name': 'password1' } )) new_password2 = forms.CharField(label='Repita a Senha', widget=forms.PasswordInput( attrs={ 'class': 'form-control', 'placeholder': "Digite novamente", 'name': 'password1' } )) def clean(self): new_password1 = self.cleaned_data.get('new_password1') new_password2 = self.cleaned_data.get('new_password2') lista_erros = {} checa_senha(new_password1, new_password2, lista_erros) if lista_erros is not None: for erro in lista_erros: mensagem_erro = lista_erros[erro] self.add_error(erro, mensagem_erro) return self.cleaned_data def save(self, commit=True): user = User.objects.create_user( password=self.cleaned_data['new_password1'] ) return user … -
Apache2 Ubuntu Server Module not found 'django'
I have been trying to move a django project on my Linode server into production. After trying to use Apache and wsgi by following an online tutorial by Corey Schafer, I have encountered the following problem. I cannot for the life of my understand why this is happening, and have included error logs, my wsgi.py and my .conf file below. [Tue Sep 29 23:20:35.753537 2020] [wsgi:error] [pid 143850:tid 140318623627008] [remote 90.214.108.58:50288] from django.core.wsgi import get_wsgi_application [Tue Sep 29 23:20:35.753556 2020] [wsgi:error] [pid 143850:tid 140318623627008] [remote 90.214.108.58:50288] ModuleNotFoundError: No module named 'django' [Tue Sep 29 23:28:18.507904 2020] [mpm_event:notice] [pid 143849:tid 140318652456000] AH00491: caught SIGTERM, shutting down [Tue Sep 29 23:28:18.590367 2020] [mpm_event:notice] [pid 143989:tid 139664706964544] AH00489: Apache/2.4.41 (Ubuntu) mod_wsgi/4.6.8 Python/3.8 configured -- resuming normal operations [Tue Sep 29 23:28:18.590439 2020] [core:notice] [pid 143989:tid 139664706964544] AH00094: Command line: '/usr/sbin/apache2' [Tue Sep 29 23:28:24.089588 2020] [wsgi:error] [pid 143990:tid 139664678135552] [remote 90.214.108.58:50411] mod_wsgi (pid=143990): Failed to exec Python script file '/home/myname/projects/uw5-backend/u> [Tue Sep 29 23:28:24.089643 2020] [wsgi:error] [pid 143990:tid 139664678135552] [remote 90.214.108.58:50411] mod_wsgi (pid=143990): Exception occurred processing WSGI script '/home/myname/projects/uw5-b> [Tue Sep 29 23:28:24.095135 2020] [wsgi:error] [pid 143990:tid 139664678135552] [remote 90.214.108.58:50411] Traceback (most recent call last): [Tue Sep 29 23:28:24.095172 2020] [wsgi:error] [pid 143990:tid … -
I tried to login an existing user in my webpage, but i'm getting 'AnonymousUser' object has no attribute '_meta'
` def login(request): if request.method == 'POST': username = request.POST['username'], password = request.POST['password'] user = auth.authenticate(request, username=username, password=password) if User is not None: auth.login(request, user) return redirect('/') else: messages.info(request, 'Invalid Credentials!') return redirect('login') else: return render(request, 'login.html' ` -
Geoserver unavailable in Geonode instalation after restarting Tomcat
I have installed geonode in a production server and it was working correctly after i execute: systemctl restart tomcat.service After this geoserver stop working. If i open the url mydomain.org/geoserver appears a tomcat 404 status. Maybe after the restart the webapp is not linked correctly? Any idea why this is? Thanks -
Django as back-end with Flutter as front-end
I was wondering how to develop a Flutter front-end (iOS & Android) along with Django for the back-end. I partially have both done separately and want to know how to connect them together. I appreciate any tips and advice, as well as if you have any recommendations for server service (Google console, Firebase, or Heroku). Thank you -
How to solve Django ManyToMany relationship with 2 levels
I have a structure like this in Django 1.11: class Profile(models.Model): username = models.CharField() class Post(models.Model): profile = models.ForeignKey(Profile) hashtag = models.ManyToManyField(Hashtag) class Hashtag(models.Model): name = models.CharField() Now this creates intermediate table post_hashtag, but how can I access all hashtags using profile.hashtags.all()? -
i want send all parameters of contact form through email django
def sales_inquiry(request): if request.method=="POST": name = request.POST["name"] company = request.POST["company"] email = request.POST["email"] contact = request.POST["contact"] package = request.POST["package"] mode = request.POST["mode"] pieces = request.POST["pieces"] gross = request.POST["gross"] country_origin = 'country_origin' in request.POST country_destination = request.POST["country_destination"] port_origin = request.POST["port_origin"] port_destination = request.POST["port_destination"] commodity = request.POST["commodity"] container = request.POST["container"] length = request.POST["length"] height = request.POST["height"] width = request.POST["width"] send_mail('Inquiry form', name, settings.EMAIL_HOST_USER, ['17201073suchan@viva-technology.org'], fail_silently=False) return render(request,'laxmi/sales_inquiry.html') now i am able to send only name in my mail body but i want to send this all attributes of this inquiry form to my mail id how should i make dict or any other option to send this whole content -
TypeError at /add-to-cart/1/
my add to cart was working fine and when i retry few pages later it gaves me that error TypeError at /add-to-cart/1/ add_to_cart() missing 1 required positional argument: 'request' My view: def add_to_cart(LoginRequiredMixin, request, slug): item = get_object_or_404(Item, slug=slug) order_item, created = OrderItem.objects.get_or_create( item=item, user=request.user, ordered=False ) order_qs = Order.objects.filter(user=request.user, ordered=False) if order_qs.exists(): order = order_qs[0] # check if the order item is in the order if order.items.filter(item__slug=item.slug).exists(): order_item.quantity += 1 order_item.save() messages.info(request, "This item quantity was updated.") return redirect("core:order-summary") else: order.items.add(order_item) messages.info(request, "This item was added to your cart.") return redirect("core:order-summary") else: ordered_date = timezone.now() order = Order.objects.create( user=request.user, ordered_date=ordered_date) order.items.add(order_item) messages.info(request, "This item was added to your cart.") return redirect("core:order-summary") my url: urlpatterns = [ path('add-to-cart/<slug>/', add_to_cart, name='add_to_cart'), ] Not sure what went wrong, help please. -
How can I assign a model to all users upon creation in Django?
I have this model: models.py class Upload_model(models.Model): content=models.CharField(max_length=200) user_name=models.ForiegnKey(User) forms.py class upload_form(ModelForm): class Meta: model=Upload_model fields=[“content”] views.py def upload_all_user_models(request): if request.method==”POST”: form=upload_form(request.POST, request.FILES) instance=form.save(commit=False) instance.user_name=User.objects.all() return redirect(“upload_all_user_models”) else: form=upload_form() return render(request,”uploadpage.html”,{“form”:form}) I want the Upload_model to be assigned to all users upon creation but I seem to be getting a ValueError. How can I solve this? -
Django Admin - Cannot change <h2> color
I am learning Django. I am customizing the Django Admin page. I have created a base_site.html file in my templates to overwrite the default admin html. Additionally, I have created a stylesheet that I've tied to it. Here's my problem: By default, there is a div on the right side of the content with an h2 header that states "Recent Actions." I want to change this texts color, but my CSS won't seem to work on these words... <div id="content-related"> <div class="module" id="recent-actions-module"> <h2>Recent actions</h2> <h3>My actions</h3> <p>None available</p> </div> </div> I have tried each of the following CSS: #content-related{ color: blue; } .module h2{ color: blue; } #recent-actions-module h2{ color: blue; } #content related h2{ color: blue; } Nothing works... Am I missing something?