Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
leaflet_map not working when used in a extended template django
I am using django-leaflet to display on my website and It works fine and displays the map on browser when I include the leaflet_map in the base template but when I use leaflet_map on a template that extends that base template then map doesn't appear on the browser. This is the code of extended template from base.html and it doesn't show the map on browser. {% extends 'base.html' %} {% load leaflet_tags %} {% block leaflet %}{% leaflet_js %}{% leaflet_css %}{% endblock %} {% block content %} {% leaflet_map %} {% endblock content%} These are the snippets from the base template. {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>{% block title %} {% endblock %}</title> <!-- Leaflet Info goes here --> {% block leaflet %}{% endblock %} <div class="content"> {% block content %}{% endblock %} </div> -
How exactly do I have to use HStoreField?
I'm using the latest version of Django and DRF. But after running it I'm getting this error: class HStoreDescriptor(models.fields.subclassing.Creator): AttributeError: module 'django.db.models.fields' has no attribute 'subclassing' I'm not sure how to use HStoreField and create an extension using migration. This is my structure of the file. webhook10/ |-- tutorial/ | |-- slack/ | | |-- migrations/ | | | +-- __init__.py | | |-- __init__.py | | |-- admin.py | | |-- apps.py | | |-- models.py | | |-- tests.py | | |-- urls.py | | +-- views.py | |-- tutorial/ | | |-- __init__.py | | |-- settings.py | | |-- urls.py | | |-- wsgi.py | +-- manage.py +-- venv/ Models.py from django.db import models from django.utils import timezone from django_hstore import hstore class WebhookTransaction(models.Model): UNPROCESSED = 1 PROCESSED = 2 ERROR = 3 STATUSES = ( (UNPROCESSED, 'Unprocessed'), (PROCESSED, 'Processed'), (ERROR, 'Error'), ) date_generated = models.DateTimeField() date_received = models.DateTimeField(default=timezone.now) body = hstore.SerializedDictionaryField() request_meta = hstore.SerializedDictionaryField() status = models.CharField(max_length=250, choices=STATUSES, default=UNPROCESSED) objects = hstore.HStoreManager() def __unicode__(self): return u'{0}'.format(self.date_event_generated) class Message(models.Model): date_processed = models.DateTimeField(default=timezone.now) webhook_transaction = models.OneToOneField(WebhookTransaction) team_id = models.CharField(max_length=250) team_domain = models.CharField(max_length=250) channel_id = models.CharField(max_length=250) channel_name = models.CharField(max_length=250) user_id = models.CharField(max_length=250) user_name = models.CharField(max_length=250) text = models.TextField() … -
How to import django import using foreign key widget
I have a model that has class Year(models.Model): year = models.IntegerField() def __str__(self): return str(self.year) class Author(models.Model): number = models.CharField( verbose_name = "Center Number", max_length = 255, default=0 ) .... class Book(models.Model): name = models.CharField( max_length=255 ) budget = models.FloatField( default=0 ) author = models.ForeignKey( Author, on_delete = models.CASCADE, verbose_name="Author" ) ... So the issue is that the Author number is same for the given year but same number can be used next year. For example, author number = 123 for 2018 and for 2019 I am trying to implement django import export Foreign Key and during the import I am using number as Foreign key lookup. In result I am receiving that more than one foreign key was found. I tried number = fields.Field( column_name='number', attribute='number', # widget=ForeignKeyWidget(Author, 'number') widget = FullNameForeignKeyWidget(number) ) class FullNameForeignKeyWidget(ForeignKeyWidget): def get_queryset(self, value, row): year = 1 author = Author.objects.filter(year=1).values('number') return self.model.objects.filter( number__iexact=value ) But getting error Line number: 1 - Author matching query does not exist. Is there any suggestion how to approach this, or any suggestions how to solve it? -
How to fix "TypeError: 'Move' object is not subscriptable"
I'm setting up a Django web application and want to use call my 'move' object to get the move's artist as defined in the Artist model. I do not encounter any errors if I remove the variable referencing the ForeignKey in the HTML or if I remove the variable from my Move class in my models.py file. Here is my models.py file: class Move(models.Model): move_artist = models.ForeignKey('Artist', on_delete=models.CASCADE, default=2) class Artist(models.Model): artist_move = models.ForeignKey(Move, on_delete=models.CASCADE, default=1) Here is my html file: {% extends 'main/header.html' %} {% block content %} <body> {% for mov in moves %} <p>{{mov.move_artist}}</p> {% endfor %} </body> {% endblock %} Here is the error I receive: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/template/base.py", line 829, in _resolve_lookup current = current[bit] TypeError: 'Move' object is not subscriptable During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/db/models/fields/related_descriptors.py", line 163, in __get__ rel_obj = self.field.get_cached_value(instance) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/db/models/fields/mixins.py", line 13, in get_cached_value return instance._state.fields_cache[cache_name] KeyError: 'move_artist' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/core/handlers/base.py", line 126, in _get_response response = self.process_exception_by_middleware(e, request) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/core/handlers/base.py", line 124, … -
Django: Integrity error installing fixtures
Foreground Hi. I´m uploading my Django app database to my Heroku production environment. When I try to manage.py loaddata I get the following error: django.db.utils.IntegrityError: Problem installing fixtures: insert or update in table "catalog_contactos" violates key constraint. I found this post where someone suggests that first you should load models that are the base for foreign key: related post Also I found this post that refers to moving a database to another app (the production version for example). Basicly it says: When you backup whole database by using dumpdata command, it will backup all the database tables If you use this database dump to load the fresh database(in another django project), it can be causes IntegrityError (If you loaddata in same database it works fine) To fix this problem, make sure to backup the database by excluding contenttypes and auth.permissions tables Link to the post My code Following that suggestions I do: python manage.py dumpdata --exclude auth.permission --exclude contenttypes > data.json Then on the server I run the following code and get the integrity error: heroku run python manage.py loaddata.json Should I dumpdata model by model and loaddata them in a certaing order? Or I´m coding something wrong? Any clues? … -
django.core.exceptions.ImproperlyConfigured: The included URLconf '' does not appear to have any patterns in it
I'm using Django 1.9 and DRF 3.9.2 for my project and I'm getting this error django.core.exceptions.ImproperlyConfigured: The included URLconf '' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import. Here's my project folder structure webhooksub/ |-- slack/ | |-- rest_slack/ | | |-- migrations/ | | | +-- __init__.py | | |-- __init__.py | | |-- admin.py | | |-- apps.py | | |-- models.py | | |-- tests.py | | |-- urls.py | | +-- views.py | |-- slack/ | | |-- __init__.py | | |-- settings.py | | |-- urls.py | | |-- wsgi.py | +-- manage.py +-- venv/ Here is my slack/urls.py from django.conf import settings from django.conf.urls import url, include from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^api/', include('slack.rest_slack.urls', namespace='rest_slack')), ] and rest_slack/urls.py from django.conf.urls import url from rest_framework import routers from rest_slack.views import DRSEventView, DRSCommandView router = routers.DefaultRouter() router.register(r'web', DRSEventView) router.register(r'events', DRSCommandView) urlpatterns = router.urls Can someone tell me what is it I'm doing wrong and what changes I can do to make it work? -
Unable to Make POST Request from Django View
TL;DR: I have a POST request (from the Requests module) that works outside of a Django view, but fails from inside the view. Can someone please tell me how to fix it? The Problem: I am using Django 1.7.11, Requests 2.14.2, and Python 2.7.14 to host a web application in Linux on AWS. The directory structure of the web application is set up like this: myproject |___myapp | | | |___templates | | | | | |___mytemplate.html | | | |___views.py | |___urls.py | |___post_request.py I have a function in views.py that is being called directly from a link in the Django template, mytemplate.html. The link in the template is not part of a form and is specified like this: <li><a href="{% url 'myapp:myview' %}">The Link to My View</a></li> The corresponding entry in myapp/urls.py is: url(r"^myview/$", the_view_function, name="myview") My function within myapp/views.py is declared without any decorators. The following line fails: the_response = requests.post(the_url, headers=headers, data=post_data, verify=False) When I click 'The Link to My View' from the page in my web browser, the request raises an exception of type 'OpenSSL.SSL.Error'. However: I have the following code in the post_request.py file: import requests the_url = "https://www.example.com/rest/endpoint/" headers = {'Authorization': 'Token aaaaabbbbbcccc'} … -
Setting up a Django eCommerce site, with B2B customers shops being populated from a database
this is my first question on stack overflow. I’ve done a good amount of googling on this issue and haven’t found anything. I am a designing an ecommerce site for a company who has private stores. The contract items are stored in a database , with pricing information, and linked to the main product database. I want the ability to access your private store when logged in; but i don’t know what ecommerce framework would be best suited for this. I am wanting to use Saleor, but I haven’t seen anyone implement anything like this. Can anyone confirm that Saleor is able to do this? If not, what ecommerce framework would best implement this? Thanks :) -
Routing Traffic from NuxtJS to Django REST on Heroku
The problem is known to me but I have no idea how to fix it. I'm deploying a Django REST as API and a Nuxt.js app to Heroku. The issue I'm facing is proxying the request from Nuxt (via axios) to the Django REST endpoint. My procfile: release: cd api && python manage.py migrate api: cd api && gunicorn api.wsgi web: npm run start The app is up and running after deployment, and if I request a page that doesn't consume the API endpoint behind the scenes, it loads swiftly. However, if I try to go for /api, the app enters (understandably) an endless cycle. It's because of these lines in my nuxt.config.js, which configures the application: axios: { proxy: true, progress: true, baseURL: "https://my-heroku-domain.herokuapp.com/api" }, proxy: { '/api': "https://my-heroku-domain.herokuapp.com/api" }, Since both processes api and web live on the same "domain" (https://my-heroku-domain.herokuapp.com/), I guess it makes little sense to try to proxy like this, since api dires to api which directs to api and so on... But how can I reference the Django instance internally in order to proxy the traffic properly? Is it possible on Heroku? -
ModuleNotFoundError: No module named 'apps'
I'm using Django 1.9 and DRF 3.9.2 in my project. In my urls.py I've used this code from django.conf import settings from django.conf.urls import url, include from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^api/', include('apps.rest_slack.urls', namespace='rest_slack')), ] and I've set a router in my rest_slack-urls.py from django.conf.urls import url from rest_framework import routers from rest_slack.views import DRSEventView, DRSCommandView router = routers.DefaultRouter() router.register(r'web', DRSEventView) router.register(r'events', DRSCommandView) urlpatterns = router.urls when I try to run server its giving me ModuleNotFoundError: No module named 'apps' error. please tell what changes I can do? -
AttributeError when using custom form field
I'm new to python and am trying to create a custom captcha field for a Django form. I wasn't able to find a good teaching tool for this, so I just poked around the code of the built-in fields and tried to learn from them. There's two major problems with my field. First of all, the widget for it is not displaying on the screen. Second of all, when I submit the form, Django raises an AttributeError saying: "'CaptchaField' object has no attribute 'disabled'". I'm not sure why this is. class CaptchaField(IntegerField): validators = [validators.ProhibitNullCharactersValidator] widget = CaptchaInput error_msgs = { 'incorrect': _('Captcha incorrect- try again'), } def __init__(self): captcha_array = [ ('What is the product of fifteen and four?', 60), ('What is four plus four?', 8), ] captcha =captcha_array.pop(random.randrange(len(captcha_array))) self.captcha = captcha def validate(self, value): for (a,b) in captcha: if value == b: return True else: raise ValidationError(self.error_msgs['incorrect'], code = 'incorrect') My widget: class CaptchaInput(Widget): template_name = 'django/forms/widgets/captcha.html' The html: <div class="card"><b>{{ a }}</b></div> {% include django/forms/widgets/input.html %} -
css file not finding image for background
I am experimenting with creating my first webpage. I am trying to get an image as my background but while testing with localhost it is not appearing, though all other css formatting is. I've gone through the other stackoverflow question relating to similar issues (seems common) but nothing has worked. I have also tried the .jpg file in the same folder as the .css file (this is the current arrangement. Below is the code as I currently have it... index.html {% load static %} <title>lvl6</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" type="text/css" href="{% static 'pages/style.css' %}"> <header class="header"> <div class="header-text">Sign in via:</div> <a href="#" class="header-link">LinkedIn</a> <a href="#" class="header-link">Facebook</a> </header> <section class="landing-section landing-main"> <h1 class="brand">lvl6</h1> <p class="landing-main-text"> "Creating a future environment within which the human soul is destined to Flourish" <br> <br> subtext.... </p> </section> style.css .landing-section { min-height: 100vh; width: 100vw; display: flex; align-items: center; justify-content: center; flex-direction: column; } .landing-main { background: url("stock.jpg") no-repeat center center fixed; background-size: cover; } .header { width: 100vw; display: flex; justify-content: flex-end; top: 0; left: 0; position: absolute; background: rgba(0,0,0,0.5); } .header-link { margin: 1rem; border-bottom: 3px solid #c55e00; font-size: 1.2rem; color: #222; text-decoration: none; color: #ccc; } .header-text { margin: 1rem; font-size: … -
why data in django framework is not storing in the database while i have done with all the migrations?
I am learning Django I have done everything that was explained in javatpoint (learning website),i have done all the migrations ,i have executed python manage.pymigrate,makemigrations,sqlmigrate appname 0001_initial everything , the form is created successfully but the data uploading is not storing in the database. i just want the data (first name and lastname ) to be stored to the employee table and the data to be downloaded as csv file. views.py from django.http import HttpResponse from django.shortcuts import render # Create your views here. from django.shortcuts import render, redirect from name.forms import EmployeeForm from name.models import Employee import csv def index(request): if request.method == "POST": form = EmployeeForm(request.POST) if form.is_valid(): try: return redirect('/') except: pass else: form = EmployeeForm() return render(request,'index.html',{'form':form}) def getfile(request): response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="file.csv"' employees = Employee.objects.all() writer = csv.writer(response) for employee in employees: writer.writerow([employee.id,employee.first_name,employee.last_name]) return response forms.py from django import forms from name.models import Employee class EmployeeForm(forms.ModelForm): class Meta: model = Employee fields = "__all__" models.py from __future__ import unicode_literals from django.db import models class Employee(models.Model): first_name = models.CharField(max_length=20) last_name = models.CharField(max_length=30) class Meta: db_table = "employee" script.js alert("Hello, Welcome to Javatpoint"); index.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Index</title> </head> <body> … -
Dropdown works on Chrom and Safari but not Firefox
I have this piece of code in my base.html which displays my username with a dropdown arrow to the right of it. {% if user.is_authenticated %} <ul class="navbar-nav ml-auto"> <li class="nav-item"> <a class="nav-link dropdown-toggle" href="#" id="userMenu"\ data-toggle="dropdown" aria-haspopup="true" aria-expanded\ ="false"> {{ user.username }} </a> <div class="dropdown-menu dropdown-menu-right"\ aria-labelledby="userMenu"> <a class="dropdown-item" href="{% url 'password_change'\ %}">Change password</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="{% url 'logout' %}"> Log Out</a> </div> </li> </ul> {% else %} If I click it, the dropdown menu appears listing Change password and Log Out. This works as expected on Chrome and Safari but when I click it on Firefox nothing happens. Is there anything I can do to fix this? -
Twilio outbound fax is getting a 500 internal server error on StatusCallback in Django
I'm trying to set up a webhook that listens for status updates on faxes sent through Twilio's API. I had no problem setting up webhooks for Twilio Messages and there's little information on setting it up for Programmable FAxes. The faxes are successfully sent but I am getting "500 Internal Server Error" codes on Ngrok. This is what the twilio api function looks like: twilio_client.fax.faxes.create( to = fax_number, from_= twilio_number, media_url=fax_url, status_callback=status_callback_url, ) And here is what my Django endpoint handler looks like: @method_decorator(csrf_exempt, name='dispatch') class ReceiveFaxStatusUpdates(View): def post(self, request): # Never executed, I have tried get as well. fax_status = request.POST['FaxStatus'] -
How to add a Django app to settings.py app_name or app_name.apps.AppNameConfig?
I have seen that there are two ways to add a Django app to the settings. Assuming the app is app_name, I've seen the following patters: Using app_name INSTALLED_APPS = [ # other apps 'app_name' ] Using app_name.apps.AppNameConfig INSTALLED_APPS = [ # other apps 'app_name.apps.AppNameConfig' ] I am wondering if there is any difference between these two patterns or if they are equivalent. I also wonder if there is any preferred way to add an application. -
Not Null constraint failed | Unknown error
I have read the posts on StackOverflow. But wasnot able to figure about this problem. My make migrations work but migrate does not, I am getting an error on field, which I am not sure even exists in models. Here is the Code from django.db import models from phonenumber_field.modelfields import PhoneNumberField from django.core.validators import MaxValueValidator class Cuisine(models.Model): Cuisine_Id = models.AutoField(primary_key=True) Cuisine_Sub = models.CharField(max_length=20, null=True) Cuisine_parent = models.CharField(max_length=20) class Label(models.Model): # , null = false, blank = false) Label_Name = models.CharField(max_length=20) Label_Id = models.AutoField(primary_key=True) class Restaurant(models.Model): def upload_image(self, filename): return 'post/{}/{}'.format(self.title, filename) Res_Id = models.AutoField(primary_key=True) Res_Name = models.CharField(max_length=75) Res_Description = models.CharField(max_length=150, null=True) Res_Contact = PhoneNumberField(null=False, blank=False, unique=True) Res_Address = models.CharField(max_length=75) Cuisine_Type = models.ForeignKey(Cuisine,on_delete=models.CASCADE,null=True) Res_Pic = models.ImageField(upload_to=upload_image, default='/media/defaultimage.png') class Menu(models.Model): Menu_Item_Id = models.AutoField(primary_key=True) Menu_Item = models.CharField(max_length=50) Menu_ItemPrice = models.DecimalField(max_digits=30, decimal_places=2) Menu_Item_Description = models.CharField(max_length=100) Menu_Res_Id = models.ForeignKey(Restaurant, on_delete=models.CASCADE, null='false', blank='false') Menu_Cuisine = models.ForeignKey(Cuisine,on_delete=models.CASCADE,null=True) #Menu_Label_Id = models.ForeignKey(Label, on_delete = models.CASCADE) class Review(models.Model): Review_Id = models.AutoField(primary_key=True) Res_Id = models.ForeignKey(Restaurant, on_delete=models.CASCADE) Review_Des = models.CharField(max_length=75, blank=True) Review_Rating = models.IntegerField( null=True, validators=[MaxValueValidator(5)]) I am getting this error return Database.Cursor.execute(self, query, params) django.db.utils.IntegrityError: NOT NULL constraint failed: restaurant_menu.Menu_Cusine_id Any help is appreciated -
graphene-python doesn't recognize ´content_type´ field
I am making my first attempt to use ´graphene-python´, and I have been able to make it work so far, but I have found that ´graphene-python´ doesn't recognize ForeignKey fields that reference ContentType model. This is my model: class ReservationComponent(models.Model): reservation = models.ForeignKey(Reservation, on_delete=models.PROTECT, related_name='components', verbose_name=_("Reservation")) dertour_bk = models.CharField(null=True, blank=True, max_length=15, verbose_name=_("Dertour Bk")) day = models.DateField(verbose_name=_('Day')) content_type = models.ForeignKey(ContentType, on_delete=models.PROTECT) object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') comment = models.TextField(null=True, blank=True, verbose_name=_("Comment")) is_invoiced = models.BooleanField(default=False, verbose_name=_("Is Invoiced")) This is my schemas.py: import graphene from graphene_django.types import DjangoObjectType from ReservationsManagerApp.models import Reservation, ReservationComponent from InvoicesManagerApp.models import Invoice, InvoiceEntry, InvoiceEntryComponent from PaymentsManagerApp.models import Payment, PaymentReservationComponent class ReservationType(DjangoObjectType): class Meta: model = Reservation class ReservationComponentType(DjangoObjectType): class Meta: model = ReservationComponent class InvoiceType(DjangoObjectType): class Meta: model = Invoice class InvoiceEntryType(DjangoObjectType): class Meta: model = InvoiceEntry class InvoiceEntryComponentType(DjangoObjectType): class Meta: model = InvoiceEntryComponent class PaymentType(DjangoObjectType): class Meta: model = Payment class PaymentReservationComponentType(DjangoObjectType): class Meta: model = PaymentReservationComponent class Query(object): all_reservations = graphene.List(ReservationType) all_reservation_components = graphene.List(ReservationComponentType) all_invoices = graphene.List(InvoiceType) all_invoice_components = graphene.List(InvoiceEntryType) all_invoice_entries_components = graphene.List(InvoiceEntryComponentType) all_payment = graphene.List(PaymentType) all_payment_reservation_components = graphene.List(PaymentReservationComponentType) def resolve_all_reservations(self, info, **kwargs): return Reservation.objects.all() def resolve_all_reservation_components(self, info, **kwargs): return ReservationComponent.objects.select_related('reservation').all() def resolve_all_invoice_entries_components(self, info, **kwargs): return InvoiceEntryComponent.objects.select_related('reservation_component').all() def resolve_all_payment_reservation_components(self, info, **kwargs): return PaymentReservationComponent.objects.select_related('reservation_component').all() And, … -
How to fix Django project deployed in AWS EC2 but CSS and photos not working
I developed my project in localhost, everything is working. Then I pushed the project to github and finally cloned it in my AWS EC2 Ubuntu server. This is the sites public IP: http://13.59.50.215 . In the said public IP, all my contents is displaying, except for images and css. I tried to login into the admin panel but same, no css and images as well. My folder structure is this: jangooCMS accounts /* an app for user creation */ articles /* an app for article creation */ assets logo-jangoo.png db.sqlite3 jangooCMS /* my main app */ settings.py urls.py views.py wsgi.py manage.py media /* all the articles images inside here */ 4-kitties-low.jpg requirements.txt templates base-layout.html Now my base-layout.html have this on top: {% load static from staticfiles %} Now going to my AWS, my settings.py is below: STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'assets'), ) MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR,'media') STATIC_ROOT = os.path.join(BASE_DIR, "assets/") Please help.. my first time to post here. Thank you! this is the instruction I followed on deploying my project from github to AWS EC2: cd Downloads/ mv blogoo.pem ~/Desktop/ cd .. cd desktop chmod ssh yes sudo apt-get update sudo apt-get install python3-pip python3-dev … -
ManyToMany Relationship "add-friend, remove-friend" in Django not working
How do I solve this many to many relationship problem. I am building a "ADD & REMOVE FRIENDS" system like Facebook. "if A is friend with B, then B is friend with A". class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) bio = models.TextField(max_length=500, null=True) location = models.CharField(max_length=50, null=True, blank=True) class Friend(models.Model): friend_user = models.ManyToManyField(User) After selecting two users in Profile from Admin to create the relationship with the superuser and saved it. When I access the shell to try the commands below, two issues come up: from django.contrib.auth.models import User from accounts.models import Friend After instantiate: friend = Friend() When I type: friend The Shell return: <Friend: Friend object (None)> I BELIEVE THE PROBLEM IS FROM THE LINE ABOVE, IT SHOULD NOT RETURN "NONE" Also, when i try to add the relationship: friend.friend_user.add(User.objects.last()) The Shell return: Traceback (most recent call last): File "<console>", line 1, in <module> File "/Users/macadmin/Documents/Django_wapps/fbook/lib/python3.7/site-packages/django/db/models/fields/related_descriptors.py", line 498, in __get__ return self.related_manager_cls(instance) File "/Users/macadmin/Documents/Django_wapps/fbook/lib/python3.7/site-packages/django/db/models/fields/related_descriptors.py", line 795, in __init__ (instance, self.pk_field_names[self.source_field_name])) ValueError: "<Friend: Friend object (None)>" needs to have a value for field "id" before this many-to-many relationship can be used. Any help would be much appreciate. PS: I am using this tutorial : https://www.youtube.com/watch?v=nwpLCa79DUw&list=PLw02n0FEB3E3VSHjyYMcFadtQORvl1Ssj&index=54 -
Adding a XP field to the default user model
So in the last hour I've been struggling to implement a XP field to the default user model. I studied the django docs and I saw there are two ways to customize the authentication - either extending the User model, or changing it. I've decided to just extend it, because I only need to add two or three more fields in the future. (I'm trying to add only this XP field rn so I can get how it should be done) I thought I made it until I got this error: 'Manager' object has no attribute 'create_user' As far as I know, this happens because the create_user method is bound to User, and I changed the model. Here's the line which creates the error: user = Utilizator.objects.create_user(username=username, password=password, email=email, first_name=first_name, last_name=last_name) So I'm doing it wrong. Here's the code: views.py from django.shortcuts import render, redirect from django.contrib import messages from django.contrib.auth.models import User from .models import Utilizator from django.contrib import auth # Create your views here. def login(req): if req.method == 'POST': username = req.POST['username'] password = req.POST['password'] user = auth.authenticate(username=username, password=password) if user is not None: auth.login(req, user) messages.success(req, 'Acum eşti logat') return redirect('dashboard') else: messages.error(req, 'Numele de utilizator … -
Separation of Concerns / DI in Django Rest Framework Applications
I'm trying to create more separation of concerns with endpoints in my Django apps but not sure how to implement a service layer. I've read through a popular python article on this topic however it doesn't seem to answer the testing issue. For instance, if I have a request come in to save a user and want to send an email after the user has been saved, it's popular to handle this logic by overriding on save like this: **models.py** class User(AbstractBaseUser, PermissionsMixin): ... def save(self, *args, **kwargs): if self._state.adding: user.activate_user(user=self) super(User, self).save(*args, **kwargs) **services.py** from services import iNotificationService ... def activate_user(user): user.active = True iNotificationService().send_message(user) In the above example, iNotificationService would be an interface that the application could choose at runtime. If this user was saved in a production environment, the application would provide a class like the following import mandrill class EmailClient(iNotificationService) def send_message(user): message = create_message(user) mandrill.send_email(message) into the services.py module so that an email was sent. But if the application was run in a testing environment, the test would mock the EmailClient by sending in an instance of the interface so that no email would actually be sent: class iNotificationService(object) def send_message(user) pass What I'm wondering … -
DataTable Editor with django backend for inline edit
I am trying to implement a data table editor with django backend for inline editing. I am not able to get the updated values in my django views while performing the edit operation in the data table. I console the data inside the 'preSubmit' method of data table editor and its working fine as I expected. editor.on( 'preSubmit', function ( e, data, action ) { console.log(data) } ) Here is the console output . {action: "edit", data: {19054002: {description: "Orion ChocoPie 560gm"}}, table_name: "rp_p_m"} But the problem is while fetching all the keys in django view I am not getting all the keys as I expect which are ['action', 'data', 'table_name']. Code Inside views.py def product_master(request): keys = [] for key in request.POST: keys.append(key) print(keys) Instead, I am getting the output like this ['action', 'data[19054002][description]', 'table_name'] All the nested keys get combined with the key 'data'. -
Django can't clear image from post object
when i try to clear the postcover from my postform i get back the following error: raise ValueError("The '%s' attribute has no file associated with it." % self.field.name) ValueError: The 'postcover' attribute has no file associated with it. e.g. for post attachment its working fine. models.py class Post(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(verbose_name="Post Title", max_length=40) content = models.TextField(verbose_name="Post Content", max_length=10000) tag = models.CharField(verbose_name="Tags/Meta - (sep. by comma)", max_length=75, blank=True) category = models.ForeignKey(Category, verbose_name="Category", on_delete=models.CASCADE, null=True) postattachment = fields.FileField( verbose_name="Post Attachment", blank=True, null=True, upload_to=get_file_path_user_uploads, validators=[file_extension_postattachment, file_size_postattachment] ) postcover = fields.ImageField( verbose_name="Post Cover", blank=True, null=True, upload_to=get_file_path_user_uploads, validators=[default_image_size, default_image_file_extension], dependencies=[FileDependency(processor=ImageProcessor( format='PNG', quality=99, scale={'max_width': 700, 'max_height': 700}))]) published_date = models.DateField(auto_now_add=True, null=True) ... forms.py class PostForm(forms.ModelForm): class Meta: model = Post widgets = { 'title': forms.TextInput(attrs={'placeholder': 'e.g.: Its a sunny day'}), 'tag': forms.TextInput(attrs={ 'placeholder': 'e.g.: Cars, Blue, Red, Green'}), } fields = ['title', 'category', 'content', 'tag', 'postcover', 'postattachment' ] captcha = CaptchaField() field_order = ['title', 'category', 'content', 'tag', 'postcover', 'postattachment', 'captcha' ] def __init__(self, *args, **kwargs): kwargs.setdefault('label_suffix', '') super(PostForm, self).__init__(*args, **kwargs) self.fields['title'].widget.attrs.update({'class': 'class-four-input-fields fieldbreak'}) ... self.fields['postcover'].widget.attrs.update({'class': 'fieldbreak'}) self.fields['postcover'].label = mark_safe('Cover:') self.fields['postcover'].help_text = mark_safe("<h4 class='help_text'>→ Choose a Cover for your Post (max. 2 MB)</h4>") From my perspective its not really clear why this is … -
error using django filter he option of multiple choices when searching'
I'm using django filter to do search on my system, and it's working. the problem is that I have two fields with multiple choices and when I go to the search page, does not appear the multiple choices, only a normal field box and looking for it does not appear the results. wanted to add the number of multiple choices I'm Brazilian and I'm using google translator for this question, I'll summarize it in a sentence: 'I need in pet_aceitos, the option of multiple choices when searching' models.py PETN_CHOICES = ( ('Cachorro Pequeno Porte','Cachorro Pequeno Porte'), ('Cachorro Médio Porte','Cachorro Médio Porte'),('Cachorro Grande Porte','Cachorro Grande Porte'),('Gato','Gato'), ('Pássaros', 'Pássaros'), ('Peixes','Peixes'), ('Reptéis','Reptéis'), ('Roedores','Roedores') ) class Negocio(models.Model): pet_aceitos = MultiSelectField(max_length=255, choices=PETN_CHOICES) forms.py class NegocioForm(UserCreationForm): pet_aceitos = forms.MultipleChoiceField( widget=forms.CheckboxSelectMultiple, choices=PETN_CHOICES, ) class Meta: model = User filter.py import django_filters from django import forms import django_filters from .models import ( Negocio, ) class NegocioFilter(django_filters.FilterSet): class Meta: model = Negocio fields = ['cidade', 'estado', 'pet_aceitos', 'tipo', 'telefone'] user_list.html {% block main %} <form method="get"> {{ filter.form.as_p }} <button type="submit">Search</button> </form> <ul> {% for negocio in filter.qs %} <li><img src="{{negocio.foto.medium.url}}"class="rounded-circle" width="50" height="50"> - {{ negocio.cidade }} - {{ negocio.estado }}- {{ negocio.pet_aceitos }} - {{ negocio.tipo }} - …