Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
AttributeError: 'NoneType' object has no attribute '_meta' Django
I am a newbie I want to change selected data (food_status) and save it to selected column (food_status column). But it shows an error for field in self._meta.concrete_fields: AttributeError: 'NoneType' object has no attribute '_meta' in this part OrderItem.save(food_status, update_fields=['food_status']) models.py class OrderItem(models.Model): Table_No = models.IntegerField(blank=False) FoodId = models.TextField() Item = models.TextField() Qty = models.IntegerField(blank=False) Price = models.TextField() Note = models.TextField(max_length=100, null=True) OrderId = models.TextField(max_length=100, null=True) FoodStatus = ( ('1', 'Has been ordered'), ('2', 'cooked'), ('3', 'ready to be served'), ('4', 'done'), ) food_status = models.CharField(max_length=50, choices=FoodStatus, default="has been ordered") views.py def kitchen_view(request): chef_view = OrderItem.objects.all() if request.method == "POST": food_status = request.POST.get("food_status") OrderItem.food_status = food_status OrderItem.save(food_status, update_fields=['food_status']) return render(request, 'restaurants/kitchen_page.html', {'chef_view':chef_view}) kitchen_page.html <form action="#" method="post"> {% csrf_token %} {% for order in chef_view %} <table width="800"> <tr> <th width="800">Table Number</th> <th width="800">Item</th> <th width="800">Quantity</th> <th width="800">Price</th> <th width="800">Note</th> <th width="800">Order Id</th> <th width="800">Status</th> </tr> <tr> <td width="800">{{ order.Table_No }}</td> <td width="800">{{ order.Item }}</td> <td width="800">{{ order.Qty }}</td> <td width="800">{{ order.Price }}</td> <td width="800">{{ order.Note }}</td> <td width="800">{{ order.OrderId }}</td> <td width="800">{{ order.Status }} <button type="button" class="close" data-dismiss="modal" aria- label="Close"><span class="glyphicon glyphicon-pencil" aria- hidden="true">&times;</span></button> <select> <option name="food_status" id="1" value="None">Has been ordered</option> <option name="food_status" id="2" value="Cooked">Cooked</option> <option name="food_status" id="3" value="Ready to … -
Query set is not empty in django shell but empty in a function
There is the following function in my views.py: def edit_theorem(theorem): print(type(theorem)) print(theorem.id) old_list = theorem.included_elements.all() print(old_list) ... The outputs of three print function is: <class 'app.models.Theorem'> 65 <QuerySet []> However, when I run python manage.py shell, t=Theorem.objects.get(id=65), print(t.included_elements.all()), it prints a nonempty queryset. Why? My models.py looks like this: class Element(models.Model): included_elements = models.ManyToManyField('Element', through='IncludedElements') ... class IncludedElements(models.Model): ... def Theorem(Element): ... DB is PostgreSQL. -
Logging django in production
I am using Django + Gunicorn + Nginx running on Digital Ocean droplet. Using Sentry New SDK I get internal errors reported on sentry dashboard, Looking at sudo less /var/log/nginx/access.log gives some sort of logs, but how can I have the development-like (DEBUG, INFO, WARNING, ERROR) output log per day written on the DO ubuntu instance to examine them ? -
WebSocket opening handshake timed out on Nginx Server
After reading ton's of articles and trying many tutorials I come to Stack Overflow for assistance. I have a server running NGINX and UWSGI. This is the error I am getting in the browser Console: WebSocket connection to 'wss://www.yolkichat.com:8001/ws/notification/' failed: WebSocket opening handshake timed out Below is just bits of code as this works on local so should be something on the actual server freaking out. I am running the following in terminal for testing issues: daphne -b 0.0.0.0 -p 8001 yolkichat.asgi:application My UFW Status: Nginx Full ALLOW Anywhere 22 ALLOW Anywhere 8080 ALLOW Anywhere Apache Full ALLOW Anywhere 10080/tcp ALLOW Anywhere 80 ALLOW Anywhere 8001/tcp ALLOW Anywhere Nginx Full (v6) ALLOW Anywhere (v6) 22 (v6) ALLOW Anywhere (v6) 8080 (v6) ALLOW Anywhere (v6) 80 (v6) ALLOW Anywhere (v6) 8001/tcp (v6) ALLOW Anywhere (v6) settings.py INSTALLED_APPS = [ 'channels', 'celery', ] ASGI_APPLICATION = 'yolkichat.routing.application' WSGI_APPLICATION = 'yolkichat.wsgi.application' CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels_redis.core.RedisChannelLayer', 'CONFIG': { "hosts": [('127.0.0.1', 6379)], }, }, } asgi.py import os import django from channels.layers import get_channel_layer from channels.routing import get_default_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "yolkichat.settings") django.setup() channel_layer = get_channel_layer() application = get_default_application() routing.py from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, URLRouter import chat.routing application = ProtocolTypeRouter({ # … -
How do you deal with template content that has to be translated in Django?
I am trying to render the following table (see screenshot): I have the following template code: <table class='table'> {% for row in task_dashboard_rows %} <tr> <td>{{ forloop.counter }}</td> <td>{{ row.where_html }}</td> <td>{{ row.key_html }}</td> <td>{{ row.value_html }}</td> </tr> {% endfor %} </table> I created an abstraction class to contain the logic in my view code: class TaskDashboardRow(object): def __init__(self, where_html=None, key_html=None, value_html=None): self.where_html = where_html self.key_html = key_html self.value_html = value_html And somewhere in my view function, I have the following: dr = TaskDashboardRow() dr.where_html = _('Voluum') dr.set_key_html(is_linking=False, label=_('Create New Lander')) if self.object.vm_campaign_id: dr.value_html = format_html(_('<span class="text-success">Not Needed</span>')) else: dr.value_html = format_html( _( '<ul class="nolist">' '<li>Name: <b>Campaign:{name}</b></li>' '<li>URL: <a href="#">{url}</a></li>' '</ul>' ), url=absolute(reverse('mediabuying:campaign:money', args=(self.object.pk,))), name=self.object ) ret.append(dr) dr = TaskDashboardRow() dr.where_html = _('Pangu') dr.set_key_html(is_linking=False, label=_('Update TA Campaign ID')) if self.object.ta_campaign_id: dr.value_html = format_html(_('<span class="text-success">No Need To Update</span>')) else: dr.value_html = format_html( _('<a href="{}">Click here</a> to update ta_campaign_id'), reverse('mediabuying:campaign:update', args=(self.object.pk,)) ) ret.append(dr) I am not a fan of this because this code is very messy due the following reasons: I have _ (from ugettext_lazy) in my view code wrapped around format_html and it gets very messy (especially with python's indentation). I have "view code" in my "controller code" (bad for separation … -
Django ORM select_related with multiple foreign keys?
I have the following models: class Sld(models.Model): sld_name = models.CharField(max_length=63, unique=True) tld = models.ForeignKey('db.Tld', on_delete=models.PROTECT) class Tld(models.Model): tld_name = models.CharField(max_length=20) class Path(models.Model): path_name = models.CharField(max_length=255) sld = models.ForeignKey('db.Sld', on_delete=models.CASCADE) And I would like to execute the following query using Django's ORM: SELECT t1.path_name, t2.sld_name, t3.tld_name FROM path t1 LEFT JOIN sld t2 ON (t2.id = t1.sld_id) LEFT JOIN tld t3 ON (t2.tld_id = t3.id); Here are a few attempts: urls = Path.objects.select_related().values('sld_name', 'tld_name', 'path_name') urls = Path.objects.all().select_related().values() What am I missing here? The data should look like this: { 'sld_name':'google', 'tld_name':'com', 'path_name':'/' } ... -
Why isn't the TextField updated after I added unique=True?
I know how to solve the problem I'm facing. But the thing is I don't know why the code behaves like that. So I need somebody to explain why this happens. I need to edit the TextField with a user input and show the new TextField and it works as expected when both the CharField and the TextField changed but it doesn't work when only the TextField changed. By the way when only the CharField changed, the CharField is updated. Let me share the snippets. This is not what I actually have in my codebase. models.py class Foo(models.Model): foo_name = models.CharField(max_length=100) foo_message = models.TextField(max_length=200) class Bar(models.Model): foo = models.ForeignKey(Foo, on_delete=models.CASCADE) bar_name = models.CharField(max_length=100, unique=True) bar_message = models.TextField(max_length=200) forms.py class BarForm(ModelForm): class Meta: model = Bar fields = ["bar_name", "bar_message"] views.py def show_bar(request, foo_name, bar_name): foo = Foo.objects.get(foo_name__iexact=foo_name) bar = foo.bar_set.get(bar_name=bar_name) if request.method == "POST": form = BarForm(request.POST) if form.is_valid(): bar.bar_name = form.cleaned_data["bar_name"] bar.bar_message = form.cleaned_data["bar_message"] bar.foo = foo bar.save() return redirect("bar-show", foo_name, bar.bar_name) return render(request, "bar_show.html", context) def edit_bar(request, foo_name, bar_name): foo = Foo.objects.get(foo_name__iexact=foo_name) bar = foo.bar_set.get(bar_name=bar_name) form = BarForm(instance=bar) return render(request, "bar_edit.html", context) templates bar_show.html <h1>bar_name</h1> <p>{{ bar.bar_name }}</p> <h1>bar_message</h1> <p>{{ bar.bar_message}}</p> <a href="{% url 'bar-edit' foo.foo_name bar.bar_name %}">edit</a> … -
error while installing mysqlclient in django project in pycharm
Got this problem while installing mysqlclient in pycharm settings ERROR: Command "'C:\Users\miaw\PycharmProjects\PleaseWork\venv\Scripts\python.exe' -u -c 'import setuptools, tokenize;file='"'"'C:\Users\miaw\AppData\Local\Temp\pycharm-packaging\mysqlclient\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(file);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, file, '"'"'exec'"'"'))' install --record 'C:\Users\miaw\AppData\Local\Temp\pip-record-qeq94583\install-record.txt' --single-version-externally-managed --compile --install-headers 'C:\Users\miaw\PycharmProjects\PleaseWork\venv\include\site\python3.6\mysqlclient'" failed with error code 1 in C:\Users\miaw\AppData\Local\Temp\pycharm-packaging\mysqlclient\ -
How do I upload files through a CreateView using an inline formset?
I can't get files to upload through a CreateView using inline formset. Ideally, it would be multiple files similar to how it behaves in the admin page, but at this point, I'm trying to get at least one up. In the following example, one Workshop should be able to have multiple files. When uploading, everything saves except the file of course models.py ... class Workshop (models.Model): title = models.CharField(max_length=120) created_by = models.ForeignKey(User) slug = models.SlugField(blank=True, null=True, unique=True) def __str__(self): return self.title ... def upload_workshop_file_loc(instance, filename): slug = instance.workshop.slug if not slug: slug = unique_slug_generator(instance.workshop) location = "workshop/{}/".format(slug) return location + filename class WorkshopFile(models.Model): workshop = models.ForeignKey(Workshop, related_name='files', on_delete=models.CASCADE) name = models.CharField(max_length=50, null=True, blank=False, default="File") file = models.FileField( upload_to=upload_workshop_file_loc, null=True, validators=[FileExtensionValidator (allowed_extensions=['pdf', 'ppt'])] ) def __str__(self): return str(self.file.name) ... forms.py from django import forms from .models import Workshop, WorkshopFile from django.forms.models import inlineformset_factory class AddWorkshopForm(forms.ModelForm): class Meta: model = Workshop exclude = [] FileFormSet = inlineformset_factory(Workshop, WorkshopFile, fields=['workshop','name', 'file'], exclude=[], extra=1, can_delete=True ) Most likely the culprit views.py ... class AddWorkshopView(LoginRequiredMixin, CreateView): model = Workshop form_class = AddWorkshopForm template_name = "modules/add-workshop.html" success_url = "/modules/workshop-list/" def post(self, request, *args, **kwargs): form = AddWorkshopForm(request.POST, request.FILES) workshop = form.save(commit=False) workshop.save() workshop.created_by = request.user return … -
How to get result with additional filtered related objects as a field in Django?
I want to get all data in one query, so I need to add some new related object field by the filter of related object (Not the Parent Object filter). def get_queryset(self): return Mailbox.objects\ .filter(owner=self.request.user.id)\ .prefetch_related('letter_set')\ .annotate( new_letter_count=Count( 'letter', filter=Q(letter__read_at=None) ), total_count=Count('letter'), latest_letter_datetime=Max('letter__created_at'), ### #################### ### ### THE QUESTION IS HERE ### ### #################### ### latest_letter_CONTENT= #(What code here could be work?)# ### I wnat to get the latest letter content ) -
How to fix django admin "add" button
I'm new to web development, and i'm building a blog web app in Django. I'm having problems adding new posts through django-admin. Clicking the "add" button gives me an "Error during template rendering - 'str' object has no attribute 'utcoffset'" error message. models.py from django.db import models from django.utils import timezone import datetime # Create your models here. class Post(models.Model): title = models.CharField(max_length=50) content = models.TextField(blank=True, null=True) post_date = models.DateTimeField(default='date posted') def published_recently(self): now = timezone.now() return now - datetime.timedelta(days=1) <= self.post_date <= now published_recently.admin_order_field = 'post_date' published_recently.boolean = True published_recently.short_description = 'Recent post?' def __str__(self): return self.title class Customer(models.Model): username = models.CharField(max_length=50) firstname = models.CharField(max_length=50) lastname = models.CharField(max_length=50) email = models.CharField(max_length=50) country = models.CharField(max_length=50) reg_date = models.DateTimeField(default='date reg') def __str__(self): return self.username class Comment(models.Model): comment_cont = models.TextField(max_length=200) user_name = models.ForeignKey(Customer, default=0, on_delete=models.CASCADE) comment_post = models.ForeignKey(Post, on_delete=models.CASCADE) votes = models.BigIntegerField(default=0) comment_date = models.DateTimeField(default='date commented') def __str__(self): return self.comment_cont class Feedback(models.Model): feedback_title = models.CharField(max_length=50) feedback_detail = models.CharField(max_length=200) user_name = models.ForeignKey(Customer, default=1, verbose_name='user_name', on_delete=models.SET_DEFAULT) admin.py from django.contrib import admin from .models import Post, Customer, Feedback, Comment # Register your models here. class CommentInLine(admin.TabularInline): model = Comment extra = 1 fields = ['comment_cont', 'votes', 'comment_date'] class CustomerAdmin(admin.ModelAdmin): fieldsets = [ (None, {'fields': ['firstname', … -
how to use multiple websockets on the same page?
I have recently tried to create a comment and delete it via the websockets and have succeeded in doing this but when I use the two together only one of them works like deleting the comment only . -
Django Model.create won't save to database
I'm trying to create an instance of a model (Transaction) from a view's post method but it's not saving to the database, but to my surprise is that, after "creating the object" and it not saving, i can pass it to my context dict and use its values, some which are autogenerated but still wont save :(. I've tried bumping up the line tjat creates that instance to the first line in the method but still wont work. (Django Admin works though) class MyView(generic.DetailView): template_name = "temps/page.html" model = Application context_object_name = "object_name" slug_field = 'uuid_id' slug_url_kwarg = 'obj_id' def dispatch(self, request, *args, **kwargs): # Check if object is accepted if not self.get_object().accepted or self.get_object().acknowledged: return HttpResponseForbidden() # Else, continue return super().dispatch(request, *args, **kwargs) def post(self, request, **kwargs): Transaction.objects.create(url="http://goo.gl/") # <- Added this to test but to no avail. It just wont save. PS: I didnt override any of the models's methods(s) -
Gunicorn not serving STATIC_ROOT after changing DEBUG = False
Using a Gunicorn proxy that Apache is routing traffic to in production that I am just testing at this point. Basically, Apache is taking 443 traffic and sending it to the port the proxy is running on. I'm finding that when I switch DEBUG = False that the app quits working with: < unexpected token. Reading about it, it has to do with the use of STATIC_ROOT being incorrect. I have my STATIC_ROOT = os.path.join(BASE_DIR, 'static'), and I'm running python manage.py collectstatic which is collecting all the assets to /static in the project root. Then I run gunicorn wsgi -D in the same directory as wsgi.py. https://docs.djangoproject.com/en/2.1/howto/static-files/deployment/ I guess I was under the assumption, wrongly, that since wsgi.py is referring to the settings in settings.py, it is delineating the static directory. What do I have to do to resolve this? -
How to update template form page text fields from mysql database by selecting different option from dropdown without submitting the request
I have a scenario where I created a form page using Django and then select the different product from the product dropdown option. Then I can pass that product name to django views.py. There I use that product value and search the matching description of that product from the table of mysql database. Now I want to throw this description to the same form page in different text field. Requirement is if I select the different product e.g. "TV" then description of the TV will be pulled from the corresponding table of mysql db and that description will be pushed to the form page. form.html ---------- <label>Product * </label> <select class="dropdown" id="dropdown" name="product"> <option value="" selected="selected"></option> <option value="TV">TV</option> <option value="Laptop">Laptop</option> <option value="Mobile">Mobile</option> </select><br> <script> $(document).ready(function(){ $('#dropdown').on('change',function(e){ var e = document.getElementById("dropdown"); var productName = e.options[e.selectedIndex].value; console.log("Dropdown Product Name: "+productName); $.ajax({ url:"", method:'GET', // send selected data to the formReq method which is in views.py data : {'product' : $(this).val()}, // 'product' will be used in request.GET.get('product') which is in views.py, $(this).val() is selected item, success:function(data){ //console.log(data); } }); }); }); </script> ============================================================================== views.py ----------- def formReq(request): #name = request.session['requestor'] if request.method == 'GET': prod_name = request.GET.get( 'product') # we are getting … -
Is there a way to execute django tags sent from external javascript file after page has loaded
I have a page where I use autocomplete to get hotels from database then try updating the hotel found into the django app but I face a problem since I am tring to execute the raw django tags from javascript after the page has loaded which is triggered by the jquery select the code I am working with now is here function updateContent(id, place){ var html_cont = '<div class="hotel{{place.id}} panel lastminute4"'+ ' style="margin:10px; padding:10px; text-align:left; padding-bottom:0px;">'+ ' {% with '+ id +'|get_hotel as sel_hotel %}'+ ' <h5 style="font-weight:900; text-transform:uppercase;">{{sel_hotel.hotel_name}}</h5>'+ ' {% with 4|get_rooms as hotel_rooms%}'+ ' {% for room in hotel_rooms %}'+ ' <h6>{{room.title}} *ksh. <span style="color:green;">{{room.amount}}</span></h6>'+ ' <button class="btn btn-default btn_minus" data-target="htl_{{place.id}}_{{room.id}}"'+ 'style="display:inline;" formtarget="cost_{{place.id}}_{{room.id}}">&minus; room</button>'+ ' <input type="number" class="form-control" min="0" value="0" formtarget="{{room.amount}}"'+ ' id="htl_{{place.id}}_{{room.id}}" readonly style="width:60px; background:white; display:inline;">'+ '<button class="btn btn-default btn_add" data-target="htl_{{place.id}}_{{room.id}}"'+ ' style="display:inline;" formtarget="cost_{{place.id}}_{{room.id}}">&plus; room</button>'+ '<b id="cost_{{place.id}}_{{room.id}}" style="font-size:15px;"> = Ksh.0</b>'+ '{% endfor %}'+ '{% endwith %}'+ '{% endwith %}'+ '</div>'; div_id = "#append_hotel"+ place; $(div_id).append(html_cont); } I expect to get executed tags rendered to the template and not the raw django tags with curly brackets and the % sign -
Django+Docker - how to serve static?
To start with - my app is simple internal app for our team only, so it means ~10 users max, nothing from "high load" stuff, nothing facing external production Internet. As I read from other posts and questions, the recommended way is to have users-facing nginx (on the host), some wsgi server (such as Gunicorn or uwsgi) in main Docker container and static server (such as nginx) for static serving. But I feel that it becomes too much for my simple app, I don't really see a need in having two Docker containers. I would like to just use typical manage.py runserver and it would be so much easier and simpler. In almost all the posts I read it's mentioned that this is "insecure and inefficient" - but would you really care about this if your service is pure internal and for 5-10-20 users? Or is there any alternative to it which does not require you to set up separated static-serving server? I have read about Whitenoise, but if I understood correctly, it still requires you to do manage.py collectstatic first, which is very inefficient for local development. Is using manage.py for also serving static is so inefficient? Would it … -
How can I reference a form when overriding a GET request in a class based view?
I overrode the GET request function handler in this class based view. In my else statement, I need to pass, as context data, the form that the class naturally creates (if I had not overridden the GET function). How can I do that? I did not create a form at forms.py to create a form for the Post model. I let the create class based view handle the form creation for me. So, how can I get this form and pass as context data. The only way I can think of doing this is creating a function based view and avoid using this class based view in this circumstance. class PostCreateView(LoginRequiredMixin, CreateView): model = Post fields = ["title", "content", "payment_option", "price"] def get(self, request): card_set = BillingProfile.objects.get(user=request.user).card_set.all() if not card_set.exists(): # The user does NOT have an inserted payment method. return redirect("/billing/payment-method?next=/post/new/") else: # The user DOES have an inserted payment method. form = "???" return render(request, "posting/post_form.html", {"form":form}) -
Update a foreign key by custom string based id
I have two django model class Course(models.Model): courseId = models.CharField(max_length = 10, primary_key = True) class Student(models.Model): name = models.CharField(max_length = 200) studentId = models.CharField(max_length = 10, primary_key = True) course = models.ForeignKey(Course , blank = True) I know that django has a default primary key field but I want to use primary key courseId for Course table Now I want to update the course field of Student table by django reset framework by passing json data data = {'courseId': '8uheydg4er', 'studentId': 'uyrt54ewsd'} I want to check validation first that courseId and studentId is exist then update. How can I do update by django serializer Thanks! -
How to do URL rewrite for Django in folder structure
I have my Django app and I have following use cases: Local development. Since my app is mostly simple, I prefer usual manage.py runserver approach. So I expect my app to work for this case. Production environment. We ahve one web server and host tools under different URLs, for example https://myserver.com/tool1, https://myserver.com/tool2 etc. So I'd like to put my app in this structure (Theoretical) Apart of use case 2, I may want to host the app under its own domain, like https://tool.myserver.com But when I tried to do this, I got an issue with static files (sigh!), because if I have STATIC_URL as relative path STATIC_URL='static/' then it doesn't work for "nested" pages (i.e. if I'm on myserver.com/tool1/page then static URL will map to myserver.com/tool1/page/static which is not correct). From the other hand, if I use absolute path STATIC_URL='/static/' then it doesn't work for case 2 at all, because Django app knows nothing about /tool1 part of URL where it's located. I can use two different variants for STATIC_URL depending on the environment and hardcode STATIC_URL='/tool1/static/', but then the same code will not work for case 3... How should I handle this situation? -
How to fix attribute-error on a inlineformset with RelatedFieldWidgetWrapper?
In the code of the E-Learning Platform https://github.com/PacktPublishing/Django-2-by-Example/tree/master/Chapter13/educa i’m trying to add a new record (subject) with a RelatedFieldWidgetWrapper and a inlineformset. With the added code i get error “no attribute _meta_get_field'. How to make this work? I have changed admin.py, forms.py and views.py of the courses. Here is my code and error. #admin.py @admin.site.register(Subject, SubjectAdmin) class SubjectAdmin(admin.ModelAdmin): model = Subject formset_factory = SubjectFormset def __init__(self, model, admin_site): super(SubjectAdmin, self).__init__(model, admin_site) self.form.admin_site = admin_site admin.site.register(Subject, SubjectAdmin) #models.py class Subject(models.Model): title = models.CharField(max_length=200) slug = models.SlugField(max_length=200, unique=True) class Meta: ordering = ['title'] def __str__(self): return self.title class Course(models.Model): owner = models.ForeignKey(User, related_name='courses_created', on_delete=models.CASCADE) subject = models.ForeignKey(Subject, related_name='courses', on_delete=models.CASCADE) title = models.CharField(max_length=200) slug = models.SlugField(max_length=200, unique=True) overview = models.TextField() created = models.DateTimeField(auto_now_add=True) students = models.ManyToManyField(User, related_name='courses_joined', blank=True) class Meta: ordering = ['-created'] def __str__(self): return self.title #forms.py SubjectFormset = inlineformset_factory( Subject, Course, fields = ['title', 'overview'], list_display = ['title', 'slug'], prepopulated_fields = {'slug': ('title',)}, title = ModelMultipleChoiceField(queryset=Subject.objects.none()), widgets = RelatedFieldWidgetWrapper( FilteredSelectMultiple(('title'),False,), Subject._meta_get_field('title').field.remote_field.model, admin_site)) #views.py class OwnerCourseMixin(OwnerMixin, LoginRequiredMixin): model = Course formset_factory = SubjectFormset #fields = ['subject', 'title', 'slug', 'overview'] success_url = reverse_lazy('manage_course_list') #error Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x75a90468> Traceback (most recent call last): File "/usr/local/lib/python3.5/dist-packages/django/utils/autoreload.py", line 225, … -
Django, @property with two functions inside of models.py
I did not know how to name the topic correctly, so I apologize if it contains errors. My model consists of something like: class Employee(models.Model): #time work monday_st = models.CharField(max_length=2, choices=CHOICES_DAY_WORK, default='8') monday_end = models.CharField(max_length=2, choices=CHOICES_DAY_WORK, default='20') tuesday_st = models.CharField(max_length=2, choices=CHOICES_DAY_WORK, default='8') tuesday_end = models.CharField(max_length=2, choices=CHOICES_DAY_WORK, default='20') wednesday_st = models.CharField(max_length=2, choices=CHOICES_DAY_WORK, default='8') wednesday_end = models.CharField(max_length=2, choices=CHOICES_DAY_WORK, default='20') thursday_st = models.CharField(max_length=2, choices=CHOICES_DAY_WORK, default='8') thursday_end = models.CharField(max_length=2, choices=CHOICES_DAY_WORK, default='20') friday_st = models.CharField(max_length=2, choices=CHOICES_DAY_WORK, default='8') friday_end = models.CharField(max_length=2, choices=CHOICES_DAY_WORK, default='20') saturday_st = models.CharField(max_length=2, choices=CHOICES_DAY_WORK, default='0') saturday_end = models.CharField(max_length=2, choices=CHOICES_DAY_WORK, default='0') sunday_st = models.CharField(max_length=2, choices=CHOICES_DAY_WORK, default='0') sunday_end = models.CharField(max_length=2, choices=CHOICES_DAY_WORK, default='0') I would like to filter employees who are currently working. So it's a reflection of their work, in a model that looks like this. @property def is_expired(self): actual_hour = int(datetime.datetime.now().strftime('%H')) if actual_hour in list(range(int(self.monday_st), int(self.monday_end))): return True return False Returns 'True' in my views.py if the employee is currently working. if instance.is_expired == True: 'the employee is working' else: 'no working' But it needs information if the employee only works on a given day, so I created a file with auxiliary functions that looks like this. def day_st(): actual_day_number = datetime.datetime.today().weekday() + 1 if actual_day_number == 1: return monday_st if actual_day_number == 2: … -
How to transform manually created form to a django forms?
I'm currently working on a survey app. The app works well, however I did it without using django forms. Now I want to be able to use Django forms for security reasons. however I am stuck because the app has certain peculiarities that make the transition difficult. Although I have read the documentation and many posts in stackoverflow I don't find a way to do it. First I'm going to explain the info that I think are relevant: models.py: class Answer(models.Model): user = models.ForeignKey(User, on_delete=models.PROTECT, null=False) item = models.ForeignKey(Item, related_name = "question", on_delete=models.PROTECT, null = True) answer = models.TextField() class Meta: unique_together = ('item','user') Each user has assigned questions (items). When the user log in, the view shows the questions assigned to him following this logic: class ViewSurvey(TemplateView): template_name="app/survey.html" def get(self,request, *arg, **kwargs): if not request.user.is_authenticated: return HttpResponseRedirect('/accounts/login/') else: exist = Answer.objects.filter(user=request.user).exists() # if the user has already answered the survey, they are redirected to another url if exist == True: return render(request, "survey/not_pending.html") items= Item.objects.filter(school__users__user = request.user ) #get the questions it has assigned to the user return render(request,self.template_name,{'items':items, 'exist':exist}) and the questions are saved by activating this view: def finish_test(request): if not request.user.is_authenticated: return HttpResponseRedirect('/accounts/login/') else: try: answers … -
Django dirty_fields and post_save
I have in my signals a method that captures the post_save signal and checks if the passed in instance has a certain dirty field. I was wondering if my implementation could run into flaws since dirty_fields compares memory and db to find those fields and I'm doing it in post_save which should fire at the end of the save method, right? Basically it is: @receiver(post_save, sender=My_Model) def process_post_save(sender, instance, created, **kwargs): reason_to_process = [ 'sample1', 'sample2', 'sample3', 'expired' ] for x in instance.get_dirty_fields(check_relationship=True): if x in reason_to_process: blah -
Reverse for 'tag_owner_lost' not found. 'tag_owner_lost' is not a valid view function or pattern name
On local machine with "runserver" the app is running without any problem. Problems occur on the staging server, Gunicorn + Nginx, where I got 'Reverse for 'tag_owner_lost' not found. 'tag_owner_lost' is not a valid view function or pattern name.' Any ideas where to look into? the view class TagOwnerLostView(LoginRequiredMixin, CreateView): template_name = 'tag_owner/tag_owner_lost.html' title = 'Inregistrare TAG pierdut' def get(self, request ): if request.user.is_owner: form = TagOwnerLostForm(request.user) if len(form["tag"]) == 1: messages.warning( request, _('Nu aveti TAG-uri asociate acestui cont') ) args = { 'form': form, 'title': self.title } return render(request, self.template_name, args ) else: return redirect('general:home') def post(self, request ): if request.user.is_authenticated: form = TagOwnerLostForm(request.POST, request.user) if form.is_valid(): * * else: return redirect('accounts:login') def get_absolute_url(self): return reverse('owner:tag_owner_lost') urls.py app_name = 'owner' urlpatterns = [ # path('', TagListView.as_view(), name='tag_list'), path('inregistrare-tag/', TagOwnerRegisteringView.as_view(), name='tag_owner_registered'), path('pierdut/', TagOwnerLostView.as_view(), name='tag_owner_lost'), ] Menu link: <a class="nav-link" href="{% url 'owner:tag_owner_lost' %}">am Pierdut<span class="sr-only"></span></a> Thanks!