Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
key error : command ,chatroom with django
i have i working chat room with django and jquery, but if i refresh the page i loose all messages, to prevent that i added a model (following a tutorial) and for this i start to modify in my consumers.py like class ChatConsumer(WebsocketConsumer): def get_messages(self, data): **print('you got the message')** pass def new_message(self, data): pass **commands** = { 'get_messages': get_messages, 'new_message': new_message } def connect(self): self.user = self.scope['user'] self.id = self.scope['url_route']['kwargs']['course_id'] self.room_group_name = 'chat_%s' % self.id # join room group async_to_sync(self.channel_layer.group_add)( self.room_group_name, self.channel_name) # accept connection self.accept() def disconnect(self, close_code): # leave room group async_to_sync(self.channel_layer.group_discard)( self.room_group_name, self.channel_name) # receive message from WebSocket **def receive(self, text_data):** **text_data_json = json.loads(text_data)** **self.commands[data['command']](self, data)** def send_chat_message(self, message): now = timezone.now() # send message to room group async_to_sync(self.channel_layer.group_send)( self.room_group_name, { 'type': 'chat_message', 'message': message, 'user': self.user.username, 'datetime': now.isoformat(), } ) # receive message from room group def chat_message(self, event): # Send message to WebSocket self.send(text_data=json.dumps(event)) just for the sake of seeing if my modifications are adding up, i runserver, if there is no problem i would see the message printing in my prompt (not the actual chat room, since its still not functionnal yet), but i get an error saying Errorkey: command, note! i test … -
Django - unable to pass user context to model form on class based Updateviews
Appreciate the help in advance guys. I am having some issues passing context from my class based UpdateView to django Model form. I am able to create new records and pass user context but when i try the same method for update view, it is failing. Note that my model has some Many-to-Many fields so in my forms, i am filtering the data on the dropdown based on specific criteria and using ajax in html to render it. #View class campaign_drive_update(SuccessMessageMixin, UpdateView): model = CampaignDrive form_class = campaign_drive_add template_name = 'campaignmanagement/campaign_drive_add.html' success_url = reverse_lazy('campaign_drive_add') success_message = "Record was created successfully" def get_form_kwargs(self): kwargs = super(campaign_drive_update, self).get_form_kwargs() kwargs['request']=self.request return kwargs form class campaign_drive_add(forms.ModelForm): def __init__(self, *args, **kwargs): """ Grants access to the request object so that only members of the current user are given as options""" self.request = kwargs.pop('request') super(campaign_drive_add, self).__init__(*args, **kwargs) self.fields['associated_location'].queryset = NonProfit_location.objects.filter( associated_nonprofit=self.request.user.user_nonprofit.id) self.fields['associated_company'].queryset = Company.objects.filter( linking=self.request.user.user_nonprofit.id) self.fields['associated_campaign_type'].queryset = CampaignType.objects.filter( associated_nonprofit=self.request.user.user_nonprofit.id) self.fields['existing_contact_id'].queryset = Contact.objects.filter( associated_nonprofit=self.request.user.user_nonprofit.id) self.fields['request_status'].queryset=RequestStatus.objects.filter(viewable_to_ops=True) # self.fields['associated_campaign_id'].queryset = Campaign.objects.none() -
Login probleme django 3
I have a problem to login to my app where I have a personalized User, the superuser can login with no probleme, but when I try with a normal user I get an error. I'm using Django 3. the code for my app: admin.py from django import forms from django.contrib import admin from django.contrib.auth.models import Group from django.contrib.auth.admin import UserAdmin from django.contrib.auth.forms import ReadOnlyPasswordHashField from django.core.exceptions import ValidationError from .forms import EmployeeCreationForm, EmployeeChangeForm, ControlorCreationForm, ControlorChangeForm from .models import * class EmployeeAdmin(UserAdmin): add_form = EmployeeCreationForm form = EmployeeChangeForm model = Employee list_display = ('registration_number', 'first_name', 'last_name', 'email', 'is_active', 'is_exploitation_admin', 'is_supervisor', 'is_controlor', 'is_driver', 'is_staff',) list_filter = ('registration_number', 'email', 'is_active', 'is_exploitation_admin', 'is_supervisor', 'is_controlor', 'is_driver',) fieldsets = ( (None, {'fields': ('registration_number', 'email', 'password')}), ('Permissions', {'fields': ('is_active', 'is_exploitation_admin', 'is_supervisor', 'is_controlor', 'is_driver', 'is_staff')}), ('Personal', {'fields': ('city_id', 'region_id')}), ) add_fieldsets = ( (None, { 'classes': ('wide',), 'fields': ('registration_number', 'first_name', 'last_name', 'email', 'password', 'is_active', 'is_exploitation_admin', 'is_supervisor', 'is_controlor', 'is_driver', 'is_staff')} ), ) search_fields = ('email','registration_number', 'first_name','last_name') ordering = ('registration_number', 'last_name') admin.site.register(Employee, EmployeeAdmin) admin.site.register([Controlor, Driver, Supervisor, Vehicle, Region, City, GazStation]) and the manager.py: from django.contrib.auth.base_user import BaseUserManager from django.utils.translation import ugettext_lazy as _ class EmployeeManager(BaseUserManager): def create_user(self, email, first_name, last_name, password, registration_number, **extra_fields): if not last_name: raise ValueError(_('Le nom est … -
Why I can't print the session variable in this Django example application?
I am following this Mozzilla's articles related about how to build a Django application and I am finding the following problem related to session, this is the specific article: https://developer.mozilla.org/it/docs/Learn/Server-side/Django/Sessions Into my Django portal I have: I have enabled sessions into locallibrary/locallibrary/settings.py file, infact I have set: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'catalog.apps.CatalogConfig', ] 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', ] Then this is my index view function code defined into the view.py file: def index(request): """View function for home page of site.""" # Generate counts of some of the main objects num_books = Book.objects.all().count() num_instances = BookInstance.objects.all().count() # Available books (status = 'a') num_instances_available = BookInstance.objects.filter(status__exact='a').count() # The 'all()' is implied by default. num_authors = Author.objects.count() # Number of visits to this view, as counted in the session variable. num_visits = request.session.get('num_visits', 0) request.session['num_visits'] = num_visits + 1 context = { 'num_books': num_books, 'num_instances': num_instances, 'num_instances_available': num_instances_available, 'num_authors': num_authors, } # Render the HTML template index.html with the data in the context variable return render(request, 'index.html', context=context) As you ca see I defined these linese related to session: # Number of visits to this view, as counted in the session variable. … -
Remove wagtail from django app, and wagtail db tables from postgres
How do I go about removing an errant wagtail install from a django project. Actually, I just want to remove the postgres tables. I accidentally was pointing to a wrong secrets file and used a database for another django project, so I have wagtail tables. I can easily drop the wagtail tables, but are there other things I need to drop? I'm thinking my django_migrations table has info I shouldn't have. -
Why the 'post' method is not working in my django app?
I am using Django to develop a blog and when I wanted to get the contact informations, the post request seems not working at all. In the contacts view I don't do much I just wanted to make sure that the post request is working but it returns a Get request instead and the get method is working really fine the javascript file //CONTACT FORM $('#contactform').submit(function(){ var action = $(this).attr('action'); $("#message").slideUp(750,function() { $('#message').hide(); $('#submit').attr('disabled','disabled'); $.post(action, { name: $('#name').val(), email: $('#email').val(), comments: $('#comments').val() }, function(data){ document.getElementById('message').innerHTML = data; $('#message').slideDown('slow'); $('#submit').removeAttr('disabled'); if(data.match('success') != null) $('#contactform').slideUp('slow'); $(window).trigger('resize'); } ); }); return false; }); view.py from django.http.response import HttpResponse from contact.forms import ContactForm from django.shortcuts import render from django.views.decorators.csrf import csrf_exempt @csrf_exempt # Create your views here. def contacts(request): if request.method == "POST" and request.is_ajax: print('hello!!') return render(request, 'contact/contact.html') forms.py from django import forms from .models import Contact class ContactForm(forms.Form): class Meta: model = Contact fields = ['cont_name', 'cont_email', 'cont_message', 'cont_date'] models.py from django.db import models from datetime import datetime class Contact(models.Model): cont_name = models.CharField( max_length = 10) cont_email = models.EmailField() cont_message = models.TextField(blank=False) cont_date = models.DateTimeField(default=datetime.now, blank=True) def __str__(self): return self.cont_name contact.html <div class="container"> <div class="row"> <div class="col-md-6"> <p class="lead">Sold old ten are … -
Django/Python unable to find GDAL Library
I have installed GDAL in a virtual environement with the following commands: $ brew install gdal $ pip3 install gdal When trying a python manage.py makemigrations or python manage.py runserver (or whatever) on the website code for which I installed it, I'm running into the following error: django.core.exceptions.ImproperlyConfigured: Could not find the GDAL library (tried "gdal", "GDAL", "gdal2.4.0", "gdal2.3.0", "gdal2.2.0", "gdal2.1.0", "gdal2.0.0"). Is GDAL installed? If it is, try setting GDAL_LIBRARY_PATH in your settings. I'm struggling to find good information on how to solve it. I'm using MacOS Catalina. I have no experiences with GDAL, at this stage I just need to install it properly to make the website run on my machine and start contributing to the code. Any help would be appreciated. -
how can I access Django rest framework using ajax
I am trying to get a form from the rest framework using ajax I already tried the ajax get method on other thing and it worked for me now I am trying to use the POST method to grab the form but i am facing difficulties my current HTML code: {% extends 'base.html' %} {% block content %} <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta name="robots" content="NONE,NOARCHIVE" /> <title>Create a Recipe</title> </head> <body class=""> </body> {%endblock%} </html> <script src="https://code.jquery.com/jquery-3.1.0.min.js"></script> <script> var data = {title:'title',tags:'tags',ingredients:'ingredients',time_minutes:'time_minutes'} $.ajax({ type: 'POST', data: data, url: '/api/recipe/recipes/', success: function(res){ for (const i in res) { console.log(res[i].) } }, error: function(error) { callbackErr(error,self) } }) </script> this is my current attempt on ajax form serializers.py class RecipeSerializer(serializers.ModelSerializer): """Serialize a recipe""" ingredients = serializers.PrimaryKeyRelatedField( many=True, queryset=Ingredient.objects.all() ) tags = serializers.PrimaryKeyRelatedField( many=True, queryset=Tag.objects.all() ) class Meta: model = Recipe fields = ( 'id', 'title', 'ingredients', 'tags', 'time_minutes', 'price', 'link' ) read_only_fields = ('id',) class RecipeDetailSerializer(RecipeSerializer): """Serialize a recipe detail""" ingredients = IngredientSerializer(many=True, read_only=True) tags = TagSerializer(many=True, read_only=True) class RecipeImageSerializer(serializers.ModelSerializer): """Serializer for uploading images to recipes""" class Meta: model = Recipe fields = ('id', 'image') read_only_fields = ('id',) Models.py def recipe_image_file_path(instance, filename): """Generate file path for new … -
How to pass dictionry in view using django
i begin to learn django i woud like to pass dictionry in view.py but in browser i get this AttributeError at /accuiel/ 'list' object has no attribute 'get' enter image description here -
DRF Could not resolve URL for hyperlinked relationship using view name on PrimaryKeyRelatedField
I have a frustrating problem with POST requests on a DRF serializer - DRF is, for some reason, going to an incorrect view name, and view_name is not a settable property on PrimaryKeyRelated Field. Models: (the class with the issue) class Section(models.Model): teacher = models.ManyToManyField(Teacher) (a class that works, using the same pattern) class Assessment(models.Model): standards = models.ManyToManyField(Standard) Serializers: (doesn't work) class SectionInfoSerializer(serializers.HyperlinkedModelSerializer): url = serializers.HyperlinkedIdentityField(view_name="gbook:section-detail") teacher = BasicTeacherSerializer(many=True, read_only=True), teachers_id = serializers.PrimaryKeyRelatedField(write_only=True, queryset=Teacher.objects.all(), many=True, source='teacher', allow_empty=False) class Meta: model = Section fields = '__all__' read_only_fields = ['sendEmails', 'teacher', 'course'] (works) class AssessmentSerializer(serializers.HyperlinkedModelSerializer): pk = serializers.PrimaryKeyRelatedField(read_only=True) url = serializers.HyperlinkedIdentityField(view_name="appname:assessments-detail") standards = serializers.PrimaryKeyRelatedField(read_only=True, many=True) standards_id = serializers.PrimaryKeyRelatedField(queryset=Standard.objects.all(), source='standards', write_only=True, many=True, allow_empty=False) class Meta: model = Assessment fields = '__all__' urls: router.register(r'teachers', teacher_views.TeacherViewSet, basename='teacher') router.register(r'sections', course_views.SectionViewSet) router.register(r'standards', gbook.views.standard_views.StandardViewSet, basename='standards') router.register(r'assessments', AssessmentViewSet, basename='assessments') I'm using the _id fields during POST and PUT to send the id's of the related obejcts, then serializing them. This worked great with AssessmentSerializer (and several others), but is failing for a reason that I can't figure out. Certainly, the appname is missing from the view returned in the error, but I don't know why that's happening, and why it didn't happen before. Stack trace: Internal Server Error: /appname/sections/ … -
Updating related objects django rest framework
In my django project, I have 2 relevant models: class User(AbstractUser): email = models.EmailField( verbose_name='e-mailaddress', max_length=255, unique=True) # other props not important class Profile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) #other props not important For both creating and retrieving, it is convenient to have User as a nested object in the serializer: class ProfileSerializer(serializers.ModelSerializer): user = UserSerializer() class Meta: model = Profile fields = '__all__' def create(self, validated_data): user_data = validated_data.pop('user') user = User.objects.create(**user_data) user.save() # because of reasons, an empty profile is created on initial save. This works, trust me d, _ = Profile.objects.update_or_create(user=user, defaults=validated_data) d.save() return d HOWEVER. One action that I want to be possible as well is to update both properties of the Profile and the User at the same time. When doing this with my serializer, serializer.is_valid() fails as the provided email is already present in the database. This also indicates that, even if the validation passes (i.e. because of an updated email address), a new User object will be created and coupled to the Profile. So my question is: How do I update properties of the profile and its related user without creating a new user? -
Django - Remove currently displayed image link In An Image Edit Form
I am using Django 2.2 for a project, I want to remove the currently displayed image link from the user update form as shown in the image below, how do I do this? image forms.py from .models import Profile class CreateUserForm(UserCreationForm): class Meta: model = get_user_model() fields = ['username', 'email', 'password1', 'password2'] class UserUpdateForm(forms.ModelForm): email = forms.EmailField() class Meta: model = User fields = ['username', 'email'] help_texts = { 'username': None, } class ProfileUpdateForm(forms.ModelForm): class Meta: model = Profile fields = ['profile_pic'] -
django 3 redirect with pk in form verification
@MODS- Although it has been asked on here before I can not find a suitable answer in Django 3, please read through all I have tried before deleting Preamble: I am working through This Tutorial that is taught in Django 1, I am following it but making necessary changes for Django 3. QUESTION: I receive an error when loading my page with a form on it. HTML for the form page: {% block title %}Start a New Topic{% endblock %} {% block breadcrumb %} <li class="breadcrumb-item"><a href="{% url 'home' %}">Boards</a></li> <li class="breadcrumb-item"><a href="{% url 'board_topics' board.pk %}">{{ board.name }}</a></li> <li class="breadcrumb-item active">New topic</li> {% endblock %} {% block content %} <form method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit" class="btn btn-success">Post</button> </form> {% endblock %} Base HTML: {% block title %}Start a New Topic{% endblock %} {% block breadcrumb %} <li class="breadcrumb-item"><a href="{% url 'home' %}">Boards</a></li> <li class="breadcrumb-item"><a href="{% url 'board_topics' board.pk %}">{{ board.name }}</a></li> <li class="breadcrumb-item active">New topic</li> {% endblock %} {% block content %} <form method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit" class="btn btn-success">Post</button> </form> {% endblock %} urls.py from django.contrib import admin from django.urls import path , re_path #uses path and re_path for regex … -
How to update dictionary value in inside for loop using Django template
This my scenario. I have 1000 dictionaries on the list. So, I will pass the list in the Django template. In the Django template, I will iterate the list and get the dictionaries one by one. In dictionaries inside, I have an image path. So, I need to assign an empty string in the image path inside the forloop. Is it possible how to achieve this scenario?. My code {%for contact in contacts%} {{c.image}} = '' <p>{{c.image}}</p> {% endfor %} In views I will achieve this scenario. but I need to handle the Django template page. -
How can I run different projects for the same domain address?
I know very little about the deployments of projects. I want to run different projects for the same domain address. Maybe these projects can be web, desktop, etc. I use Django and Python technologies for these projects. Examples: www.companyname.com/project1/... www.companyname.com/project2/... www.companyname.com/project3/... How should I go about a problem like this in Python? I have no experience with deploy stages. What structure can be used for such a thing? How can I make this system more effective. Docker and aws are enough for such a problem? How should I go about this challenge? Thank you for replies. -
Django Elastic Search: Elastic returns nothing
I have been studying the documentation and third resources for 2 days, but I cannot solve the problem with the information output. my code: models.py: class Course(models.Model): name = models.CharField(max_length=200, unique=True) description = models.TextField() owner = models.ForeignKey(UserAccount, related_name='courses_created', on_delete=models.CASCADE) category = models.ForeignKey(Category, related_name='category', on_delete=models.CASCADE) slug = models.SlugField(max_length=200, unique=True) created = models.DateTimeField( auto_now_add=True) cover = models.ImageField(upload_to='courses/', null=True, blank=True) video = models.URLField(null=True, blank=True) class Meta: verbose_name = 'Course' verbose_name_plural = 'Courses' search_indexes.py: from elasticsearch_dsl import analyzer from django_elasticsearch_dsl.registries import registry from django_elasticsearch_dsl import Document, Index, fields from courses import models as courses_models course_index = Index('courses') course_index.settings( number_of_shards=1, number_of_replicas=0 ) html_strip = analyzer( 'html_strip', tokenizer="standard", filter=["standard", "lowercase", "stop", "snowball"], char_filter=["html_strip"] ) class CourseDocument(Document): id = fields.IntegerField(attr='id') name = fields.TextField( analyzer=html_strip, fields={ 'raw': fields.TextField(analyzer='keyword'), } ) description = fields.TextField( analyzer=html_strip, fields={ 'raw': fields.TextField(analyzer='keyword'), } ) owner = fields.IntegerField(attr='owner_id') category = fields.TextField( analyzer=html_strip, fields={ 'raw': fields.TextField(analyzer='keyword'), } ) created = fields.DateField() class Django: model = courses_models.Course serializers.py: from django_elasticsearch_dsl_drf.serializers import DocumentSerializer from courses import search_indexes as courses_documents import json from rest_framework import serializers class CourseDocumentSerializer(serializers.Serializer): id = serializers.SerializerMethodField() name = serializers.CharField() description = serializers.CharField() owner = serializers.IntegerField() created = serializers.DateField() class Meta: fields = ( 'id', 'name', 'description', 'owner', 'created', 'category' ) views.py: from django_elasticsearch_dsl_drf.constants … -
Django: Adding object using a reverse relation in ManyToMany relationship
I'm new to Django and trying to Understand the Many To Many Relationship. I've created two models Movie and Actor. One movie can have many Character and One Character can have many Movies. class Movie(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name class Actor(models.Model): name = models.CharField(max_length=100) movies = models.ManyToManyField(Movie) def __str__(self): return self.name Using the Relationship I can add Multiple Movies to an Actor like this : avengers = Movie(name='Avengers') avengers.save() sherlock_holmes = Movie(name='Sherlock Holmes') sherlock_holmes.save() robert_downey_jr = Actor(name='Robert Downey Jr') robert_downey_jr.save() robert_downey_jr.movies.add(avengers) robert_downey_jr.movies.add(sherlock_holmes) Now, in some cases I would like to add Actors to a Movie avengers but failing to do so. I'm doing the following : chris_evans = Actor(name='Chris Evans') chris_evans.save() avengers.actor.add(chris_evans) The error is throws : Traceback (most recent call last): File "<console>", line 1, in <module> AttributeError: 'Movie' object has no attribute 'actor' I Understand there is not property in Movie Model called Actor I though it will work like in OneToMany Relationship but it is not. -
Rolling 12 months regardless of year in Django
How would I go about setting up a rolling 12 month period in Django without any year. I am trying to plot the academic year but the problem I am finding mainly due to my lack of knowledge is that I have to set the year in datetime The academic year runs from beginning of April to the End of March the following year, therefore the easiest way for me to calculate this I guess is to provide a rolling 12 months or to set the date regardless of the year. As always, thank you for the help. -
I want to know why secret_key is wrong
I'm making website using Python Framework of 'Django'. I have some problems with Django about secret_key . When I set a secret_key in .env file on private and change settings.py, there is problem. I'm trying to solve it by myself, but its so difficult. When I runserver on django, It errors contain: (venv) C:\pragmatic>python manage.py runserver C:\pragmatic\venv\lib\site-packages\environ\environ.py:637: UserWarning: Error reading C:\ pragmatic\.env - if you're not configuring your environment separately, check this. warnings.warn( Traceback (most recent call last): File "C:\pragmatic\venv\lib\site-packages\environ\environ.py", line 273, in get_value value = self.ENVIRON[var] File "C:\Users\PJJ\AppData\Local\Programs\Python\Python38-32\lib\os.py", line 675, in __ getitem__ raise KeyError(key) from None KeyError: 'SECRET_KEY' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\pragmatic\venv\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\pragmatic\venv\lib\site-packages\django\core\management\__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\pragmatic\venv\lib\site-packages\django\core\management\base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "C:\pragmatic\venv\lib\site-packages\django\core\management\commands\runserver.py", line 61, in execute super().execute(*args, **options) File "C:\pragmatic\venv\lib\site-packages\django\core\management\base.py", line 371, in execute output = self.handle(*args, **options) File "C:\pragmatic\venv\lib\site-packages\django\core\management\commands\runserver.py", line 68, in handle if not settings.DEBUG and not settings.ALLOWED_HOSTS: File "C:\pragmatic\venv\lib\site-packages\django\conf\__init__.py", line 83, in __getatt r__ self._setup(name) File "C:\pragmatic\venv\lib\site-packages\django\conf\__init__.py", line 70, in _setup self._wrapped = Settings(settings_module) File "C:\pragmatic\venv\lib\site-packages\django\conf\__init__.py", line … -
Django - is it possible to include two templates with different styles?
I created a template on my Django app, it uses it's own CSS files and its own style. Now i would like to add on top of this template my own navbar that i'm using on the rest of the app. The problem is that the navbar has its own styles, and the template has its style too, so mixing them messes up both the navbar and the rest of the template. I thought that using include instead of extends would fix my problem, but the i problem is that when i try with template.html {% include 'navbar.html' %} ... the two parts will still collide. Is there any way to import an element in a template without applying all the styles of the element to the rest of the template in Django? Or is mine a CSS problem and i should solve it there? Any kind of advice is appreciated. -
Django CSS HTML Not Applying
I am new to Django and am currently trying to customize the aesthetics of my polling app. I cannot get my style sheet to apply to my polling app. Specifically, I am looking to change the fonts/color of the questions/h1 tag as well as adding in a background image. The background remains white, and the links do not reflect the style.css file. Any ideas what I am doing wrong? polls/style.css li a { color: red; font-family: 'Lobster'; } body { padding-left: 15px; background-image: white url({%static 'C:\Users\xxxx\Python\Price Tracking\Django\mysite\polls\static\polls\images\sample123.jpg'%}) repeat; } index.html <head> <title>Polling</title> <link href="//fonts.googleapis.com/css?family=Lobster&subset=latin,latin-ext" rel="stylesheet" type="text/css"> <link rel="stylesheet" href="{% static 'polls/style.css' %}"> </head> <body> <div> <h1><a href="https://www.google.com">Welcome to the polling app!</a></h1> </div> <!-- Question List --> {% if latest_question_list %} <ul> {% for question in latest_question_list %} <li><a href="{% url 'polls:detail' question.id %}">{{ question.question_text }}</a></li> {% endfor %} </ul> {% else %} <p>No polls are available.</p> {% endif %} </body> -
One-to-One and One-to-Many relation to the same model with same reverse accessor
I have an order model with a one to many relation to a OrderDate Model. Now I want have an additional field on order named 'chosen_date' with a one to one relation to the same OrderDate Model. The Problem is that my relations at OrderDate both have the name 'order', which clashes. How can I solve this problem without adding a new field like 'Order_2' on the OrderDate Model? Here are my models: class Order(TimeStampedModel): chosen_date = models.OneToOneField('OrderDate', on_delete=models.CASCADE, blank=True, null=True) class OrderDate(TimeStampedModel): order = models.ForeignKey(Order, related_name='dates', on_delete=models.CASCADE) date = models.DateField() morning = models.BooleanField(default=False) noon = models.BooleanField(default=False) evening = models.BooleanField(default=False) -
Image doesn't load fully at first, only after refresh
I made a django application which is online at: https://www.casualspotter.com/. On my homepage I have a carousel with multiple images. The problem I'm having is that for some reason the images don't load fully. After refreshing the page the images do load fully. The carousel code: <div class="carousel carousel-slider" id="demo-carousel-content" data-indicators="true" > <a class="carousel-item" href="/cp_company"> <img class='carouselitem' src="{% static 'images/cp_company.jpg' %}"> <h2 class="bottom-left">C.P. COMPANY</h2> </a> <a class="carousel-item" href="/stone_island"> <img class='carouselitem' src="{% static 'images/stone_island.jpg' %}"> <h2 class="bottom-left">STONE ISLAND</h2> </a> <a class="carousel-item" href="/ma_strum"> <img class='carouselitem' src="{% static 'images/mastrum.jpg' %}"> <h2 class="bottom-left">MA.STRUM</h2> </a> <a class="carousel-item" href="/barbour"> <img class='carouselitem' src="{% static 'images/barbour_lookbook.jpg' %}"> <h2 class="bottom-left">BARBOUR</h2> </a> <a class="carousel-item" href="/lacoste"> <img class='carouselitem' src="{% static 'images/lacoste_banner.jpg' %}"> <h2 class="bottom-left">LACOSTE</h2> </a> <a class="carousel-item" href="/perry"> <img class='carouselitem' src="{% static 'images/perry_banner.jpg' %}"> <h2 class="bottom-left">FRED PERRY</h2> </a> <a class="carousel-item" href="/paul_shark"> <img class='carouselitem' src="{% static 'images/paul_shark_banner.jpg' %}"> <h2 class="bottom-left">PAUL & SHARK</h2> </a> <a class="carousel-item" href="/napa"> <img class='carouselitem' src="{% static 'images/napa_banner.jpg_large' %}"> <h2 class="bottom-left">NAPAPIJRI</h2> </a> <a class="carousel-item" href="/tnf"> <img class='carouselitem' src="{% static 'images/tnf_banner.jpg' %}"> <h2 class="bottom-left">THE NORTH FACE</h2> </a> </div> CSS: img.carouselitem{ height: auto; } Thanks in advance! -
Order of Operations Django Templates
I have a float variable mynumber in Django templates, and I need to round it to the nearest integer without third party filters, so I'm following this logic: int(mynumber - 0.5) + 1 In Django templates I can do this: {{ mynumber|add:"-0.5"|add:"1" }} But the problem, as you can see, is that there is no order of operations, so I get a different number than the expected, how can I solve this? I haven't found a way of putting parenthesis, and also I need to convert to integer after the first operation. -
How can I make this Function Based View work?
views.py from django.views.generic.detail import DetailView from django.shortcuts import redirect from django.urls import reverse from django.contrib.auth.decorators import login_required class RoomDetail(DetailView): """ RoomDetail Definition """ model = models.Room ........ #omitted ........ @login_required def delete_room(request, room_pk): user = request.user user_pk = user.pk try: room = models.Room.objects.get(pk=room_pk) if room.host.pk != user.pk: messages.error(request, "Can't delete the Room") else: room.delete() messages.success(request, "Room Deleted") return redirect(reverse("users:profile", kwargs={"pk": user_pk})) except models.Room.DoesNotExist: return redirect(reverse("core:home")) users/urls.py from django.urls import path from . import views app_name = "users" urlpatterns = [ ....... #omitted ....... path("<int:pk>/", views.UserProfileView.as_view(), name="profile"), ] html ........ <-- omitted --> ........ <div class="mt-1 mb-3 sm:my-0 w-full sm:w-1/3"> {% if room.host == user %} <a href="{% url 'rooms:edit' room.pk %}" class="btn-link block mb-3 bg-green-500">Edit Room</a> <a href="{% url 'rooms:delete' room.pk %}" class="btn-link block">Delete Room</a> <div class="w-full text-center"> <span class="font-extrabold mx-auto mt-px text-yellow-600" >WARNING!!! THIS ACTION IS NOT RETRIEVABLE!!</span> </div> {% endif %} </div> ........... <-- omitted --> ........... In the code above, I've tried to make "Delete Room" anchor function, whose function is deleting room and redirect users to their profile, if they are the owner of the room. But clicking that "Delete Room' didn't function as I expected, just turning back the error below to me. And I …