Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
saving model and linking template to views.py
I cannot call the thanks-template after submitting data into contact-form. Why? The contact page repeat itself. Also no data is saved on database. What I am missing? Query of database in python-shell shows nothing is saved: Contact.objects.all() ###View.py def contact(request): if request.method == 'POST' : form = ContactForm(request.POST) if form.is_valid(): name = form.cleaned_data['name'] email = form.cleaned_data['email'] subject = form.cleaned_data['subject'] message = form.cleaned_data['message'] form.save() return render ('thanks.html', {'name' : name, 'email' : email, 'subject' : subject, 'message' : message}) else: form = ContactForm() return render(request, 'contact.html', {'form':form}) ###models.py from django.db import models class Contact (models.Model): name = models.CharField (max_length=100) email = models.EmailField (max_length=100) subject = models.CharField (max_length=100) message = models.CharField (max_length=100) ###forms.py from django import forms from .models import Contact class ContactForm (forms.ModelForm): class Meta: model = Contact fields = ['name', 'email', 'subject', 'message'] ###urls.py urlpatterns = [ path('', views.index, name='index'), path('contact', views.contact, name='contact'), path('thanks', views.thanks, name='thanks'),] ###contact.html <body> <div class="container"> <br /> <form action="contact" method="post"> {% csrf_token %} ... ###thanks.html <body> <div class="container"> <br /> <form action="contact" method="post"> {% csrf_token %} ... -
View with more than one button redirecting to different pages
I have a View (I use FormView) that will render a dropdown option. When I select an option, an Ajax function populate the rest of the Form. After the datas are shown, the user can press different buttons to redirect to other pages. For now, I want just 2 buttons. But I don't know how to do this, I've tried some codes and got nothing, not even got redirect to other page. The first page are "Teste" and the buttons need to redirect to "identificacao", or "mapa". Here are my following code urls.py: path('teste', views.TesteView.as_view(), name="teste"), path('identificacao', TemplateView.as_view(template_name = 'solid/identificacao.html'), name="identificacao"), path('mapa', views.MapaView.as_view(), name="mapa") view.py: class DutosView(generic.FormView): # FormView precisa ser relacionada a um Model. Mesmo que não use ao longo do # programa a variável "model", como é o caso presente. template_name = 'solid/teste.html' form_class = Dutos # success_url = 'solid/mapa.html' # success_url = reverse_lazy('mapa') success_url = '/mapa/' def form_valid(self, form): nomeDuto = form.cleaned_data['nomeDuto'] codigoDuto = DUTO.objects.values_list('DU_CD_ID_Duto',flat = True).filter(DU_DS_Nome_Do_Duto = nomeDuto) self.request.session['nomeDuto'] = nomeDuto latlongs = PIG.objects.values_list("PI_VL_Latitude","PI_VL_Longitude").filter(PI_CD_ID_Duto = codigoDuto) latlongs = [[float(x[0]),float(x[1])] for x in latlongs] latitudeIni = latlongs[0][0] longIni = latlongs[0][1] self.request.session['latlongs'] = latlongs self.request.session['latitudeIni'] = latitudeIni self.request.session['longIni'] = longIni return super().form_valid(form) # I've tried the code above … -
How to make all celery tasks log into one file
I have Django application with such logging configuration. LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'default': { 'format': '%(asctime)s [%(levelname)s] %(filename)s:%(lineno)s: %(message)s' }, }, 'handlers': { 'cron': { 'class': 'logging.FileHandler', 'filename': 'cron.log', 'formatter': 'default', }, 'admin': { 'class': 'logging.FileHandler', 'filename': 'admin.log', 'formatter': 'default', }, 'app': { 'class': 'logging.FileHandler', 'filename': 'app.log', 'formatter': 'default', }, 'core': { 'class': 'logging.FileHandler', 'filename': 'app.log', 'formatter': 'default', }, 'metrics': { 'class': 'logging.FileHandler', 'filename': 'metrics.log', 'formatter': 'default', }, 'pixel': { 'class': 'logging.FileHandler', 'filename': 'pixel.log', 'formatter': 'default', }, }, 'loggers': { 'cron_api': { 'handlers': ['cron'], 'level': 'DEBUG', }, 'main': { 'handlers': ['app'], 'level': 'INFO', }, 'admin': { 'handlers': ['admin'], 'level': 'INFO', }, 'spa_api': { 'handlers': ['app'], 'level': 'INFO', }, 'metrics': { 'handlers': ['metrics'], 'level': 'INFO', }, 'pixel': { 'handlers': ['pixel'], 'level': 'INFO', }, }, } I'd like all celery tasks write to worker (it's executed at) .log file. Is there a way of defining it without creating specific logger for every task? So, instead of writing 'loggers': { 'main.celery_tasks.task1': { ... } } write something like 'loggers': { 'celery': { ... } } Or just define a file when starting worker (with -f param). -
Django Allauth, Twitter Scope
I'd like to get the user email from the twitter oauth. So I requested this in the app settings. I added the scope (to settings.py): SOCIALACCOUNT_PROVIDERS = { 'linkedin': { 'SCOPE': [ 'r_emailaddress', 'r_basicprofile', 'r_fullprofile', ], 'PROFILE_FIELDS': [ 'id', 'first-name', 'last-name', 'positions', 'email-address', 'picture-url', 'public-profile-url', 'headline', 'skills', 'summary', 'location', 'industry', 'positions', 'company', 'specialties', 'public-profile-url', ], 'LOCATION_FIELDS': [ 'location', ], 'POSITION_FIELDS': [ 'company', ] }, 'twitter': { 'SCOPE': ['email'], }, } However, I'm still having the user data like the name, picture ..etc but not the email. Any suggestion ? -
User profiles not being created at sign up
It seemed to be working quite well over the past few days but, since adding follow functionality, profiles are not created when they sign up. I read through the other questions like this one and I see things about using @reciever, do we have to use receivers? I followed a tutorial on how to allow profile creation at the time of sign up, the line goes as follows User.profile = property(lambda u: CustomUserProfile.objects.get_or_create(user=u)[0]) It's in my models.py but not inside of a function nor the profile class, is that my mistake or do we really have to use receivers? Forgive me, I've been teaching myself through tutorials and docs but alot of tutorials were deprecated (and I had no idea) so I just went off on my own and now i'm regretting it. -
How to get / or create a taggit model for each related model?
I want to use taggs, but I have something to do something like: To get all tags added only in Post instances: post_tags.objects.all() To get all tags added only in Snippet instances: snippet_tags.objects.all() How can I do this? -
ModuleNotFoundError: No module named 'ethereum' in django Metamask installation
Now, I'm trying a work for django and metamask connection. But while I tried to runserver, I faced with ... urlconf_module = import_module(urlconf_module) File "C:\Users\Emma\AppData\Local\Programs\Python\Python37-32\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "C:\Users\Emma\Desktop\web3start\web3auth\urls.py", line 3, in <module> from web3auth import views File "C:\Users\Emma\Desktop\web3start\web3auth\views.py", line 10, in <module> from web3auth.forms import LoginForm, SignupForm File "C:\Users\Emma\Desktop\web3start\web3auth\forms.py", line 8, in <module> from .utils import validate_eth_address File "C:\Users\Emma\Desktop\web3start\web3auth\utils.py", line 2, in <module> import ethereum ModuleNotFoundError: No module named 'ethereum' ... So I tried a command such as pip install ethereum, pip install -r requirements.txt, pip install 'rlp==0.6.0' but still error comes out. Anyone can help me with this? -
How to determine if I am currently inside a Redis Task Worker
if i have a function def I_TAKE_A_LONG_TIME(): if I_AM_RUNNING_IN_A_REDIS_WORKER: # do something special # do some stuff that takes a while from rq.job import Job @Job('default') def worker(): return I_TAKE_A_LONG_TIME() sometimes this is called directly, I_TAKE_A_LONG_TIME() other times it is called via worker.delay() (redis task stuff) is there a builtin redis way to tell if I_TAKE_A_LONG_TIME is being run in a task worker vs being run directly? get_current_job() I think returns any the current running job (not necessarily this running job) -
django panda read sql query map parameters
I am trying to connect sql server database within django framework, to read sql query result into panda dataframe from django.db import connections query = """SELECT * FROM [dbo].[table] WHERE project=%(Name)s""" data = pd.read_sql(query, connections[database], params={'Name': input} ) the error message I got is 'format requires a mapping' if I do it something like below, it will work, but I really want to be able to map each parameter with names: from django.db import connections query = """SELECT * FROM [dbo].[table] WHERE project=%s""" data = pd.read_sql(query, connections[database], params={input} ) I was using odbc driver 17 for sql server -
Klaviyo Form shows twice on homepage
I embedded a klaviyo form on shopify and it showed twice on the homepage of the shop I'm working on. I'm quite new to shopify development but know django and a little rails but still get confused on reading codes. <div class="homepage-page {{ section.settings.homepage_page_color }}" data-section-id="{{ section.id }}" data-section-type="index-page"> <div class="klaviyo-form-LLvHeC"></div> {% for block in section.blocks %} <div class="wrapper"> <div class="grid"> {% case block.type %} {% when 'page' %} {% if block.settings.home_page_content != blank %} {% assign page = pages[block.settings.home_page_content] %} {% assign page_src = page.content | escape %} {% if page_src contains '&lt;img' %} {% assign homepage_page_grid = 'one-whole' %} {% else %} {% assign homepage_page_grid = 'large--five-sixths push--large--one-twelfth' %} {% endif %} <div class="grid__item {{ homepage_page_grid }}"> {% if block.settings.home_page_show_title %} <h4 class="home__subtitle">{{ page.title }}</h4> {% endif %} <div class="rte homepage-page__content"> {% unless page == blank or page.empty? %} {{ page.content }} {% else %} {{ 'home_page.onboarding.no_content' | t }} {% endunless %} </div> </div> {% endif %} {% when 'text' %} <div class="grid__item large--five-sixths push--large--one-twelfth"> <div class="rte homepage-page__content"> {% if block.settings.home_page_richtext != blank %} {{ block.settings.home_page_richtext }} {% else %} {{ 'home_page.onboarding.no_content' | t }} {% endif %} </div> </div> {% else %} {% endcase %} </div> … -
Adding a Sold Out option to price field in Django
at present I have a basic shop with a price model defined as a decimal field. price = models.DecimalField(max_digits=10, decimal_places=2) I'd like to be able to keep products visible but add a sold out option. Is there a way to allow this field to include a blank price or a Sold Out option? I had also tried adding another model field that would be tested for truth and displaying sold out otherwise, but this didn't end up showing in template. Here, my idea was: soldout = models.BooleanField(defualt = False) and in the template: {% if product.soldout %} <button type="button" class="btn btn-danger">SOLD OUT!</button> Thanks! -
Fromset ModelChoiceField Initial value
When i edit formset the ModelChoiceField don't show initial value (it show the empty label). I use this example https://whoisnicoleharris.com/2015/01/06/implementing-django-formsets.html demande\forms.py class LinkForm(forms.Form): etabz = forms.ModelChoiceField(empty_label="Choisir un établissement",\ queryset=Etablissement.objects.all().order_by('univ','etablissement').distinct(), ) # etabz = forms.CharField() def __init__(self, *args, **kwargs): dbz = kwargs.pop("dbz", None) super(LinkForm, self).__init__(*args, **kwargs) if dbz: self.fields["etabz"].queryset = Etablissement.objects.filter(univ__corps=dbz) class BaseLinkFormSet(BaseFormSet): def clean(self): if any(self.errors): return anchors = [] urls = [] duplicates = False for form in self.forms: if form.cleaned_data: dona = form.cleaned_data.get('etabz') anchor = dona.etablissement if anchor : if anchor in anchors: duplicates = True anchors.append(anchor) if duplicates: raise forms.ValidationError( 'Vous ne pouvez choisir le même établissement plusiuers fois.', code='duplicate_etab' ) def __init__(self, *args, **kwargs): super(BaseLinkFormSet, self).__init__(*args, **kwargs) for form in self.forms: form.empty_permitted = False Demande\views.py @login_required def demande(request): user = request.user corpsorigine = user.profile.corps uz = get_object_or_404(session, active=True, destine = user.profile.corps) choice_links = choix.objects.filter(demandeur = user, session = uz ) link_data = [{'etabz': l} for l in choice_links] LinkFormSet = formset_factory(LinkForm, formset=BaseLinkFormSet, extra=1) if request.method == 'POST': link_formset = LinkFormSet(request.POST,form_kwargs={'dbz':corpsorigine }) if link_formset.is_valid(): new_links = [] for link_form in link_formset: dona = link_form.cleaned_data.get('etabz') try: univ = dona.univ etablissementa = dona.etablissement except: messages.error(request, 'Une exception à provoqué une erreur. veuillez ré-essayer ultérieurement') return redirect(reverse('blog:post_list')) if etablissementa and … -
How to fix reverse-matching URL error in Django?
I'm making a blog app using Django. The error appears when I click on save button on a new post and the 'Post-Detail' page is not just showing up. I'm trying debugging it since last 2 days but still unable to find the solution. I'm using Django(2.1.7) and the error I'm getting is NoReverseMatch at /post/new/ Reverse for 'post_detail' with no arguments not found. 1 pattern(s) tried: ['post/(?P<pk>\\d+)/$'] There are some other urls as well but I'm just giving the 2 path that most probably creating the errors. I've tried giving simply redirect_field_name='post_detail' in my CreateView but then I get error saying there's no get_absolute_url() method even when I've already added it in the model. Models.py class Post(models.Model): author = models.ForeignKey('auth.user',on_delete=models.PROTECT) title = models.CharField(max_length=200) text = models.TextField() create_date = models.DateTimeField(default=timezone.now) published_date = models.DateTimeField(blank=True,null=True) objects = models.Manager() comments = models.Manager() def publish(self): self.published_date = timezone.now self.save() def approve_comments(self): return self.comments.filter(approved_comment=True) def get_absoulute_url(self): return reverse('post_detail',kwargs={'pk':self.pk}) def __str__(self): return self.title urls.py urlpatterns = [ path('admin/',admin.site.urls), path('',include(blogapp.urls)), ] blogapp.urls urlpatterns = [ ... re_path(r'^post/(?P<pk>\d+)/$',views.PostDetailView.as_view(), name='post_detail'), re_path(r'^post/new/',views.CreatePostView.as_view(),name='post_new'), ... ] views.py class PostDetailView(DetailView): model = Post class CreatePostView(LoginRequiredMixin, CreateView): form_class = PostForm model = Post login_url = '/login/' def get_success_url(self): return reverse('post_detail') post_form.html <h1>New Post</h1> <form … -
How to fix failed sql create table auth_permission error
When trying to migrate using python manage.py migrate() I am facing this error: djongo.sq12mongo.SQLDecodeError: Failed SQL: Create table "auth_permission".... djongo version : 2.2.3 pymongo : 3.2.0 sqlparse : 0.2.4 python : 3.7 mongodb version: 4.0.11 mysqlclient : 1.4.2 error Settings.py: DATABASES = { 'default': { 'ENGINE': 'djongo', 'NAME': 'djangoproject1', } } -
How to setup celery worker to log all task function calls to one file
I have Django application with such logging configuration. LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'default': { 'format': '%(asctime)s [%(levelname)s] %(filename)s:%(lineno)s: %(message)s' }, }, 'handlers': { 'cron': { 'class': 'logging.FileHandler', 'filename': 'cron.log', 'formatter': 'default', }, 'admin': { 'class': 'logging.FileHandler', 'filename': 'admin.log', 'formatter': 'default', }, 'app': { 'class': 'logging.FileHandler', 'filename': 'app.log', 'formatter': 'default', }, 'core': { 'class': 'logging.FileHandler', 'filename': 'app.log', 'formatter': 'default', }, 'metrics': { 'class': 'logging.FileHandler', 'filename': 'metrics.log', 'formatter': 'default', }, 'pixel': { 'class': 'logging.FileHandler', 'filename': 'pixel.log', 'formatter': 'default', }, }, 'loggers': { 'cron_api': { 'handlers': ['cron'], 'level': 'DEBUG', }, 'main': { 'handlers': ['app'], 'level': 'INFO', }, 'admin': { 'handlers': ['admin'], 'level': 'INFO', }, 'spa_api': { 'handlers': ['app'], 'level': 'INFO', }, 'metrics': { 'handlers': ['metrics'], 'level': 'INFO', }, 'pixel': { 'handlers': ['pixel'], 'level': 'INFO', }, }, } Also I have a celery worker. I want to log every activity that happens inside the task to celery_worker.log, even if task calls a function from main or cron_api application. For example: If main.celery_tasks.task1.task1 calls main.service.google.get_campaign, I want all logs from get_campaign to be in worker.log. Also I want no logs related to this task to be in app.log. How to achieve this? P.S.: Also I'd like to have a scalable … -
is there any way to solve" project=Project.objects.get(pk=pk) "
why is it that when I visit http://127.0.0.1:8000/project/1/ an error occur it says DoesNotExist and when I try http://127.0.0.1:8000/project/2/ it works without any error.i think the problem is either in urls.py or views.py my url code : ` urlpatterns =[ url(r'^$', views.firstindex, name='firstindex'), url(r'^(?P<pk>[0-9]+)/',views.project_detail, name='project_detail'),] and this is the view.py `def project_detail(request,pk): project=Project.objects.get(pk=pk) context={ 'project':project } return render(request,'project/detail.html') . -
NoReverseMatch at /1/ipd/
I am trying to create the list of all Ipd that are created using form, I am trying to redirect the form page to Idp list after I submit for Ipd form but ending with this error "NoReverseMatch at /1/ipd/", One thing I want to clear is each Ipd is having unique id and Ipd is created from patient with one to many relationship which also have another unique id , the number which is in the error is patient id views.py @login_required def ipd(request, patient_id): object = get_object_or_404(Patient,pk=patient_id) if request.method == "POST": formtwo = IpdForm(request.POST) if formtwo.is_valid() : instance = formtwo.save(commit=False) instance.save() return HttpResponseRedirect(reverse('ipd_list', args=[patient_id])) else: return HttpResponse(formtwo.errors) else: formtwo = IpdForm() return render(request, 'newipd.html', {'object':object, 'form2': formtwo}) @login_required def ipd_list(request): ipdlist = Ipd.objects.all() return render(request, 'Ipdlist.html', {'ipd': ipdlist }) urls.py re_path(r'^(?P<patient_id>\d+)/ipd/$', my_patient.ipd, name='ipd'), path(r'^ipdlist/', my_patient.ipd_list,name='ipdlist' ), -
How to connect metamask to django through vscode?
I'm now working with blockchain project in hurry. This is my first project, and I have no idea where to start. All I want to do is Connecting Metamask with django web page. I want delicate description because I don't that much basic programming skills. I first started with this, https://django-web3-auth.readthedocs.io/en/latest/readme.html but is it OK to start in QUICK START menu without any settings in advance? I need your help desperately. Thank you! -
How do I get a background color to fill the entire page and fade into a picture with an svg on top?
I created a grey color background so I could overlay it on top of a picture I currently have. The picture is in a urls.py file and is passed as the background. I want the grey to fade into a picture but the grey background isn't covering up the entire screen just some of it. I know it has to do with the padding and margins probably but I am pretty new to html and css. I also have an animation I made with an svg I want to be on top of the grey background. It is doing the fading part but after 10 seconds the grey color comes back and doesn't disappear. I am also using my django server as my backend to run the website. I have tried making the margins and padding 0 which didn't work and also varying the numbers on the margins and padding which doesn't make it fill the whole website. Here's my code.pen so it's easier to see https://codepen.io/anon/pen/zgzxRz html code <html> <div id="header"> <div id="content"> <head> <style> body { font-family: 'Arimo'; height: 100%; margin: 0; } .animated { background-color:grey; background-repeat: no-repeat; -webkit-animation-duration: 10s;animation-duration: 10s; padding: 0 0; margin:10px; } @-webkit-keyframes fadeOut … -
I've stuck on this for days now gunicorn is using the old virtual environment even after unistalling it and deleting the directory?
I deployed a Django project on an ubuntu server using gunicorn and Nginx but I had to delete the project and use a new Github repo and set a new virtual env so I deleted the virtual env and deleted gunicorn.config and removed and installed Nginx and tried deploying the app it started giving weird errors and finally no when I ran sudo journalctl -u gunicorn i found that it still refers to the old env and gives a file not found error. How can I reset it correctly? -
Django null value in column "project_id" violates not-null constraint
So I can see why this is happening, the page is not linking to the project I am trying to update, but I don't know how this is done, I thought that was what "get_object" method was for, but I'm clearly not using it properly. I can get this working if I uncomment "project" in the form which lets me choose which project I am attempting to update from a dropdown, however, I would like to do away with that field and have the update dynamically linked to the project. Here is my models: class Project(models.Model): date_published = models.DateTimeField(auto_now_add=True) user = models.ForeignKey(User, null=True, on_delete=models.SET_NULL) area = models.ForeignKey(Area, on_delete=models.PROTECT) title = models.CharField(max_length=128, unique=True) slug = models.SlugField(max_length=64) summary = models.CharField(max_length=256) others = models.CharField(max_length=128, blank=True) deadline = models.DateField(null=True, blank=True) priority = models.ForeignKey(Priority, on_delete=models.PROTECT) closed = models.DateTimeField(null=True, blank=True) def save(self, *args, **kwargs): if not self.id: self.slug = slugify(self.title) super(Project, self).save(*args, **kwargs) def __str__(self): return self.title class Update(models.Model): project = models.ForeignKey( Project, on_delete=models.CASCADE, related_name='updates' ) category = models.ForeignKey(UpdateCategory, on_delete=models.PROTECT) update = models.TextField(max_length=240, blank=True) added = models.DateTimeField(auto_now_add=True) class Meta: ordering = ["-added"] def __str__(self): return self.update forms.py class ProjectUpdateForm(forms.ModelForm): update = forms.CharField() class Meta: model = Update fields = [ # 'project', 'category', 'update' ] views.py … -
I want to add dynamic input box on button click and then save the value into database (postgresql)
This is my button <input type="button" value="add-entry" id="add"> This is the ajax call made on clicking the button <script> $(document).ready(function(){ $("#add").click(function(e){ event.preventDefault() var htmlAppend='<div><table><tr><td><input type="text" name="user-name"></td></tr>'+ // '<tr><td><input type="text" name="e-mail"></td></tr>'+ '<input type="button" value="delete" id="delete" /></table></div>' $('#items').append(htmlAppend); localStorage.setItem("htmlAppend", htmlAppend); }); var htmlAppend = localStorage.getItem("htmlAppend"); if (htmlAppend) { $("#items").append(htmlAppend); } $('body').on('click','#delete',function(e){ $(this).parent('div').remove(); }); }); </script> The problem is if I click on button 2 times then the name of the input field will be same then how can I fetch the value of two different text boxes with the same name. Please suggest any other way if possible. -
Child class post method to return different template and context
I want to be able to take the same form input and use it to do calculations (using different urls) for different products and send product results to a product template I tried having a base class with get and post methods from which child classes(different product urls) will inherit especially the post method to remain DRY from .models import InputForm class InputView(TemplateView): template_name = 'input.html' def get(self, request, *args, **kwargs): form = InputForm() return render(request, self.template_name, {'form': form}) def post(self, request, *args, **kwargs): form = InputForm(request.POST) if form.is_valid(): self.cleaned_data = form.cleaned_data a =cleaned_data['mbr_l'] b =cleaned_data['es_l'] c =cleaned_data['wic_l'] d =cleaned_data['br2_l'] length = a + b + c + d qty = 0.8*length return render(request, 'result.html', {'qty': qty}) else: return render(request, self.template_name, {'form': form}) class B(InputView): def post(self, request, *args, **kwargs): qty2 = super().post(self, request, *args, **kwargs) return super().render(request, 'result2.html', {'qty2': qty2}) I expect the url B in url conf to do calculation and send context(qty2) to results2.html but it always renders results.html with qty which is correct because B is inheriting InputView and all methods. -
ManyToOneRel field for Following functionality?
I read this question thread ( Difference between ManyToOneRel and ForeignKey? ) and I'm not understanding it completely. I need a many to one relationship so I can add in following functionality. Tried with a many to many and that makes two users follow each other even when one didn't want to (if one user clicks 'follow' then it acts as though the other did the same.) Question is, will I need to use a ManyToOneRel field for the followers (who follows the logged in user) and the same for who the user is following? Forgive me, I'm teaching myself everything and some stuff can be difficult to grasp at times. -
Django 1.8-1.11 upgrade error, AttributeError: type object 'DemoModel' has no attribute 'lower'
I am upgrading my app from Django 1.8 to 1.11. When I try to run migrations or tests I am getting the following error. On debugging I can see that method is_referenced_by_foreign_key is expecting f.related_model to be string, but in my case its actually an instance. Can some one please help with this. ipdb> c Traceback (most recent call last): File "formtastic/manage.py", line 11, in <module> execute_from_command_line(sys.argv) File "/home/vagrant/.virtualenvs/py3/lib/python3.6/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File "/home/vagrant/.virtualenvs/py3/lib/python3.6/site-packages/django/core/management/__init__.py", line 356, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/vagrant/.virtualenvs/py3/lib/python3.6/site-packages/django/core/management/commands/test.py", line 29, in run_from_argv super(Command, self).run_from_argv(argv) File "/home/vagrant/.virtualenvs/py3/lib/python3.6/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/home/vagrant/.virtualenvs/py3/lib/python3.6/site-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/home/vagrant/.virtualenvs/py3/lib/python3.6/site-packages/django/core/management/commands/test.py", line 62, in handle failures = test_runner.run_tests(test_labels) File "/home/vagrant/.virtualenvs/py3/lib/python3.6/site-packages/django/test/runner.py", line 601, in run_tests old_config = self.setup_databases() File "/home/vagrant/.virtualenvs/py3/lib/python3.6/site-packages/django/test/runner.py", line 546, in setup_databases self.parallel, **kwargs File "/home/vagrant/.virtualenvs/py3/lib/python3.6/site-packages/django/test/utils.py", line 187, in setup_databases serialize=connection.settings_dict.get('TEST', {}).get('SERIALIZE', True), File "/home/vagrant/.virtualenvs/py3/lib/python3.6/site-packages/django/db/backends/base/creation.py", line 69, in create_test_db run_syncdb=True, File "/home/vagrant/.virtualenvs/py3/lib/python3.6/site-packages/django/core/management/__init__.py", line 131, in call_command return command.execute(*args, **defaults) File "/home/vagrant/.virtualenvs/py3/lib/python3.6/site-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/home/vagrant/.virtualenvs/py3/lib/python3.6/site-packages/django/core/management/commands/migrate.py", line 163, in handle pre_migrate_state = executor._create_project_state(with_applied_migrations=True) File "/home/vagrant/.virtualenvs/py3/lib/python3.6/site-packages/django/db/migrations/executor.py", line 81, in _create_project_state migration.mutate_state(state, preserve=False) File "/home/vagrant/.virtualenvs/py3/lib/python3.6/site-packages/django/db/migrations/migration.py", line 92, in mutate_state operation.state_forwards(self.app_label, new_state) File "/home/vagrant/.virtualenvs/py3/lib/python3.6/site-packages/django/db/migrations/operations/fields.py", line 209, in state_forwards not …