Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How typing the correct path to my json file inside a javascript file
python 3.6.4 , django 2.0 I have a index.html which load this javascript file script.js and inside this i have problems to type the correct path to one json file data.json. The index.html now is displayed without the information from data.json , I am using a XmlHttpRequest object. function makeRequest(url){ ... http_request = new XMLHttpRequest(); http_request.open('GET', url, true); } ... window.onload = function(){ makeRequest("here/have/problems"); } Tree of my files inside index.html use {% static 'bar/scripts/script.js'%} and that work well, then inside script.js was trying typing "bar/data/data.json" but doesn't work. Guide me please in the correct way about this issue. -
social auth django: disconnect vs disconnect_individual
So I have added the disconnection pipeline to my application using python-social-auth. I noticed that there are two endpoints in the urls.py: disconnect - /oauth/disconnect/<backend>/ disconnect_individual - oauth/disconnect/<backend>/<association_id>/ Where backend could refer to the social provider (facebook, google-plus, linkedin, ...). Through my experiments, I find that the first endpoint, disconnect, will remove the logged in user's associated UserSocialAuth table entry. What does the second endpoint do? What does the association_id represent? Is it a way of dissociating one individual account if the user has two UserSocialAuth entries with the same backend? That doesn't make sense since the uid + provider must be unique. Can someone provide an example of when one would call the disconnect_individual? -
django model for subsite wagtail multisite
I am creating a wagtail instance which includes actually 4 sites: a portal-site and three nearly identical subsites. The subsites contain in the footer a django-form, and within this django-form I want to include a number of date-objects that are specific for the subsite. To clarify the setup: there will be a subsite for kids-training, youth-training and adults-training. The form needs to include the next three training-dates (DateTime) for the target-group, and these dates need to be created by the site-owner. I have not yet found a way to create a non-page model (django-model) that can be added to a subsite. Snippets seem not the way to go, and Site Settings does not seem to cover this usecase. Any solution-suggestion would be welcome. -
Just django dynamic formset and ajax
I use django dynamic formset and ajax to chekc the inventory. When I add a form, how to have ajax pick up change on the new form? dynamic formset adding forms $('#form-inline tbody tr').formset({ addText: 'add link', deleteText: 'remove', prefix: 'ptpositions' }); I loop the form in ajax but I don't think this is a good way. $(document).ready(function(){ {% for forms in formset %} $(".{{forms.stock.value}}").change( function(){ var symbol = $(".{{forms.stock.value}} option:selected").text(); {% endfor %} {% for forms in formset %} $.ajax({ url: "{% url 'inventory:get_position' ptinventory_obj.id date %}", type: "GET", data: { 'product': product }, datatype: 'json', success: function(data) { $(".{{forms.id.value}}_ouput").html(data.price); }}); {% endfor %} }); }) Now if I add form, then the ajax doesn't work. -
Visualization of xlsx files in a django project
I am willing to work on a project, in which I have a database (xlsx files), and I want to migrate it to a nosql database in order to visulize the data in plots, and then integrate it in a django website using plotly to make the graphs. My question is, is it better to migrate to a nosql database knowing that files will be added daily, or just use a sql one like postgresql? And which is better to do the job, mongoDB or Elasticsearch ? -
Trying to pass arguments from java script to python, and have python return back the result on my java script page
I am trying to test a simple function using java script and python. I am trying to pass some arguments from java script / HTML to python (which is running as a server) and get the results back to my HTML page. I noticed that the following isn't getting executed "utf-8">{% csrf_token %}", but i cant seem to know the reason. This snippet can be seen below int he HTML script. I really appreciate your help, and Thank you. I have attached both scripts: PYTHON: from django.http import HttpResponse from django.shortcuts import render_to_response from django.template import RequestContext def index(request): return render_to_response('index.html') def result(request): p = request.POST['answer'] return render_to_response('index.html', {'answer': p}, context_instance=RequestContext(request)) HTML: <head> <title>Index page</title> </head> <body> <div id="header">Welcome to index page</div> <div id="content"> <p>Enter your name</p> <form action="/MYURL" method="post" accept-charset="utf-8">{% csrf_token %} <input type="text" name="answer"> <input type="submit" value="Send!"> </form> <div id="header"> result</div> <div id="content"> <p>Your name is: {{ answer }}</p> </div> </div> </body> -
WSGI script cannot be loaded as Python Module
I have been trying to troubleshoot a internal server error ive been getting from my local install of django 2.0.2 whlist trying to run it in a python 3.6.3 virtualenv on apache 2.4.27 via mod-wsgi-py3 4.5.17 running in Daemon mode. In my apache2 error.log file I can see [Thu Feb 08 10:34:24.694864 2018] [wsgi:error] [pid 94364] [remote 127.0.0.1:47002] mod_wsgi (pid=94364): Target WSGI script '/var/www/wsgi-scripts/wurstblog.wsgi' cannot be loaded as Python module. Searching the internet far and wide I have found various potential solutions that include WSGI Script Cannot Be Loaded as Python Module -- 500 Internal Server Error 'How python is installed' 'Missmatch of mod-wsgi and python environment version' 'conflict with mod_python and mod_wsgi' I am not sure how to correct any problem with my python3 instalation, nor that of mod_python I read somewhere that the wsgi script needed to be executable so ls -l /var/www/wsgi-scripts gives -rwxr-xr-x 1 root root 454 Feb 8 10:52 wurstblog.wsgi it looks like this: import os import sys from django.core.wsgi import get_wsgi_application sys.path.append('/home/mike/blog-env/wurstblog/wurstblog') os.environ["DJANGO_SETTINGS_MODULE"] = "wurstblog.settings" application = get_wsgi_application() blog-env is my pthon3 virtualenv and wurstblog is where my django project is I have configured a virtualhost /etc/apache2/sites-enabled/wurst.conf <VirtualHost *:80> ServerAdmin myname@nospam.com <Directory /var/www/wsgi-scripts> <Files … -
Issues redirecting in Django
I'm deploying a django app, and I have two forms: One for rating and another for contact in the home page. Both of them redirect to the home page after save a model. The contact form works fine, but the rating form keeps the post url and doesn't save the model, and after doing it again, it save it. For example, I'm in www.site.com, then I send a post request from the rating form, the form redirect me to www.site.com/rating/ without saving the data. Then, if I'm send from www.site.com/rating/ the same form, the data is saved and redirect to www.site.com/rating/rating/ (404). The contact form works fine with the same process, and I think both are similar. The contact form redirects me to www.site.com like I want. I don't know why is this happening. urls.py urlpatterns = i18n_patterns( url(r'^admin/', admin.site.urls), url(r'^i18n/', include('django.conf.urls.i18n')), url(r'^', include('myapp.urls')), prefix_default_language=False ) myapp/urls.py urlpatterns = [ url(r'^contact/', views.contact, name='contact'), url(r'^rating/', views.raiting, name='rating'), url(r'^', views.index, name='home'), ] myapp/views.py def contact(request): if request.method != 'POST': raise Http404('acceding from GET') msg = ContactForm(request.POST) if not msg.is_valid(): context = { 'contact_errors': msg.errors } return render(request, 'home.html', context) msg.save() return redirect('home') def rating(request): if request.method != 'POST': raise Http404('acceding from GET') … -
Breadcrumps doesn't work correctly in django
I'am creating from the one template a categories and subcategories model in django. Now I have a few categories and subcategories added by Admin Panel. But now when I want to display in html the list of breadcrumps they doesn't displaying correctly and I getting a error. views.py from django.shortcuts import render, get_object_or_404 from .models import Kategoria, Firma def strona_glowna(request): return render(request, 'ogloszenia/index.html', {}) def show_category(request,hierarchy= None): category_slug = hierarchy.split('/') category_queryset = list(Kategoria.objects.all()) all_slugs = [ x.slug for x in category_queryset ] parent = None for slug in category_slug: if slug in all_slugs: parent = get_object_or_404(Kategoria,slug=slug,parent=parent) else: instance = get_object_or_404(Firma, slug=slug) breadcrumbs_link = instance.get_cat_list() category_name = [' '.join(i.split('/')[-1].split('-')) for i in breadcrumbs_link] breadcrumbs = zip(breadcrumbs_link, category_name) return render(request, "ogloszenia/detale.html", {'instance':instance,'breadcrumbs':breadcrumbs}) return render(request,"ogloszenia/kategorie.html",{'firma_set':parent.firma_set.all(),'sub_categories':parent.children.all()}) urls.py from django.urls import path from . import views urlpatterns = [ path('', views.strona_glowna, name='strona_glowna'), path('<hierarchy>/', views.show_category, name='category'), ] kategorie.html {% if sub_categories %} <h3>Podkategorie</h3> {% for i in sub_categories %} <a href="{{ i.slug }}"> {{ i.name }} </a> {% endfor %} {% else %} Brak podkategorii {% endif %} <div class="row small-up-1 medium-up-3" > {% if firma_set %} {% for i in firma_set %} <a href="{{ i.slug }}"> <img src="{{ i.title }}"> </a> <a href="{{ i.slug }}"> … -
When an object can belong to several other objects, where does the foreign key belong?
Using Django 1.11.6 and Postgres 9.2 If I have the following models: class RoughDraft(models.Model) class Manuscript(models.Model): rough_draft = models.ForeignKey(RoughDraft) class AudioBook(models.Model): manuscript = models.ForeignKey(Manuscript) class Series(models.Model): class Book(models.Model): manuscript = models.ForeignKey(Manuscript) series = models.ForeignKey(Series) I want to add a Notes model to my project to allow multiple users add comments to RoughDrafts, Manuscripts, Books and AudioBooks. Further, when a RoughDraft becomes a Manuscript or Manuscript becomes a Book or AudioBook, I want the Notes to be carried forward. Is it better to create a notes model like this: class Notes(models.Model): text = models.TextField() and add a notes = models.ManyToMany(Notes) field to each of RoughDraft, Manuscript, Book, Series and AudioBook or class Notes(models.Model): text = models.TextField() rough_draft = models.ForeignKey(RoughDraft, null=True, blank=True) manuscript = models.ForeignKey(Manuscript, null=True, blank=True) series = models.ForeignKey(Series, null=True, blank=True) book = models.ForeignKey(Book, null=True, blank=True) audio_book = models.ForeignKey(AudioBook, null=True, blank=True) Or should I create a ManuscriptNotes model, a RoughDraftNotes model, etc... -
Django CreateView autofill custom user
I want to use Django's GCBV CreateView to autofill the created_by field on my model with the current user. The official docs have a good example here but I'm using a custom user model and having trouble making it work. Here's my current setup: # models.py from django.conf import settings from django.contrib.auth.models import User from django.db import models class Author(models.Model): name = models.CharField(max_length=200) created_by = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, ) # views.py from django.contrib.auth import get_user_model from django.views.generic.edit import CreateView from myapp.models import Author class AuthorCreate(CreateView): model = Author fields = ['name'] def form_valid(self, form): form.instance.created_by = self.request.get_user_model() return super().form_valid(form) However upon form submission I get the error: AttributeError at /posts/new/ 'WSGIRequest' object has no attribute 'get_user_model' I'm setting my custom user incorrectly but not sure exactly where the error is. -
Make jenkins indicate failure on failed tests
I have a django test suite which is running on jenkins with the following build: virtualenv -p /usr/bin/python3.5 etl_api_virtualenv cd etl_api_virtualenv source bin/activate python --version cd $WORKSPACE/leg_apps ls pip install -r requirements-dev.pip ./api/test/run_api_tests.sh $WEB_ENV This is working, but when some of the unit tests fail, the job/build still is marked as a success. I can't figure out how to make the job indicator turn red and mark as a failure if the tests don't all pass. I'm not even sure what to Google to try to figure this out, so please forgive the apparent "lack of effort"... it's not the case. I'm just dead-ended at the start. -
Retrieving information form several textbox (Template) in Django
**I want to fetch information from course titile & course code textbox ,,,, if title & code both are given or only title /code data will be showed. Bt, in my code not working when only title are given.. what are the logical mistake..?? My View Code def search_view(request): c = 0 d = 0 c_title = '' c_code = '' course_Details = '' course_Details1 = '' if request.GET.get('Code'): c_code = request.GET.get("Code") if request.GET.get('Course_Title'): c_title = request.GET.get("Course_Title") if c_code != '': course_Details = Course.objects.filter(course_code=c_code) if (course_Details): c = 1 if c_title != '': if c == 1: course_Details1 = course_Details.filter(course_title=c_title) if (course_Details1): d = 1 if d == 1: course_Details = course_Details1 if d == 0: course_Details = Course.objects.filter(course_title=c_title) if c == 1 | d == 1: return render(request, 'index.html', {'course_Details': course_Details}) else: return render(request, 'index.html') -
How to best include field from Django ManyToManyField custom intermediary model when using prefetch_related?
Models: class User(models.Model): teams = models.ManyToManyField('Team', through='TeamMember', related_name='members') class Team(models.Model): pass class TeamMember(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) team = models.ForeignKey(Team, on_delete=models.CASCADE) position = models.CharField(max_length=255) I am trying to build a queryset that will fetch users and (running another query with prefetch_related) teams for those users with TeamMember.position included as one of the fields on the team without running any unnecessary queries or joins. Here is the queryset I have so far: User.objects.prefetch_related(Prefetch('teams', queryset=Team.objects.annotate(position=F('teammember__position')))) But it is doing an unnecessary join: SELECT `appname_user`.`id` FROM `appname_user` LIMIT 21; args=() SELECT (`appname_teammember`.`user_id`) AS `_prefetch_related_val_user_id`, `appname_team`.`id`, `appname_teammember`.`position` AS `position` FROM `appname_team` LEFT OUTER JOIN `appname_teammember` ON (`appname_team`.`id` = `appname_teammember`.`team_id`) INNER JOIN `appname_teammember` T3 ON (`appname_team`.`id` = T3.`team_id`) WHERE T3.`user_id` IN (1); args=(1,) It is joining appname_teammember twice when it doesn't need to. Anyone know how to eliminate that extra join? -
Django REST framework rendering a field (or not) based on context
I've a Car class class Car(serializers.ModelSerializer): engine = EngineSerializer(many=False, required=False) owner = UserSerializer(many=False, required=False) and now I want to hide engine for users except the owner (this should be checked at self.context['user'] == self.owner. I can accomplish this by making engine into a SerializerMethodField() class Car(serializers.ModelSerializer): engine = serializers.SerializerMethodField() owner = UserSerializer(many=False, required=False) def get_engine(self, obj): if self.context['user'] == self.owner: return EngineSerializer(self.engine, many=False).data else: return None or so but this would create problems when creating + updating. What is the best practice for this? I don't aim privacy but just want to avoid cost of serializing the engine (imagine it takes a long time to serialize and it's useless for people except the owner) -
Django Rest Framework - Return row and its adjacent rows on GET
I would like to return a given row and the row before and after it (sorted by file_created_time desc) when calling GET with a uid parameter representing the row. URL ex: https://<domain>/api/videos/cbf02e8c-b2f5-4cd8-b3ec-87417eae2f7d?with_adjacent=true { "uid": "fd5d5936-8183-495f-9a9d-8ffca25a9bab", "is_thumbnail": true, "file_name": "2018-02-03_05-00-40.jpg", "file_path": "thumbnails/2018-02-03_05-00-40.jpg", "file_created_time": "2018-02-03T05:00:40-07:00", "owner": "system_user", "created_time": "2018-02-04T14:49:29.355156-07:00" }, { "uid": "cbf02e8c-b2f5-4cd8-b3ec-87417eae2f7d", "is_thumbnail": true, "file_name": "2018-02-03_01-09-30.jpg", "file_path": "thumbnails/2018-02-03_01-09-30.jpg", "file_created_time": "2018-02-03T01:09:30-07:00", "owner": "system_user", "created_time": "2018-02-04T14:49:30.464810-07:00" }, { "uid": "ed626576-cc9d-4434-9f44-93a4f8f525ad", "is_thumbnail": true, "file_name": "2018-02-03_00-59-15.jpg", "file_path": "thumbnails/2018-02-03_00-59-15.jpg", "file_created_time": "2018-02-03T00:59:15-07:00", "owner": "system_user", "created_time": "2018-02-04T14:49:32.611105-07:00" } Given the model: class Videos(models.Model): """This class represents the Videos model.""" uid = models.UUIDField( primary_key=True, default=uuid.uuid4, editable=False) is_thumbnail = models.BooleanField(default=False) file_name = models.CharField(unique=True, max_length=64) file_path = models.CharField(unique=True, max_length=256) file_created_time = models.DateTimeField() owner = models.ForeignKey('auth.User', related_name='videos', on_delete=models.CASCADE) created_time = models.DateTimeField(auto_now_add=True) def __str__(self): """Return a human readable representation of the model instance.""" return "{}".format(self.file_name) And View: class DetailsView(generics.RetrieveUpdateDestroyAPIView): """This class handles the http GET, PUT and DELETE requests.""" queryset = Videos.objects.all() serializer_class = VideosSerializer permission_classes = (permissions.IsAuthenticated, IsOwner) lookup_field = 'uid' I'm happy the adjust the view as necessary, that's just what I have now. -
Celery starts the scheduler more often than specified in the settings
Tell me in what there can be a problem with Celery worker? When I run it, it starts executing the task more often than once a second, although it takes an interval of several minutes. Running the bit: "celery market_capitalizations beat -l info --scheduler django_celery_beat.schedulers: DatabaseScheduler" Launch of a vorker: "celery -A market_capitalizations worker -l info -S django" Maybe I'm not starting the service correctly? Settings: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'exchange_rates', 'django_celery_beat', 'django_celery_results', ] TIME_ZONE = 'Europe / Saratov' USE_I18N = True USE_L10N = True USE_TZ = True CELERY_BROKER_URL = 'redis: // localhost: 6379' CELERY_RESULT_BACKEND = 'redis: // localhost: 6379' CELERY_ACCEPT_CONTENT = ['application / json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' CELERY_TIMEZONE = TIME_ZONE CELERY_ENABLE_UTC = False CELERYBEAT_SCHEDULER = 'django_celery_beat.schedulers: DatabaseScheduler' running services When the task is started, a request is not sent. admin panel Tell me, please, how to make a celery pick up task time from a web page and run the task with it? I tried to run the task through the code, but it still runs more often than in a second. from celery.schedules import crontab app.conf.beat_schedule = { 'add-every-5-seconds': { 'task': 'save_exchange_rates_task', 'schedule': 600.0, # 'args': (16, 16) }, } -
Elasticsearch or mongodb for storing data and ploting it (Visualization)
I am willing to work on a project, that take a big excel database, migrate it to a nosql database in order to visulize the data in plots, and then integrate it in a django website. My question is, which is better to do the job, mongoDB or Elasticsearch ? -
Django aggregation for Avg
I have a model as below. class Transaction(models.Model): time1 = models.DateTimeField(null=True) time2 = models.DateTimeField(null=True) I need to get the average of the (time2 - time1) in seconds for a list of records, if both values are not null. -
AJAX post request slow every second time [Django]
As a little side-project I created a Django-based Web Application. So far I have created my webpage with basic Javascript. I can successfully get data from the database and create an AJAX POST-request via Javascript. Everything is working BUT there is something that really bothers me: Every second POST-request takes a significantly longer time to reach the server. For example: Request1 returns successful after 29ms. Request2 needs (for the exact same task!) over 300ms. This goes on and is 100% replicable. I have no idea what the reason for that issue is. I hope someone can guess what the root for this problem is. Image of "request-waterfall" from the developer tool. Used Code: //THIS IS THE POST REQUEST IN THE JS-SCRIPT (CLIENT-SIDE) $.ajax({ type: "POST", url: '/update_database', data: { "habit_name": habits[h].habit_name, "meta_data": meta_data }, success: function(result) { update(); console.log('Successful'); } }); Server-side handling of the POST-request: def update_database(request): post_dict = dict(six.iterlists(request.POST)) habit_name = post_dict["habit_name"][0] meta_data = post_dict["meta_data"][0] change_meta_data(habit_name, meta_data) data = { "Habits": Habit.objects.all().values() } return JsonResponse(list(data["Habits"]), safe=False) -
Authenticating users with ldap in Django project
I am trying to authenticate users against my ldap server. I have successfully ran pip install python-ldap and django-auth-ldap.. I am running python 2.7.. Every time I try to login my to Django admin with my superuser account I get the following error: AttributeError at /admin/login/ 'module' object has no attribute 'LDAPError' Request Method: POST Request URL: http://localhost:8000/admin/login/?next=/admin/ Django Version: 1.11.9 Exception Type: AttributeError Exception Value: 'module' object has no attribute 'LDAPError' Exception Location: C:\Python27\lib\site-packages\django_auth_ldap\backend.py in authenticate, line 384 Python Executable: C:\Python27\python.exe Python Version: 2.7.13 Python Path: ['C:\\Users\\donallane\\Desktop\\My_Django_Stuff\\ldap-login\\learning_users', '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\\python_ldap-2.4.10-py2.7-win32.egg'] Server time: Thu, 8 Feb 2018 16:59:10 +0000 ldap configurations in settings.py: ####### --------------- LDAP Configuration ------------ ####### import ldap from django_auth_ldap.config import LDAPSearch, GroupOfNamesType # AUTH_LDAP_START_TLS = True # AUTH_LDAP_GLOBAL_OPTIONS = { # #ldap.OPT_X_TLS_REQUIRE_CERT: False, # #ldap.OPT_REFERRALS: False, # } # # AUTH_LDAP_SERVER_URI = "ldaps://ldap.ecf.orca.ie" # AUTH_LDAP_BIND_DN = 'cn=myapp,ou=apps,o=company' # AUTH_LDAP_BIND_PASSWORD = 'myapp_password' # AUTH_LDAP_USER_SEARCH = LDAPSearch("ou=people,o=company", ldap.SCOPE_SUBTREE, "(uid=%(user)s)") # # AUTH_LDAP_ALWAYS_UPDATE_USER = False # # # AUTH_LDAP_USER_ATTR_MAP = { # "first_name": "givenName", # "last_name": "sn", # "email": "mail" # } # import ldap # # AUTH_LDAP_CONNECTION_OPTIONS = { # ldap.OPT_REFERRALS: 0 # } AUTHENTICATION_BACKENDS = ( 'django_auth_ldap.backend.LDAPBackend', 'django.contrib.auth.backends.ModelBackend', ) auth_connection.py: import ldap … -
Django: Creating categories using querysets/filtering
I'm trying to figure out if it's possible to create categories using custom filters. I am building an e-commerce app and I have set up my category model using mptt. I am importing a csv that creates my top level categories which works fine. The problem is I will need to have sub-categories that are more specific e.g Men's Clothing(Top Level) > Jeans. The csv has several fields that contains info relating to each product e.g description: "stone wash bootcut jeans". I would ideally like to check these fields for keywords and add each product to the correct categories. Is it possible to set up categories this way or is there an alternative solution? I am a django newbie so any help is appreciated. models.py from django.db import models from mptt.models import MPTTModel, TreeForeignKey class Category(MPTTModel): name = models.CharField(max_length=50, unique=True) parent = TreeForeignKey('self', null=True, blank=True, related_name='children', db_index=True, on_delete=models.CASCADE) slug = models.SlugField() class MPTTMeta: order_insertion_by = ['name'] class Meta: unique_together = (('parent', 'slug',)) verbose_name_plural = 'categories' def get_slug_list(self): try: ancestors = self.get_ancestors(include_self=True) except: ancestors = [] else: ancestors = [ i.slug for i in ancestors] slugs = [] for i in range(len(ancestors)): slugs.append('/'.join(ancestors[:i+1])) return slugs def __str__(self): return self.name class Brands(models.Model): … -
Categories and subcategories in Django
I have a little problem. I've create a model for Categories, and Posts. In my project I used a categories->subcategories model. When I finished, createsuperuser and login in to the Admin Panel I show a Fields 'Category' and 'Posts'. When I want to add a new category as a parent, after I need to add children. I added 1 record 'Biznes' and Child 'Własna Firma'. I clicked add next and for that moment the Admin Panel thinking, thinking and not respond. I can't add Post, delete or Edit Category. Here is my models.py from django.db import models from django.contrib.auth.models import User class Kategoria(models.Model): name = models.CharField(max_length=250, verbose_name='Kategoria') slug = models.SlugField(unique=True,verbose_name='Adres SEO') parent = models.ForeignKey('self', blank=True, null=True, related_name='children', on_delete=models.CASCADE) class Meta: unique_together = ('slug', 'parent',) verbose_name = 'Kategoria' verbose_name_plural = 'Kategorie' def __str__(self): full_path = [self.name] k = self.parent while k is not None: full_path.append(k.name) k = k.parent return ' / '.join(full_path[::-1]) class Firma(models.Model): user = models.ForeignKey(User, default=1, verbose_name='Użytkownik', on_delete=models.CASCADE) title = models.CharField(max_length=250, verbose_name='Nazwa firmy') slug = models.SlugField(unique=True, verbose_name='Adres SEO') category = models.ForeignKey('Kategoria', null=True, blank=True, verbose_name='Kategoria', on_delete=models.CASCADE) content = models.TextField(verbose_name='Opis') draft = models.BooleanField(default=False, verbose_name='Szablon') publish = models.DateField(auto_now=False, auto_now_add=False) class Meta: verbose_name='Firma' verbose_name_plural='Firmy' def __str__(self): return self.title def get_cat_list(self): k = self.category … -
How to write test for class methods?
How to write tests for this manager in pytest? class OperatorLogManager(models.Manager): def active(self): """Mark object as active""" return self.filter(is_delete=False) def get_by_user_id(self, id): return self.active().filter(pk=id) def get_by_client_id(self, client_uid): return self.active().filter(client_uid=client_uid) -
AttributeError: 'DeferredAttribute' object has no attribute 'rel'
I'm new to Wagtail and Django, and I am trying to build a model that will pull data from a REST API and put it into an object that can be iterated on the template. However, when trying to migrate, I get this error: related = getattr(model, self.relation_name).rel AttributeError: 'DeferredAttribute' object has no attribute 'rel' From what I've been able to gather so far, it has something to with the description and image fields in the OFSLOrgWebPage page model. Here are the relevant models: from __future__ import absolute_import, unicode_literals from django.db import models from django.shortcuts import render from django.conf import settings from wagtail.wagtailcore.models import Page, Orderable from wagtail.wagtailcore.fields import RichTextField, StreamField from wagtail.wagtailadmin.edit_handlers import FieldPanel, FieldRowPanel, MultiFieldPanel, \ InlinePanel, StreamFieldPanel from wagtail.wagtailimages.edit_handlers import ImageChooserPanel from wagtail.wagtailsearch import index from wagtail.wagtailcore.blocks import StructBlock, StreamBlock, CharBlock, RichTextBlock, RawHTMLBlock, BooleanBlock from wagtail.wagtailimages.blocks import ImageChooserBlock from wagtail.wagtaildocs.blocks import DocumentChooserBlock from modelcluster.fields import ParentalKey import datetime import json import requests class OFSLOrgWebPage(Page): description = RichTextField(blank=True) image = models.ForeignKey( 'serenity.Images', null=True, blank=True, on_delete=models.SET_NULL, related_name='+', help_text="Council image that appears at the top of the page. Size: 500px x 400px" ) def get_context(self, request): context = super(OFSLOrgWebPage, self).get_context(request) context['greek_orgs'] = self.greek_bios.objects.child_of(self).live() return context search_fields = Page.search_fields + [ …