Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Join 2 tables with no ForeignKey link
I have a SQL query that joins 2 tables and I'm trying to replace it with Django ORM. The query: SELECT * FROM students r JOIN class_teachers c ON c.class_room_id = r.class_room_id Pretty simple. Purpose of it is to get all values from students and the Teachers ID from class_teachers table. I created 3 models that are using pre built tables in the db: class ClassRoom(models.Model): class_room = models.AutoField(primary_key=True) name = models.CharField(max_length=32) class ClassTeachers(models.Model): class_room = models.ForeignKey(ClassRoom) teacher = models.ForeignKey(Teachers) class Students(models.Model): class_room = models.ForeignKey(ClassRoom) name = models.CharField(max_length=32) But with this setup I can't figure out how to create a two table join like before. The closest I got was with this which is horrible... but works: dd = ClassTeachers.objects.filter( company_id=company_id, ).annotate( name=F('classroom__classteachers__name'), all_student_fields... ).values( 'teacher_id', 'name', all_student_fields... ) and it creates a 3 table join: SELECT st.*, ct.teacher_id FROM class_teachers ct INNER JOIN class_room cr ON (ct.class_room_id = cr.class_room_id) LEFT OUTER JOIN students st ON (cr.class_room_id = st.class_room_id) WHERE ct.class_room_id = '123'; Is there a way to create a 2 table join getting the teacher id and all student table fields without the need to join the ClassRoom table? -
Dynamic Datasets filters in Chart.js
I have a chart.js line chart displaying data for a year. The data is coming from Django view (apiview). I want the user to be able to select a range eg. 1 week, 1 month and so forth. So far I have the view as : class AcctReceivableData(APIView): def get(self, request, format = None): dt = [dates.dt for dates in FirstTest.objects.filter(variable = "Accounts receivable (days)", kpi_category = "Finance")] value = [values.value for values in FirstTest.objects.filter(variable = "Accounts receivable (days)", kpi_category = "Finance")] data = { "labels": dt, "default": value, } return Response(data) This is the html file: var endpoint = '/client/primarycare/acctreceivable/chart/data/' var defaultData = [] var target = [] var labels = []; $.ajax({ method: "GET", url: endpoint, success: function(data){ labels = data.labels defaultData = data.default target = data.target setChart() }, error: function(error_data){ console.log("error") console.log(error_data) } }) function setChart(){ var ctx = document.getElementById("myChart").getContext('2d'); var myChart = new Chart(ctx, { type: 'line', data: { labels: ["January", "February", "March","April","May","June","July", "August","September","October","November","December"], datasets: [{ label: '# Actual', data: defaultData, backgroundColor: [ 'rgba(255, 159, 64, 0.2)' ], borderColor: [ 'rgba(255, 159, 64, 1)' ], borderWidth: 5, fill: true }, { label: '# Target', data: target, backgroundColor: [ 'rgba(255, 206, 86, 0.2)' ], borderColor: [ 'rgba(255, … -
Django admin form redirect to view
I have an admin form called UserCreationForm. There is no view that holds the form. The relative url of the form is admin/accounts/user/add/. I would like to permanently redirect any requests for this url to a view in another app (manage/add-user/). How can I do this? -
Is it possible to update a django context dictionary without reloading the page?
I'm trying to use AJAX to update a Django context dictionary so that it can display different assignments on a web page when a certain button is clicked. My view creates a different context dictionary based on either GET or POST methods used to request the page. The former is the default and the later occurs when the user clicks the button. Everything works, the AJAX sends the correct data and the view is able to find the correct corresponding assignments. My issue, however, is that the page content (the django template code) never changes updates with the response. What am I doing wrong? @login_required def assignments(request): terms = Course.objects.filter(students = request.user).values('term__season', 'term__year').distinct() courses = Course.objects.filter(students = request.user) assignments = Assignment.objects.filter(course__in=courses) if request.method == 'POST': # retrive ajax data data = request.POST course_subject = data['course_subject'] course_number = data['course_number'] course_section = data['course_section'] term_season = data['term_season'] term_year = data['term_year'] # get the associated course for the click course = Course.objects.filter(subject = course_subject, number = course_number, section = course_section, term__year = term_year, term__season = term_season) # get the assignments associated with that course assignments = Assignment.objects.filter(course = course) context_dict = { 'assignments': assignments, 'courses': courses, 'terms': terms, } return render(request, 'mainapp/assignments.html', context_dict) -
How to call aditional URL parameters from template in DJANGO
I'm passing a variable "referer" to my template that's a string of aditional url parameters using this code: {% if type_disp == 'charts' %}<li class="active">{% endif %}<a href="{% url 'matching:analytics' action=action type_disp='charts' %}{{referer}}" class="text-primary"><i class="fa fa-fw fa-bolt"></i>Charts</a></li> {% if type_disp == 'tables' %}<li class="active">{% endif %}<a href="{% url 'matching:analytics' action=action type_disp='tables' %}{{referer}}" class="text-primary"><i class="fa fa-fw fa-calendar"></i>Table</a></li> I've validated that "referer" is correct before passing, but it's not being referenced when I click on the buttons. How do I make it so the url contains the referer string as well? Thank you -
Dynamic variable value on HTML with Django
I'm looking to display a constantly-changing python variable (that's read from a websocket server) onto a HTML file, currently i'm using a Django tag as it follows: templatetags/mytag.py from django import template register = template.Library() current_value = 0 @register.filter def c_value(placeholder): return current_value #more code that modifies current_value reading from a websocket server index.html {% load mytag %} <script> function mytimer() { setInterval(function(){ $('#stuff').html( {{ placeholder|c_value }} ); } , 1000); } mytimer(); </script> #some code from the website <span id="stuff">Holder</span> However naturally '{{ placeholder|c_value }}' only outputs the first ever value of 'current_value', which is 0 in this case, and so the source code of index.html ends up being: source code after '{{ placeholder|c_value }}' <script> function mytimer() { setInterval(function(){ $('#stuff').html( 0 ); } , 1000); } mytimer(); </script> Which is not desired since we would like to print the changing-value of 'current_value' each second. What is the normal approach for these kind of dynamic texts? Many thanks! -
Python return in for loop not returning
@staticmethod def observation_for(region_name: str, date: datetime): snapshots = RegionSnapshot.objects.filter(ref_name=region_name).order_by('date').reverse() for r_snapshot in snapshots: if r_snapshot.date < date: triggered = True print('should return') if triggered: print('after triggered, still here for some reason') return r_snapshot raise RegionSnapshot.DoesNotExist('request epoch for {} does not exist in criteria'.format(str(date))) I'm using the above code, which should return when it get to the return r_snapshot line (at least, I believe). However, it doesn't seem to be returning. It throws the exception and prints the following which is consistent with it not returning. Is there anything that I'm doing incorrectly? should return after triggered, still here for some reason should return after triggered, still here for some reason -
Django 2.0 'post' is not a registered namespace
Im doing a udemy course but is it on django 1.11, and im trying to doit with 2.0. The exercise is do a social network clone with groups, users and posts, the exersize have 3 main apps, accounts, groups and posts. And this is the file path: - Django exercize - Django exercize - groups app - template - groups app - html files - urls.py - views.py - posts app - template - posts app - html files - urls.py - views.py - accounts app - template - accounts app - html files - urls.py - views.py At some point when i try to load 'Groups list' or 'Create new group' the server show this error: NoReverseMatch at /groups/ 'post' is not a registered namespace This is the views.py of create and list on group folder class CreateGroup(LoginRequiredMixin,generic.CreateView): fields = ('name','description') model = Group template_name = 'groups/groups_form.html' class ListGroups(generic.ListView): model = Group template_name = 'groups/groups_list.html' This is the urls.py on groups folder from django.urls import path from . import views app_name = 'groups' urlpatterns = [ path('',views.ListGroups.as_view(),name='all'), path('new/',views.CreateGroup.as_view(),name='create'), path('post/in/<slug:slug>',views.SingleGroup.as_view(),name='single'), path('join/<str:slug>/',views.JoinGroup.as_view(),name='join'), path('leave/<str:slug>/',views.LeaveGroup.as_view(),name='leave'), ] This is the urls.py on django main folder from django.contrib import admin from django.urls import path, include … -
model in django,how to change two value when I edit one in admin?
in models.py: class Projects(models.Model): # 项目名称 pro_name = models.CharField('项目名称',max_length=50) # 项目内容 # content = models.CharField('项目内容',max_length=200) content = models.TextField('项目内容', max_length=200) # 外键 person = models.ForeignKey(Person, on_delete=models.CASCADE) # 金额 sum_money = models.IntegerField('项目金额',default=0) # 付款 payed_money = models.IntegerField('已付金额',default=0) # 欠钱 owe_money = models.IntegerField('未付金额',default=0) # 是否欠钱 is_debt = models.BooleanField('是否欠账',default=True) # 发布日期 pub_date = models.DateTimeField('保存日期',default=timezone.now,) def was_published_recently(self): return self.pub_date >= timezone.now() - datetime.timedelta(days=1) def __str__(self): return self.pro_name class Meta: verbose_name = '项目' verbose_name_plural = '项目' admin screen capture: when I changed the 'payed_money(已付金额:)' the 'owe_money(未付金额:)' = sum_money - payed_money, and if sum_money == payed_money the is_debt = False what should I do? rewrite save() mehtod? -
If statement skipped in django view for authenticated user
Good evening, I have a view that works only if im logged as superuser, but not as "departmentsupervisor" def detail_employee(request, pk, employee_pk): department = get_object_or_404(Department, pk=pk) print(department.supervisor, request.user.username) if request.user.username == department.supervisor or request.user.is_superuser: employee = get_object_or_404(Employee, department__pk=pk, pk=employee_pk) review = get_object_or_404(Result, pk=pk) print(employee, review.id) return render(request, 'review_employee.html', {'employee': employee}) return redirect('dept_employees', pk=department.pk) Im validating with the print that user logged is == department.supervisor but the if statement is skipped, if im logged with superuser it works properly. Im trying to look what I did wrong here. Thanks -
Pycharm autocomplete doesn't work in conda env
I have python2/python3 env on my local machine. Python2 is installed in /usr/bin/python2.7, and python3 is installed with anaconda. I set up python3/Django2.0 project, set up isolated env for Django with anaconda. conda create --name Activated new env. source activate And installed dependencies with pip3 pip3 install -r requirements.txt Python, Django version: python --version: Python 3.6.4 :: Anaconda, Inc. django-admin.py version: 2.0.2 And, set python interpreter properly, as shown in the image. But, pycharm autocomplete is not working for me. Pycharm autocomplete doesn't work with pip installed packages in anaconda environment? Is this something you faced before? -
Django model QuerySet not returning when filtered
I'm not really sure what's happening here. I can see that I have a couple of emails in my database, but I can't seem to filter them. for example, when I run qs1 = EmailActivation.objects.all() >>> print(qs1) <EmailActivationQuerySet [<EmailActivation: a@yahoo.com>, <EmailActivation: b@gmail.com>]> however, when I run the following I get nothing qs2 = EmailActivation.objects.all().filter(email='a@yahoo.com') >>> print(qs2) <EmailActivationQuerySet []> my model looks like this: class EmailActivation(models.Model): user = models.ForeignKey(User) email = models.EmailField() I'd expect my qs2 to return 'a@yahoo.com' since it is in the database as seen by qs1. Does someone see what I'm doing wrong? Thanks, -
Django/python model form type error
I am getting a "quote_from_bytes() expected bytes" error when I am following the Django documentation for using Model form. It appears to write to the sqlite DB but every time I fill out the form it gives this error. forms.py from django.forms import ModelForm from .models import * class inputforms(ModelForm): class Meta: model = Inputform fields = ['auditid', 'audittask', 'responsibleperson', 'auditstatus', 'auditnotes', 'auditdate'] views.py def inputview(request): form = inputforms(request.POST) if form.is_valid(): form.save() return HttpResponseRedirect(reverse, 'auditpage') args = {'form': form} # row = [str(s).encode() for s in {'form': form}] return render(request, 'auditentry.html', args) models.py class Inputform(models.Model): auditid = models.IntegerField(blank=True, null=True) audittask = models.TextField(blank=True, null=True) responsibleperson = models.TextField(blank=True, null=True) auditstatus = models.TextField(blank=True, null=True) auditnotes = models.TextField(blank=True, null=True) auditdate = models.TextField(blank=True, null=True) class Meta: managed = False db_table = 'inputform' -
Django - Query To Check if Item In Many to Many Relationship Field
I have a User and a Deal model as shown below. The User model has a 'favorites' field which is a many to many relationship with the Deal model. I'm trying to allow a user to save a Deal to their Favorites. I have tested both the favorite and remove_favorite views and both are doing exactly what they are supposed to do. Here's My Issue -- The conditional statement on my deal_detail.html page which checks to see if the current deal on the page is a favorite of the logged in user doesn't seem to be working. {% if deal_detail in user.favorites %} I'm just having a hard time wrapping my head around how to check this. class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(unique=True, error_messages={'unique':"This email has already been registered."}) username = models.CharField(max_length=40, default='') first_name = models.CharField(max_length=40, default='', blank=True) last_name = models.CharField(max_length=40, default='', blank=True) date_joined = models.DateTimeField(default=timezone.now) favorites = models.ManyToManyField(Deal, related_name='favorited_by', null=True, blank=True) class Deal(models.Model): title = models.CharField(max_length=200) slug = models.SlugField(max_length=140, unique=True) description = models.TextField(default='') My corresponding views look like this: def deal_by_detail(request, slug): deal_detail = Deal.objects.get(slug=slug) user = request.user return render(request, 'deals/deal_detail.html', {'deal_detail': deal_detail, 'user': user}) @login_required(login_url='/accounts/sign_in/') def favorite(request, pk): if request.method == 'POST': favorite = Deal.objects.get(pk=pk) user = request.user … -
How to handle pagination in django templates and views?
I used bootstrap pagination in my templates. My productlist.html looks like this: <div> {% for i in products %} {% if i.is_published %} <div class="thumbnail"> <a href="{{ i.get_absolute_url }}"><img src="{{ i.thumb_url }}" alt="sample"/></a> <a href="{{ i.get_absolute_url }}"><p class="Content">{{ i.description }}</p></a> </div> <nav class="text-center"> <!-- Add class .pagination-lg for larger blocks or .pagination-sm for smaller blocks--> {% if contacts.has_other_pages %} <ul class="pagination"> {% if contacts.has_previous %} <li> <a href="?page={{ contacts.previous_page_number }}" aria-label="Previous"> <span aria-hidden="true">&laquo;</span> </a> </li> {% else %} <li class="page-item disabled"> <a class="page-link" aria-label="Previous"> <span aria-hidden="true">&laquo;</span> </a> </li> {% endif %} {% for i in page_range %} {% if contacts.number == i %} <li class="active"><a class="page_link" href="#">{{ i }} <span class="sr-only">(current)</span></a></li> {% else %} <li><a class="page_link" href="?page={{ i }}">{{ i }}</a></li> {% endif %} {% endfor %} {% if contacts.has_next %} <li> <a href="?page={{ contacts.next_page_number }}" aria-label="Next"> <span aria-hidden="true">&raquo;</span> </a> </li> {% else %} <li class="page-item disabled"> <a aria-label="Next"> <span aria-hidden="true">&raquo;</span> </a> </li> {% endif %} </ul> {% endif %} </nav> In my views: def product_list(request, category_slug=None): category = None products = Product.objects.filter(is_published=True) *** *** if category_slug: category = get_object_or_404(Category, slug=category_slug) products = products.filter(category=category) *** *** paginator = Paginator(products, 5) page = request.GET.get('page') num_pages = paginator.num_pages try: contacts = paginator.page(page) … -
Migrating the Entry Model and TypeError: __init__() missing 1 required positional argument: 'on_delete'
Basically when setting up Django, I'm trying to migrate the entry model but I keep getting error with the activation of ll_env when typing python manage.py makemigrations learning_logs Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/Users/james/Desktop/The_Universe/CS/Python/Practice_PCC/learning_log/ll_env/lib/python3.6/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line utility.execute() File "/Users/james/Desktop/The_Universe/CS/Python/Practice_PCC/learning_log/ll_env/lib/python3.6/site-packages/django/core/management/__init__.py", line 347, in execute django.setup() File "/Users/james/Desktop/The_Universe/CS/Python/Practice_PCC/learning_log/ll_env/lib/python3.6/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/james/Desktop/The_Universe/CS/Python/Practice_PCC/learning_log/ll_env/lib/python3.6/site-packages/django/apps/registry.py", line 112, in populate app_config.import_models() File "/Users/james/Desktop/The_Universe/CS/Python/Practice_PCC/learning_log/ll_env/lib/python3.6/site-packages/django/apps/config.py", line 198, in import_models self.models_module = import_module(models_module_name) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/Users/james/Desktop/The_Universe/CS/Python/Practice_PCC/learning_log/learning_logs/models.py", line 12, in <module> class Entry(models.Model): File "/Users/james/Desktop/The_Universe/CS/Python/Practice_PCC/learning_log/learning_logs/models.py", line 14, in Entry topic = models.ForeignKey(Topic) TypeError: __init__() missing 1 required positional argument: 'on_delete' Which should have showed like this as below from a book. (ll_env)learning_log$ python manage.py makemigrations learning_logs Migrations for 'learning_logs': 0002_entry.py: - Create model Entry (ll_env)learning_log$ python manage.py migrate Operations to perform: --snip-- Applying learning_logs.0002_entry... OK So basically the error, as TypeError shows, is that I missed … -
Django duplicate key violates unique constraint within transaction.atomic()
2018-03-06T23:57:28+00:00 app[postgres.20511]: [SILVER] [9-1] sql_error_code = 23505 ERROR: duplicate key value violates unique constraint "api_championitems_pkey" 2018-03-06T23:57:28+00:00 app[postgres.20511]: [SILVER] [9-2] sql_error_code = 23505 DETAIL: Key (champ_id)=(110) already exists. 2018-03-06T23:57:28+00:00 app[postgres.20511]: [SILVER] [9-3] sql_error_code = 23505 STATEMENT: INSERT INTO "api_championitems" ("champ_id", "item_blob") VALUES (110, '{}') I have a get_or_create wrapped within an atomic transaction and I have no idea why I am getting duplicate key errors. This is the only code that creates and writes to the UserChampionItems model. Also, is there a way to speed up this query? I am using postgres10 and django2.0 class UserChampionItems(models.Model): user_id = models.IntegerField() region = models.CharField(max_length=10) champ_id = models.IntegerField() lane = models.CharField(max_length=50) item_blob = models.TextField(default="{}") class Meta: unique_together = (("user_id", "region", "champ_id", "lane"),) @shared_task() def update_items(summoner_id, region, data): t = time.time() * 1000 for champ_id, lanes in data.items(): for lane, items in lanes.items(): with transaction.atomic(): uci, created = UserChampionItems.objects.select_for_update().get_or_create( user_id=summoner_id, region=region, lane=lane, champ_id=champ_id ) cur_data = ujson.loads(uci.item_blob) for item_id, occurence in items.items(): if item_id in cur_data: cur_data[item_id] += occurence else: cur_data[item_id] = occurence new_data = ujson.dumps(cur_data) uci.item_blob = new_data uci.save() print("ui:", time.time() *1000 - t) -
Django redirect from form to view in a different app
I have a django form that is now useless. I would like to always redirect from that form to a view in a different app. Here's what I have: return HttpResponseRedirect(reverse_lazy("management:management_account_add_user")) But I'm not sure where to put it. -
How I can integrate payment with maroc telecommerce in django-oscar?
I need to integrate payment method maroc telecommerce in django-oscar. -
Django display context variable (message) in template using .as_html
I am using some forms from django-graphos, and in order to draw the grpah, in the view def view(): make_your_data_somehow = [ [dataHeaders], [data1], [data2], etc… ] data_source = SimpleDataSource(data=make_your_data_somehow) your_chart = ChartType(data_source) return render(request, 'dataViewer.html', { 'chart' : your_chart, }) and in the template you would: <div> {{chart.as_html}} </div> <!-- the `chart` itself is a graphos object i think, it prints '<graphos.renderers.gchart.LineChart object at 0x107ecb190>' without `.as_html`--> In my case I need to have a certain data structure (more than one dataN in the example above). I can correctly detect if the data structure is correct in the view, but I am trying to avoid making an entirely new template for just one case (or restructuring for a template include). How do I make a variable have text that will be processed when called as variable.as_html in the view as actual text. I have tried: chart = 'Need more than one data to display Graph' chart = None a few others I can't retrace :\ but they all display nothing, unless I remove the .as_html in the template, which then would make displaying the graph non-existent. The only thing I know to do is to declare them as None … -
editing a slug post in django
I have an application where user create posts and can view them. the problem I face is with the edit button and how to make only users who created the post be able to edit their own post or delete them else another user can not. if I enter into the browser url field for example http://127.0.0.1:8000/soko/edit it opens the form field and it is ready to be edited but if I use input button from my template I get the following error Reverse for 'edit' with no arguments not found. 1 pattern(s) tried: ['(?P<slug>[\\w-]+)/edit/$'] below is my views.py def edit(request, slug = None): instance = get_object_or_404(Post, slug = slug) form = PostForm(request.POST or None, request.FILES or None, instance = instance) if form.is_valid(): instance = form.save(commit=False) instance.save() messages.success(request, "Post updated") #redirecting to landing page return HttpResponseRedirect(instance.get_absolute_url()) context = { "title": instance.title, "instance": instance, "form": form, } template = 'edit.html' return render(request, template, context) def delete(request, slug=None): instance = get_object_or_404(Post, slug=slug) instance.delete() messages.success(request, "Post Deleted") return redirect(index) urls.py url(r'^(?P<slug>[\w-]+)/edit/$', views.edit, name='edit'), url(r'^(?P<slug>[\w-]+)/delete/$', views.delete, name='delete'), html <a class="btn btn-default" href="{% url 'posts:edit' %}"></a> futher codes would be supplied on request -
django_rest_swagger using http not https in "try it out" button
I'm using Django Rest Framework with Django Rest Swagger for API documentation. It seems that the "try it out" button always submits http requests, not https requests, even though the browser is https. I know how to do this if I rebuilt entire CoreAPI spec, but want to just pass something like protocol = 'https' to django_rest_swagger or something else that does not require re-coding the API documentation framework. -
Django view not recognizing request
I have a form that is filled out on a webpage. The goal of the form is to gather some basic info, and then save the IP of the sender to the DB too. The form submits a POST request to my Django view, but Django gives me the error: if request.method() == 'POST': TypeError: 'str' object is not callable Here is the view: from .form import SignUpForm from django.shortcuts import render from django.http import HttpResponseRedirect def index(request): if request.method() == 'POST': form = SignUpForm(request.POST) if form.is.valid(): signup_item = form.save(commit=False) signup_item.ip_address = request.META['HTTP_X_FORWARDED_FOR'] signup_item.save() return HttpResponseRedirect(request.path) else: form = SignUpForm() return render(request, 'index.html', {'form': form}) Here is the urls.py from django.conf.urls.import url from django.contrib import admin from form import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'', views.index, name='home). ] -
Django Template syntax/tag to filter and check if a related data exists in that model
I'm working on a project with python-3.6.4 and django-2.0.2. For simplicity, I'm explaining the situation in short. Suppose, there are three apps:- "problems", "solve_activities" and "profiles" having three models(mentioned below) inside them. I have a "DetailView" page for each problem. I want to show if the logged in user has solved the problem or not. The django template tag that I wanted to do use was something like this: " {% if user.is_authenticated and problem.solved.objects.all.filter(solver={{user.username}}) %} " Here are the above mentioned files: "problems/models.py": class Problem(models.Model): name = models.CharField(max_length=20) slug = models.SlugField(allow_unicode=True, max_length=100, unique=True) def __str__(self): return self.name def get_absoulte_url(self): return reverse('problems') return reverse('problems:problem_detail', kwargs={'slug':self.slug}) I've used the urlpatterns in 'problems/urls.py' as "path('/', views.ProblemDetail.as_view(), name='problem_detail')". "profiles/models.py"(inherited from auth.models.User): class User(auth.models.User, auth.models.PermissionsMixin): def __str__(self): return self.username "solve_activities/models.py": class Solve(models.Model): problem = models.ForeignKey(Problem, on_delete=models.CASCADE, related_name="solved") solver = models.ForeignKey(User, on_delete=models.CASCADE, related_name="solved") I'm only creating this object when the user solves a problem. Now, my ProblemDetail view on problems/views.py: class ProblemDetail(generic.DetailView): model = Problem template_name = 'problems/problem_detail.html' And the "problems/problem_detail.html" file where I'm facing the complexity basically: <h1>{{problem}}</h1> <h4>Solve Status: {% if user.is_authenticated and problem.solved.objects.all.filter(solver={{user.username}}) %}Solved{% else %}Unsolved{% endif %}</h4> Again, {% if user.is_authenticated and problem.solved.objects.all.filter(solver={{user.username}}) %} this is what I want to do, … -
Django/Celery - SIGSEGV error accessing database
I have a Python-based Django app using the Celery task queue. I need to access my database, which I'm trying to do using the private key (See tasks.py). However, trying to access the database raises a segmentation fault error, and I'm not sure why. When I run this code directly from views.py, that is, I run dummyTask(user_model.id) rather than dummyTask.delay(user_model.id) the tasks runs to completion without any error messages. What could be causing this error with accessing my database? I looked at this question but couldn't find a solution. I'm running Python 3.6, Django 2.0.3 and celery 4.1.0 currently, and am also using db.sqlite3 with redis. The error message is: [2018-03-06 21:35:51,083: ERROR/MainProcess] Process 'ForkPoolWorker-1' pid:96231 exited with 'signal 11 (SIGSEGV)' [2018-03-06 21:35:51,097: ERROR/MainProcess] Task handler raised error: WorkerLostError('Worker exited prematurely: signal 11 (SIGSEGV).',) Traceback (most recent call last): File "/Users/rouskinlab/.pyenv/versions/3.6.0/envs/EMDC/lib/python3.6/site-packages/billiard/pool.py", line 1223, in mark_as_worker_lost human_status(exitcode)), billiard.exceptions.WorkerLostError: Worker exited prematurely: signal 11 (SIGSEGV). The relevant code is: views.py ... from .forms import UserForm, SampleFormSet, StructureFormSet from .tasks import dummyTask def upload(request): # Create FormSets for validating uploads. StructureFormSet = formset_factory(StructureForm, formset=BaseLinkFormSet) LinkFormSet = formset_factory(LinkForm, formset=BaseLinkFormSet) if request.method == 'POST': display(request.POST) display('request POSTed... Checking form validity...') structure_formset = StructureFormSet(request.POST, request.FILES) #, …