Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
DRF M2M Nested Serializer Field Incorrectly Typed as String
Whenever I attempt to deserialize a list of Technology objects while creating a TechnologyStack I receive the message: "Field \"technologies\" of type \"String\" must not have a sub selection." I'm using djangorestframework==3.8.2. Anyone know what's causing this and/or a potential solution? Also, please note that I'm using the graphene-django library. But, it seems this problem is attributable to the drf serializer. class TechnologyProfile(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=100, unique=True) class Technology(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) profile = models.ForeignKey(TechnologyProfile, blank=True, null=True, on_delete=models.CASCADE) class Meta: verbose_name_plural = "technologies" class TechnologyStack(models.Model): technologies = models.ManyToManyField(Technology, related_name='technology_stacks') class TechnologyProfileSerializer(serializers.ModelSerializer): user_id = RelayIdField() name = serializers.CharField() class Meta: model = TechnologyProfile fields = ('id', 'name', 'user_id') class TechnologySerializer(serializers.ModelSerializer): user_id = RelayIdField() profile = TechnologyProfileSerializer(many=False) class Meta: model = Technology fields = '__all__' class TechnologyStackSerializer(serializers.ModelSerializer): technologies = TechnologySerializer(many=True) class Meta: model = TechnologyStack read_only_fields = ('id',) fields = '__all__' -
Django display related count
i currently try to display who many posts a category has. Therefor i created the Post Model and the Category Model (See below): models.py # Categorys of Post Model class Category(models.Model): title = models.CharField(max_length=255, verbose_name="Title") class Meta: verbose_name = "Category" verbose_name_plural = "Categories" ordering = ['title'] def __str__(self): return self.title #Post Model class Post(models.Model): author = models.ForeignKey('auth.User', on_delete=models.CASCADE) title = models.CharField(max_length=200) text = models.TextField(max_length=10000) category = models.ForeignKey(Category, verbose_name="Category", on_delete=models.CASCADE, null=True) tag = models.CharField(max_length=50, blank=True) postattachment = fields.FileField(upload_to='postattachment/%Y/%m/%d/', blank=True, null=True) postcover = fields.ImageField(upload_to='postcover/%Y/%m/%d/', blank=True, null=True, dependencies=[ FileDependency(processor=ImageProcessor( format='JPEG', scale={'max_width': 300, 'max_height': 300})) ]) created_date = models.DateTimeField(default=timezone.now) published_date = models.DateTimeField(blank=True, null=True) def publish(self): self.published_date = timezone.now() self.save() def __str__(self): return self.title category_list.html {% extends 'quickblog/base.html' %} {% block content %} {% for categories in categories %} <div> <h1><u>{{ categories.title }} {{ $NumCountGetHere }}</u></h1> </div> {% endfor %} {% endblock %} Now i have no idea how to get the related objects counted...? -
how to use django objects in views
my intent is every time a sms is sent to my server the server should look thru the database to see if the number from the sms is already a stored object if it isn't then create and save the object to the database what am i doing wrong? views.py from django.http import request from django_twilio.decorators import twilio_view from django_twilio.request import decompose from twilio.twiml.messaging_response import MessagingResponse from .models import Contacts @twilio_view def sms_choice(request): twilio_request = decompose(request) contact_num = twilio_request.from_ contact_info = ['Thanks for your subscription', "How old are you?", "Annual Income?"] response = twilio_request.body resp = MessagingResponse() subscribers = [Contacts.objects.all()] for contact in subscribers: if contact_num != contact.customer_number: b = Contacts(customer_number=contact_num) b.save() resp.message(contact_info[0]) elif contact_num == contact.customer_number: resp.message(contact_info[1]) print(contact_num, response) return str(resp) models.py from django.db import models class Contacts (models.Model): customer_number = models.CharField(max_length=15) customer_age = models.CharField(max_length=4, null=True) customer_income = models.CharField(max_length=10, null=True) def __unicode__(self): return self.customer_number -
Django auth: How to get user data?
I´m trying to develop app which when user requests will give his additional details only if he is logged-in I am using Django-Rest-Framework. I´m able to login, get token, but how can I retrieve additional User data? class BasicUserInfo(AbstractUser): email = models.EmailField(primary_key=True, unique=True, db_index=True) class UserInfo(models.Model): user = models.ForeignKey(BasicUserInfo, on_delete=models.CASCADE) phoneNo = PhoneField(default="") So basically if user requests with GET API endpoint I want to send only that user's phone number -
Sort by field value in Django 2.0
This question is like django sorting but I can't make any of the solutions work. I have the following model: from django.db import models from django.contrib.auth.models import User class Product(models.Model): title = models.CharField(max_length=200) pub_date = models.DateTimeField() body = models.TextField() url = models.TextField() image = models.ImageField(upload_to='images/') icon = models.ImageField(upload_to='images/') votes_total = models.IntegerField(default=1) hunter = models.ForeignKey(User, on_delete=models.CASCADE) def summary(self): return self.body[:50] def pub_date_pretty(self): return self.pub_date.strftime('%b %e %Y') def __str__(self): return self.title I would like to sort by votes_total so that when I loop through the database results are ordered by votes_total. {% extends 'base.html' %} {% block content %} {% for product in products.all %} <div class="row pt-3"> <div class="col-2" onclick="window.location='{% url 'detail' product.id %}';" style="cursor:pointer"> <img src="{{ product.icon.url }}" class="img-fluid" alt=""> </div> <div class="col-6" onclick="window.location='{% url 'detail' product.id %}';" style="cursor:pointer"> <h1>{{ product.title }}</h1> <p>{{ product.summary }}</p> </div> <div class="col-4" onclick="window.location='{% url 'detail' product.id %}';" style="cursor:pointer"> <a href="javascript:{document.getElementById('upvote{{ product.id }}').submit()}"><button class="btn btn-primary btn-lg btn-block"><span class="oi oi-caret-top"></span> Upvote {{ product.votes_total }}</button></a> </div> </div> <form id="upvote{{ product.id }}" method="POST" action="{% url 'upvote' product.id %}"> {% csrf_token %} <input type="hidden"> </form> {% endfor %} {% endblock %} How do I sort my results? -
Can't upload image and get expecteds behavior in django rest framework
I've tried all possible options on this over the last two days and nothing seems to work. Please bear with me this will be a little long. This is my UserProfile model class UserProfile(models.Model): user = models.OneToOneField(User, related_name='profile', on_delete=models.CASCADE, ) status = models.CharField(max_length=255, null=True, blank=True) thumbnail = models.ImageField(upload_to='media/user/', blank=True, null=True) This is the Serializer, class UserProfileSerializer(serializers.ModelSerializer): thumbnail = serializers.ImageField(max_length=256, use_url=True, allow_empty_file=False) class Meta: model = models.UserProfile fields = ('status', 'thumbnail',) Now when I try to upload this image using POSTMAN, this the output that I get, { "thumbnail": [ "No file was submitted." ] } Reading some SO posts I tried replacing the default serializer.ImageField to the this, class Base64ImageField(serializers.ImageField): """ A Django REST framework field for handling image-uploads through raw post data. It uses base64 for encoding and decoding the contents of the file. Heavily based on https://github.com/tomchristie/django-rest-framework/pull/1268 Updated for Django REST framework 3. """ def to_internal_value(self, data): # Check if this is a base64 string if isinstance(data, six.string_types): # Check if the base64 string is in the "data:" format if 'data:' in data and ';base64,' in data: # Break out the header from the base64 content header, data = data.split(';base64,') # Try to decode the file. Return validation … -
AWS EB django app /opt/python/ondeck/app/requirements.txt' returned non-zero exit status 1
My django app was deployed and working fine but all of a sudden when I added a few dependencies and pip freeze > requirements.txt and re-eb deploy it. I receive this error At top level: cc1: warning: unrecognized command line option "-Wno-unused-result" error: command 'gcc' failed with exit status 1 ---------------------------------------- Command "/opt/python/run/venv/bin/python3.6 -u -c "import setuptools, tokenize;__file__='/tmp/pip-build-ugvss5p7/python-ldap/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record /tmp/pip-baqi8ce7-record/install-record.txt --single-version-externally-managed --compile --install-headers /opt/python/run/venv/include/site/python3.6/python-ldap" failed with error code 1 in /tmp/pip-build-ugvss5p7/python-ldap/ You are using pip version 9.0.1, however version 10.0.1 is available. You should consider upgrading via the 'pip install --upgrade pip' command. 2018-05-28 16:32:58,033 ERROR Error installing dependencies: Command '/opt/python/run/venv/bin/pip install -r /opt/python/ondeck/app/requirements.txt' returned non-zero exit status 1 Traceback (most recent call last): File "/opt/elasticbeanstalk/hooks/appdeploy/pre/03deploy.py", line 22, in main install_dependencies() File "/opt/elasticbeanstalk/hooks/appdeploy/pre/03deploy.py", line 18, in install_dependencies check_call('%s install -r %s' % (os.path.join(APP_VIRTUAL_ENV, 'bin', 'pip'), requirements_file), shell=True) File "/usr/lib64/python2.7/subprocess.py", line 186, in check_call raise CalledProcessError(retcode, cmd) CalledProcessError: Command '/opt/python/run/venv/bin/pip install -r /opt/python/ondeck/app/requirements.txt' returned non-zero exit status 1 (Executor::NonZeroExitStatus) I removed all the new dependencies and the code looks exactly like the way it was last deployment but it still get the same error. Please help. -
Django: using items in list without executing for loop in view
Apologies for the unclear title, I'm not sure how to articulate my question in a few words. Basically, within my view I have a variable containing a list of objects (photos): photos = Photo.objects.all() In my template I have a for loop for these objects where I display the attributes (e.g. photo.author ). I would like to have some logic to be run on individual photo instances: all_likes = Like.objects.all() for photo in photos: pic_likes = all_likes.filter(photo_id=id) like_count = len(pic_likes) liker = pic_likes.filter(liker_id=request.user.id) if len(liker) != 0: liked=True but using a for loop inside the view causes the error int() argument must be a string, a bytes-like object or a number, not 'builtin_function_or_method' How should I go about having logic for the photo instances but not the object list as a whole? -
Locate the coordinates within a certain radius
I want to locate certain stores(coordinates known), say, within 10km from my home. Below is a snippet of my code but the approach is still not very clear to me, yet. def within_bounding_box(lat_in_degrees, lng_in_degrees, distance_km): assert lat_in_degrees >= -90.0 and lat_in_degrees <= 90.0 assert lng_in_degrees >= -180.0 and lng_in_degrees <= 180.0 distance_km = 10 lat = radians(lat_in_degrees) lon = radians(lng_in_degrees) How do I proceed further? -
Django error "invalid literal for int()" when attempting to use pk_url_kwarg
Newbie here, having trouble understanding why this won't work and what is causing this error. I just want to put the program code into the URL and have it display the detail page. It works fine with the primary key but can't figure it out using the kwarg. What am I doing wrong? Exception Value: invalid literal for int() with base 10: 'T0001' Views: class ProgramDetailView(DetailView): model = Program template_name = 'submissions/program_details.html' pk_url_kwarg = 'program_code' URLS: path('<program_code>/', ProgramDetailView.as_view(), name='program-detail'), Models: class Program(models.Model): client = models.ForeignKey(Client, on_delete=models.CASCADE) program_code = models.CharField(max_length=5) program_name = models.CharField(max_length=50) program_board = models.CharField(max_length=10) monthly_quantity = models.IntegerField(default=0) def __str__(self): return self.program_code -
Designing model architecture for assembly manufacturing
I have the following domain: A Product (literal, ie. shoe) is made by doing doing certain Jobs (literal again, e.g. stitching, cutting, sewing...). This is a simple enough relationship, a certain Product has many Job and so a one-to-many (FK) relationship. The problem comes when there are a lot of Products and they start to share quite a few common Jobs, e.g. certain Products are always packed into the same box the same way. Hence one would want to be able to use the same Job instance in all of these Products because later on editing will be much easier. Therefore a M2M relationship is more appropriate. However, most of the Jobs are still product specific, they are truly unique to the Product and so I'm not sure how to design this domain. The baseline is that common Jobs should be abstracted (e.g. GenericJob) because it will be really time consuming to edit so many duplicated Jobs in the future. At the same time it is important to be able to query all the Jobs relating to certain Product in order to calculate stuff like cost and/or time it takes to make. Any suggestions? -
Django: How can I Do multiple POST in a loop?
I need to do multiple post in a loop, but when i try to do it, django does every element in the loop, and after that, django does multiple posts, so i think that i need a promise or something like that, to synchronous the post. function create_charts() { $('.monitor-chart').each(function (index, item) { elem = $(item); var id = elem.attr('id'); var measure = elem.data('measure'); var unit = elem.data('unit'); var meter = elem.data('meter'); var meter_name = elem.data('meter_name'); var name = elem.data('name'); var option_measure = elem.data('measure_name'); var datos = {'graphics_len': index, 'option_meter': meter, 'option_measure':option_measure, 'div_id':id, 'csrfmiddlewaretoken': '{{ csrf_token }}' }; $.post("{% url 'dashboard_operative' %}", datos).then(function(response){ jsonData = JSON.parse(response); var chart = new Highcharts.Chart(elem[0], jsonData); chart.setTitle({text: "", useHTML: true}); reflow_chart(chart, unit); }, function(error){ console.log(error); }); }); } -
Django postgres Json field with numeric keys
I have model with postgres json field. class MyModel(models.Model): data = JSONField(null=True) then, I do: m1 = MyModel.objects.create(data={'10':'2017-12-1'}) m2 = MyModel.objects.create(data={'10':'2018-5-1'}) I want query all the MyModel whose key '10' starts with '2017', so I want to write: MyModel.objects.filter(data__10__startswith='2017') The problem is that the 10 is interpreted as integer, and therefore, int he generated query it is considered as list index and not key. Is there anyway to solve this? (except writing raw queries). This is the generated query: SELECT "systools_mymodel"."id", "systools_mymodel"."data" FROM "systools_mymodel" WHERE ("systools_mymodel"."data" ->> 10)::text LIKE '2017%' LIMIT 21; And I want the 10 to be quoted (which would give me the right answer). Thanks! -
Execution time difference between Django query and raw sql query in terminal
I have a Django query which running well but I the execution slower than I make this same query in terminal. In curiosity I have run the django query (i have read it from Django Debug Tooltbar) in terminal and I got the same slow query. I tried to find out what could be the problem and I suspect to the ::timestamp conversion. I try to present my problem below: My django query: query=Table.filter(time_stamp__range=('2017-05-28 01:00:00', '2017-05-28 07:00:00')).values('time_stamp', 'value') Which is equalt to this raw sql statment according to Django Debug Toolbar: SELECT * FROM "table" WHERE "table"."time_stamp" BETWEEN '2018-05-28T01:00:00.004325'::timestamp AND '2018-05-28T07:00:00.004325'::timestamp Based on the Debug Toolbar result I got 1436,11 ms running time. After that I logged in into my PostgreSQl database via terminal and I used this query: select * from table where time_stamp between '2018-05-28 01:00:00' and '2018-05-28 07:00:00'; Here I got 753.086 ms execiton time. In my mind the two query is the same except the timestamp (::timestamp) conversation in Django query. How could I avoid the the timestamp conversation in my Django query which I think coused the slow query? Thank you in advace for your help! -
Django template inheritance not working on apache server
When I am using django template tagging/inheritance, just plain text is being rendered. For instance, index.html below is just the text in the html file rather than loading in base.html. It works on my local machine, but I just can't get to work on the server. I ran python manage.py collectstatic before running. I'm also using mod_wsgi. Here is my setup base.html {% load static %} ...stuff... {% block head_block %} {% endblock %} ...stuff... {% block body_block %} {% endblock %} index.html {% extends 'base.html' %} {% block body_block %} {% endblock %} settings.py STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) STATIC_ROOT = os.path.join(BASE_DIR, 'static/') etc/sites-enabled/000-default.conf Alias /static /home/myuser/myproject/static <Directory /home/myuser/myproject/static> Require all granted </Directory> -
What is the difference between path() and re_path()?
In Django2.0 were introduced path() and re_path(). But the difference between boths is unclear to me : is it about the ability to use or not regexps with it? Would that mean that I couldn't use both <type:name> and (?P<name>\d+) syntaxes in the same pattern? -
save_m2m() not able to save many to many field
if form.is_valid(): a = form.save(commit=False) files = request.FILES.getlist('a_file') for f in files: file_model = aFile(filename=f, user=request.user) file_model.save() a.a_file.add(file_model) a.save() form.save_m2m() This the views.py I am using for saving the file but below is the traceback error I am receving- 2018-05-28 14:30:16,604 ERROR exception.py handle_uncaught_exception: Internal Server Error: /inv/as Traceback (most recent call last): File "/usr/local/v/on/lib/python3.6/site-packages/django/core/handlers/exception.py", line 41, in inner response = get_response(request) File "/usr/local/v/on/lib/python3.6/site-packages/django/core/handlers/base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "/usr/local/v/on/lib/python3.6/site-packages/django/core/handlers/base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "./inv/views.py", line 160, in contract_list form.save_m2m() File "/usr/local/v/on/lib/python3.6/site-packages/django/forms/models.py", line 451, in _save_m2m f.save_form_data(self.instance, cleaned_data[f.name]) File "/usr/local/v/on/lib/python3.6/site-packages/django/db/models/fields/related.py", line 1686, in save_form_data getattr(instance, self.attname).set(data) File "/usr/local/venv/nemo/lib/python3.6/site-packages/django/db/models/fields/related_descriptors.py", line 983, in set objs = tuple(objs) TypeError: 'NoneType' object is not iterable I have a custom save() method defined, dont think that should effect the function of save_m2m(). If I remove the form.save_m2m(), the form gets saved but the manytomany fields are not saved. The traceback, I think shows that my form is not getting saved and hence save_m2m()is not working but I am not sure why. Please suggest. -
Cleanest way to decorate Django's dispatch method
I stumbled upon a code that is used to provide some args to the request method. Problem is that I'm not that sure if it is the cleanest way to handle this case. def check_permissions(check_mixins): """ :param check_mixins: is given to the inner decorator Decorator that will automatically populate some parameters when using dispatch() toward the right method (get(), post()) """ def _decorator(_dispatch): def wrapper(request, *args, **kwargs): Is it a problem if "self" isn't passed in the method definition in here... for mixin in check_mixins: kwargs = mixin.check(request, *args, **kwargs) if isinstance(kwargs, HttpResponseRedirect): return kwargs return _dispatch(request, *args, **kwargs) return wrapper return _decorator class UserLoginMixin(object): def check(request, *args, **kwargs): ... and here ? It seems so ugly in my IDE user = request.user if user.is_authenticated() and not user.is_anonymous(): kwargs['user'] = user return kwargs return redirect('user_login') class AppoExistMixin(object): def check(request, *args, **kwargs): Here too... appo_id = kwargs['appo_id'] try: appoff = IdAppoff.objects.get(id=appo_id) kwargs['appoff'] = appoff del kwargs['appo_id'] return kwargs except IdAppoff.DoesNotExist: pass messages.add_message(request, messages.ERROR, "Item doesn't exist!") return redirect('home') class SecurityMixin(View): """ Mixin that dispatch() to the right method with augmented kwargs. kwargs are added if they match to specific treatment. """ data = [] def __init__(self, authenticators): super(SecurityMixin, self).__init__() # Clearing … -
Django - Export List of dictionaries to CSV
I have created a list of dictionaries in views.py, my_list= [ {'user': 1000, 'account1': 100, 'account2': 200, 'account3': 100}, {'user': 1001, 'account1': 110, 'account2': 100, 'account3': 250}, {'user': 1002, 'account1': 220, 'account2': 200, 'account3': 100}, ] I want to export it to csv file. response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="mylist.csv"' writer = csv.writer(response) for data in my_list: writer.writerow(data) return response I know there is a error for "for data in my_list". my_list contains all the keys and values. How to get only keys for my_list? or there is another method to export list to csv? (I'm using django 2 with python3.4) -
Assertion failed on google maps polyline extraction and buffer
I am working on a django project where the user inputs their start and end location in the form a string. My application must connect to the google direction service API, take the string and convert it to coords. Then from the coordinates create a polyline, and add a 1km buffer. Which will be saved in a postgis database as a polygon. from django.db import models from django.contrib.gis.db import models from django.forms import ModelForm from django_google_maps import fields as map_fields import shapely.geometry import googlemaps from googlemaps import Client # Create your models here. class Route(models.Model): startPoint_address = PointField() startPoint_geolocation = Pointfield() endPoint_address = PointField() endPoint_geolocation = Pointfield() # endPoint = models.PointField() # deviationDistance = models.IntegerField(default=20) # routeName = models.CharField(max_length=50) # https://github.com/geodav-tech/decode-google-maps-polyline def decode_polyline(polyline_str): '''Pass a Google Maps encoded polyline string; returns list of lat/lon pairs''' index, lat, lng = 0, 0, 0 coordinates = [] changes = {'latitude': 0, 'longitude': 0} # Coordinates have variable length when encoded, so just keep # track of whether we've hit the end of the string. In each # while loop iteration, a single coordinate is decoded. while index < len(polyline_str): # Gather lat/lon changes, store them in a dictionary to apply them later … -
Django - how to dynamically generate a menu in base template
I want to dynamically generate a menu from the database, and separate this menu into a template base.html. I dynamically generated the menu Html in home's view.py, and then output this html to base.html. However, I can only display the menu when I visit the Home page, but not when I jump to another page. How can I display the menu on each page? home/view.py def dashboard(request): """ :param request: :return: """ if 'user_id' not in request.session: return HttpResponseRedirect('login') menus = load_nav(request) context = {'menus': menus, 'username': request.session.get('user_name')} return render(request, 'home/index.html', context) def load_nav(request): """ :param request: :return: """ current_user = User.objects.get(id=request.session.get('user_id')) if current_user is None: return render(request, './unauthorized.html') try: current_user_role = current_user.role.all()[:1].get() except User.DoesNotExist: return render(request, './unauthorized.html', {'message': 'No Auth.'}) menus = current_user_role.nav.filter(parent=None).all() sub_menus = current_user_role.nav.exclude(parent__isnull=True).all() menu_html = '' if menus is None: menu_html += '<li><a href="javascript:void(0);">Index</a>' else: for menu in menus: if not menu.hasChildNav(): menu_html += '<li><a href="{url}" target="{target}"><i class="icon {icon}"></i><span>{name}</span></a>' else: menu_html += '<li class="submenu"><a href="#" target="{target}"><i class="icon {icon}"></i><span>{name}</span></a>' menu_html += '<ul style="display: none;">' menu_html += load_sub_nav(menu.id, sub_menus) menu_html += '</ul>' menu_html = menu_html.format(url=menu.url, icon=menu.icon, target=menu.target, name=menu.name) return format_html(menu_html) def load_sub_nav(parent_id, menu): """ :param parent_id: :param menu: :return: """ sub_menu_html = '' sub_menus = menu.filter(parent=parent_id).all() if sub_menus … -
Translate ?page_no=5 to <QueryDict: {'page_no': ['5']}>
When I send a query request like ?page_no=5 from the brower: http://127.0.0.1:8001/article/list/1?page_no=5 I get the output in the debugging terminal def article_list(request, block_id): print(request.GET) <QueryDict: {'page_no': ['5']}> Django encapsulates the page_no=5 to a dict {'page_no': ['5']} How Django accomplish such a task, are the regex or str.split employed? -
Selenium - socket.error: [Errno 111] Connection refused
I'm trying to create Selenium tests for my web application. So far I have: from selenium import webdriver import httplib driver = webdriver.Chrome('v1/chromedriver-Linux64') #in tutorial, it was just webdriver.Chrome() but that didn't work url = "http://127.0.0.1:8000/loty/accounts/login/" try: driver.get(url) except httplib.BadStatusLine as bsl: pass #in tutorial, it was just driver.get(url) but that didn't work driver.find_element_by_css_selector("#menu") Unfortunately, I get a long traceback ending with socket.error: [Errno 111] Connection refused. How can I get it to work? -
django restframework token causes ImportError
I tried using django rest framework Token package. after I ran migration then I implemented the get or create method but ran into an error so I decided to run migrations again then i got an error saying ImportError: No module named authtokencashondelivery . I have an application in my project named cash on delivery but I dont know the problem now. If I comment out the rest_framework.token in my settings , everything works fine but I still want to work with it -
If I get the IP adress from a user in django, how should I store it in a model?
I am able to find out how to get the users IP in django. But, I do not know how to store it in a model. I was planning on just putting it in a TextField.