Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Javascript function doesn't wait until the end of promises
I have got a function that invokes when a button is clicked, and I am trying to fetch data through API upon clicking. and below is the function that gets triggered onclick. I have to fetch data through API once and then based on a field from the fetched data, I need to fetch another data from another data table. so, I have designed my coding as below, and my console looks like this: And the console looks like this: All done []length: 0__proto__: Array(0) 1466 (customer_id logged during for loop) 1663 (customer_id logged during for loop) I thought based on the promise logic, all done should have been read in the end, am I missing anything here? so Ideally, Alldone console should have invoked at the end containing data fetched based on customer_ids 1466, 1663. I am not sure what I am missing, I am new to javascript as well as stack overflow, so detailed answer would be so much appreciated. function test(pmt_id, crm_supplier_id) { const url = 'http://127.0.0.1:8000/creditor-detail/'+pmt_id+'/supplier/'+crm_supplier_id+'/' let promises = []; const results = fetch(url) .then(resp => resp.json()) .then(function (item) { var list = item; for (var i in list) { promises.push(getCustomer(list[i].customer_id)); console.log(list[i].customer_id) } }) Promise.all(promises) .then((results) … -
How to solve 302 Issue in Django?
I have a form in django, which is working for rating. if a user will submit that form then it will save procuct_id and user_id in database, so that i can calculate the ratings which is given by users after login. But when i submit this form, it's showing 302 found. so i checked after HttpResponse and it's printing Hi, please check my code and let me know where i am mistaking. Here is my models.py file... class Comment(models.Model): STATUS=( ('New', 'New'), ('True', 'True'), ('False', 'False') ) product=models.ForeignKey(Product, on_delete=models.CASCADE) user=models.ForeignKey(User, on_delete=models.CASCADE) subject=models.CharField(max_length=250, blank=True) comment=models.CharField(max_length=50, blank=True) rate=models.IntegerField(default=1) ip=models.CharField(max_length=250, blank=True) status=models.CharField(max_length=10, choices=STATUS) created_at=models.DateField(auto_now_add=True) updated_at=models.DateField(auto_now=True) def __str__(self): return self.subject class CommentForm(ModelForm): class Meta: model=Comment fields=['subject', 'comment', 'rate'] here is my views.py file... def addcomment(request,id): url = request.META.get('HTTP_REFERER') #get last url #return HttpResponse(url) if request.method == 'POST': form = CommentForm(request.POST) if form.is_valid(): data = Comment() #create relation with model #data.name = form.cleaned_data['name'] #get form input data data.subject = form.cleaned_data['subject'] data.comment = form.cleaned_data['comment'] data.ip = request.META.get('REMOTE_ADDR') data.product_id=id current_user=request.user data.user_id=current_user.id data.save() #save data to table messages.success(request, "Your Review has been Send. Thank you for your interest") return HttpResponse("Hello") return HttpResponse("Hi") here is my urls.py file... urlpatterns = [ path('product/addcomment/<int:id>', views.addcomment, name='addcomment'), ] here is my product.html … -
Can't access self.request.user when overriding FilterSet.qs
I have written code for a filter that takes into account some fields of a given patient (name, age and id). The users of the website will be doctors, and I want only patients of the current logged in doctor to come up in the search. After reading the docs and trying to do so in many different ways, I have accomplished nothing. It seems the best method is to override the FilterSet.qs function and so I did, similarly to what is present in the documentation. However, when I try to access self.request.user it comes back as none, even though there is a user currently logged in. I am new to Django and still trying to figure things out. Any help is highly appreciated. I believe I have pasted in all that is relevant, but I am sorry in advance if something is missing. # filters.py import django_filters from .models import Patient, Teams from django import forms from django.contrib.auth.models import User class PatientFilter(django_filters.FilterSet): id = django_filters.NumberFilter(widget=forms.NumberInput(attrs={ 'min': '1'})) age = django_filters.NumberFilter(widget=forms.NumberInput(attrs={ 'min': '0'})) class Meta: model = Patient fields = { 'first_name' : ['icontains'], 'age' : ['exact'], 'id' : ['exact'] } @property def qs(self): parent = super().qs author = getattr(self.request, … -
how to get the default user details (username, email, first_name, last_name) along with token (in created login API) via Django Rest framework?
I am trying to get the user details (username, email, first_name, last_name) along with token via API, but just getting token, I am a beginner in Django REST framework, Please help me regarding this, here is my code. settings.py INSTALLED_APPS = [ ... 'rest_framework', 'knox', ] REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'knox.auth.TokenAuthentication', ], } views.py from django.contrib.auth import login from rest_framework import permissions from rest_framework.authtoken.serializers import AuthTokenSerializer from knox.views import LoginView as KnoxLoginView class LoginAPI(KnoxLoginView): permission_classes = (permissions.AllowAny,) def post(self, request, format=None): serializer = AuthTokenSerializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.validated_data['user'] login(request, user,)[enter image description here][1] return super(LoginAPI, self).post(request, format=None) urls.py from knox import views as knox_views from .views import LoginAPI from django.urls import path urlpatterns = [ path('api/login/', LoginAPI.as_view(), name='login'), ] http://127.0.0.1:8000/api/login/ { "username": "admin123", "password": "Password@123" } and response is { "expiry": "2020-07-30T13:34:14.041631Z", "token": "f4767171f1017d2bd772fd3bae43489659e8e63649361845bedc5ebabff09c15" } -
Select widget value appearing in POST but not cleaned_data
One of my forms has a Select widget that is not working properly. Using the VS Code debugger, I found that the data is showing up in POST but not cleaned_data. Here is my code: views.py def index(request): if request.method == 'GET': return render(request, 'quotes/index.html', { 'form': QuoteRequestForm(), }) elif request.method == 'POST': form = QuoteRequestForm(request.POST) g_recaptcha_response = request.POST.get('g-recaptcha-response') ip = get_client_ip(request) api_response = verify(g_recaptcha_response, ip) api_response_content = json.loads(str(api_response.content, encoding='utf-8')) if not api_response_content['success'] or api_response.status_code != 200: messages.error(request, 'There was an error submitting the form.') messages.error(request, 'Please prove you are human by clicking the last checkbox and possibly completing a security challenge.') return render(request, 'quotes/index.html', {'form': form}) if form.is_valid(): quote_request = form.save() messages.success(request, 'Thank you for submitting a quote request. We will contact you via phone or email within 1-3 business days.') return redirect('quotes:index') messages.error(request, 'There was an error submitting the form.') return render(request, 'quotes/index.html', { 'form': form, }) return HttpResponseBadRequest() forms.py class QuoteRequestForm(forms.ModelForm): title = forms.MultipleChoiceField( label='', choices=Contact.title_choices, widget=forms.Select( attrs={ 'class': 'form-control', 'data-label': 'Title', }, ), ) first_name = forms.CharField( label='', max_length=35, widget=forms.TextInput(attrs={ 'class': 'form-control', 'placeholder': 'First Name', }), ) last_name = forms.CharField( label='', max_length=70, widget=forms.TextInput(attrs={ 'class': 'form-control', 'placeholder': 'Last Name', }), ) family_first = forms.BooleanField( required=False, label='Family Name … -
Render many to many relationship in django
I have two models Order and Supplement. The order model is connected to the Supplement model with many to many relationship.In my template, I want to display supplements selected in the Order model in an HTML page. In an order object I have selected two kinds of supplements , but in my HTML page when I try to render them I'm getting " accounts.Supplement.None" as the output. class Order(models.Model): name = models.CharField(max_length=30) address = models.CharField(max_length=100) status = models.CharField(max_length = 100) supplement = models.ManyToManyField('Supplement') class Supplement(models.Model): stockId = models.AutoField(primary_key=True) brand_name = models.CharField(max_length=100) supplement_name = models.CharField(max_length=100) supplement_type = models.CharField(max_length=100) quantity = models.IntegerField(default='0', blank=True, null=True) def __str__(self): return self.supplement_name HTML page {% for Order in order %} <h1>{{supplement.supplement}}</h1> {% endfor %} -
Remove the last char for the last item of a django template loop
I have this django template: <script type="application/ld+json"> { "@context": "https://schema.org", "@type": "FAQPage", "mainEntity": [ {% for q_a_ins in q_a_set %} { "@type": "Question", "name": "{{ q_a_ins.question }}", "acceptedAnswer": { "@type": "Answer", "text": "{{ q_a_ins.answer }}" } }, {% endfor %} ] } </script> The result is: <script type="application/ld+json"> { "@context": "https://schema.org", "@type": "FAQPage", "mainEntity": [ { "@type": "Question", "name": "q1", "acceptedAnswer": { "@type": "Answer", "text": "a1" } }, { "@type": "Question", "name": "q2", "acceptedAnswer": { "@type": "Answer", "text": "a2" } }, ] } </script> The result is exactly what I want except one tiny little character!! The last comma in the list causing me trouble and I am getthing error in structured data testing tool. How can I remove comma from the last }, ] ? The result I need is this : <script type="application/ld+json"> { "@context": "https://schema.org", "@type": "FAQPage", "mainEntity": [ { "@type": "Question", "name": "q1", "acceptedAnswer": { "@type": "Answer", "text": "a1" } }, { "@type": "Question", "name": "q2", "acceptedAnswer": { "@type": "Answer", "text": "a2" } } ] } </script> How can I remove that comma? -
What are the Challenges in Migrating Core-PHP without OOP to a framework? How we'll manage DB for both apps?
What are the Challenges in Migrating Core-PHP without OOP to a framework? DB also needs to be optimized. I'm planning it features by feature. Should I use same DB for both or create a new optimized DB? Also If the Old app needs new data which is entered by new app (dependency), How will manage it? Switching to Laravel or Django which is better? -
Linking Different List Views of 2 models together who share the same User
I am trying to add a Post to a list view, the class DesignerPostListView(ListView) has already an Item context. In my project, a user can add a post and add an item each is a different app with different models. So In my DesignerPostListView(ListView), I have my items related to a specific user looped. What I am trying to do is check if this item.user has a post existing related to the user and if it does exist a button show appears in the page linking to another page with these posts related to the very same user. There is another list view called class UserPostListView(ListView): with the same idea looping posts filtered to a specific user. In order words if there are no posts related to the user the button should not appear but if there is 1 or more the button should appear. I have tried to add a condition to the template but it is not working correctly and I think there might be another easier way to do it through the views. here is the item models.py class Item(models.Model): designer = models.ForeignKey( User, on_delete=models.CASCADE) title = models.CharField(max_length=100) here is the designer list views.py class DesignerPostListView(ListView): model … -
how to send image base64 to django server from flutter
Can anyone help me in this? I am sending image from flutter to django (python) server . here i am successfully take the image from mobile camera/gallery and successfully converted(encoded) the image to base64. flutter code Future classifyImage() async{ if(imageFile==null) return; String base64Image = base64Encode(imageFile.readAsBytesSync()); String fileName = imageFile.path.split("/").last; http.post(phpEndPoint, body: { "image" : base64Image, //"name" : fileName, }).then((res) { print(res.body); }).catchError((err) { print(err); //print(base64Image); //print(fileName); }); } here is the converted string in flutter by base64 /9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAEBAQEBAQEBAQEBAQEBAQICAQEBAQMCAgICAwMEBAMDAwMEBAYFBAQFBAMDBQcFBQYGBgYGBAUHBwcGBwYGBgb/2wBDAQEBAQEBAQMCAgMGBAMEBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgb/wAARCAPXAy0DASIAAhEBAxEB/8QAHwAAAgICAwEBAQAAAAAAAAAABgcEBQMIAAIJAQoL/8QAaBAAAQMDAwIEAwQFBwQJEAITAQIDEQAEIQUSMQZBEyJRYQcycRRCgZEICSNSoRUzYnKxtMEWN3bRCiRDZHSChJLwFyY2U1ZjZWZzhZSipbO14Sc0NUR1g5WkGEWTJSg4RkdXWHej8f/EABcBAQEBAQAAAAAAAAAAAAAAAAACAQP/xAAaEQEAAwEBAQAAAAAAAAAAAAAAAgMyATER/9oADAMBAAIRAxEAPwDzr/2W4wXv0yf0cSCRH6MDY/8Abuo1+SpOmqUoJEyTzX66/wDZZbC3v0x/0dClBUB+jG3JA/8ADmo1+U6ysFF9uWiM+lXZvqY5DbfTDy07hvIA4FW+n9E3Nw4ghLme4px6ZpqC2NyEkd5FMbp/SrfcgKQ2M+lQomrHogtIAcSQoeoq7Z6SS2UmAY4pwa1Zhq6CGmgRnKRUZixddKR4RAjPloAS20YNH5AcZxV41aBsD9mD6YpgWnTy3YBQoe8VeNdIKWAYI9hQK9Ol/avOGgkTkRU9jQCCP2ZwKbNv019nSEFAk8kirVnQgIGz+FAqWNBOPJ/CrRvQDM7DEelNpnQhjyfhFWzegDEJ+hIoF7pekFpopKYxgRVujTck7e1HrOjBsQUYqa1pSceWgB2dLKgPKffFWKNJMfIaOmdMAgBP8KsEaanAKe1AGWmn7EREGPSpYssj/VRWLMIJAQRHEiu6bOe0fhQDKbPvH8KzC0BE8fhRKizjEc94rKLIA8A+o20 but the problem is the string which is received in django server is different from the string which is converted in flutter. here is the string which is received in django server python code @csrf_exempt def android_predict(request): try : print('Request method is : ' + request.method) if request.method == 'POST' : print('method is POST') print('Body is : ' + str(request.body)) decoded = request.body.decode("UTF-8") print(decoded) name_image = decoded.split('&')[1].split('=')[1] print('name is : ' + name_image) b64_image = decoded.split('&')[0].split('=')[1] print('Base64 image is : ' + b64_image) missing_padding = len(b64_image)%4 print('Length is : ' + str(len(b64_image))) if missing_padding : b64_image += '='*(4-missing_padding) print('Modified Base64 image is : ' + b64_image) print('New length is : ' + str(len(b64_image))) image = PIL.Image.open(io.BytesIO(base64.b64decode(b64_image))) target_image = image.resize((500,500),PIL.Image.ANTIALIAS) print(type(target_image)) image_array = … -
How to have multiple sign up options (ie. Social accounts) in one page using allauth in django?
I'm following a tutorial on making a bookstore using django. I successfully have a standard sign up page using email and username. I then added a social account connection for github. It worked but it has its own page to connect. I'd like all sign up options available to use on one page. There's also no method of logging back in after signing up with Github. Below is home.html {% extends '_base.html' %} {% load static %} {% load socialaccount %} <p><a href="{% provider_login_url 'github' process='connect' %}">Connect a github account</a></p> {% block title %}Home{% endblock title %} {% block content %} <h1>Homepage</h1> <img class="bookcover" src="{% static 'images/djangoforprofessionals.jpg' %}"> {% if user.is_authenticated %} <p>Hi {{ user.email }}!</p> <p><a href="{% url 'account_logout' %}">Log Out</a></p> {% else %} <p>You are not logged in</p> <p><a href="{% url 'account_login' %}">Log In</a> | <a href="{% url 'account_signup' %}">Sign Up </a> | <a href="{% provider_login_url 'github' %}">Sign Up/Login with Github</a></p> {% endif %} {% endblock content %} Relevant portion of settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', # Third-party 'crispy_forms', 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.github', # Local 'users.apps.UsersConfig', 'pages.apps.PagesConfig', ] # django-allauth config LOGIN_REDIRECT_URL = 'home' ACCOUNT_LOGOUT_REDIRECT = 'home' SITE_ID = 1 AUTHENTICATION_BACKENDS = … -
Heroku: Django Migration release not running in deployment
I have a Django application running in Heroku. On the initial deployment, I manually migrated the database schema using heroku run. The next time I needed to push migrations to the app, the release went off without a complaint. However, when I went to the page to see it live, I was returned a programming error: the new column didn't exist. The migrations had never been run. Here's my Procfile: web: gunicorn APP_NAME.wsgi --log-file - release: python manage.py migrate release: python manage.py collectstatic --noinput worker: celery worker -A APP_NAME -B -E -l info The collectstatic release is run successfully, but the migrate release is seemingly ignored or overlooked. When I manually migrated, they migrated without error. There is an empty __init__.py file in the migrations folder. If anyone knows what could possibly be hindering the migrate release from running, that would be awesome. -
Unable to convert UTC timestamp to local time in templates
I'm having difficulty converting this timestamp value to local time using the template tags provided in the Django documentation: {% load tz %} {% get_current_timezone as TIME_ZONE %} {{ private_message.timestamp|timezone:TIME_ZONE|date:'m/d/Y: h:i a' }} I've tried many different template tags include load localtime and others. Regardless, the time still displays as UTC. Settings: TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True And I'm saving the timestamp as timezone.now() in my views.py Any help would be greatly appreciated. Thanks! -
How can I convert this uploadfile Function written in Flask to Django?
I need to convert my flask code to Django ! Any suggestions please ? photos = UploadSet('photos', IMAGES) app.config['UPLOADED_PHOTOS_DEST'] = 'static/img' configure_uploads(app, photos @app.route('/process', methods=['POST']) def upldfile(): if request.method == 'POST' and 'photo' in request.files: filename = photos.save(request.files['photo']) dataF = imageToTable(filename) file_path = photos.path(filename) os.remove(file_path) return dataF -
How to wait for a promise to resolve before the next iteration in for loop
I have got two data tables I want to query some data from, so the way i thought about doing it is fetch url and based on a field from list, I do fetch(url) once more to get related data from another data table and I want to append them together to display on the browser. The issue here is that for loop iteration doesn't wait until the previous fetch is finished. I am using django_restframework, and it is me trying to fetch data by passing criteria(variables) through urls. can anyone help? var url = 'http://127.0.0.1:8000/creditor-detail/'+pmt_id+'/supplier/'+crm_spplier_id+'/' var results = fetch(url) .then((resp) => resp.json()) .then(function(item){ var list = item for (var i in list){ getCustomer(list[i].customer_id) .then(function test(user) { return user[0].customer_name }); var spmt = ` <tr id="data-row-${i}"> <td>${list[i].po_no}</td> <td>${list[i].amount}</td> <td>${I want return value[user[0].customer_name]}</td> </tr> ` wrapper.innerHTML+= spmt } }) function getCustomer(customer_id){ var url = 'http://127.0.0.1:8000/user-detail/'+customer_id+'/' var results = fetch(url) .then((resp) => resp.json()) .then(function(item){ return item }) return results } -
Create local files with python in Django
I want to create files with the extension .txt, .csv, .bin, etc. so the ideal would be with import os I think or if there is some other better way. But I don't want to save those in the DB they are to consult the once or sporadically, that is, locally are uploaded to the server and then it is replaced and that's it. In a simple way, I create the files I need, upload them and replace them when I need something that will not be so common. The directory for these local files would be /app/files/. -
Adding shipping information @ Stripe payment | Django
I'm trying to add some shipping information in my view.py to charge a customer but it's not working out. I'm using Stripe payment and below is my Django view: charge = stripe.Charge.create( customer=customer, amount=100, currency='brl', description='First Test Ever!', shipping={ "address": { "line1": request.POST['rua'], "line2": request.POST['bairro'], "city": request.POST['cidade'], "state": request.POST['estado'], "postal_code": request.POST['cep'], }, } If I remove the 'shipping' dict, the code runs without any problem. Link for more Stripe charge information: https://stripe.com/docs/api/charges/create?lang=python#create_charge-shipping-address-country Do you have any idea? Thank you! -
ProgrammingError during TestCase
I am trying to create my first functional TestCase and having an issue with a ProgrammingError occurring. I will first start by showing my TestCase. Note: I am using TenantTestCase because I am using Django-Tenant-Schemas to separate clients to separate schemas/sub-domains. I am not sure what self.c = TenantClient(self.tenant) does. class FunctionalTestCase(TenantTestCase): def setUp(self): self.browser = webdriver.Chrome() self.c = TenantClient(self.tenant) def test_company_reg_btn_works(self): self.browser.get('http://localhost:8000') time.sleep(3) reg_btn = self.browser.find_element_by_id('register-link') reg_btn.click() self.c.get('/company-reg/', follow=True) def tearDown(self): self.browser.quit() After running this I get the traceback: File "/home/david/PycharmProjects/clearpath_project/venv/lib/python3.8/site-packages/django/db/utils.py", line 89, in __exit__ raise dj_exc_value.with_traceback(traceback) from exc_value File "/home/david/PycharmProjects/clearpath_project/venv/lib/python3.8/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) django.db.utils.ProgrammingError: relation "memos_memo_company" does not exist LINE 1: ..."memo_id", "memos_memo_company"."company_id" FROM "memos_mem... I am guessing this error is occurring as if the migration has not been run, but I am not sure. Can someone help explain what my next troubleshooting steps should be? Or what may cause this? -
Buildpack error when proper buildpack is already installed
I'm trying to Deploy to heroku on my django app, but I'm receiving an error saying: remote: -----> App not compatible with buildpack: https://buildpack-registry.s3.amazonaws.com/buildpacks/heroku/python.tgz remote: More info: https://devcenter.heroku.com/articles/buildpacks#detection-failure however I'm running the correct build pack as far as I can see: (virtual) MacBook-Pro-de-Stephen:src stephenlang$ heroku buildpacks === programatic-learning Buildpack URL heroku/python Could it be the way I have my files structured? Procfile: web: gunicorn blog.wsgi --log-file - runtime.txt: python-3.8.5 Is there something I'm missing with regards to deployment? -
How to use Django with PGBouncer?
I have an application launched in Django, which has a very high traffic of requests and queries to the databases. I am having problems and I have read that with PGBouncer and some settings in Django I can solve the problem. The question is how to integrate PGBouncer with Django. I have the Django application in Docker. The database is Postgres and it is in the RDS service of Amazon web services. Would PGBouncer be installed on the instance where the Django application runs? -
'bytes' object has no attribute 'objects' in django
here is my views.py function def searchfromimage(request): image_file = request.FILES['file'] os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = 'home/ServiceAccountToken.json' client = vision.ImageAnnotatorClient() content = image_file.read() image = vision.types.Image(content=content) response = client.document_text_detection(image=image) docText = response.full_text_annotation.text docText.replace('\n',' ') searchquery = docText allposts = content.objects.filter(title__icontains=searchquery) context = {'allposts':allposts} return render(request,'searchpage.html',context) when I am trying to print docText it gives the desired output but I am not able to use it to search it showing the error 'bytes' object has no attribute 'objects' I have tried str(docText, 'utf-8') but it is giving 'str' object has no attribute 'decode' error and I also tried with base64 and ASCII but nothing is working -
Why did djongo create a migration on my local server when I specified the host to be on Mlab?
In my settings.py file I have the following: 'ENGINE': 'djongo', 'NAME': '<db_name>, 'HOST': 'mongodb://username:<password>@ds147436.mlab.com:47436/<db_name>', 'USER': 'username', 'PASSWORD': '<password>', But when I run 'py manage.py makemigrations' then 'py manage.py migrate', the MongoDB collections get created on my local server MongoDB Compass. I don't know why it isn't creating my database over at Mlab? Where do I have to change my settings, or perhaps run a few different commands? In my terminal I get the following when I run 'py manage.py migrate': (env) PS D:\Business\Daydoa\v6-Django_with_MongoDB3\djongo_project> python manage.py migrate Operations to perform: Apply all migrations: admin, auth, contenttypes, sessions Running migrations: This version of djongo does not support "NULL, NOT NULL column validation check" fully. Visit https://www.patreon.com/nesdis Applying contenttypes.0001_initial...This version of djongo does not support "schema validation using CONSTRAINT" fully. Visit https://www.patreon.com/nesdis OK Applying auth.0001_initial...This version of djongo does not support "schema validation using KEY" fully. Visit https://www.patreon.com/nesdis This version of djongo does not support "schema validation using REFERENCES" fully. Visit https://www.patreon.com/nesdis OK Applying admin.0001_initial... OK Applying admin.0002_logentry_remove_auto_add... OK Applying admin.0003_logentry_add_action_flag_choices... OK Applying contenttypes.0002_remove_content_type_name...This version of djongo does not support "COLUMN DROP NOT NULL " fully. Visit https://www.patreon.com/nesdis This version of djongo does not support "DROP CASCADE" fully. Visit https://www.patreon.com/nesdis OK Applying auth.0002_alter_permission_name_max_length... … -
Can you resave a Django object in same method
I have a django function, I am saving the object twice in the same function. As I need the id for the object in my .delay (python celery) function. Is it ok to use .save() twice, or is it not good practice: def some_function(request, emailname, emailbody): email = Email() email.name = emailname email.save() email_id = email.id celery_task = send_email.delay(email_id, emailbody) email.celery_task_id = celery_task.id email.save() -
Django Import error for foreign key field on the Admin Screen
I am looking to put together a basic motor vehicle database app using Django. I am getting the error msg below when I try to upload a file containing fk values of the cat make and model to match to the car make/manufacturer. I have tried to resolve this a number of ways and have the FK Widget resource in place but having no luck, greatly appreciate some guidance. Error msg Models.py class MotorModelsV2(models.Model): MotorMakeName2 = models.ForeignKey("MotorMakes",on_delete=models.CASCADE, to_field='MotorMakeName',null=True) MotorModelName = models.CharField(max_length=50) def __str__(self): return self.MotorMakeName2 or '' def __unicode__(self): return u'%s' % (self.MotorMakeName2) or '' class MotorMakes(models.Model): MotorMakeName = models.CharField(max_length=50, unique=True) def __str__(self): return self.MotorMakeName or '' def __unicode__(self): return u'%s' % (self.MotorMakeName) or '' Admin.py class MotorMakeResource(resources.ModelResource): class Meta: model = MotorMakes exclude = ('is_active',) class MotorModelResource(resources.ModelResource): class Meta: model = MotorModelsV2 exclude = ('is_active',) class MotorModelResource(resources.ModelResource): motormakename = import_export.fields.Field( column_name='MotorMakeName1', attribute='MotorMakeName1', widget=ForeignKeyWidget(MotorMakes, 'MotorMakeName')) class Meta: fields = ('MotorMakeName1',) admin.site.register(MotorModelsV2, MotorModelsV2FileAdmin) admin.site.register(MotorMakes, MotorMakesFileAdmin) -
Hitcount Not Counting No. of Visits for A Detail View
I have followed https://github.com/thornomad/django-hitcount to implement Django Hitcount but I might be missing something I am not sure what it is as the count is 0 and remained like this even if I refreshed and even changed users. I think there might be some problem in the views just before the context where there is an arrow Here is the models.py @python_2_unicode_compatible class Post(models.Model): designer = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=100, unique=True) hit_count_generic = GenericRelation(HitCount, object_id_field='object_pk', related_query_name='hit_count_generic_relation') Here is the views.py class PostDetailView(HitCountDetailView, DetailView): model = Post template_name = "post_detail.html" def get_context_data(self, *args, **kwargs): context = super(PostDetailView, self).get_context_data() post = get_object_or_404(Post, slug=self.kwargs['slug']) comments = Comment.objects.filter( post=post, reply=None).order_by('-id') total_likes = post.total_likes() liked = False if post.likes.filter(id=self.request.user.id).exists(): liked = True if self.request.method == 'POST': comment_form = CommentForm(self.request.POST or None) if comment_form.is_valid(): content = self.request.POST.get('content') reply_id = self.request.POST.get('comment_id') comment_qs = None if reply_id: comment_qs = Comment.objects.get(id=reply_id) comment = Comment.objects.create( post=post, user=self.request.user, content=content, reply=comment_qs) comment.save() return HttpResponseRedirect("post_detail.html") else: comment_form = CommentForm() context.update({ 'popular_posts': Post.objects.order_by('-hit_count_generic__hits')[:3], <----- I think error from here }) context["total_likes"] = total_likes context["liked"] = liked context["comments"] = comments context["comment_form"] = comment_form return context here is the urls.py app_name = 'score' urlpatterns = [ path('', PostListView.as_view(), name='score'), path('details/<slug:slug>/', PostDetailView.as_view(), name='post-detail'), path('hitcount/', include(('hitcount.urls', 'hitcount'), …