Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to edit value of a record when Django admin page of the model gets opened
In my Django app, I have a model that has an IntegerField for holding the number of queries done today and another field that holds the date of last modification of that field. class logs(models.Model): today_queries = models.IntegerField("today's queries", default=0, help_text="Total number of today's queries.") update_date = models.DateField(default=datetime.date.today) My problem is that every time I open the Django admin page for the logs model, the value for today_queries gets retrieved and shown (the default behavior obviously) but that number would be incorrect if tomorrow and other days come (it should be 0). How can I edit the value of today_queries as soon as the Django admin page for the logs model gets opened (so that I compare update_date with now and if it is a new day, reset the value of today_queries) -
Django page navigation- home list not visible
I am super new to Dango; pardon me for a rookie question :) I am learning Django by creating a "Note taking app". This is how the application home page looks. When I click on any of the notes from the note list, it opens the details on the right-side page. But the problem is it wipes-out the left-hand side note list. To reload the list I need to click on the Home link again. The expected behavior is, it should retain the note-list on the left side as well as show the details on the right frame. urls.py from django.urls import path from .views import NoteListView, NoteDetailView, NoteCreateView, NoteUpdateView, NoteDeleteView from . import views urlpatterns = [ path('', NoteListView.as_view(), name='lekha-home'), path('note/<int:pk>/', NoteDetailView.as_view(), name='note-detail'), path('note/new/', NoteCreateView.as_view(), name='note-create'), path('note/<int:pk>/update', NoteUpdateView.as_view(), name='note-update'), path('note/<int:pk>/delete', NoteDeleteView.as_view(), name='note-delete'), path('about/', views.about, name='lekha-about'), ] enter code here views.py class NoteListView(ListView): model = Note template_name = 'lekha/home.html' context_object_name = 'notes' ordering = ['-date_created'] class NoteDetailView(DetailView): model = Note # success_url = 'lekha/note_detail.html' class NoteCreateView(LoginRequiredMixin, CreateView): model = Note fields = ['title', 'content'] def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) home.html {% extends "lekha/base.html" %} {% block content %} {% for note in notes %} <div class="list-group"> <a … -
Is it necessary to create new app for homepage models in Django?
I want to add a slider to my homepage. What is best way to do it? Should I create a new app for slider? Or can I create a class for slider in home(app)/models.py? I tried to create Slider class in home/models.py. But I couldn't list on homepage. home/views.py def slider_index(request): slides = Slider.objects.all() return render(request, 'home.html', {'slides': slides}) def slider_detail(request, id): slide = get_object_or_404(Slider, id=id) context = { 'slide': slide, } return render(request, 'home.html', context) home/models.py class Slider(models.Model): title = models.CharField(max_length=120, verbose_name='Başlık') content = models.TextField(verbose_name='Açıklama') publishing_date = models.DateTimeField(verbose_name='Yayınlanma Tarihi', auto_now_add=True) image = models.ImageField(null=True, blank=True) def __str__(self): return self.title def get_absolute_url(self): return reverse('slide:detail', kwargs={'id': self.id}) # return "/slider/{}".format(self.id) class Meta: ordering = ['-publishing_date', '-id'] urls.py urlpatterns = [ path('admin/', admin.site.urls), path('', home_view), path('slider/', slider_index, name='index'), path('slider/<int:id>/', slider_detail, name='detail'), path('post/', include('post.urls')), ] and home.html: {% for slide in slides %} <!-- Slide #1 image --> {% if slide.image %} <img src="{{ slide.image.url }}" alt="{{ slide.content }}" title="{{ slide.title }}" /> {% endif %} {% endfor %} Nothing appears about slider. I'm newbie in django. I want to learn how to list slides in homepage. Thanks in advance. -
Django interaction with Gitlab API
How to use Gitlab API in Django app e.g for Ruby on Rails there is Gitlab API wrapper gem and for Django there is no such equivalent. I want to see repositories for given user/organization. -
Best practice to schedule a long running django batch job on Heroku
I have developed a Django web application that runs in Heroku. Everything has been working fine using 1 web dyno. Now I need to run a web scrapping batch job (also in Django) that takes approximately 12 hours to complete. I plan to execute it twice a week. Which would be the best way to accomplish this? Heroku documentation recommends using worker dynos and a scheduler to initiate the request. As far as I know, If I implement it this way I will have to pay for an entire worker dyno even if it is used only 24 hours a week. The other option is to execute the batch job within the scheduler but Heroku does not recommend executing long lasting processes that way. Any suggestions? Thanks. -
Object not being saved in Celery task
I am using celery=4.3 Django package and Django 2.2.6. I noticed that object is not saved when I try to update it from celery task function @app.task def update_object(object_id, points): object = MyObject.objects.get(pk=object_id) object.update_points(points) My object looks like this: class MyObject(models.Model): .... def update_points(self, points): self.points += points self.save() I am calling celery task with: update_object.delay(object_id, points) And this doesn't work :/ Does anyone have some suggestion why? -
Django Unit Test - ID's of created objects
Sample models.py models.py class Food(models.Model): name = models.CharField(max_length=50, verbose_name='Food') def __str__(self): return self.name Suppose that I have written unit test/s: from django.test import TestCase from myapp.models import Food class TestWhateverFunctions(TestCase): """ This class contains tests for whatever functions. """ def setUp(self): """ This method runs before the execution of each test case. """ Food.objects.create(name='Pizza') # Will the created object have id of 1? Food.objects.create(name='Pasta') # Will the created object have id of 2? def test_if_food_is_pizza(self): """ Test if the given food is pizza. """ food = Food.objects.get(id=1) self.assertEqual(food.name, 'Pizza') def test_if_food_is_pasta(self): """ Test if the given food is pasta. """ food = Food.objects.get(id=2) self.assertEqual(food.name, 'Pasta') I was wondering if it's safe to assume that the id's of the created objects in setUp() method will always start at id 1 and so on and so forth? If not, is there a specific reason why if the test database is always destroyed after running all tests? -
Can`t deploy Django app in Heroku via Github
First of all, I tried to deploy my app with heroku website. My action algorithm: 1) Choose app name and region. 2) Select Deploy tab to deploy app by Github. 3) Choose my repo and press Deploy Branch button, with master branch selected. Here is were I'm got firt error: ! No default language could be detected for this app. HINT: This occurs when Heroku cannot detect the buildpack to use for this application automatically. See https://devcenter.heroku.com/articles/buildpacks ! Push failed 4) Select Settings tab and add heroku/python buildpack Second error is: -----> App not compatible with buildpack: https://buildpack-registry.s3.amazonaws.com/buildpacks/heroku/python.tgz More info: https://devcenter.heroku.com/articles/buildpacks#detection-failure ! Push failed First what I found about this error, is: this. But, I already got requirments.txt', andProcfile, and, I tried to put my.git` folder inside of project directory, and whole app generally. I also tried to uninstall and install this python buildpack myself through heroku CLI , but, still, nothing works. You can view my github repo here. Also, I will update this post if will find an answer. -
Dynamically change the buttons in Navbar FE: Bootstrap, BE: Django
How to change Log-in to Logged-in in the dropdown menu once the user has logged in. FE: Bootstrap BE: Django login.html: {% extends 'base.html' %} {% load staticfiles %} {% load crispy_forms_tags %} {%block login%} <body> <link rel='stylesheet' href='{%static "css/main1.css" %}'/> <div class='row'> <div class='col-md-5 col-md-offset-1'> <h1> {{ title }}</h1> <form method="Post" action="">{%csrf_token%} {{form|crispy}} <input type='submit' value='submit form' class=btn 'btn-default' /> </form> </div> </div> </body> {%endblock%} Navbar.html: <li {%if request.path == login%} class="active"{%endif%}><a href="{%url 'login'%}">Login</a></li> <li {%if request.path == register%} class="active"{%endif%}><a href="{%url 'register'%}">Register</a></li -
Django inlineformset_factory how to properlu override the __init__ function
everyone! I'm trying to pass a value to the init function and fill one of my field with data from another model. I hardcoded the value to get the right data in my field. I want to know, how to pass initial values into init function? I found a lot of solutions but they doesn't work for me. I've tried to pass primary key into initial func: forms.py class ObservationPartsForm(forms.ModelForm): def __init__(self, pk=None, *args, **kwargs): super(ObservationPartsForm, self).__init__(*args, **kwargs) primary = kwargs.get('pk') print('Get pk',primary) #Get pk None instance = kwargs.get("instance") meteostation = MeteoStation.objects.get(id=pk) if instance == None: meteoparam = forms.ModelChoiceField( queryset=meteostation.meteo_parametrs.select_related().filter(is_active=True), label='Метеопараметр', ) self.fields['meteoparam'] = meteoparam else: value_selected = forms.ChoiceField(label='Значение для выбора') self.fields['value_selected'] = value_selected #print(instance) class Meta(): model = ObservationParts fields = ('meteoparam', 'value_digit', 'value_selected', 'author_parts', 'who_updated') ObservationEntireFormset = inlineformset_factory(ObservationEntire, ObservationParts, form=ObservationPartsForm, extra=1, ) views.py class ObservePartsCreateView(CreateView): template_name = 'dairy/test.html' model = ObservationParts #form_class = ObservationPartsForm success_message = 'Метеопараметры добавлены к наблюдению.' formset = None def get_form(self, form_class=None, **kwargs): pk_ = self.kwargs.get("pk") print(pk_) form = ObservationPartsForm(pk=pk_) return form def get_initial(self, **kwargs): initial = super(ObservePartsCreateView, self).get_initial() initial['value_selected'] = ObserveDate.objects.all() return initial def get(self, request, *args, **kwargs): pk_ = kwargs.get("pk") observe_entire = ObservationEntire.objects.get(pk=pk_) self.formset = ObservationEntireFormset(instance=observe_entire) return super(ObservePartsCreateView, self).get(request, *args, **kwargs) def … -
how to test django get_absolute_url with unittest
I am trying to test get_absolute_url with unittest but i keep failing to pass the test. Any thought on how to test it properly? models.py class Address(models.Model): venue = models.CharField(max_length=1000) longitude = models.CharField(max_length=1000) latitude = models.CharField(max_length=1000) postal_code = models.IntegerField() person = models.ForeignKey(User, on_delete=models.CASCADE, related_name='person_addresses') def __str__(self): return self.venue def get_absolute_url(self): return reverse('core:address_detail', kwargs={'pk': self.pk }) urls.py from django.contrib import admin from django.urls import path, include from . import views app_name = 'core' urlpatterns = [ path('', views.address_list, name='address_list'), path('<int:id>/', views.address_detail, name='address_detail'), ] test_models.py from django.test import TestCase from core.models import Address from django.contrib.auth import get_user_model from django.urls import reverse User = get_user_model() class AddressModelTest(TestCase): def setUp(self): self.user = User.objects.create(username='amanda', password='amanda') self.address = Address.objects.create( venue="901 S Miami Ave, Miami, FL", person=self.user, longitude="-80.193039", latitude="25.765051", postal_code="33130", ) def test_address_get_absolute_url(self): # I tried 'self.client.post' and 'self.client.get' below, both are not working. response = self.client.post(reverse('core:address_detail', kwargs={'pk':self.address.pk})) self.assertEqual(response, self.address.pk) error from console django.urls.exceptions.NoReverseMatch: Reverse for 'address_detail' with keyword arguments '{'pk': 4}' not found. 1 pattern(s) tried: ['(?P<id>[0-9]+)/$'] Any help would be much appreciate. -
Object of type 'AttributeError' is not JSON serializable
I have just started learning Django and was trying to create an API. It is a simple API which fetches a definition from the table and returns it as a response. But whenever I am trying to send a keyword in the request, I am getting the error, Object of type 'AttributeError' is not JSON serializable. What am I doing wrong in here? @api_view(['POST']) def getdetails(request): try: connection = sqlite3.connect('{}.db'.format('insure')) cursor = connection.cursor() plan = json.loads(request.body.decode('utf-8')) cursor.execute( """SELECT INSURANCE_TYPE_DESC FROM tblInsurancePlans WHERE INSURANCE_TYPE LIKE '%{}%'""".format(plan) ) rows = cursor.fetchall() for row in rows: return JsonResponse(str(row), safe=False) except Exception as e: return Response(e) However, when I try to hard-code the keyword (plan), it works and I get the response. -
DJANGO_SETTINGS_MODULE (error generated in code for Python Crash Course)
All good with Django setup, virtual env, etc. until I simply run the models.py to define models. Writing and running the code in VS Code for Windows. Run it in terminal session. I've tried editing the settings file in learning_log directory but did not solve the problem. For example, I added the last line to settings: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'learning_log', ] Also tried adding this line to settings: DJANGO_SETTINGS_MODULE=learning_log.settings Here is the offending code: from django.db import models class Topic(models.Model): """A topic the user is learning about.""" text = models.CharField(max_length=200) date_added = models.DateTimeField(auto_now_add=True) --snip-- Here is the error message from the terminal: c:/Users/Jeff/py_projects/learning_log/models.py Traceback (most recent call last): File "c:/Users/Jeff/py_projects/learning_log/models.py", line 3, in <module> class Topic(models.Model): File "C:\Users\Jeff\py_projects\env\lib\site- packages\django\db\models\base.py", line 103, in __new__ app_config = apps.get_containing_app_config(module) File "C:\Users\Jeff\py_projects\env\lib\site- packages\django\apps\registry.py", line 252, in get_containing_app_config self.check_apps_ready() File "C:\Users\Jeff\py_projects\env\lib\site- packages\django\apps\registry.py", line 134, in check_apps_ready settings.INSTALLED_APPS File "C:\Users\Jeff\py_projects\env\lib\site- packages\django\conf\__init__.py", line 79, in __getattr__ self._setup(name) File "C:\Users\Jeff\py_projects\env\lib\site- packages\django\conf\__init__.py", line 64, in _setup % (desc, ENVIRONMENT_VARIABLE)) django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. -
Django rest framework multiple fields to one
class Wall(BaseComponent): studs_material = models.CharField(max_length=255, null=True, blank=True) studs_spacing = models.FloatField(null=True, blank=True) studs_size = models.CharField(max_length=255, null=True, blank=True) I have a model that must represent flatten data from different sources. To validate data from this sources I'm using DRF Serializers. I faced the issue how to elegant group 3 fields into one in representation method. Data comes to me in following format: { `studs`: 'Steel, 2x4, 16' } I use model serializer and use source='*' to populate data class FoundationWallSerializer(serializers.ModelSerializer): studs = StudTypeSerializer(source='*', required=False) class Meta: model = Wall fields = ('studs',) in child serializer I do the following thing: class StudTypeSerializer(serializers.Serializer): """ StudType objects are serialized into 'Steel, 2x4, 16&quot; o.c.' notation. """ MATERIAL_CHOICES = ( ('Steel', 'steel'), ) size = serializers.CharField( source='studs_size', label='Type of stud, joist, etc. (2x4, 2x6, etc)') spacing = serializers.FloatField( source='studs_spacing') material = SimulationMappingField(source='studs_material', choices=MATERIAL_CHOICES) def create(self, validated_data): raise NotImplementedError def update(self, instance, validated_data): raise NotImplementedError def to_representation(self, instance): try: material = instance.pop('material') size = instance.pop('size') spacing = instance.pop('spacing') except KeyError: return 'None' return f'{material}, {size}, {spacing}\'\' o.c.' def to_internal_value(self, data): if data == 'None': return {} material, size, spacing = [col.strip() for col in data.split(',')] return { 'material': material, 'size': size, 'spacing': spacing } Problem when … -
Django: Filtering one models records to show all records of other model
I'm trying to filter all subjects from my model subjects, and then show all the evaluations within that subject from my other model evaluations for a specific employee which is also a model. So when I click on a subject, which are fetched from my subject model, I want to get all the evaluations for that employee within that subject. I'm thinking each of the subjects are buttons or anchor tags that when clicked show the evaluations within that subject. Subject model class Subject(models.Model): id = models.AutoField(primary_key=True) subjectname = models.CharField(max_length=255, help_text="Indtast navnet på faget.") slug = models.SlugField(max_length=200, unique=True) Evaluation model class Evaluation(models.Model): id = models.AutoField(primary_key=True) employee_num = models.ForeignKey('Employee', on_delete=models.CASCADE, null=True) subjectname = models.ForeignKey('Subject', on_delete=models.CASCADE, null=True) Employee model class Employee(models.Model): id = models.AutoField(primary_key=True) slug = models.SlugField(max_length=200) employee_num = models.IntegerField(help_text="Indtast medarbejderens MA-nummer. (F.eks 123456)") firstname = models.CharField(max_length=30, help_text="Indtast medarbejderens fornavn.") lastname = models.CharField(max_length=30, help_text="Indtast medarbejderens efternavn.") subjectname = models.ForeignKey('Subject', on_delete=models.CASCADE, null=True) Employee subject view class EmployeeDetailView(DetailView): template_name = 'evalsys/employee/alle_employees_eval.html' model = Employee # Uses employee PK to make a detail view def view_employee_with_pk(self, pk=None): if pk: employee = Employee.objects.get(pk=pk) else: employee = self.employee args = {'employee': employee, } return render(self, 'evalsys/employee/alle_employees_eval.html', args) def get_context_data(self, **kwargs): context = super(EmployeeDetailViewDetailView, self).get_context_data(**kwargs) context['evaluation'] = Evaluering.objects.all() … -
How to fix ImportError: cannot import name 'HTTpResponse' from 'django.http'
After several trials, I still get the same ImportError: cannot import name 'HTTpResponse' from 'django.http' (/Users/mac/my_env/lib/python3.7/site-packages/django/http/init.py) after running '$ python manage.py runserver' in the terminal. Can someone please enlighten me with this issue? Thanks! The code below were originally taken from the Django tutorial on its official website. from django.shortcuts import render from django.http import HTTpResponse def index(request): return HTTpResponse("Hello, world. You're at the polls index.") -
I have a comment model on home page, but it does not autoly detect which post I am writing my comment amongst all posts
So the error I am encountering. Pk can not be recognized. Because there are too many posts on the main page. I have been trying yto solve this by changing pk to id, changing my models of comments many ways. But there is no use The real reason is that ı have to go into detailview so that page can easily detect. Oh look he is here on this page path('post//', PostDetailView.as_view(), name ="post-detail"), so we can save this comment on a spesific post.pk. But I want everything is connected NameError at / name 'pk' is not defined class PostListView(ListView, DetailView): model = Post template_name = "blog/home.html" # <app>/model>_viewtype>html context_object_name = "posts" paginate_by = 15 template = loader.get_template('blog/post_detail.html') def get(self, request, *args, **kwargs): posts = Post.objects.all().order_by("-id") gallerys = Gallery.objects.all() comments = Comment.objects.filter() likes = Post.objects post = request.POST.get(Post) # cnc = Contact.objects.all() today = timezone.now().date() is_liked = False # if posts.likes.filter(id = request.user.id).exists(): # is_liked = True comment_form = CommentForm(request.POST or None) context = { 'posts': posts, "likes": likes,"comment_form":comment_form, "comments": comments, "gallerys":gallerys, "today": today} # return render(request, "blog/home.html") return render(request, "blog/home.html", context) def post(self, request, *args, **kwargs): form = PostForm() posts = Post.objects.all().order_by("-id") data2 = Gallery.objects.all() comments = Comment.objects.filter() likes … -
Is there a way to control the behavior of django-from wizard done() method?
I have 3 forms in django-form wizard which are rendered correctly. After the last form has been filled up, I want to display data of all 3 forms on done.html page using done() method and add a submit button on done.html which will submit the data to the the same or any other view so that I can save it in database. I have to save data across multiple tables so I need to extract data individually from the request object. I have overloaded the done() method in a way to display the data on the page and it is also able to save data in DB. But I want to just display data using done method() and have a submit button on the done.html page to POST the request so that I can save data in DB later. views.py class FormWizardView(SessionWizardView): template_name = 'crispyFormTemplate.html' form_list = [Form1,Form2,Form3] def done(self, form_list,form_dict, **kwargs): return render(self.request, 'done.html', {'form_data': [form.cleaned_data for form in form_list], 'no_of_pages':len(form_list)}) done.html {% extends 'base.html' %} {% block container_body %} <h1>This is done page</h1> <h6>NUmber of pages are: {{ no_of_pages }}</h6> <ul> {% for f in form_data %} <p>{{ forloop.counter }}</p> <li>{{ f }}</li> {% endfor %} </ul> {% … -
HTML - Disabling a widget in one of my pages
I need to disable a widget for some of my pages, How can i do it? A hard try that i thought will be to somehow put a condition in the html (django or php?) of the widget that if the site URL != the URL i don't want. it will appear. How can i do it? Any other different method? the widget code is: <div class="{%- if settings.cart_position == 'side' -%}jas-mini-cart jas-push-menu{%-else-%}dropdown-cart{%-endif-%}"> {%- if settings.cart_position == 'side' -%} <h3 class="mg__0 tc cw bgb tu ls__">{{ 'cart.widget.title' | t }}<i class="close-cart pe-7s-close pa"></i></h3> {%- endif -%} <div class="widget_shopping_cart pr"> <div class="widget_shopping_cart_content"> {%- include 'cart_body' -%} </div> </div> </div> -
quero passar base64 do template para a view
I have a variable that gets a base64 I need to pass to my django view, but it's too big a format to pass in url, how could I pass it? -
Django-Tenants - How to name domain when running in Docker
I want to create the shared tenant and customer tenant schemas with django-tenants, but I'm unsure how to name them since I'm running in a Docker container from 0.0.0.0. from customers.models import Client, Domain domain = Domain() domain.domain = 'my-domain.com' # don't add your port or www here! on a local server you'll want to use localhost here domain.tenant = tenant domain.is_primary = True domain.save() I've tried domain.domain ='t1.0.0.0.0' (for my customer tenant) or domain.domain = '0.0.0.0' (for my shared tenant) with no success. -
Django Rest Framework: Updating subobject with new route, not partial update to model
I'm trying to create an API object, Roster, which has a list of Members as a subobject on it. However, I do not want to update the subobject by partially updating the Roster object -- instead, I want a route for "add member" and "remove member". Goal: GET /Roster/{ROSTERID} response body: { id: {roster id}, members: # members sub object is read only [ {member subobject}, {member subobject}, ... ], } POST /Roster/{RosterID}/AddMember { {member id}, {member id}, ... } and then a similar thing for removing a member. Note: I want to be able to pass a existing member id in. I don't want to create new members here. What should I be looking for in the docs to be able to add a route to update the member list with a user id, instead of having to pass in the whole user object? serializers.py class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['url', 'username', 'email', 'groups'] class RosterSerializer(serializers.ModelSerializer): members = serializers.ListField( child=UserSerializer() ) class Meta: model = Roster fields = ('id', 'name', 'members') depth = 2 app/models.py class Members(User): on_pto = models.BooleanField(default=False) class Roster(models.Model): objects = models.Manager() name = models.CharField(max_length=80, blank=True, default='', unique=True, null='') members = models.ForeignKey( … -
Add data to modelserializer field based on request
Basically what I am looking for is to auto-populate the two fields created_by and last_modified_by based on a fixed value. class SupportingAttachment(models.Model): order = models.ForeignKey(Order,null = True,blank = True) file = models.FileField(upload_to= upload_supporting_attachment, null=True, blank=True) created_by = models.ForeignKey(User,blank = True,related_name = 'support_created_by') created = models.DateTimeField(auto_now_add=True) last_modified_by = models.ForeignKey(User,blank = True,related_name = 'support_modified_by') last_modified = models.DateTimeField(auto_now=True) As of now, as a makeshift solution, I am writing a manual serializer and adding the data by overriding the validate function and calling create. def validate(self, attrs): userid = self.context['request'].user.id x = attrs.update({"created_by": userid, "last_modified_by": userid}) return attrs I want to do this in a ModelSerializer without specifying the fields manually. I am assuming I have to override one of the functions of the ModelViewSet or the CreateAPIView So which function do I override on the View layer to set the user_id on the two fields and pass it to the serializer? Also is this the correct way of doing it? -
Djagno: django.db.utils.InternalError: (1046, u'No database selected')
I'm trying to use Django with mariadb 10.4.8 My settings.py file is as follows: DATABASES = { 'default': { 'NAME:': 'mydb', 'ENGINE': 'django.db.backends.mysql', 'USER': 'staff', 'PASSWORD': 'mypassword', 'HOST': 'localhost', 'PORT': '', } } In init.py: import pymysql pymysql.install_as_MySQLdb() "./manage.py makemigrations" and "./manage.py migrate" yield the same error: File "./manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/home/ubuntu/wemu_app/wemu_app_env/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File "/home/ubuntu/wemu_app/wemu_app_env/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 356, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/ubuntu/wemu_app/wemu_app_env/local/lib/python2.7/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/home/ubuntu/wemu_app/wemu_app_env/local/lib/python2.7/site-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/home/ubuntu/wemu_app/wemu_app_env/local/lib/python2.7/site-packages/django/core/management/commands/migrate.py", line 83, in handle executor = MigrationExecutor(connection, self.migration_progress_callback) File "/home/ubuntu/wemu_app/wemu_app_env/local/lib/python2.7/site-packages/django/db/migrations/executor.py", line 20, in __init__ self.loader = MigrationLoader(self.connection) File "/home/ubuntu/wemu_app/wemu_app_env/local/lib/python2.7/site-packages/django/db/migrations/loader.py", line 52, in __init__ self.build_graph() File "/home/ubuntu/wemu_app/wemu_app_env/local/lib/python2.7/site-packages/django/db/migrations/loader.py", line 210, in build_graph self.applied_migrations = recorder.applied_migrations() File "/home/ubuntu/wemu_app/wemu_app_env/local/lib/python2.7/site-packages/django/db/migrations/recorder.py", line 65, in applied_migrations self.ensure_schema() File "/home/ubuntu/wemu_app/wemu_app_env/local/lib/python2.7/site-packages/django/db/migrations/recorder.py", line 52, in ensure_schema if self.Migration._meta.db_table in self.connection.introspection.table_names(self.connection.cursor()): File "/home/ubuntu/wemu_app/wemu_app_env/local/lib/python2.7/site-packages/django/db/backends/base/introspection.py", line 55, in table_names return get_names(cursor) File "/home/ubuntu/wemu_app/wemu_app_env/local/lib/python2.7/site-packages/django/db/backends/base/introspection.py", line 50, in get_names return sorted(ti.name for ti in self.get_table_list(cursor) File "/home/ubuntu/wemu_app/wemu_app_env/local/lib/python2.7/site-packages/django/db/backends/mysql/introspection.py", line 56, in get_table_list cursor.execute("SHOW FULL TABLES") File "/home/ubuntu/wemu_app/wemu_app_env/local/lib/python2.7/site-packages/django/db/backends/utils.py", line 79, in execute return super(CursorDebugWrapper, self).execute(sql, params) File "/home/ubuntu/wemu_app/wemu_app_env/local/lib/python2.7/site-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) File "/home/ubuntu/wemu_app/wemu_app_env/local/lib/python2.7/site-packages/django/db/utils.py", line 94, in __exit__ six.reraise(dj_exc_type, dj_exc_value, traceback) File "/home/ubuntu/wemu_app/wemu_app_env/local/lib/python2.7/site-packages/django/db/backends/utils.py", line 62, in … -
Move record from first Django model to second and then delete it from first
I want to move a record from NewUsers model to PendingUsers model on the button click. After moving, the record should be removed(deleted) from NewUsers model. Here's the models: class NewUser(models.Model): user = models.OneToOneField(User, on_delete = models.CASCADE, default=1) newuser_name = models.CharField(max_length=50) newuser_company = models.CharField(max_length=100) newuser_mobile = models.CharField(max_length=10) newuser_designation = models.CharField(max_length=50) newuser_image = models.ImageField(upload_to='userprofile_pics/users/', blank=True) def __str__(self): return self.user.email class PendingUsers(models.Model): pendinguser = models.OneToOneField(NewUser, on_delete = models.CASCADE, default=1) def __str__(self): return self.pendinguser.newuser_name On Button click, the code to move the record is: query_user = get_object_or_404(NewUser, id=id) pendingUser = PendingUsers() pendingUser.pendinguser = query_user pendingUser.save() And to delete it from NewUsers: NewUser.objects.filter(id=id).delete() It is successfully moving the record to PendingUsers. But as soon as I'm deleting it from NewUser, it is automatically deleted from PendingUser as well. Can anybody help me out with this about how to achieve this successfully? Do I need to change my PendingUsers model? Thanks in advance!