Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
do backend frameworks will exist?
Do firebase or aws ends the necessity of a backend framework like django? I am keen to learn django but I'm confused that after some years there could be no need for any backend framework. Is that so? -
Many to one relationship in Django template
I have a one to many relationship and I want to render it to my template class DataType(models.Model): name = models.CharField(max_length=100, blank=True) code = models.CharField(max_length=5) def __str__(self): return self.name class AgroDataType(models.Model): name = models.CharField(max_length=100, blank=True) code = models.CharField(max_length=5) dataType = models.ForeignKey(DataType, on_delete=models.CASCADE) def __str__(self): return self.name I tried to use it like this. but it doesn't work. {% for data in agro_data_types %} <h1>{{data.name}}</h1> {% for datas in data.dataType %} <h1>{{datas.name}}</h1> {% endfor %} {% endfor %} -
How to resolve “Error during WebSocket handshake: Unexpected response code: 503” error in a Django Channels Heroku app?
The error in the console : app.e05f6d1a6569.js:105 WebSocket connection to 'wss://domecode.com/wss?session_key=${sessionKey}' failed: Error during WebSocket handshake: Unexpected response code: 503 (anonymous) @ app.e05f6d1a6569.js:105 mightThrow @ jquery.js:3762 process @ jquery.js:3830 I'm running a Django Channels app ( Messaging app ) on Heroku using Daphne. All the files that correspond to this problem are included in this question. routing.py - messaging app from messaging import consumers from django.urls import re_path websocket_urlpatterns = [ re_path(r'^ws$', consumers.ChatConsumer), ] app.js - snipped of the websocket part of the app.js file var ws_scheme = window.location.protocol == 'https:' ? 'wss' : 'ws'; var socket = new WebSocket(ws_scheme + '://' + window.location.host + '/' + ws_scheme + '?session_key=${sessionKey}'); asgi.py - project's asgi import os import django # from django.core.asgi import get_asgi_application from channels.routing import get_default_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'domecode.settings') django.setup() # to deploy with asgi when using channels application = get_default_application() Procfile release: python3 manage.py makemigrations && python3 manage.py migrate web: daphne domecode.asgi:application --port $PORT --bind 0.0.0.0 -v2 worker: python3 manage.py runworker channel_layer -v2 Any information on what went wrong here? Sidenote: It works perfectly fine in the development server however it gives the error mentioned at the top in the production server at https://domecode.com/chat/. When I send a message … -
How to store a list of values inside a variable and trigger them dynamically in Django?
Hello: complete newbie here. I'd like to store a list of values inside a variable (in a DB) in such a manner: Variable = $FavoriteShoes Values = fave shoes, favorite kicks, lucky shoes Variable = $BrandOfShoes Values = nike, vans, aldo's I'd like to make it so that when $FavoriteShoes is found on a page, any one of the values (randomly) is triggered. So, I could have on a template: My $FavoriteShoes are $BrandOfShoes. And it would be executed as: My fave kicks are vans. How would this be possible in Django? -
Python Django - how to show model changes on a page without refreshing it using Ajax? HELP ME PLEASE)
Python Django. I have a model: class text(models.Model): text = models.TextField('Текст' ,blank = False) time = models.CharField('Время',max_length = 200,blank = False) And I output them all in html: {% for object in text %} <div class="row"> <div class="col-xl-3 block_messeage"> <span class="span_block_messeage"> ,{{object.time}}</span> <br> {{object.text}} </div> </div> {% endfor %} everything is displayed successfully, but the class text is increasing every second and I need to show these changes without refreshing the page. Tell me how this can be implemented using ajax, I will be very grateful) -
How to resolve "Error during WebSocket handshake: Unexpected response code: 503" error in Django Channels app on Heroku?
Error in the console : app.e05f6d1a6569.js:105 WebSocket connection to 'wss://domecode.com/wss?session_key=${sessionKey}' failed: Error during WebSocket handshake: Unexpected response code: 503 (anonymous) @ app.e05f6d1a6569.js:105 mightThrow @ jquery.js:3762 process @ jquery.js:3830 I'm running a Django Channels app ( Messaging app ) on Heroku using Daphne. All the files that correspond to this problem are included in this question. routing.py - messaging app from messaging import consumers from django.urls import re_path websocket_urlpatterns = [ re_path(r'^ws$', consumers.ChatConsumer), ] app.js - snipped of the websocket part of the app.js file var ws_scheme = window.location.protocol == 'https:' ? 'wss' : 'ws'; var socket = new WebSocket(ws_scheme + '://' + window.location.host + '/' + ws_scheme + '?session_key=${sessionKey}'); asgi.py - project's asgi import os import django # from django.core.asgi import get_asgi_application from channels.routing import get_default_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'domecode.settings') django.setup() # to deploy with asgi when using channels application = get_default_application() Procfile release: python3 manage.py makemigrations && python3 manage.py migrate web: daphne domecode.asgi:application --port $PORT --bind 0.0.0.0 -v2 worker: python3 manage.py runworker channel_layer -v2 Any clue what went wrong? Extra information: It works perfectly fine in the development server however it gives the error mentioned at the top in the production server at https://domecode.com/chat/. When I send a message on the … -
django-import-export append column to imported .xlsx
i want to append a column to the imported excel table, this column will contain the foreignKey to a model (the same in all rows, this foreignKey is obtained from the same form as the .xlsx), but i can't make it work. If i upload the excel with the column and the id it works perfectly. This is my code: views.py def article_import(request): if request.method == 'POST': provider_id = request.POST['provider_id'] article_resource = ArticleResource() dataset = Dataset() nuevos_articulos = request.FILES['xlsfile'] data_to_import = dataset.load(nuevos_articulos.read()) result = article_resource.import_data(dataset, dry_run=True, provider_id=provider_id) #Test data if not result.has_errors(): article_resource.import_data(dataset, dry_run=False, provider_id=provider_id) #Import data return redirect('dash-articles') return redirect('/dashboard/articles/?error=True') else: providers = Provider.objects.all().order_by('razon_social') return render(request, 'import/articles_import.html', {'providers': providers}) resource.py class ArticleResource(resources.ModelResource): class Meta: model = Article skip_unchanged = True report_skipped = False import_id_fields = ('codigo',) def before_import(self, dataset, using_transactions, dry_run, **kwargs): dataset.append_col([kwargs['provider_id'],], header='proveedor') print(dataset) return super().before_import(dataset, using_transactions, dry_run, **kwargs) The code in "before_import" is what i was testing but i can't make work the "append_col" function. I will apreciate the help, and if there is a better solution please tell me, thanks!!! -
How to send a 2 Django view context objects to single html template in Django?
Please help me, I'm working on a project where I need to display a page about tutors and need to add their ratings also.so I created 2 models and 2 views for both tutors but I don't know how to display the context objects of both views in a single template. class tutors(models.Model): category = models.ForeignKey(Category, related_name='tutors', on_delete=models.CASCADE) name = models.CharField(max_length=100, db_index=True) Tagline = models.CharField(max_length=100, db_index=True) slug = models.SlugField(max_length=100, db_index=True) description_tutor = models.TextField(blank=True) price = models.DecimalField(max_digits=10, decimal_places=2) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) images=models.ImageField(upload_to="media") qualification=models.TextField(null=True) class Meta: ordering = ('name', ) index_together = (('id', 'slug'),) def __str__(self): return self.name def get_absolute_url(self): return reverse('onlinetutors:tutor_detail', args=[self.id, self.slug]) class ratings(models.Model): username= models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,) rating=models.FloatField() tutorname=models.ForeignKey(tutors,related_name='ratingss',on_delete=models.CASCADE) created_date=models.DateTimeField(auto_created=True) def tutor_detail(request, id, slug): tutor = get_object_or_404(tutors, id=id, slug=slug) context = { 'tutor': tutor, } return render(request, 'detail.html', context) def rating(request,tutorname_id): display_rating = ratings.objects.filter(tutorname_id=tutorname_id).aggregate(find_average=Avg('rating')) display = display_rating["find_average"] return render(request, 'detail.html',{'display':display}) -
How to display two models as one in Django?
I have two models - Image and Article, that are not related to each other in any other way than both having the creation date field. I want to treat them as though they "were one" - I need to display them both in one div. class Image(models.Model): image = models.ImageField(upload_to="slider/") created = models.DateTimeField(auto_now_add=True) class Article(models.Model): author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT) body = models.TextField() created = models.DateTimeField(auto_now_add=True) Having this, I want to be able to render them both in one div so they all go by the creation day, regardless of their class; I want them to be mixed up. -
All django project failed after upgrading to Ubuntu 20.04
I upgraded my system from Ubuntu 18.04 to 20.04.1 LTS, and ALL my Django projects crashed. One of the errors related to psycopg2 in the virtual environment. But this is solvable by not specifying the version in requirements.txt. However, there are different errors for different projects even if I rebuilt the virtual environment one by one. I think it might be due to the fact that those packages do not support python 3.8 yet. So, how to I get my Django project running in Ubuntu 20.04? -
How to make django celery use the redis broker url?
(venv) [riyad@Fury django_celery]$ celery -A django_celery worker -l info <Celery django_celery at 0x7f0917d57fa0> -------------- celery@Fury v4.3.0 (rhubarb) ---- **** ----- --- * *** * -- Linux-5.8.6-1-MANJARO-x86_64-with-glibc2.2.5 2020-09-30 02:54:36 -- * - **** --- - ** ---------- [config] - ** ---------- .> app: django_celery:0x7f0917d57fa0 - ** ---------- .> transport: amqp://guest:**@localhost:5672// - ** ---------- .> results: - *** --- * --- .> concurrency: 4 (prefork) -- ******* ---- .> task events: OFF (enable -E to monitor tasks in this worker) --- ***** ----- -------------- [queues] .> celery exchange=celery(direct) key=celery [tasks] . django_celery.celery.debug_task . example.task.sleepy [2020-09-30 02:54:36,989: ERROR/MainProcess] consumer: Cannot connect to amqp://guest:**@127.0.0.1:5672//: [Errno 111] Connection refused. Trying again in 2.00 seconds... [2020-09-30 02:54:38,996: ERROR/MainProcess] consumer: Cannot connect to amqp://guest:**@127.0.0.1:5672//: [Errno 111] Connection refused. Trying again in 4.00 seconds.. the main issue cause by this redis broker url, so far i am running a redis server on my other terminal. i am using two libraries redis and celery my settings.py file-> CACHES = { "default": { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": "redis://127.0.0.1:6379/1", "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient" }, "KEY_PREFIX": "example" } } BROKER_TRANSPORT = "redis" BROKER_HOST = "localhost" # Maps to redis host. BROKER_PORT = 6379 # Maps to redis port. BROKER_VHOST = "1" # Maps … -
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 …