Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Adding python script to views.py in django and firing with button click
Total novice here. Trying to make a web app that generates and displays a random video when a button is clicked on a django page. I have a python script that generates the video. I have a django project with templates/home.html, views.py, urls.py, and my python script videogenfull.py in it. For now it looks like this.. views.py: from django.http import HttpResponse from django.shortcuts import render def home_view(request, *args, **kwargs): print(args, kwargs) print(request.user) return render(request, "home.html", {}) urls.py: from django.contrib import admin from django.urls import path from pages.views import home_view urlpatterns = [ path('', home_view, name='home'), path('admin/', admin.site.urls) ] videogenfull.py - pulls random videos from web, edits them and exports them out as one (very small) video. I have setup a static folder where the generated video will go to and put in some html code in home.html for the video to play. The html page successfully shows up in my browser - text header and temp video for now. Next I know that I need to: make a html/ajax/jquery button in my html file write some code in views.py to get videogenfull.py in there so it fires when the button is clicked I've been at this last part for a … -
How to generate random URL in urls.py each time the user logs in (Django)?
I am trying to create a random URL that can be accessed only once after the user logs in. I am using django-sesame to generate different URLs each time the user logs in. To do this, I have set the SESAME_ONE_TIME setting to True in settings.py, and I am able to redirect the user to the random URL like this: views.py: import sesame @login_required() def password_form(request): url_extension = sesame.utils.get_query_string(request.user) if request.method == 'POST': form = PasswordChangeForm(request.user, request.POST) if form.is_valid(): user = form.save() update_session_auth_hash(request, user) return redirect('/success/' + url_extension) else: form = PasswordChangeForm(request.user) context = {'form': form} return render(request, "form.html", context) However, in urls.py I don't know how to add the URL to urlpatterns properly. This probably sounds weird, but, for a lack of better wording, is there any way you can add a parameter that can accept a randomly generated value in path, like: urls.py: from app.views import password_form urlpatterns = [path('success/' + random_variable, password_form),] If not, is there any way I can make the url_extension variable global, so that I can use it in urls.py, by bypassing the need for request (e.g. setting url_extension as an attribute to a function in views.py and using it as function.url_extension in urls.py)? -
Why in this example uploaded_by which is (uploaded_by_id) gets passed to DB as NULL?
why uploade_by_id is not set to user ID? want to map uploaded files to the user which uploads. models.py from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save class Profile(models.Model): CUSTOMER_TYPE = ( ('Business', 'Business'), ('Personal', 'Personal'), ) user = models.OneToOneField(User, on_delete=models.CASCADE) customer_type = models.CharField(max_length=10,choices=CUSTOMER_TYPE) phone = models.CharField(max_length=10, blank=True) def __str__(self): return self.user.username class Document(models.Model): uploaded_by = models.ForeignKey(User, on_delete=models.CASCADE) document_name = models.FileField() date_created = models.DateTimeField(auto_now_add=True) -
Button not executing Django/Python script
In my home.html template: <button type="button" class="btn btn-dark" method = 'GET' action = '/action_name/' name="audio_record">Record Audio</button> In my views.py: def audio_functions(request): print('called function') In my urls.py: path('/action_name/', views.audio_functions, name='audio-record'), what am i doing wrong? -
Getting the context of a specific page in Wagtail / Puput
I have a Django/Wagtail/Puput site with this structure: RootPage | |- BlogPage (Puput) |- InformationPage I'm trying to display summary info from the Puput blog on the InformationPage. This works with this code, as long as I only have one BlogPage: class InformationPage(Page): body = RichTextField(verbose_name=_("body")) def get_context(self, request, *args, **kwargs): context = super(InformationPage, self).get_context( request, *args, **kwargs) context['blog_page'] = BlogPage.objects.first() context['information_page'] = self return context But I'm trying to make it work with more than one blog page. It seems like this should work: class InformationPage(Page): body = RichTextField(verbose_name=_("body")) blog_page = models.ForeignKey('wagtailcore.Page', on_delete=models.PROTECT, related_name="information_blog") content_panels = [ MultiFieldPanel( [ FieldPanel("title", classname="title"), FieldPanel("body", classname="full"), PageChooserPanel('blog_page'), ], heading=_("Content"), )] def get_context(self, request, *args, **kwargs): context = super(InformationPage, self).get_context( request, *args, **kwargs) context['blog_page'] = self.blog_page context['information_page'] = self return context But it doesn't. This was suggested here. In other words, if I refer to the blog page properties using context['blog_page'] = BlogPage.objects.first(), everything works fine, but switching it out to use context['blog_page'] = self.blog_page (and selecting the correct blog page in the admin) does not work. Without switching it out, I think I can only ever have a single instance of BlogPage, because all InformationPages will have to pull from the first … -
Why don't variables work with "instance" in Django signals?
This works: @receiver(pre_save, sender=MyModel) def some_signal_function(sender, instance, *args, **kwargs): instance.field_name = 'foo' return None ...this will save 'foo' as the field_name. Simple enough. But why doesn't this work: @receiver(pre_save, sender=MyModel) def some_signal_function(sender, instance, *args, **kwargs): foo = 'field_name' instance.foo = 'bar' return None In the second case, django ignores the variable "foo" or treats it as a literal. Using string method on the variable doesn't help. Not finding anything in the docs. -
How can I provide users option to add search results, with click of button, to database model in Django?
I am a django beginner and am creating a simple app where users can search players from a model and then be given option to add those players as their favorite player, which is stored in a different model. I have created a search view as shown below: ```def search(request): try: q = request.GET.get('q') except: q = None if q: Players = Player.objects.filter(First_Name__icontains=q) context = {'query': q, 'Players': Players} template = 'home/results.html' else: template = 'home/index.html' context = {} return render(request,template,context)``` The search view shows redirects users to home/results.html where results are displayed. I would like for users to be able to click a button next to each of results and add that player to favorites database. I have tried to use Django ModelForms in forms.py as follows: from django import forms from .models import favoritePlayer class favoritePlayerForm(forms.ModelForm): class Meta: model = favoritePlayer fields = ['First_Name',] The following is the view function I have wrote to add player into favorites database: def favorite_create_view (request): form = favoritePlayerForm(request.POST or None) if form.is_valid(): form.save() context = {'form':form} template = 'home/results.html' return render(request,template,context) Finally, below is the results.html file: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>Searched for {{ query … -
Object of type is not JSON serializable
Just started with Django Rest framework and following the great tutorial: https://sunscrapers.com/blog/ultimate-tutorial-django-rest-framework-part-1/ I have created a test model: class Test(models.Model): name = models.CharField(max_length=100) age = models.IntegerField And to make the object available through the API, I have implemented a serializer. This would serialize to XML, YAML or JSON, the latter is what I am interested in. Below is my serialization class. class TestSerializer(serializers.ModelSerializer): class Meta: model = models.Test fields = ('name', 'age') However, it doesn't seem to serialize to JSON as expected as the error below shows: File "C:\Program Files\Python38\lib\json\encoder.py", line 179, in default raise TypeError(f'Object of type {o.__class__.__name__} ' TypeError: Object of type type is not JSON serializable Worth adding, that it worked for like 2 hours then just went bad. -
Python SAML not returning assertion (NoneType-Error)
I'm trying to enable a login via shibboleth to my django-app. The redirect to the IdP works fine, but python-saml2 throws an error: 'NoneType' object has no attribute 'authn_statement'. I'm using djangosaml2 for the connection. Error: 2020-05-29 00:18:35,929 ERROR Internal Server Error: /saml2/acs/ Traceback (most recent call last): File "/var/www/django/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/var/www/venv/lib/python3.6/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/var/www/venv/lib/python3.6/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/var/www/venv/lib/python3.6/site-packages/django/views/decorators/http.py", line 40, in inner return func(request, *args, **kwargs) File "/var/www/venv/lib/python3.6/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/var/www/venv/lib/python3.6/site-packages/djangosaml2/views.py", line 329, in assertion_consumer_service session_info = response.session_info() File "/var/www/venv/lib/python3.6/site-packages/saml2/response.py", line 1108, in session_info authn_statement = self.assertion.authn_statement[0] AttributeError: 'NoneType' object has no attribute 'authn_statement' Log: 020-05-29 00:18:30,959 DEBUG Login process started 2020-05-29 00:18:30,960 WARNING delete_tmpfiles is set to False; temporary files will not be deleted. 2020-05-29 00:18:31,031 DEBUG service => {'urn:mace:shibboleth:1.0:profiles:AuthnRequest': [{'__class__': 'urn:oasis:names:tc:SAML:2.0:metadata&SingleSignOnService', 'binding': 'urn:mace:shibboleth:1.0:profiles:AuthnRequest', 'location': 'https://{***}/idp/profile/Shibboleth/SSO'}], 'urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect': [{'__class__': 'urn:oasis:names:tc:SAML:2.0:metadata&SingleSignOnService', 'binding': 'urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect', 'location': 'https://{***}/idp/profile/SAML2/Redirect/SSO'}], 'urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST': [{'__class__': 'urn:oasis:names:tc:SAML:2.0:metadata&SingleSignOnService', 'binding': 'urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST', 'location': 'https://{***}/idp/profile/SAML2/POST/SSO'}], 'urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST-SimpleSign': [{'__class__': 'urn:oasis:names:tc:SAML:2.0:metadata&SingleSignOnService', 'binding': 'urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST-SimpleSign', 'location': 'https://{***}/idp/profile/SAML2/POST-SimpleSign/SSO'}]} 2020-05-29 00:18:31,031 DEBUG Trying binding urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect for IDP https://{***}/idp/shibboleth 2020-05-29 00:18:31,031 DEBUG service(https://{***}/idp/shibboleth, idpsso_descriptor, single_sign_on_service, None) 2020-05-29 00:18:31,031 DEBUG service => {'urn:mace:shibboleth:1.0:profiles:AuthnRequest': [{'__class__': 'urn:oasis:names:tc:SAML:2.0:metadata&SingleSignOnService', … -
I have these two tables, one is Airtable, other Sqlite, how can i merge them into one?
I have a Django REST api serving the sqlite data. I also have an airtable databse that serves as a backup and has the same rows as the sqlite. What is a proper way of combining both and don't have repeated fields. Im doing the front in REACT. -
Django, adding on localhost in admin panel error but working when manually on db.sqlite3
Working on my first django website. In the Admin panel on the local host unable to add anything simply by clicking add. Error added at the bottom. Manual change of db.sqlite3 with DB browser for SQLite is working fine. Exception Type: OperationalError Exception Value: no such table: main.auth_user__old Exception Location: C:\Users\cex.virtualenvs\Web-IP9wVexr\lib\site-packages\django\db\backends\sqlite3\base.py in execute, line 296 Python Executable: C:\Users\cex.virtualenvs\Web-IP9wVexr\Scripts\python.exe Python Version: 3.8.3 Python Path: ['C:\Localpath\Documents\Web', 'C:\Localpath\.virtualenvs\Web-IP9wVexr\Scripts\python38.zip', 'c:\Localpath\appdata\local\programs\python\python38-32\DLLs', 'c:\Localpath\appdata\local\programs\python\python38-32\lib', 'c:\Localpath\appdata\local\programs\python\python38-32', 'C:\Localpath\.virtualenvs\Web-IP9wVexr', 'C:\Localpath\.virtualenvs\Web-IP9wVexr\lib\site-packages'] -
sort data between many table django rest framework
Here is my class diagram. I receive a lot of data in Product table with differente type. When i receive the data i want to sort it in inherit tables. Example: if type is "example1" she will put herself automaticly in table Example 1. class ProductModelSerializer(serializers.ModelSerializer): class Meta: model = Product fields = "__all__" class ProductViews(viewsets.ModelViewSet): permission_classes =(permissions.IsAuthenticated, permissions.IsAdminUser) queryset = Product.objects.all() serializer_class = ProductSerializer filter_backends = [DjangoFilterBackend] filterset_fields = ['desination'] def create(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data, many=isinstance(request.data,list)) serializer.is_valid(raise_exception=True) self.perform_create(serializer) headers = self.get_success_headers(serializer.data) return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers) I don't know what to do. I am blocked. Any help ? -
Returning all data from django backend
I have this problem, that my backend does not return all data. It returns the database table rows, that the token of the logged user matches the user's id of the model. Here is the Blog model class Blog(models.Model): title = models.CharField(max_length=100) content = models.CharField(max_length=500) created_at = models.DateTimeField(auto_now_add=True) userID = models.ForeignKey(User, on_delete=models.CASCADE, related_name='posts', null=True) And here is the class that returns the data class BlogViewSet(viewsets.ModelViewSet): permission_classes = [ permissions.IsAuthenticated ] serializer_class = BlogSerializer def get_queryset(self): return self.request.user.posts.all() How can I return every row from the db regardless of the user who posted it? -
'HttpResponse' object has no attribute 'data' in DRF
I've defined a url in urls.py to export some data as csv using Django 3.0.6 and djangorestframework 3.10.3 re_path( r'^(?:v1/)?export/csv/$', api.ExportAPIView.as_view(), name='export' ), And here is the api.py code to handle this url: class ExportAPIView(APIView): def get(self, request, *args, **kwargs): http_response = HttpResponse(content_type='text/csv') http_response[ 'Content-Disposition'] = 'attachment; filename="somefilename.csv"' writer = csv.writer(http_response) writer.writerow(['First row', 'Foo', 'Bar', 'Baz']) writer.writerow( ['Second row', 'A', 'B', 'C', '"Testing"', "Here's a quote"]) return http_response The response of this code should be simple csv file containing two rows but I'm getting this error instead: AttributeError at /v1/export/csv/ 'HttpResponse' object has no attribute 'data' Note that I've used renderer_classes = [CSVRenderer] from djangorestframework-csv and StreamingHttpResponse with no luck either. So what is the problem that I'm missing here? -
psycopg2 Installation Problems
In the psycopg2 directory after you install the library, __init__.py contains from psycopg2.psycopg .... But there is no _psycopg.py file in the psycopg2 directory. So I get the error: Failed to get real commands on module "mysite": python process died with code 1: Traceback (most recent call last): File "C:\Users\Jack\Anaconda3\envs\mysite\lib\site-packages\django\db\backends\postgresql\base.py", line 25, in <module> import psycopg2 as Database File "C:\Users\Jack\Anaconda3\envs\mysite\lib\site-packages\psycopg2\__init__.py", line 50, in <module> from psycopg2._psycopg import ( # noqa ImportError: DLL load failed while importing _psycopg: The specified module could not be found. During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Program Files\JetBrains\PyCharm 2019.3.1\plugins\python\helpers\pycharm\_jb_manage_tasks_provider.py", line 25, in <module> django.setup() File "C:\Users\Jack\Anaconda3\envs\mysite\lib\site-packages\django\__init__.py", line 24, in setup -
Django: Multiple, Grouped Annotations with Filtered ManyToMany
I'm bumping up against an issue with a series of grouped annotations on a Django QuerySet which is being filtered by a ManyToMany. Since I've been staring at my screen for too long, lets imagine a series of models about Wine tastings: class Event(model.Model): # Some Fields class Wine(models.Model): # Some Fields class Tasting(models.Model): event = models.ManyToManyField(Event) wine = models.ForeignKey(Wine) score = models.IntegerField() I want to get some aggregations on the data by wine, optionally filtering on certain events. With this sample Tasting data (which is what I'll be running the aggregation on): | wine_id | score | event_ids | | ------- | ----- | --------- | | 1 | 50 | [1] | | 1 | 50 | [1] | | 1 | 50 | [1, 2] | | 2 | 100 | [1, 2] | | 2 | 150 | [1, 2] | | 3 | 75 | [1] | The expected output, for the above data is: [ {'wine_id': 1, 'total_scores': 150, 'average_scores': 50}, {'wine_id': 2, 'total_scores': 250, 'average_scores': 125}, {'wine_id': 3, 'total_scores': 75, 'average_scores': 75}, ] Attempt 1 Just some regular values and annotation Tasting.objects.filter( event__in=Event.objects.filter(id__in=[1,2]) ).distinct().values('wine_id').annotate( total_scores=Sum('score'), average_scores=Avg('scores'), ) Which outputs: [ {'wine_id': 1, 'total_scores': … -
Can't set value from marker of a map when POST my Django form
I'm trying to render a Django form with information when I use the POST method, but I don't know why cannot save the latitude and longitude from a marker that I put in my Leaflet map. This is my code: forms.py: class RegistrationForm(forms.Form): #more things location_name = forms.CharField(widget=forms.HiddenInput(), required=False) location_lat = forms.CharField(widget=forms.HiddenInput(), required=False) location_lng = forms.CharField(widget=forms.HiddenInput(), required=False) register.html: <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>JS Bin</title> </head> <body> <form method="POST" onkeydown="return event.key != 'Enter';"> {% csrf_token %} <div class="control-group"> <div class="form-group floating-label-form-group controls mb-0 pb-2"> {{ form.as_p }} <p style="font-size:1.5em;color:#6c757d;margin-top:2em">Institución * (busque en el mapa)</p> <div id="leafletMap-registration"></div> </div> </div> <div> <br> <span class="badge badge-warning">* Campo Requerido</span> </div> <div class="mt-4 form-group"> <button type="submit" class="btn btn-primary btn-xl" id="submitButton">Registrarse</button> </div> </form> </body> </html> This is my Javascript code where I make the map: //leaflet map var leafletMap = L.map('leafletMap-registration', { fullscreenControl: true, // OR fullscreenControl: { pseudoFullscreen: false // if true, fullscreen to page width and height }, minZoom: 2 }).setView([0,0], 2); L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', { attribution: '&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors' }).addTo(leafletMap); /* Create searchcontrols */ var GeoSearchControl = window.GeoSearch.GeoSearchControl; var OpenStreetMapProvider = window.GeoSearch.OpenStreetMapProvider; var provider = new OpenStreetMapProvider({}); // Define search controls var searchControl = new GeoSearchControl({ provider: provider, style: 'bar', … -
Trying to know how many rows I have from the different fleets in django
I'm working with a project that has 3 models. Devices: All the devices involved in the project. Fleets: Each device is in one fleet. Data: The data that the devices send. Now I want to know how much data have come me today. In my view I have this, def dataPlots(request): today = datetime.date(2020, 5, 18) data = DevData.objects.filter(data_timestamp__date=today) data = loads(serializers.serialize('json', data)) If I use len() I can now the total value. But how can I know how much data do I have for each fleet? I have come to create this loop that would tell me for each device, but what I need is the value for each fleet and furthermore I think I am getting complicated. data_dict = {} for d in data: if d['fields']['dev_eui'] in data_dict: data_dict[d['fields']['dev_eui']] = data_dict[d['fields']['dev_eui']] + 1 else: data_dict[d['fields']['dev_eui']] = 1 print(data_dict) The models are: class Fleet(models.Model): fleet_id = models.IntegerField(primary_key=True, unique=True) fleet_name = models.CharField(max_length=20, unique=True) class Device(models.Model): dev_eui = models.CharField(max_length=16, primary_key=True, unique=True) dev_name = models.CharField(max_length=20, unique=True) fleet_id = models.ForeignKey(Fleet, on_delete=models.CASCADE) def __str__(self): return self.dev_eui class DevData(models.Model): data_uuid = models.UUIDField(primary_key=True, default=uuid.uuid1, editable=False) data_timestamp = models.DateTimeField() data = models.FloatField() dev_eui = models.ForeignKey(Device, on_delete=models.CASCADE) def __str__(self): return self.dev_eui Can somebody help me? I imagine that … -
Django how to call JsonResponse function to other function
I hope you understand my question, or any suggestion of another solution How to call a JsonResponse function in another function inside views.py I have a function like the following, which I call it from a template, using ajax def ajax_response(request): something = Model.objects.filter(name='something') only_id = [i.id for i in something] data = list(data.values()) return JsonResponse(data, safe=False) The case is that I also need the only_id inside another function -
filtering data in django rest framework with django-filter
i want to select all data with the same item in Product table. class ProductViews(viewsets.ModelViewSet): permission_classes =(permissions.IsAuthenticated, permissions.IsAdminUser) queryset = Generate.objects.all() serializer_class = GenerateSerializer Here is my modelViewSet. Any help ? -
Django - Redirect page slug to detailview - shortening urls
Alright, I have a simple setup with pages which belong to certain categories. In my urls I have path('<slug:category_slug>/', views.PageByCategoryView.as_view(), name='page_by_category'), path('<slug:category_slug>/<slug:page_slug>/', views.PageDetailView.as_view(), name='page_detail'), So for example; www.mywebsite.com/activities/cycling/ points to the correct detailview for a page about cycling. Now I thought It would be nice if we could shorten the url like; www.mywebsite.com/cycling/ So I wrote the following view; def redirect_with_category(request, page_slug): ''' This redirect view points to the canonical url ''' page = get_object_or_404(Page, slug=page_slug) return redirect(page, permanent=True) The urls.py are like this; path('<slug:category_slug>/', views.PageByCategoryView.as_view(), name='page_by_category'), path('<slug:page_slug>/', views.redirect_with_category, name='page_detail_redirect'), path('<slug:category_slug>/<slug:page_slug>/', views.PageDetailView.as_view(), name='page_detail'), And now we get into trouble, even though the redirect works. Django stops trying to solve the category_slug if it can't find a match. Somehow to get this to work, Django should try to resolve the next path it it does not find a match within category_slug. Apparently Django throws an error according to the documentation; "or if an exception is raised during any point in this process, Django invokes an appropriate error-handling view" Is there anyway we can solve this? Can Django be forced to look for the next matching results if it doesn't find a matching slug in the first url? So I want to … -
Django database cache queryset methods
I have a database cache for my django application. I can do the following to get multiple cache rows from the table: cache.get_many(cache_keys_list) This is a sequential query retreving one record at a time: Is it possible to have a queryset method for a database cache like would for any other model object to retreive multiple values ? -
Django Natural Keys Unable to Load For Some Models
I have a project with several models All of which I am implementing natural keys. Most of these are working but there is one model (so far) that refuses to load when I export using natural keys. NOTE: If I don't use natural keys when exporting it works. The model that will not load is CampaignTransaction, Campaign works. Here are my models and Managers: class CampainManager(models.Manager): def get_by_natural_key(self, title, org): return self.get(title=title, org__name=org) class Campaign(models.Model): """Donation Campaign information **Referenced By:** :class:`CampaignTransaction`""" title = models.CharField(max_length=100) """Campaign Title""" org = models.ForeignKey(Organization, on_delete=models.PROTECT) """:class:`~FundingHub.common.models.Organization` conducting campaign""" description = models.TextField() """Description of campaign""" start_date = models.DateTimeField() """Start date of campaign""" end_date = models.DateTimeField() """End date of campaign""" objects = CampainManager() def __str__(self): return self.title def natural_key(self): return (self.title, self.org.natural_key()) natural_key.dependencies = ['common.Organization'] class Meta: unique_together = ('org', 'title') class CampaignTransactionManager(models.Manager): def get_by_natural_key(self, cc_type, trans_id, campaign): return self.get(cc_type=cc_type, cc_transaction_id=trans_id, campaign__name=campaign) class CampaignTransaction(models.Model): """A single donation""" campaign = models.ForeignKey(Campaign, on_delete=models.PROTECT) """The :class:`Campaign` that is being donated to""" user = models.ForeignKey(get_user_model(), on_delete=models.PROTECT) """The :class:`~FundingHub.common.models.User` that is making the donation""" amount = models.DecimalField(max_digits=9, decimal_places=2) """Amount of donation""" cc_type = models.CharField(max_length=3, choices=CC_TYPES) """Type of credi card used to make the donation :data:`~FundingHub.common.models.CC_TYPES` contains the valid options""" cc_transaction_id = models.CharField(max_length=200) … -
Django isn't creating db constraints for foreign keys with SQLite
I'm using Django 3.0.6 I'm adding ForeignKey and ManyToManyField to my models, but I've noticed that django creates the INDEX, but not the actual FOREIGN KEY constraints in the db. I've tried to explicitly set db_constraint=True but as expected is useless, since it's True by default. I've found so many answers explaining this, but only for very old Django versions, doing tricks for enabling it when it was otherwise disabled. Now instead it should just work out of the box. Couldn't find anything AT ALL regarding Django 3. Code class Token (models.Model): owner = models.ForeignKey(Chiefdom, on_delete=models.CASCADE, db_constraint=True) county = models.ManyToManyField(County, db_constraint=True) amount = models.PositiveSmallIntegerField() SQLite CREATE TABLE IF NOT EXISTS Piece_token ( id integer PRIMARY KEY AUTOINCREMENT NOT NULL, amount smallint unsigned NOT NULL, owner_id integer NOT NULL ); CREATE INDEX IF NOT EXISTS Piece_token_owner_id_d27c77f0 ON Piece_token (owner_id); CREATE TABLE IF NOT EXISTS Piece_token_county ( id integer PRIMARY KEY AUTOINCREMENT NOT NULL, token_id integer NOT NULL, county_id integer NOT NULL ); CREATE INDEX IF NOT EXISTS Piece_token_county_county_id_57802417 ON Piece_token_county (county_id); CREATE INDEX IF NOT EXISTS Piece_token_county_token_id_e7798ae9 ON Piece_token_county (token_id); CREATE UNIQUE INDEX IF NOT EXISTS Piece_token_county_token_id_county_id_b06b16cc_uniq ON Piece_token_county (token_id, county_id); -
Setting unique id for User model upon creation of User
I have a custom user model like this: class User(AbstractBaseUser): email = models.EmailField( verbose_name='email address', max_length=255, unique=True, ) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) objects = UserManager() USERNAME_FIELD = 'email' def __str__(self): return self.email def has_perm(self, perm, obj=None): return True def has_module_perms(self, app_label): return True @property def is_staff(self): return self.is_admin I want to override the primary_key and create a unique 11 character long id whenever a user is created. How can I do this automatically whenever the user is made and how do I ensure that the key is unique? Thanks.