Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to migrate test database
So, I have some project on django. Now, I need to run existing tests in project. I am use ./manage.py test and get this message: Then I try to migrate database as written in message above and I see django try to apply migrations for 'origin' database. By default for tests django create new database for testing with 'test_' prefix. So, my question is: How can I apply migrations to 'test_' database? Thanks. -
Django RF, unable to pass user instance to serializer.save() method
I have a blog project where auth.users can Post new posts. When sending POST message to server it is unable to add loggedin user with new posts. VIEWS.PY class PostListCreate(APIView): parser_class = (FileUploadParser,) permission_classes = [IsAuthenticatedOrReadOnly] def get(self,request): posts = Post.objects.all() serializer = PostSerializers(posts,many=True,context={'request':request}) return Response(serializer.data) def post(self,request): #postAuthor = self.request.user serializer = PostSerializers(data=request.data,context={'request':request}) if serializer.is_valid(): serializer.save() return Response(serializer.data,status=status.HTTP_201_CREATED) return Response(serializer.errors,status=status.HTTP_400_BAD_REQUEST) SERIALIZER.PY class PostSerializers(serializers.ModelSerializer): comments = serializers.HyperlinkedRelatedField(many=True,read_only=True,view_name = 'comment_details') likes_count = serializers.SerializerMethodField() user_has_voted = serializers.SerializerMethodField() # postAuthor = serializers.SerializerMethodField() class Meta: model = Post fields = '__all__' #exclude=('voters',) def get_likes_count(self, instance): return instance.voters.count() def get_user_has_voted(self, instance): request = self.context.get("request") return instance.voters.filter(pk=request.user.pk).exists() ERROR MESSAGE { "postAuthor": [ "This field is required." ] } -
Datetime Validation Error using datetime-local
I am trying to render basic HTML template that would allow me to input a date-time values into database using datetime-local input type. However every time I try to enter a value it always return the Enter a valid date/time error models.py class AirframeOperation(models.Model): id = models.AutoField(primary_key=True) takeoff = models.DateTimeField() landing = models.DateTimeField() flight_time = models.DurationField() metadata = models.OneToOneField( Metadata, on_delete=models.CASCADE ) def save(self, *args, **kwargs): self.block_time = self.block_on - self.block_off self.flight_time = self.landing - self.takeoff return super(AirframeOperation, self).save(*args, **kwargs) forms.py class InsertAirframeOperation(forms.ModelForm): takeoff = forms.DateTimeField( input_formats=['%d-%m-%YT%H:%M'], widget=forms.DateTimeInput( attrs={ 'type': 'datetime-local', 'class': 'form-control' }, format='%d-%m-%YT%H:%M') ) landing = forms.DateTimeField( input_formats=['%d-%m-%YT%H:%M'], widget=forms.DateTimeInput( attrs={ 'type': 'datetime-local', 'class': 'form-control' }, format='%d-%m-%YT%H:%M') ) class Meta: model = AirframeOperation fields = ['takeoff', 'landing'] widgets = {} views.py @login_required(login_url='/accounts/login/') def dataentry(request): if request.method == 'POST': form_meta = forms.InsertMetadata(request.POST) form_airframe = forms.InsertAirframeOperation(request.POST) print(form_airframe.errors) metadata = None if form_meta.is_valid(): metadata = form_meta.save(commit=False) metadata.save() meta_id = metadata.id print(meta_id) metadata = Metadata.objects.get(id=meta_id) if form_airframe.is_valid(): airframe = form_airframe.save(commit=False) airframe.metadata = metadata airframe.save() return redirect('/') else: form_meta = forms.InsertMetadata() form_airframe = forms.InsertAirframeOperation() return render(request, "dashboard/data_entry.html", {'form': form_meta, 'form2': form_airframe}) data_entry.html {% extends "base.html" %} {% block content %} <div id="data_entry_container"> <h3>Metadata General</h3> <form method="post" action="" enctype="multipart/form-data"> {% csrf_token %} <p>{{ form.errors }}</p> … -
Session is not storing variables - Django
I've been having trouble storing my tokens on session. I've found few solutions on stackoverflow but none of them worked. currently, I store user's token when client send a POST request to /api/login and here is my views logic request.session['token'] = auth.token.key request.session.modified = True I'm 100% sure auth.token.key is not None and the logic stores just fine. but when it comes to /api/update (some sample api), I always get None here is how I get the Item from session: print(request.session.get('token')) ** The Code above always returns None** I read the Django docs. I set both the session middleware and session app: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'rest_framework.authtoken', 'user' ] MIDDLEWARE = [ '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', ] I've done all the migrations.django_session table exists. -
elasticsearch.service: main process exited, code=exited, status=1/FAILURE
While running elasticsearch 6.2.3 on my centos based system, I found this error. Unable to start, checked the port number and localhost ip in elasticsearch.yml , anybody can help me out? -
Django: Prefetch_related on nested attributes
I need to list all my devices. To do this I use a prefetch related to reduce the amount of queries. But one of them is consuming to much time.. I wonder if it can't go better. I will start with the model constructions: I want a list of devices. class Device(models.Model): name = models.CharField(max_length=250, null=True, blank=True) class GatewayDevice(models.Model): gateway = models.ForeignKey( Gateway, on_delete=models.CASCADE, related_name="devices" ) device = models.ForeignKey( Device, on_delete=models.CASCADE, related_name="gatewaydevices" ) In the real code the device model is larger, but that code is irrelevant. As you can see, a device has some gatewaydevices (which is a model between gateway and device) So in my list of devices, I want for every device, the linked gateway. This is my view: class AdminDeviceView(GenericAPIView): def get_permissions(self): return IsAuthenticated() # noinspection PyMethodMayBeStatic def get_serializer_class(self): return AdminDeviceInfoSerializer @swagger_auto_schema( responses={ 200: openapi.Response( _("Successfully fetched all data from devices."), AdminDeviceInfoSerializer, ) } ) def get(self, request): """ GET the data from all the devices. """ devices = ( Device.objects.filter() .all() .prefetch_related( "site__users", "software_update_history", "supplier", Prefetch( "gatewaydevices", queryset=GatewayDevice.objects.filter(end_date=None) .order_by() .distinct() .prefetch_related("gateway"), ), ) ) serializer_class = self.get_serializer_class() serializer = serializer_class(devices, many=True) devices_data = serializer.data return Response( {"total": devices.count(), "items": devices_data}, status=status.HTTP_200_OK ) This is the … -
Date as a percentage for the progress bar
Good afternoon. Help me please. There is a project on Django. The project has a code from bootstrap4 - progress-bar, I need this progress bar, but I can’t understand how to implement its performance, since it has data stored in percent, but I don’t have percent, but the project date, that is, there is a beginning Let's say the project is 01 02 2000 and the end of the project 01 02 2002 there are 730 days difference between them. Here's how I turn these 730 days into 100%, and the remainder - let's say 140 days, also turn into percent. HTML Template <div class="progress"> <div class="progress-bar bg-success" role="progressbar" style="width: 10%" aria-valuenow="10" aria-valuemin="0" aria-valuemax="100"></div> </div> Python Template prjauth = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, verbose_name="") prjtitle = models.CharField(max_length=200, verbose_name="") prjdesc = models.TextField(verbose_name="") prjfiles = models.FileField(upload_to='files_project', verbose_name="") prjdatestart = models.DateTimeField(default=timezone.now, verbose_name="") prjdateend = models.DateTimeField(blank=True, null=True, verbose_name="") prjproekts = models.DateTimeField(blank=True, null=True, verbose_name="") prjproekte = models.DateTimeField(blank=True, null=True, verbose_name="") prjdatesnabs = models.DateTimeField(blank=True, null=True, verbose_name="") prjdatesnabe = models.DateTimeField(blank=True, null=True, verbose_name="") prjdatelines = models.DateTimeField(blank=True, null=True, verbose_name="") prjdatelinee = models.DateTimeField(blank=True, null=True, verbose_name="") -
create url endpoint for social auth partial pipeline
I am trying to setup partial authentication pipeline in a Django rest project. Users register/login to the app using facebook. The partial function then checks for an address field in the data dictionary. If nothing a message is returned to the frontend with the backend name, partial token and a custom message. The frontend then prompts the user to complete the address form and this data is submitted along with the token and backend name to an endpoint. This endpoint should call the complete view from social_django. This is where am currently stuck. How do I craft the url resolver to respond to the frontend. INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'users', 'rest_framework', 'oauth2_provider', 'social_django', 'rest_framework_social_oauth2', 'rest_framework.authtoken', 'corsheaders', ] SOCIAL_AUTH_PIPELINE = ( 'social_core.pipeline.social_auth.social_details', 'social_core.pipeline.social_auth.social_uid', 'social_core.pipeline.social_auth.auth_allowed', 'social_core.pipeline.social_auth.social_user', 'users.pipeline.get_address', 'users.pipeline.create_user', 'social_core.pipeline.social_auth.associate_user', 'social_core.pipeline.social_auth.load_extra_data', 'social_core.pipeline.user.user_details', ) @partial def get_address( request, strategy, details, user=None, is_new=False, *args, **kwargs ): if user: return elif is_new and not details.get('street'): street = strategy.request_data().get('street') if street: details['street'] = street return else: current_partial = kwargs.get('current_partial') data = { "message": "Address information missing", "partial_token": current_partial.token, "backend": current_partial.backend, } return Response(data, status=403) urlpatterns = [ path('admin/', admin.site.urls), path('social_providers/', include('oauth2_provider.urls', namespace='oauth2_provider')), path('api/auth/oauth/', include('rest_framework_social_oauth2.urls')), path('complete/<str:backend>/<str:partial_token>', include('social_django.urls', namespace='social_django')), ] complete/<str:backend>/<str:partial_token> ^login/(?P<backend>[^/]+)/$ [name='begin'] complete/<str:backend>/<str:partial_token> … -
How to register a normal user in django from front end using custom user model?
# Custom User Model Code from django.db import models from django.contrib.auth.models import ( BaseUserManager, AbstractBaseUser ) class MyUserManager(BaseUserManager): def create_user(self, email, favorite_color, password=None): """ Creates and saves a User with the given email, favorite color and password. """ if not email: raise ValueError('Users must have an email address') user = self.model( email=self.normalize_email(email), favorite_color=favorite_color, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, favorite_color, password): """ Creates and saves a superuser with the given email, date of birth and password. """ user = self.create_user( email, password=password, favorite_color=favorite_color, ) user.is_admin = True user.is_superuser = True user.save(using=self._db) return user class MyUser(AbstractBaseUser): email = models.EmailField( verbose_name='email address', max_length=255, unique=True, ) favorite_color = models.CharField(max_length=50) bio = models.TextField(null=True) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) objects = MyUserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['favorite_color'] def __str__(self): return self.email def has_perm(self, perm, obj=None): "Does the user have a specific permission?" # Simplest possible answer: Yes, always return True def has_module_perms(self, app_label): "Does the user have permissions to view the app `app_label`?" # Simplest possible answer: Yes, always return True @property def is_staff(self): "Is the user a member of staff?" # Simplest possible answer: All admins are staff return self.is_admin # Templates Code as I want to … -
Django error: "Models aren't loaded yet."
I have been making changes to my models and adding new ones (many times). But now when I ran python3 manage.py makemigrations, I suddenly got this error: django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet. I deleted all migrations and the sqlite database file to start from scratch, but I get the same error again. All my models are registered in admin.py. I'm using Django 2.0.3. Can someone help me with this? Here is the full traceback: Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/home/anna/py3_cs50W/lib/python3.6/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line utility.execute() File "/home/anna/py3_cs50W/lib/python3.6/site-packages/django/core/management/__init__.py", line 347, in execute django.setup() File "/home/anna/py3_cs50W/lib/python3.6/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/anna/py3_cs50W/lib/python3.6/site-packages/django/apps/registry.py", line 112, in populate app_config.import_models() File "/home/anna/py3_cs50W/lib/python3.6/site-packages/django/apps/config.py", line 198, in import_models self.models_module = import_module(models_module_name) File "/usr/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/mnt/c/git/project3/orders/models.py", line 85, in <module> class PizzaOrder(models.Model): File "/mnt/c/git/project3/orders/models.py", line 90, in PizzaOrder p = Pizza.objects.get(pk=pizza_id) File "/home/anna/py3_cs50W/lib/python3.6/site-packages/django/db/models/manager.py", line 82, in manager_method return getattr(self.get_queryset(), … -
a post with border and no border using for or if in django
models.py: class post(models.Model): title = models.CharField(max_length=40) picture = models.ImageField(upload_to='somewhere/dir') active_post = models.BooleanField(default=True) commercial_post = models.BooleanField(default=False) normal_post = models.BooleanField(default=True) post_with_colored_border = models.BooleanField(default=False) post_title_bold = models.BooleanField(default=False) post_with_border_and_title_bold = models.BooleanField(default=False) def __str__ (self): return self.title views.py: def index(request): posts= post.objects.filter(active_post=True) normal_post = posts.filter(normal_post=True) commercial_post = posts.filter(commercial_post=True) post_with_border = posts.filter(post_with_colored_border=True) post_title_bold = posts.filter(post_title_bold=True) post_with_border_and_title_bold = posts.filter(post_with_border_and_title_bold=True) context = { 'posts':posts, 'commercial_post':commercial_post, 'post_with_border':post_with_border, 'post_title_bold':post_title_bold, 'post_with_border_and_title_bold':post_with_border_and_title_bold, } return render(request, 'index.html', context) index.html: {% if post_with_border AND commercial_post %} {% for abc in posts %} <div> <a href="#" class="border border-danger"> <img src="{{abc.picture.url}}"> </a> <h1> <a href="#" class="SomeClass"> {{abc.title}} </a> </h1> </div> {% endfor %} {% else %} {% for abc in normal_post %} <div> <a href="#"> <img src="{{abc.picture.url}}"> </a> <h6> <a href="#"> {{abc.title}} </a> </h6> </div> {% endfor %} {% endif %} i want to make it to list if its a commercial post it should have a border and a H1 in title but if its a normal post it should have no border and H6. But the problem is it shows all posts with border and H1. I need your help please Thank you -
Error while trying to open image in new tab
URL : 127.0.0.1:8000/media/IUl8isvYHPfsxcOFbc9Bi/Tulips_P0asGX5.jpg Page not found (404) Request Method: GET Request URL: 127.0.0.1:8000/media/IUl8isvYHPfsxcOFbc9Bi/Tulips_P/403.shtml Raised by: django.views.static.serve The image exists in media/IUl8isvYHPfsxcOFbc9Bi directory, the path given is correct. -
How do I set a user as inactive in Django when registering?
When registering, I'd like a moderator to manually set users as active instead of allowing them to be automatically set as active. Here's what I'm using in my users/views.py def register(request): if request.method == 'POST': form = UserRegisterForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') password = form.cleaned_data.get('password1') user = authenticate(username=username, password=password) # login(request, user) # messages.success(request, f'Your account has been created! You are now able to log in!') return redirect('login') else: form = UserRegisterForm() return render(request, 'users/register.html', {'form': form}) -
Manipulating data from a form to model django
I am quite new to django and having trouble manipulating data from a form before it reaches the table (model). Html: <p><label for="id_1">Choice 1:</label> <select name="choice_1" id="id_1"> <option value="1">Apple</option> <option value="2">Orange</option> </select></p> <p><label for="id_2">Choice 2:</label> <select name="Choice_2" id="id_2"> <option value="1">Cat</option> <option value="2">Dog</option> </select></p> <p><label for="id_3">Choice 3:</label> <select name="Choice_3" id="id_3"> <option value="1">Italy</option> <option value="2">France</option> </select></p> The results of this form are currently being sent to the table like: | ID | Choice 1 | Choice 2 | Choice 3 | ---- ---------- ---------- ---------- | 1 | Apple | Cat | Italy | ---- ---------- ---------- ---------- I would like it to be sent as: | ID | Choice | Preference | ---- ---------- ------------ | 1 | Choice 1 | Apple | | 1 | Choice 2 | Cat | | 1 | Choice 3 | Italy | ---- ---------- ------------ So if my model is: class user_choice(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) choice = models.CharField(max_length=30) preference = models.CharField(max_length=30) My form: class SubmitChoiceForm(forms.ModelForm): choice_1 = forms.ChoiceField(choices=choice1, required=False) choice_2 = forms.ChoiceField(choices=choice2, required=False) choice_3 = forms.ChoiceField(choices=choice3, required=False) class Meta: model = user_choice fields = ( ) My View: def post(self, request): form = SubmitChoiceForm(request.POST) if form.is_valid(): tip = form.save(commit= False) tip.user = request.user … -
Django user registration with phone and password
i am creating custom user model in django using abstract base user class, i want to create user with only two fields "phone and password " and name being the optional field , which i have set in my models .py that blank =true. i have created a rest api for user registration using my custom user model, but every time i try to create new user with phone and password it gives me below error:- IntegrityError at /api/users/ UNIQUE constraint failed: accounts_user.name Request Method: POST Request URL: http://127.0.0.1:8000/api/users/ Django Version: 3.0.1 Exception Type: IntegrityError Exception Value: UNIQUE constraint failed: accounts_user.name Exception Location: /usr/local/lib/python3.7/site-packages/django/db/backends/sqlite3/base.py in execute, line 396 Python Executable: /usr/local/opt/python/bin/python3.7 Python Version: 3.7.6 Python Path: ['/Users/raghav/milkbasketdemo/milkbasketdemo', '/usr/local/Cellar/python/3.7.6_1/Frameworks/Python.framework/Versions/3.7/lib/python37.zip', '/usr/local/Cellar/python/3.7.6_1/Frameworks/Python.framework/Versions/3.7/lib/python3.7', '/usr/local/Cellar/python/3.7.6_1/Frameworks/Python.framework/Versions/3.7/lib/python3.7/lib-dynload', '/usr/local/lib/python3.7/site-packages'] Please help where i am going wrong , i have searched and tried changing code number of times but nothing is working for me. please find the below code of models.py class UserManager(BaseUserManager): def create_user(self,phone, password=None,is_staff=False,is_admin=False,is_active=True): if phone is None: raise TypeError('Users must have a phonenumber.') user = self.model(phone=phone) user.set_password(password) user.staff=is_staff user.admin=is_admin user.active=is_active user.save(using=self._db) return user def create_staffuser(self, phone, password): """ Creates and saves a staff user with the given email and password. """ user = self.create_user( phone, password=password, … -
little bit confuse in dgetting absolute url in django
#project url from django.conf import settings from django.conf.urls import url from django.conf.urls.static import static from django.contrib import admin from django.urls import path, include import products urlpatterns = [ path('admin/', admin.site.urls), path('', include('products.urls')), url(r'^product/(?P<title>[\w-]+)/$', products.views.single,name='single') ] # app url from django.urls import path, include import products from . import views urlpatterns = [ path('', views.home, name='home'), ] #model class products(models.Model): title = models.CharField(max_length=120) desc = models.TextField() price = models.DecimalField(max_digits=10, decimal_places=2, default=29.99) sales_price = models.DecimalField(max_digits=10, decimal_places=2, blank=False, null=False, default=0) slug = models.SlugField(unique=True) timestamp = models.DateTimeField(auto_now_add=True, auto_now=False) update = models.DateTimeField(auto_now_add=False, auto_now=True) active = models.BooleanField(default=True) def __str__(self): return self.title def get_price(self): return self.price def get_absolute_url(self): return reverse("single", kwargs={"title": self.title}) #views def home(request): product = products.objects.all() template = 'home.html' context = {'product': product} return render(request, template, context) def single(request,title): try: product = products.objects.get(title=title) template = 'products.html' context = {'product': product} return render(request, template, context) except: raise Http404 plz view my code .. i m littlebit confuse in absolute url.. it returns title of the product after clicking some link but it doesnt give me the title if i change produc to other. for eg:http:/127.0.0.1:8000/product/T-shirt/ gives title but wheni hit http:/127.0.0.1:8000/productS/T-shirtgives eroror -
How to clear all data from an app in Django?
I want to remove all data from all models defined in a single Django app. The number of models might change in the app, hence I don't want to hard code model names. It would be great if it might be done using manage.py command, however I was not able to find one. The manage.py flush command is not suitable, because it only allows to clear data from all apps. -
Django:How to setup static files in django project
I created a simple project in Django but static files(CSS) not working. settings.py STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), ] urls.py urlpatterns = [ path('admin/', admin.site.urls), path('',views.portfolio), ]+ static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) HTML file {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <link rel="stylesheet" href="{% static 'portfolio.css' %}"> </head> <body> <h1>hello world</h1> </body> </html> picture of the project directory blog is app and my_site is a project. -
Django cannot find static file on proxy pass
I have managed to make my Django app work from a VPS location, but now it does not load one of the static files which is requested by the app template. The application path is 'http://dev.apps.gdceur.eecloud.dynamic.nsn-net.net/tacdb/' static files config in settings.py: STATIC_URL = "/static/" STATIC_ROOT = os.path.join(BASE_DIR, "mysite/static") # Site name. SITE_NAME = basename(DJANGO_ROOT) # Absolute filesystem path to the top-level project folder. SITE_ROOT = dirname(DJANGO_ROOT) STATICFILES_DIRS = (os.path.join(BASE_DIR, "mysite", "/static"),) The javascript request in the html file: {% block javascript %} <script src="{% static '/js/books.js' %}"></script> {% endblock %} the html file is located /tacdb/mysite/tacdashboard/templates/items/item_list.html the request for the static file is http://dev.apps.gdceur.eecloud.dynamic.nsn-net.net/static/js/books.js I use a proxy pass to in Apache for this app. If I run the app directly on the port using runserver, everything works fine. Any ideeas what is going wrong? P.S. this problem appeared when i added location to the proxypass. Thanks a lot! -
Form wont load in the django app
Code below for Django app. I am not sure why the forms wont load up in the "http://localhost:8000/.../new/" HTML page. Only the label "New Post" shows up in the web page. The form is missing. #models.py from django.db import models class Post(models.Model): title = models.CharField(max_length=255) body = models.TextField() #forms.py from django import forms from blog.models import Post from django.forms import ModelForm class PostForm(ModelForm): class Meta: model = Post fields = ('title', 'body') #views.py from django.shortcuts import render from .models import Post from .forms import PostForm def post_new(request): thisform = PostForm() return render(request, "post_edit.html", {'thisform': thisform}) #post_edit.html {% extends "base.html" %} {% load static %} {% static 'images' as base_url %} {% block content %} <h2>New post</h2> <form method="POST" >{% csrf_token %} {{ thisform.as_p }} <button type="submit" class="save btn btn-default">Save</button> </form> {% endblock %} #base.html <li class="nav-item"> <a class="nav-link" href="{% url 'post_new' %}">Add Post</a> </li> #blog/urls.py from django.urls import path from . import views urlpatterns = [ path("", views.index, name="index"), path("new/", views.post_new, name="post_new"), ] -
Displaying an image from a model in a Django template
I'm trying to access an image from a model in my template: In my template, I have: {% for server in servers %} <div class="hs-item set-bg" data-setbg="{{ server.image.url }}"> <div class="hs-text"> <div class="container"> <h2>The Best <span>Games</span> Out There</h2> <p>Lorem ipsum.</p> <a href="#" class="site-btn">Read More</a> </div> </div> </div> {% endfor %} And my models look like this: class Server(models.Model): Name = models.CharField(max_length=100) IP = models.CharField(max_length=50) Port = models.IntegerField() Image = models.ImageField(default='default.jpg', upload_to='server_pics') def __str__(self): return str(self.Name) if self.Name else '' I've added this to my settings.py: MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' And this to my urls.py: if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) But it doesn't display the image, and I don't get an error in the console... Not sure what I'm doing wrong here -
referencing field from different model from a function field
I have a Game model and an ActiveGame model. I want to track the games in progress which will have a start_time (current time) and end_time(start time - Game.duration) This is my model (redacted for easy read): class Game(models.Model): title = models.CharField(max_length=255,null=False, blank=False) tiempo = models.DurationField(null=True, blank=True,default="00:60:00") def get_end_time(): return datetime.now() + timedelta(1d) --> here I want to retrieve Game.tiempo class ActiveGame(models.Model): game = models.ForeignKey(Game, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) start_time = models.DateTimeField(default=timezone.now) end_time = models.DateTimeField(default=get_end_time) I defined the start_time default in a separate function as recommended and works fine with hardcoded values but I want to retrieve that information from Game model. I have tried many variants of: def get_end_time(self): return datetime.now() + timedelta(self.Game.tiempo) end_time = models.DateTimeField(default=get_end_time(self)) I can't figure out how a field that calls a function can gather information of other model that has already a relationship with a foreign key -
Django: ViewSets not accepting login required, rending SessionAuthentication useless
I am having issues using the DRF SessionAuthentication with views defined as ModelViewSets. The "LoginRequiredMixin" works fine in generics views, but I really don't like those as they require me to define all the urls manually and set them in the proper order. Very tedious when ViewSets allow you to define routes way more neatly. I have tried using the "@login_required" decorator following Django's doc authentication login(), but it doesn't accept it. Have tried specifying the authentication_class SessionAuthentication in my ViewSet but to no avail, following those posts: JWT required login login required Current FooBar_views.py file. The only way I have here so far to make sure a user is authenticated, is to check his JWT provided in the headers of his http request. foobar_vews.py with ViewSets # @login_required not being accepted when imported class FooBarViewSet(viewsets.ModelViewSet): """ Foo Bar ViewSet calling various serializers depending on request type (GET, PUT etc.) """ # Trying to filter FooBars list by status: Exluding unwanted ones queryset = FooBar.objects.exclude(status__name = 'SOLD').exclude(status__name = 'DELETED').order_by('id').reverse() # mapping serializer into the action serializer_classes = { 'list': FooBarIndexSerializer, 'retrieve': FooBarDetailsSerializer, 'create': FooBarCreateSerializer, } # Your default serializer default_serializer_class = FooBarIndexSerializer def get_serializer_class(self): """ Method to detect request type … -
TypeError: __str__ returned non-string (type int) Django
i'm trying to do a GET request, but i get this error: TypeError: str returned non-string (type int) I do not know what I'm doing wrong. Here's my code: in my models.py class Prueba(models.Model): id_prueba = models.AutoField(primary_key=True) nombre = models.CharField(max_length=255, blank=False, null=False) descripcion = models.TextField(max_length=255, blank=True, null=True) fecha_creacion = models.DateTimeField(default=datetime.now) id_cliente = models.ForeignKey(Cliente, related_name='clientes', on_delete=models.CASCADE) id_atentusiano = models.ForeignKey(Atentusiano, related_name='atentusianos', on_delete=models.CASCADE) id_carga = models.ForeignKey(Carga, related_name='cargas', on_delete=models.CASCADE) id_estado = models.ForeignKey(EstadoPrueba, related_name='estados', on_delete=models.CASCADE) id_costo = models.ForeignKey(Costo, related_name='costos', on_delete=models.CASCADE) class Meta: verbose_name = 'Prueba' verbose_name_plural = 'Pruebas' ordering = ['nombre'] def __str__(self): return self.nombre i tried with return str(self.nombre) but I keep getting the same error. In all other tables and models I have no problem. Help me please. -
How to star Tailwind CSS inside Django?
I'm starting to use Tailwind CSS. I've found django-tailwind to make the integration of tailwind as an app. I've followed all steps to install it on Windows 10, and it gave me no errors. https://github.com/timonweb/django-tailwind Then I reach step 7: Now, go and start tailwind in dev mode: python manage.py tailwind start But when running: python manage.py tailwind start To start tailwind in dev mode, I get: (ministerios_elim) PS D:\web_proyects\ministerios_elim> python manage.py tailwind start > django_tailwind@ start D:\web_proyects\ministerios_elim\theme\static_src > watch "npm run build-postcss" ./src > Watching ./src > django_tailwind@ build-postcss D:\web_proyects\ministerios_elim\theme\static_src > postcss --config . --map false --output ../static/css/styles.min.css ./src/styles.scss Terminal doesn't allow me to type anything else, it is just like the process is still running: What should I do? Should I enter some command? I've never worked with node before. I tried to look into the code of the library, to figure out what exactly python manage.py tailwind start does. https://github.com/timonweb/django-tailwind/blob/master/tailwind/management/commands/tailwind.py But couldn't find it.