Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django celery for download large file
I am developing a django app and my app need to user to upload the urls in excel files. On server side i am reading the excel file by each cells, extracting the news article of the urls and generating the summary of article. This process can take up to 5-10 minutes for the long list of urls. I am using celery for managing the long running task but somehow server is giving me error 500 - Internal server error after 2 min without completing the task __init__.py from .celery import app as celery_app __all__ = ['celery_app'] Setting.py BROKER_URL = 'django://' CELERY_ACCEPT_CONTENT = ['json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' celery_app.py from __future__ import absolute_import import os import django from celery import Celery from django.conf import settings from kombu import serialization serialization.registry._decoders.pop("application/x-python-serialize") os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'news.settings') django.setup() app = Celery('news') app.config_from_object('django.conf:settings') app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) summary.py from celery import shared_task @shared_task def WritesummaryfromArticleToExcel(input_file,noofline,lang): try: data=False wb = xlrd.open_workbook(file_contents=input_file.read()) wb_sheet=wb.sheet_by_index(0) df=pd.DataFrame(columns=['Full Article','Summary']) for rownum in range(0, wb_sheet.nrows): # for colnum in range(0,1): try: rw=wb_sheet.cell_value(rownum,0) if type(rw)==float or type(rw)==int: rw= str(rw) # if len(rw)>15000: data=True articletext=rw # nooflines=request.data["numberofline"] lantext="" lantexttemp= articletext.split('\n')[0:2] for l in lantexttemp: lantext=lantext +"\n" +l lan=detect(lantext) view.py def translatedoc(request): data="" convrowstr="" if request.method=='POST': … -
djang template loop for with ajax script multiply
I've been following with "Django by example' practice book doing like unlike system. I encountered some problem with Ajax script when I a nested then into an loop for ( "for post in posts iterating view"). When I put into my template’s loop, this ajax I get looping likes in all iterated post. Do You have any tips how can I tackle with this ? enter code here <script> var csrftoken = $.cookie('csrftoken'); function csrfSafeMethod(method) { // these HTTP methods do not require CSRF protection return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method)); } $.ajaxSetup({ beforeSend: function(xhr, settings) { if (!csrfSafeMethod(settings.type) && !this.crossDomain) { xhr.setRequestHeader("X-CSRFToken", csrftoken); } } }); $.each(document).ready(function(){ $('a.like').click(function(e){ e.preventDefault(); $.post('{% url "like" %}', { id: $(this).data('id'), action: $(this).data('action') }, function(data){ if (data['status'] == 'ok') { var previous_action = $('a.like').data('action'); // toggle data-action $('a.like').data('action', previous_action == 'like' ? 'unlike' : 'like'); // toggle link text $('a.like').text(previous_action == 'like' ? 'Unlike' : 'Like'); // update total likes var previous_likes = parseInt($('span.count .total'). text()); $('span.count .total').text(previous_action == 'like' ? previous_likes + 1 : previous_likes - 1); } } ); }); }); </script> enter code here {% for post in posts %} <small>Posts: {{ post.message}}</small> {% include 'posts/like.html' %} {% endfor%} -
Access the Django-Rest-Framework url do not load the styles file
I have a project with the settings.py: # -*- coding: utf-8 -*- """ Django settings for Qiyun02 project. Generated by 'django-admin startproject' using Django 1.11.5. For more information on this file, see https://docs.djangoproject.com/en/1.11/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.11/ref/settings/ """ import os import sys #import django.contrib.auth.middleware # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) PARENT_DIR = os.path.abspath(os.path.join(BASE_DIR, os.pardir)) # 增加sys目录 sys.path.insert(0, BASE_DIR) sys.path.insert(0, os.path.join(PARENT_DIR,'旗云管理员后台')) sys.path.insert(0, os.path.join(PARENT_DIR,'用户前台')) sys.path.insert(0, os.path.join(PARENT_DIR,'用户管理后台')) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'u8ctyimjuy7t-7r3%$&4sc2g^5fhc8dathp8z&(7pp=&eee@zn' # SECURITY WARNING: don't run with debug turned on in production! 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', 'django.contrib.sites', 'corsheaders', 'rest_framework', 'rest_framework.authtoken', 'rest_framework_docs', # API文档 'rest_auth', 'allauth', 'allauth.account', 'allauth.socialaccount', 'rest_auth.registration', ...... ] SITE_ID = 1 # email backend TODO 这个,每个商户可以自己定义邮箱 EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' #EMAIL_USE_TLS = True EMAIL_USE_SSL = True EMAIL_HOST = 'smtp.gmail.com' # QQ:smtp.qq.com 163:smtp.163.com EMAIL_PORT = 465 EMAIL_HOST_USER = 'qiyunserver@gmail.com' EMAIL_HOST_PASSWORD = 'qiyunserver123' DEFAULT_FROM_EMAIL = EMAIL_HOST_USER # TODO 方便调试,关闭Token验证 REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES':[], #'rest_framework.permissions.IsAuthenticated' 'DEFAULT_AUTHENTICATION_CLASSES':( 'rest_framework.authentication.TokenAuthentication', 'rest_framework.authentication.SessionAuthentication', ), #['rest_framework.authentication.TokenAuthentication'], # 'rest_framework.authentication.TokenAuthentication' #'DEFAULT_PAGINATION_CLASS': ('rest_framework.pagination.PageNumberPagination',), 不能打开这个 #'PAGE_SIZE':10, … -
payment via PayPal payout API
I am using Payout API (in Django) for PayPal mass payments . How can i make all these payments as "PERSONAL" from api . Code snippet of PayPal object that i am using : payout = Payout({ "sender_batch_header": { "sender_batch_id": batch_id, "email_subject": mail['subject'] }, "items": [ { "recipient_type": "EMAIL", "amount": { "value": amount, "currency": "USD" }, "receiver": receiver_email, "note": mail['body'] "sender_item_id": id } ] }) Reference : https://developer.paypal.com/docs/api/payments.payouts-batch/#payouts . Is there any Key value that needs to be sent with the above object or is there any different approach for PERSONAL payment from PayPal API. -
None type error in Django rest RegisterView
I am using Django RestFramework's RegisterView for the registration api in my project.I use a custom adapter as well, it is as follows. class CustomAccountAdapter(DefaultAccountAdapter): """ Override all_auth's default adapter """ def send_confirmation_mail(self, request, emailconfirmation, signup): # current_site = get_current_site(request) promo_code = emailconfirmation.email_address.user.promo_code activate_url = "%s/#/verifyEmail/%s/" % ( settings.FRONTEND_HOSTNAME, emailconfirmation.key ) if promo_code: activate_url = "%s/#/verifyEmail/%s/?promo_code=%s" % ( settings.FRONTEND_HOSTNAME, emailconfirmation.key, promo_code ) ctx = { "user": emailconfirmation.email_address.user, "activate_url": activate_url, "current_site": settings.FRONTEND_HOSTNAME } if signup: email_template = 'account/email/email_confirmation_signup' else: email_template = 'account/email/email_confirmation' self.send_mail(email_template, emailconfirmation.email_address.email, ctx) I get an error while the sending the confirmation mail to the newly registered user.The error is below File "/home/ubuntu/fizprod_env/local/lib/python2.7/site-packages/django/core/mail/message.py", line 283, in send return self.get_connection(fail_silently).send_messages([self]) File "/home/ubuntu/fizprod_env/local/lib/python2.7/site-packages/django/core/mail/backends/smtp.py", line 99, in send_messages sent = self._send(message) File "/home/ubuntu/fizprod_env/local/lib/python2.7/site-packages/django/core/mail/backends/smtp.py", line 110, in _send from_email = sanitize_address(email_message.from_email, email_message.encoding) File "/home/ubuntu/fizprod_env/local/lib/python2.7/site-packages/django/core/mail/message.py", line 105, in sanitize_address nm, addr = addr TypeError: 'NoneType' object is not iterable Can anyone tell me what is the error and how it's happening.I use Django 1.7, python 2.7, Django REST 3.1.1 -
Is it possible to add a custom attribute to a model field?
Here's my model: def Post(models.Model): ... video = models.BooleanField(default=False, youtube=False) is it possible to add the youtube attribute so I can use it in my template like so: {% if video.youtube %} <p>text</p> {% endif %} -
Django: raw passwords via request.POST
This question concerns the standard UserCreationForm within Django, and the way that passwords are stored, extracted and used through a request object. Specifically the fact that I seem to be able to print raw passwords through print(request.POST). File contents will be provided at the end of this post. I have created a registration page. I have set up a very basic class-based view that authenticates and logs the newly created user in. The actual HTML of that page is rendered automatically in this case, through {{ form.as_p }} where form is an instance of UserCreationForm. How come, when I execute print(request.POST), I get something along the lines of this returned: <QueryDict: {'csrfmiddlewaretoken': ['keeping_this_private'], 'username': ['William'], 'password1': ['ACTUALPASSWORD'], 'password2': ['ACTUALPASSWORD'], 'button': ['']}> Is this really secure? As I have only been programming for a couple of months, I am still learning. Views.py: class RegisterView(View): def get(self, request): form = UserCreationForm() return render(request, 'authentication/registration.html', {'form': form}) def post(self, request): form = UserCreationForm(request.POST) if form.is_valid(): print(request.POST) form.save() username = form.cleaned_data.get('username') raw_password = form.cleaned_data.get('password1') user = authenticate(username=username, password=raw_password) login(request, user) return redirect('home') else: return render(request, 'authentication/registration.html', {'form': form}) Registration.html {% extends 'base.html' %} {% block body %} <body class="text-center"> <form method="post"> {% csrf_token %} … -
Django 2.0 + Postgres heroku migrations
I am trying to run a Django application with Postgres in Heroku. I have created an app for the application but the problem is that the app migrations are not being applied in Heroku. I am using the heroku starter base template and have committed the necessary migration files. When I run heroku run python manage.py migrate, the first set of migrations apply: Applying contenttypes.0001_initial... OK Applying auth.0001_initial... OK blah blah blah But when I run it the second time it gives me the the output Operations to perform: Apply all migrations: admin, auth, contenttypes, sessions Running migrations: No migrations to apply. If I specify the app using heroku run python manage.py migrate phone I get the error CommandError: No migrations present for: phone In my local development, I have an app called phone that I have added to the settings.py and can run local migrations. -
How to integrate Django into an existing database without using models
I have been asked to provide a web interface to access some scientific data which is being saved in a laboratory. The data are stored in folders, each containing some number of FITS files, and the application collecting the data is already written and functional. The web interface I am supposed to implement should have the following features: View all the data taken so far; Allow the user to make queries; File downloading; Only read-only operations are allowed. I know Django quite well and would like to use it. However, this kind of application is quite different from what I am used to. Usually a Django application implements models which are linked to a database, and this database is completely managed by Django itself. In this case, the database would be the plain tree of folders, which is being modified by an external application while Django is running. Can Django be adapted to this task, or should I turn to other more low-level solutions? (e.g., microframeworks like Flask) -
In what sequence Model.save() and ModelForm.save() called
I understand that both models.Model and forms.ModelForm both contain .save() method that you can override. My question is how and when are they used to save an object and in what sequence. -
Django: why Using a custom user model when starting a project is not made compulsory?
I was working on a project and after the mid way, i wanted to work on the users. That time i decided to use email as the login. I found that custom user migration should be done only in the start of the project. Using a custom user model when starting a project If you’re starting a new project, it’s highly recommended to set up a custom user model, even if the default User model is sufficient for you. This model behaves identically to the default user model, but you’ll be able to customize it in the future if the need arises: https://docs.djangoproject.com/en/dev/topics/auth/customizing/#using-a-custom-user-model-when-starting-a-project So why such a thing should not be made as compulsory thing before one starts a project. Assuming I am in the middle of a project. How can i transfer all the database data to my new project with custom_user. -
Redirect user from login page
When the user presses on login, nothing happens. I would like to redirect them to calculator.html where i intend to make some entry fields to obtain parameters from the user to calculate a certain value at the end. Django 1.11.11 Python 3.6.4 Thanks. urls.py from django.conf.urls import url, include from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'', include('webapp.urls')), ] views.py from django.shortcuts import render, redirect from django.contrib.auth.forms import AuthenticationForm from django.contrib.auth.decorators import login_required # Create your views here. def login_view(request): if request.method == 'POST': form = AuthenticationForm(data=request.POST) if form.is_valid(): # log the user in user = form.get_user() login(request, user) return redirect('/calculator/') else: form = AuthenticationForm() return render(request, 'registration/login.html', { 'form': form }) @login_required(login_url="/login/") def calculator(request): return render(request, 'webapp/calculator.html') app urls.py from django.conf.urls import url from . import views from django.contrib.auth.views import login from django.contrib.staticfiles.urls import staticfiles_urlpatterns from django.conf.urls.static import static from django.conf import settings from django.views.generic.base import RedirectView urlpatterns = [ url(r'^login/$', views.login_view, name='login'), url(r'^calculator/$', views.calculator, name='calculator'), url(r'^.*$', RedirectView.as_view(pattern_name='login', permanent=False)), ] urlpatterns += staticfiles_urlpatterns() urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) login.html {% extends 'webapp/base_layout.html' %} {% block content %} <h1>Log in</h1> <p></p> <p></p> <form class="site-form" action="/registration/login" method="post"> {% csrf_token %} {{ form }} <input type="submit" value="Login" /> </form> {% endblock … -
checking celery task queue on local running django heroku application
I am running a django app. I use redis as a broker for celery. I boot redis separately with redis-server /usr/local/etc/redis.conf Once redis has started, I run my Django code in the CLI of heroku heroku local I have tasks that I can process, the set-up works I would like to monitor the tasks from the "bash"/"Shell"/"console" to see which tasks are running. I have some scheduled tasks but no idea if they eventually get scheduled or not. probably this is some kind of one-liner but I have no clue where to start looking for it. What i have tried: reading heroku documentation on the shell and running heroku locally I have tried to run a separate python shell inside the virtualenv where I run the django app I also tried accessing tasks from a separate shell but that didn't worked out either thanks for the help! -
How to get an image from HttpRequest in Django without using HTML form?
I picked up Django just a few days ago, so I only have a very limited knowledge of how it works, and I can't figure out how to get file a POST. All tutorials, SO questions, etc. focus on images being uploaded from HTML forms, then saving those files, or using Django rest framework and so on, however I need none of those things. I use Postman to send an image to Django, so naturally HttpRequest.FILES dict is empty. The file is encoded in HttpRequest.body as a byte stream. In theory, I could parse that byte stream into an image, but that would require accounting for different image headers(png, jpg, gif...) and also cut out irrelevant parts of the stream, such as Content-Disposition: form-data; name=""; filename="image.png"\r\nContent-Type: image/png. which is quite annoying to work with. Is there simply no other way to access the file in the HttpRequest that would result in an actual image object, say PIL.Image? -
Heroku generates Server Error (500) in Django application
I have deployed a Django application on Heroku and attached PostgreSQL database to it successfully. On running the application I have observed that it behaves unexpectedly Sometimes it produces Server Error (500) Sometimes only half of the page is loaded Sometimes jQuery ajax call gets failed all these problems only appear on Heroku, when I run the same application on my system locally it runs smoothly without any problem. These errors are appearing only on 2 pages of my projects all other pages work fine. To overcome this problem, I followed these posts Post 1, Post 2, Post 3, Post 4 and tried changing the parameters in settings.py but nothing worked. settings.py import os #from .base import import dj_database_url # 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/2.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '***' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [".herokuapp.com", "127.0.0.1"] # Application definition INSTALLED_APPS = [ 'blog', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', … -
Django Action RedirectView need to go with querystring
I have a RedirectView where action redirects specific Url. But I need to filter and click action also. So when I filter the items and click action it redirects me to a specific page. But I want now that action will redirect me to current page always no matter what happens. If the current page is included in query string it redirects me with a query string. If there is no query string its redirect me without the query string, But on the current page. I am using Django FSM for state management and when I click action it changes the state. Here is my code of redirect. class OrderStateChangeView(LoginRequiredMixin,RedirectView): state_change_method: str = None reverse: str = 'orders:manager-orderfilter-search' @property def reverse_kwargs(self): return {} def get_redirect_url(self, *args, **kwargs): obj = get_object_or_404(Order, pk=self.kwargs['pk']) self.obj = obj try: getattr(obj, self.state_change_method)() obj.save() except: messages.add_message( self.request, messages.ERROR, extra_tags='alert alert-error', message='Unable to process your request.' ) return reverse(self.reverse, kwargs=self.reverse_kwargs) -
Django Rest framework conditional delete
I want to add some condition when DELETE data. Here is my models.py and serializers.py [serializers.py] class articleSerializer(serializers.ModelSerializer): userkey = serializers.CharField(write_only=True) password = serializers.CharField(write_only=True) class Meta: model = article fields = ('articleNo', 'content', 'date', 'userkey', 'password') [models.py] class article(models.Model): articleNo = models.AutoField(primary_key=True) userkey = models.CharField(max_length=50, null=False) content = models.CharField(max_length=500, null=False) password = models.CharField(max_length=20, null=False, default='1234') date = models.DateTimeField(auto_now_add=True) For example, below data is in database. | articleNo | content | date | userkey |password| --------------------------------------------------------------------------------- | 33 | test article | 2018-03-11 05:00:15.428661 | a1b2c3d4 | 1234 | When "DELETE" method request, I want to compare request's password and article's password. If it is same, data will be deleted. Refer to document, I think I have to override def delete(). But I don't know exactly what should I do. How can I solve this issue? Thanks. -
How to filter 404 errors getting reported in rollbar
Is there any way to filter 404 error reporting in rollbar? I am using rollbar (0.13.18) in django (1.11). -
How to save ArrayField as set in Django
The goal is removing of duplicates from list field while saving model. For example: m = MyModel.objects.create( array_field=['123','123'], ) m.array_field # ['123'] I tried to overwrite save but it doesn't work class MyModel(models.Model): array_field = ArrayField(models.CharField(max_length=5)) def save(self, *args, **kwargs): if self.array_field: self.array_field = list(set(self.array_field)) super(MyModel, self).save(*args, **kwargs) How can I do this? -
Why other docker containers do not see the accepted migrations?
docker-compose.yml version: '3' services: # Django web server web: volumes: - "./app/back:/app" - "../front/public/static:/app/static" - "./phantomjs-2.1.1:/app/phantomjs" build: context: . dockerfile: dockerfile_django #command: python manage.py runserver 0.0.0.0:8080 #command: ["uwsgi", "--ini", "/app/back/uwsgi.ini"] ports: - "8080:8080" links: - async - ws_server - mysql - redis async: volumes: - "./app/async_web:/app" build: context: . dockerfile: dockerfile_async ports: - "8070:8070" # Aiohtp web socket server ws_server: volumes: - "./app/ws_server:/app" build: context: . dockerfile: dockerfile_ws_server ports: - "8060:8060" # MySQL db mysql: image: mysql/mysql-server:5.7 volumes: - "./db_mysql:/var/lib/mysql" - "./my.cnf:/etc/my.cnf" environment: MYSQL_ROOT_PASSWORD: root MYSQL_USER: user_b520 MYSQL_PASSWORD: buzz_17KN MYSQL_DATABASE: dev_NT_pr MYSQL_PORT: 3306 ports: - "3300:3306" # Redis redis: image: redis:4.0.6 build: context: . dockerfile: dockerfile_redis volumes: - "./redis.conf:/usr/local/etc/redis/redis.conf" ports: - "6379:6379" # Celery worker celery: build: context: . dockerfile: dockerfile_celery command: celery -A backend worker -l info --concurrency=20 volumes: - "./app/back:/app" - "../front/public/static:/app/static" links: - redis # Celery beat beat: build: context: . dockerfile: dockerfile_beat command: celery -A backend beat volumes: - "./app/back:/app" - "../front/public/static:/app/static" links: - redis # Flower monitoring flower: build: context: . dockerfile: dockerfile_flower command: celery -A backend flower volumes: - "./app/back:/app" - "../front/public/static:/app/static" ports: - "5555:5555" links: - redis dockerfile_django FROM python:3.4 RUN mkdir /app WORKDIR /app ADD app/back/requirements.txt /app RUN pip3 install -r requirements.txt … -
How To Create A Form In Django That Combines Choice and Text Data
I am working with Django to create a form for a restaurant app where I would need a user to first select type of product that it has from a list and enter the price they would like to have each item set to. This data will then be passed to an API. Right now I have something like this: class Drinks(models.Model): TYPE = ( ('Sizes', ( ('small', 'Small'), ('medium', 'Medium'), ('large', 'Large') )), drink_size = models.CharField(max_length=1, choices=TYPE) I need for the restaurant to be able to select the size of the drink and then place a value on each drink size. So I think I would need a checkbox and a way to record the value for each size. If you have any idea on how to do this, It would truly appreciated. -
Django Rest framework except specific column
I want to exclude specific column in rest framework only for view data. (not for put data) [models.py] class article(models.Model): articleNo = models.AutoField(primary_key=True) userkey = models.CharField(max_length=50, null=False) content = models.CharField(max_length=500, null=False) password = models.CharField(max_length=20, null=False, default='1234') date = models.DateTimeField(auto_now_add=True) [serializers.py] class articleSerializer(serializers.ModelSerializer): class Meta: model = article fields = ('articleNo', 'userkey', 'content', 'password', 'date') After I change fields = ('articleNo', 'content', 'date') from serializers.py, Only articleNo, content, date will be show in rest framework. But, When I PUT data to article, It doesn't inserted properly. After insert data, MySQL data is below. articleNo|content | date |userkey |password 37 | Test | 2018-03-13 08:01:07.424564 | | 1234 userkey is blank and password is default value. Maybe I have to modify serializers.py I think, But I don't know how to fix it. How can I insert data properly? -
How to save model form Data(User input) into a csv or dict in Django
I am trying to set up a Website for Employee Schedulling with Django. Since i am new to Web development, I run into some problems. I need to pass information to a solver using pyomo. For this employees should be able to pass information his availability through a model form. The information has to be saved like this: Available ={(“Employee name”, “shift”, “day”): 0, (“Employee name”, “shift”, “day”): 0, (“Employee name”, “shift”, “day”): 1} 0 means that the employee is not available on that shift on that day and 1 means he is. Right now I get my data from a csv and transform it into a dict using pandas. Is there any way to save the passed information as a csv or a dict into a database? -
Django CSS not working
settings.py STATIC_ROOT = 'static/' STATIC_URL = '/static/' STATICFILES_DIRS = ['guide/static/css', 'guide/static/js', ] base.html {% load staticfiles %} ... <link href="{% static bootstrap.css %}" rel="stylesheet" type="text/css" media="all" /> <link rel="stylesheet" href="{% static flexslider.css %}" type="text/css" media="screen" Department="" /> <link href="{% static services.css %}" rel="stylesheet" type="text/css" media="all" /> <link href="{% static ziehharmonika.css %}" rel="stylesheet" type="text/css"> <link href="{% static JiSlider.css %}" rel="stylesheet"> <link href="{% static style.css %}" rel="stylesheet" type="text/css" media="all" /> <!-- font-awesome icons --> <link href="{% static font_awesome.css %}" rel="stylesheet" type="text/css" media="all"/> Here is the project structure: guide - guide - guideapp - templates - base.html - index.html - static - css - js - fonts - db.sqlite3 - manage.py Here, index extends base.html. The content shows up, but the css does not. -
django hide form after submit
Hello i want to have a link form in my post but i want to have only one link per post so if some user add a link i want the form disabled .How can i achieve this ? model and view --> models.py class Link(models.Model): post = models.ForeignKey(Post,related_name='links',on_delete=models.CASCADE) url_link = models.URLField() created = models.DateField(auto_now_add=True) updated = models.DateField(auto_now=True) active = models.BooleanField(default=True) views.py if request.method == 'POST': link_form = LinkForm(data=request.POST) if link_form.is_valid(): new_link = link_form.save(commit=False) new_link.post =post new_link.save() else: link_form=LinkForm()