Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to make composition query based on POST data
I'm stuck, can't find a way to solve this task. I have a simple search form with 4 fields, and can't do composite query based on it. form.py class ViewerForm(forms.Form): text_search = forms.CharField(required=False) birthday_search = forms.DateField(required=False) study_from_search = forms.DateField(required=False) study_to_search = forms.DateField(required=False) I tried to do things like that, but it doesn't work properly. view.py def viewer(request): if request.method == 'POST': form = ViewerForm(request.POST) if form.is_valid: persons_list = Person.objects.all() query = [] if len(request.POST['text_search']): text = request.POST['text_search'] query.append(persons_list.filter(Q(fio__contains=text) | Q(sex__contains=text) | Q(mobile_number__contains=text) | Q(group__contains=text) | Q(edu_organization__contains=text))) if len(request.POST['text_search']): birthday = request.POST['birthday_search'] query.append(persons_list.filter(Q(birthday_date__exact=birthday))) if len(request.POST['study_from_search']): study_from_search = request.POST['study_from_search'] query.append(persons_list.filter(Q(birthday_date__exact=study_from_search))) if len(request.POST['study_to_search']): study_to_search = request.POST['study_to_search'] query.append(persons_list.filter(Q(period_of_study_to__exact=study_to_search))) persons_list.filter(query) How to make query based on POST data, if data in a filed is exist then do some filter. -
How to preserve the order in serializing JSON via MultipleChoiceField
I have a pre-defined list of valid choice: allowed_choices = ['yes', 'no', 'I don't know'] I'm working on an API using the Django rest framework. To validate and serialize the inputs I'm using the Django Fields. For this purpose I have a chosen a MulitpleChoiceField. dataColumns = serializers.MultipleChoiceField( choices=allowed_choices, allow_blank=False, source="data_columns", ) I built afterwards a pandas data frame with the inputs as columns. It is important that they are preserved in the same order. How can I validate using the MulitpleChoiceField and get returned a set with the same order as the input? -
Django celery task that will execute every day from 00:00 to 02:00
I need to set up django celery task my_task that will execute every day from 00:00 to 02:00 with 5 minutes interval in this period. It seems it is unable to set up this task in admin via django-celery-beat. How to set it properly? I need something like celery_app.conf.beat_schedule = { 'my_task_1': { 'task': 'tasks.my_task', 'schedule': crontab(minute=5), 'start': crontab(hour=0, minute=0), 'expires': crontab(hour=2, minute=0), 'args': ("94"), }, } Thank you for your time. -
how to save user gps location in django
I need to track and save user location in my database to delever his order to the location from django.contrib.gis.utils import GeoIP -
Not able to verify SendGrid verification with Django
I'm currently reading a book on Django (for beginners) and I reached the point where I need to implement a password reset feature to the test website using SendGrid SMTP Relay. After creating an account and starting to create the SMTP relay I greeted with the following screen: Based on this page I added the following lines of code to my setting.py file: EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' EMAIL_HOST = 'smtp.sendgrid.net' EMAIL_HOST_USER = 'apikey' EMAIL_HOST_PASSWORD = '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' EMAIL_PORT = 587 EMAIL_USE_TLS = True After running the website and trying to reset my password (the password of the superuser) I get the desired message with the reset link in my console but sadly nothing comes to my email. Thus I get the following error message when trying to verify integration. What I tried so far: I tried creating multiple different API keys to make sure nothing was wrong with the API key I created a new SendGrid account I tried removing EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' from the settings.py file (this only made things worst) I've been trying to solve this issue for over a day now, any help would be greatly appreciated! -
How do I write this piece of code in a clean way?
I am just starting out with Django right now and I am trying to display certain div's based on a field that is picked by a user. However this code looks really sloppy and I am repeating myself. I feel like this can be fixed with a loop, but I don't know how. Can someone help me out? <div class="pitch"> <div class="container-field"> <div class="box1"> <div class="pen1"> {% if page.primary_field_position and page.secondary_field_position == 'GK' %} <div class="pos" style="margin: 5px 15px;">1</div> {% endif %} </div> </div> {% if page.primary_field_position and page.secondary_field_position == 'LB' %} <div class="pos" style="margin: 70px 40px">2</div> {% endif %} {% if page.primary_field_position and page.secondary_field_position == 'LCD' %} <div class="pos" style="margin: 70px 116px">6</div> {% endif %} {% if page.primary_field_position and page.secondary_field_position == 'RCD' %} <div class="pos" style="margin: 70px 196px;">3</div> {% endif %} {% if page.primary_field_position and page.secondary_field_position == 'RB' %} <div class="pos" style="margin: 70px 270px">4</div> {% endif %} {% if page.primary_field_position and page.secondary_field_position == 'LM' %} <div class="pos" style="margin: 198px 40px">5</div> {% endif %} {% if page.primary_field_position and page.secondary_field_position == 'DM' %} <div class="pos" style="margin: 140px 153px">6</div> {% endif %} {% if page.primary_field_position and page.secondary_field_position == 'RM' %} <div class="pos" style="margin: 198px 270px">7</div> {% endif %} {% if page.primary_field_position and … -
Django template showing data of all users instead of one user
I am trying to retrieve information regarding a user's profile to display on a page. The issue is it retrieves the relevant information from every user instead of just the one logged in. I have tried requesting for only the user logged in at the time, but I unfortunately could not get it to work. HTML <!-- Bio --> <div> <span class="bold"> <p>Bio:</p> </span> <p> {% for profile in profiles %} {{ profile.bio }} {% endfor %} </p> </div> models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) bio = models.CharField(max_length=2000) instrument = models.CharField(max_length=255, choices=instrument_list, blank=True) level = models.CharField(max_length=255, choices=level_list, blank=True) preferred_language = models.CharField(max_length=255, choices=language_list, blank=True) time_zone = models.CharField(max_length=255, choices=time_list, blank=True) def __str__(self): return self.profile @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() views.py def profile_page(request): form = ProfileForm profiles = Profile.objects.all() args = {'form' : form, 'profiles' : profiles} return render(request, 'student/profile_page.html', args) I am trying to get the profile_page view to display the relevant model information for only one user (the one currently logged in). -
After click button and refresh website all buttons are like selected on django detail view
I have app in django 1.11 and I have problem with voting up or down on comments on detail page of post. For each I would like to check if is voted up or voted down. Now if I click vote up - jquery code - change only this button on voted up, counter of votes also works ok, but after refresh website all vote up buttons of comments are like voted up. Below is my code class Post(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=200) text = RichTextUploadingField() votes_up = models.ManyToManyField(settings.AUTH_USER_MODEL, blank=True, related_name='up_votes') votes_down = models.ManyToManyField(settings.AUTH_USER_MODEL, blank=True, related_name='down_votes') def __str__(self): return self.text def total_vote_up(self): return self.votes_up.count() def total_vote_down(self): return self.votes_down.count() class Comment(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments') text = RichTextUploadingField() Below is my detail view with comments objects. class PostDetail(generic.DetailView, FormMixin): context_object_name = 'post' model = Post form_class = CommentForm def get_context_data(self, **kwargs): is_voted_up = False is_voted_down = False comments = self.get_object().comments.all() for comment in comments: if comment.votes_up.filter(id=self.request.user.id).exists(): is_voted_up = True if comment.votes_down.filter(id=self.request.user.id).exists(): is_voted_down = True context = super(PostDetail, self).get_context_data(**kwargs) context['comments'] = self.get_object().comments.all() context['form'] = CommentForm(initial={'post': self.get_object(), 'author': self.get_user()}) context['is_voted_up'] = is_voted_up context['is_voted_down'] = is_voted_down return context -
Keyerror: django BaseModelFormSet clean key error
i have build transiction formset i have want to validate so no double item preset in formset i have use clean for it it but it give error when there is empty form in present in formset.it is modelformset_factory error message is "KeyError at /saleformformset_update/1024 'item " class SaleTransictionFormSet(BaseModelFormSet): def clean(self): super().clean() """Checks that no two articles have the same title.""" if any(self.errors): # Don't bother validating the formset unless each form is valid on its own return titles = [] for form in self.forms : title = form.cleaned_data['item'] if not title == '': if title in titles: raise forms.ValidationError(" %s in a set must have distinct titles." % title) titles.append(title) i want to clean to ignore form in formset if they are empty or if they are mark with delete -
Using Django Window Functions on a Filtered QuerySet
I ran into a surprising conundrum with Window Functions no Filtered QuerySets. Consider with models: mymodel and relatedmodel where there is a one to many relationship (i.e. relatedmodel has a ForeignKey into mymodel). I was using something like this: window_lag = Window(expression=Lag("pk"), order_by=order_by) window_lead = Window(expression=Lead("pk"), order_by=order_by) window_rownnum = Window(expression=RowNumber(), order_by=order_by) qs1 = mymodel.objects.filter(relatedmodel__field=XXX) qs2 = qs1.annotate(row=window_rownnum, prior=window_lag, next=window_lead) qs3 = qs2.filter(pk=myid) which returns a lovely result in for the object pk=myid I now now it's position in the filtered list and its prior and next and I use this to great effect in browsing filtered lists. Significantly len(qs1) = len(qs2) is the size of the list and len(qs3)=1 Alas I just discovered this break badly when the filter is less specific: window_lag = Window(expression=Lag("pk"), order_by=order_by) window_lead = Window(expression=Lead("pk"), order_by=order_by) window_rownnum = Window(expression=RowNumber(), order_by=order_by) qs1 = mymodel.objects.filter(relatedmodel__field__contains=X) qs2 = qs1.annotate(row=window_rownnum, prior=window_lag, next=window_lead) qs3 = qs2.filter(pk=myid) In this instance, qs2 suddenly has more rows in it that qs1!And len(qs2)>len(qs1). Which totally breaks the browser in a sense (as prior and next are not reliable any more). The extra rows are duplicate mymodel objects, wherever more than one relatedmodel object matches the criterion. I've traced this to the generated SQL. This is … -
Is there a way to define a Django form field as integer in such way, so it takes the number from the slider in the template?
I want to save a model attribute through from as a number from 1 to 10. models.py attr1 = models.IntegerField() index.html <div class="slidecontainer"> {{ form.attr1.label_tag }} {{ form.attr1 }} <br> <input type="range" min="1" max="10" value="5" class="slider" id="Scale1"> </div> Is it possible to somehow get the value from the slider, and put it to the IntegerField? Is there any better way to solve this issue? -
django cms breakes down after installing django-cms blog and python manage.py migrate
Immediately i install djangocms-blog, then add the djangocms_blog to INSTALLED_APPS i get errors on server restart RuntimeError: Model class cmsplugin_filer_image.models.FilerImage doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. When i remove the the cond from the setting.py its fine INSTALLED_APPS = ( 'djangocms_admin_style', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.admin', 'django.contrib.sites', 'django.contrib.sitemaps', 'django.contrib.staticfiles', 'django.contrib.messages', 'cms', 'menus', 'sekizai', 'treebeard', 'djangocms_text_ckeditor', 'filer', 'easy_thumbnails', 'djangocms_column', 'djangocms_file', 'djangocms_link', 'djangocms_picture', 'djangocms_style', 'djangocms_snippet', 'djangocms_googlemap', 'djangocms_video', 'mptt', 'aldryn_bootstrap3', 'aldryn_background_image', 'djangocms_icon', 'djangocms_blog', 'web_nia' ) I expect this to set up and enable me put some blogs on my django cms site -
Django doesn't log to specified file from celery.py
I'm trying to figure out what to do when I want to log something outside project. I have a file celery.py in project/project/ directory. I'm trying to use logger automatic_actions which setting is specified in settings.py. Unfortunately, it doesn't log anything in it. logger = logging.getLogger('automatic_actions') @periodic_task(run_every=timedelta(seconds=5)) def export_properties(): logger.info('EXPORTING STARTED...') I suppose it is because when celery run this task, there is no Django environment setup. But when I try to setup Django: from project import settings BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.append(BASE_DIR) os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project.settings') django.setup() app = Celery('project',broker='redis://localhost') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() logger = logging.getLogger('automatic_actions') And run for example shell_plus: AttributeError: 'Settings' object has no attribute 'COMPRESS_ROOT' Do you know how to make it work? -
Use two querysets in one for loop in Django?
I'm building an inventory management app for an organisation in Django. This organisation has multiple rooms each with storage sections on shelves. I'm trying to display the number of storage spaces free in each room plus the number of occupied storage spaces using one for loop. So far, I have managed to display this data but I have to use two separate for loops and two querysets, 'Vacant_location_data' and 'Occupied_location_data'. I would like to be able to use a single for loop for this if possible as it will allow me to plot this data in a graph. Is this possible? Below is a simplified version of my code: My models.py: class Location(models.Model): loc_room = models.CharField(max_length=20, blank=True, null=True) loc_section = models.IntegerField(blank=True, null=True) loc_shelf = models.CharField(max_length=4, blank=True, null=True) My views.py: def dashboard(request): Vacant_location_data = Location.objects.values('loc_room').filter(box__isnull=True).annotate(nempty=Count('id')).order_by('loc_room') Occupied_location_data = Location.objects.values('loc_room').filter(box__isnull=False).annotate(nempty=Count('id')).order_by('loc_room') My HTML: <div class="container"> {% for each_room in Vacant_location_data %} { <p>"Room name": "Room {{each_space.loc_room}}"</p> <p>"Free Space": {{ each_room.nempty }}</p> }, {% endfor %} </div> <div class="container"> {% for each_room in Occupied_location_data %} { <p>"Room name": "Room {{each_room.loc_room}}"</p> <p>"Occupied Space": {{ each_room.nempty }}</p> }, {% endfor %} </div> -
How to fix urlpatternes does not match
I am using Django and javascript to create an URL that is entered by a form input but after submitting it I am getting an error that page does not exist even I have the pattern urlpatterns=[ path('chat',views.index,name='index'), path('chat/<str:room_name>',views.room,name='room'), ] and the javascript code is document.querySelector('#room-name-submit').onclick = function(e) { var roomName = document.querySelector('#room-name-input').value; window.location.pathname = '/chat/' + roomName + '/'; }; for example, if we enter lobby my url will be chat/looby and it should match with the 'room' , but I am getting error Using the URLconf defined in mychat.urls, Django tried these URL patterns, in this order: chat [name='index'] chat/ [name='room'] admin/ The current path, chat/lobby/, didn't match any of these. -
Django ORM: construct query that would look for match on field in object at the last position of many to many field
I stumbled upon something I can't figure out by myself - while filtering (in Django ORM) query I would like to query for objects meeting condition, that some field of last object in the list of many to many objects is equal to some input. It may sound not so obvious, so below I provide an example: Animal model class Animal(models.Model): name = models.TextField(null=True, blank=False) awards = models.ManyToManyField(Award, related_name='awards') Award model class Award(models.Model): name = models.TextField(null=False, blank=False) place = models.TextField(null=True, blank=True) date = models.DateTimeField(null=True) Having these classes, I would like to construct query like this: Animal.objects.filter(awards__name__last='National Award') Because Animal.objects.filter(awards__name='National Award') normally returns (when using .values()) list looking like this: [{'name': u'National Award', 'place': u'capital', 'date': datetime.datetime(2018, 7, 13, 5, 2, 45, 23000), u'id': 1}, {'name': u'International Award', 'place': u'capital', 'date': datetime.datetime(2018, 10, 1, 1, 1, 55, 79000), u'id': 2}] and for such object, query would ommit it, because 'National Award' is not on the last position on the list, but if this object would have switched these entries, it would be returned by this query, since the last object name is equal to 'National Award'. I do not want to use date field for this query. -
CORS did not succed when deployed on heroku https, works locally
I have a fullstack Django and React app, which works perfectly on my local machine with no issues, but when I deploy it on Heroku I got this well-known error: Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at (...), but the problem does not occur when I use HTTP instead of HTTPS. Could it has something to do with https configuration? Middleware MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', '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', ] CORS config CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_CREDENTIALS = True -
Django constance variable check in settings.py
I am trying to enable custom logging toggle check inside settings.py as shown below(the code is at the bottom of the file): from constance import config if config.CUSTOM_LOGGING: LOGGING = { 'version': 1, 'disable_existing_loggers': True, 'formatters': { 'standard': { 'format': '%(asctime)s [%(levelname)s] : %(message)s' }, }, 'handlers': { 'default': { 'level': 'DEBUG', 'class': 'logging.handlers.RotatingFileHandler', 'filename': 'pd_temp/celery_logs/allume_feed_jobs.log', 'maxBytes': 1024 * 100, # 100 kB 'backupCount': 5, 'formatter': 'standard', }, }, 'loggers': { '': { 'handlers': ['default'], 'level': 'DEBUG', 'propagate': True }, } } But I am getting this error: django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. Any workaround for the above scenario would be very helpful. Thanks! Ref: Django constance (https://django-constance.readthedocs.io/en/latest/) -
Error: Please define stage 'create_pg_db' in your Zappa settings
Intro: I am deploying a django app to aws lambda severlessly using zappa. My RDS instance has a postgres database. I am watching rich jones djangocon video on how to deploy django app severlessly using zappa. So far I have managed to reach the part where I need to add a database to my project. I have already done pip install zappa-django-utils and added it to my INSTALLED_APPS. Now when I try to run zappa manage create_pg_db production I get the error Error: Please define stage 'create_pg_db' in your Zappa settings. I even tried zappa manage create_pg_db I am still getting the same error Below is how my zappa_settings.json file looks: { "production": { "aws_region": "us-east-1", "django_settings": "Cool.settings", "profile_name": "default", "project_name": "cool", "runtime": "python3.6", "s3_bucket": "cool-7dsfsdf5", "project_directory": "/tmp/code", "slim_handler": true, "vpc config": { "SubnetIds": [ "subnet-3132ss13b", "subnet-321321319", "subnet-2c2313223", "subnet-5ljlkjljd", "subnet-132121357", "subnet-f925f9c7" ], "SecurityGroupIds": [ "sg-a9asdasd" ] } }, "production_ap_northeast_1": { "aws_region": "ap-northeast-1", "extends": "production" }, "production_ap_northeast_2": { "aws_region": "ap-northeast-2", "extends": "production" }, ... All regions.. } How do I define stage 'create_pg_db' in your Zappa settings. Does anyone know the steps ahead of this -
How to send data with multiple dynamic form id with Djano, Ajax, and javascript?
Sorry before that i have bad english. So i want to send data from django form with ajax and javascript, but the problem is i have add button to add more field, every time i add field the field id increase i already tried with single form id, its success, but with multiple dynamic id it fail My html : {{ ipform.management_form }} {% for form in ipform %} <div class="form-group"> <div class="row form-row spacer"> <div class="col-2"> <label>{{form.ipaddr.label}}</label> </div> <div class="col-4"> <div class="input-group"> {{form.ipaddr}} <div class="input-group-append"> <button class="btn btn-success add-form-row">+</button> </div> <div class="col-2"> <p id="cekip"></p> </div> </div> </div> </div> </div> {% endfor %} Javascript: function updateElementIndex(el, prefix, ndx) { var id_regex = new RegExp('(' + prefix + '-\\d+)'); var replacement = prefix + '-' + ndx; if ($(el).attr("for")) $(el).attr("for", $(el).attr("for").replace(id_regex, replacement)); if (el.id) el.id = el.id.replace(id_regex, replacement); if (el.name) el.name = el.name.replace(id_regex, replacement); } function cloneMore(selector, prefix) { var newElement = $(selector).clone(true); var total = $('#id_' + prefix + '-TOTAL_FORMS').val(); newElement.find(':input').each(function() { var name = $(this).attr('name') if(name) { name = name.replace('-' + (total-1) + '-', '-' + total + '-'); var id = 'id_' + name; $(this).attr({'name': name, 'id': id}).val('').removeAttr('checked'); } }); total++; $('#id_' + prefix + '-TOTAL_FORMS').val(total); $(selector).after(newElement); var … -
dynamically generate category list into base template with django class base views
views.py from django.shortcuts import render, get_object_or_404 from django.utils.decorators import method_decorator from django.views.decorators.gzip import gzip_page from django.views.decorators.http import condition from django.views.generic.detail import SingleObjectMixin from django.utils import timezone from django.views.generic import \ ListView, DetailView from .models import ( Book, Category, Author, Language, Currency, Tag, ) from django.db.models import Q class BookList(ListView): model = Book context_object_name = 'book_list' template_name = 'books/book_lists.html' paginate_by = 12 extra_context = { 'category_list': Category.objects.all(), 'author_list': Author.objects.all(), 'language_list': Language.objects.all(), } def get_queryset(self): query = self.request.GET.get('q') if query: object_list = self.model.objects.filter( Q(name_of_the_book__icontains=query) | Q(author__first_name__icontains=query) | Q(category__name__icontains=query) ) else: object_list = self.model.objects.all() return object_list class SingleCategoryView(DetailView): model = Category template_name = 'books/single_category.html' paginate_by = 12 extra_context = { 'category_list': Category.objects.all(), 'author_list': Author.objects.all(), 'language_list': Language.objects.all(), } class SingleAuthorView(DetailView): model = Author template_name = 'books/single_author.html' extra_context = { 'category_list': Category.objects.all(), 'author_list': Author.objects.all(), 'language_list': Language.objects.all(), } class SingleLanguage(DetailView): model = Language template_name = 'books/single_language_list.html' extra_context = { 'category_list': Category.objects.all(), 'author_list': Author.objects.all(), 'language_list': Language.objects.all(), } class BookDetails(DetailView): model = Book template_name = 'books/book_details.html' # extra_context = { # 'category_list': Category.objects.all(), # 'author_list': Author.objects.all(), # 'language_list': Language.objects.all(), # } def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['now'] = timezone.now() return context Here BookList view is my home page. In my base template, I've added some kind of … -
Django template, loop through items if their id is equal to parent loop name
I'm trying to loop through different Zones and then show the items which are part of this zone Zone is a model, has a name and a ForeignKey. Planche is a model which has Zone as ForeignKey. I'm looping through zones to display each zone. In that loop I'm looping all Planches and would like to display only the ones that have Zone as a ForeignKey. class Zones(models.Model): name = models.CharField(max_length=30) genre = models.ForeignKey(ZoneTypes, on_delete=models.CASCADE) def __str__(self): return self.name class Planche(models.Model): pzone = models.ForeignKey(Zones, on_delete=models.CASCADE) ref = models.CharField(max_length=5, default="1") length = models.IntegerField() width = models.IntegerField() orientation = models.CharField(max_length=30) def __str__(self): return self.ref Template <div> <h1><a href="/">My list of planches</a></h1> </div> {% for z in zones %} <div> <h2><a href="/zone/{{ z.name }}">Zone name: {{ z.name }}</a></h2> {% for p in planches %} {% if p.pzone == z.name } <h1><a href="planche/{{ planche.ref }}">Ref: {{ p.ref }}</a></h1> <p>Length: {{ p.length }} - Width: {{ p.width }}</p> <p>Orientation: {{ p.orientation }} {% endif %} {% endfor %} </div> {% endfor %} {% if p.pzone = z.name %} returns False, They both return the same string if I just display them {{ p.pzone }} and {{ z.name }} but I guess they aren't the same … -
NoReverseMatch Django Chat message another user
I'm probably missing something here, but I have a connect page in which the logged in user can chat to another user by clicking on a Chat? link located on each users profile. The chat functionality is built using Django Channels and is accessed via the url pattern site/messages/username where username is the other_user that the current_user is chatting with. I currently have the chat? link as <a class='btn btn-light' href="{% url 'thread' username %}" id="chat">Chat?</a> However that throws the error NoReverseMatch Reverse for 'thread' not found. 'thread' is not a valid view function or pattern name. I have tried following the docs and adding username as an arg / taking it off but I keep hitting this same error. The chat app is included in settings.py and the urls are included in admin.py. The connect and chat are separate apps. Below is relevant code. Thank you for your time and help! chat/urls.py from django.urls import path, re_path from .views import ThreadView, InboxView app_name = 'chat' urlpatterns = [ path("", InboxView.as_view()), re_path(r"^(?P<username>[\w.@+-]+)", ThreadView.as_view(), name='thread'), ] chat/views.py class ThreadView(LoginRequiredMixin, FormMixin, DetailView): template_name = 'chat/thread.html' form_class = ComposeForm success_url = './' def get_queryset(self): return Thread.objects.by_user(self.request.user) def get_object(self): other_username = self.kwargs.get("username") obj, created … -
'NewPost 'Object has no attribute 'user'
In my forum app,I want to show post details with it's author name. In 'new-post' class in views.py I tried to save the author name by post.user = self.request.user But whenever my current login user submits his new post it gives the mentioned error. views.py: class NewPost(CreateView): form_class = PostForm template_name = 'post_form.html' @login_required def form_valid(self,form): post = form.save(commit=False) post.user= self.request.user post.save() return redirect('website:details', post=post) forms.py: class PostForm(forms.ModelForm): class Meta: model = Post fields=('title','description') Models.py: class Post(models.Model): user = models.ForeignKey(User, on_delete =models.CASCADE) title = models.CharField(max_length = 500, blank = False) description = models.TextField() def __str__(self): return self.title AttributeError at /website/add/ 'NewPost' object has no attribute 'user' Request Method: POST Request URL: http://127.0.0.1:8000/website/add/ Django Version: 1.9 Exception Type: AttributeError Exception Value: 'NewPost' object has no attribute 'user' Exception Location: C:\Python27\lib\site-packages\django-1.9-py2.7.egg\django\contrib\auth\decorators.py in _wrapped_view, line 22 Python Executable: C:\Python27\python.exe Python Version: 2.7.14 Python Path: ['C:\Users\as_couple\Desktop\STUDENTTRACKERSYSTEM', 'C:\WINDOWS\SYSTEM32\python27.zip', 'C:\Python27\DLLs', 'C:\Python27\lib', 'C:\Python27\lib\plat-win', 'C:\Python27\lib\lib-tk', 'C:\Python27', 'C:\Python27\lib\site-packages', 'C:\Python27\lib\site-packages\django_admin-1.1.1-py2.7.egg', 'C:\Python27\lib\site-packages\django_excel_response2-2.0.8-py2.7.egg', 'C:\Python27\lib\site-packages\django_six-1.0.4-py2.7.egg', 'C:\Python27\lib\site-packages\django-1.9-py2.7.egg'] -
Connecting django with oracle database
Im a beginner to django. Someone help to connect Oracle 11g db with django 2.0 in windows. What is the requirements and how to connect and what are the changes to be done.