Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django AttributeError: dict object has no attribute 'pk'
I'm making a simple django rest framework project. This is just creating a new user, and logging in. When I used django basic auth user model, everything worked well. But after changing basic user model to custom user, dict object has no attribute 'pk' this error comes out when creating a new user. Custom user model is made referred to django docs.(https://docs.djangoproject.com/ko/2.1/topics/auth/customizing/) Error says that File "/home/seokchan/server/mdocker/lib/python3.5/site-packages/django/contrib/auth/init.py", line 100, in login if _get_user_session_key(request) != user.pk or ( AttributeError: 'dict' object has no attribute 'pk' This seems to say that user model has no pk, but I don't get it. models.py class MyUserManager(BaseUserManager): def create_user(self, username, email, password=None): if not email: raise ValueError('Users must have an email address') if not username: raise ValueError('Users must have an user name') user = self.model( email=self.normalize_email(email), username = username ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, username, email, password): user = self.create_user( username, password=password, email = email, ) user.is_admin = True user.save(using=self._db) return user class MyUser(AbstractBaseUser): id = models.AutoField(primary_key=True) username = models.CharField( verbose_name='user name', max_length=30, unique=True, ) email = models.EmailField( verbose_name='email address', max_length=255, unique=True, ) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) sth_test = models.TextField(blank = True) objects = MyUserManager() USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['email'] … -
Error NET::ERR_CERT_COMMON_NAME_INVALID from google when using Django 2.0 for password recovery through email
I am creating a "password recovery" system using django 2.0 auth. When I send the email containing the password reset link, I get redirected to a google page with an error that looks like this: "Your connection is not private" NET::ERR_CERT_COMMON_NAME_INVALID I looked into the error a bit, and I've read that google has deprecated the use of the COMMON_NAME field. How can I change my settings in order to account for this error? Or am I doing something inherently wrong? django say to use a template name password_reset_email.html and password_reset_complete to generate the link in email and the password change form destination. Here is my code: password_reset_email.html {% autoescape off %} Dear {{user.first_name}}, You are receiving this message because you have requested to have your password changed for your account on ___. To initiate the password reset process for your account, please click the link below: {{protocol}}://{{domain}}{% url 'password_reset_confirm' uidb64=uid token=token %} Your username is "{{user.username}}"" in case you've forgotten. If clicking the link above doesn't work, please copy and paste the URL in a new browser window instead. Sincerely, _____ {% endautoescape %} password_reset_confirm.html {% extends 'base.html' %} {% load crispy_forms_tags %} {% block content %} {% if … -
Facets from many to many fields do not display in template
I tried to use faceting with Haystack on a many to many field. I tried many options to finally end up to a road block. I am able to make it work (apparently) as shown below through the shell. However, when implementing into the template the faceted fields do not show up. Extract from Django Shell from haystack.query import SearchQuerySet sqs = SearchQuerySet().facet('type') sqs.facet_counts() {'fields': {'type': [('Soccer', 2), ('Basketball', 1), ('Golf', 1), ('Swimming', 1)]}, 'dates': {}, 'queries': {}} Search Index.py class EventIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=True, use_template=True) name = indexes.CharField(model_attr='name') owner = indexes.CharField(model_attr='user') created_on = indexes.DateTimeField(model_attr='created_on') type = indexes.MultiValueField(faceted=True) def get_model(self): return Event def prepare_type(self, obj): return [(t.name) for t in obj.type.all()] def index_queryset(self, using=None): return self.get_model().objects.prefetch_related('type').all() Template <!-- Begin faceting. --> <div> {% if facets.fields.type %} <h5>Categories</h5> {# Provide only the top 5 categories #} {% for category in facets.fields.type|slice:":5" %} <a href="{{ request.get_full_path }}&amp;selected_facets=type_exact:{{ type.0|urlencode }}"> {{ type.0 }} </a> ({{ type.1 }}) {% endfor %} {% else %} <p>No categories.</p> {% endif %} </div> event_text.txt {{ object.name }} {{ object.description }} {% for type in event.type.all %} {{ event.type }} {% endfor %} I should be able to see the different types as facets (soccer, basketball, etc..). … -
How to fix 403 "Access Denied" response when trying to access files from Google Cloud Storage
The Problem When trying to load the static content for my web application from a Google Cloud Storage bucket, a handful of files return a 403 response code, while all others are downloaded successfully. The Setup The application is a Django-powered (2.1.3) Python (3.7) application hosted on Google App Engine, using service account credentials that have been given Editor permissions in IAM. We use Bootstrap 3.3.7 for our frontend, hosting its source files in our GCS bucket, and the django-storages (1.7.1) plugin for interfacing with the GCS API. The troublesome files are the Glyphicon images provided with Bootstrap, as well as a CSS map. All other Bootstrap resources load without issue. I've tried: Giving the service account numerous combinations of IAM permissions Recreating the service account and the key file we use to authenticate it Disabling and reenabling the Google Cloud Storage API Creating a new bucket and reloading all the static files to it using the service account credentials Granting AllUsers read access to the problematic files (as the policies are currently set) Granting AllUsers read access to the entire bucket The last fix attempt (#6) did enable access to the glyphicons, but isn't an acceptable solution. The Code … -
inlineformset: how to add parent form?
I have two entities: pizza and topping. I also created an extra table to associate the amount of topping for each pizza. # models.py class Topping(models.Model): name = models.CharField(max_length=50) class Pizza(models.Model): name = models.CharField(max_length=50) class PizzaTopping(models.Model): pizza = models.ForeignKey('Pizza') topping = models.ForeignKey('Topping') amount = models.FloatField() # forms.py class IngredientForm(forms.ModelForm): class Meta: model = Ingredient class IngredientRecipeForm(forms.ModelForm): class Meta: model = IngredientRecipe class RecipeForm(forms.ModelForm): class Meta: model = Recipe Problem: I want to create a form to let the user create a pizza and topping. What I tried: inlineformset_factory(Pizza, PizzaTopping) But the form that results from this won't have the fields associated with Pizza. I couldn't find any information on how to add these fields and create the Parent and Child objects at the same time using this feature. My next attempt would be overriding BaseInlineFormSet, but I didn't find it well documented and before I embrace this adventure I thought it'd be wiser to ask here. -
Django tests giving random assert result
I'm running one confidential app on my machine... This is irrelevant, but I cannot share the code. The basic issue is... The app is on Python, have lots of unit tests... but two tests are a little bit different of all others... The test just give random results... $ run... test fail... $ run... test fail... $ run... test pass... $ run... test pass... $ run... test pass... $ run... test pass... $ run... test fail... $ run... test pass... $ run... test fail... $ run... test fail... $ run... test pass... $ run... test pass... All other functions that the unit tested class is calling are on unit test also, none of they are giving any fail... None of those tests depends on random numbers or calcs... None of they uses Threads... All are simple class that run some action, interact with database, run another action and done. But, when runs this test, that calls 3 other functions, it fails... Maybe you will say, ok, one of they doesn't cover an situation.. but no errors are raised... On result of run, the function should update the database, setting the current user balance for log purposes. All runs, no exceptions, … -
How can DRF browsable API upload a file and send nested JSON data?
I would like to use the browsable developer web API provided by django-rest-framework to interact with a WritableNestedModelSerializer that contains both an ImageField as well as a nested Serializer. Using this sample code: from django.db import models from drf_writable_nested import WritableNestedModelSerializer from rest_framework.serializers import ModelSerializer from django.urls import include, path from rest_framework import routers, viewsets class House(models.Model): image = models.ImageField() class Cat(models.Model): house = models.ForeignKey(House, related_name='cats', on_delete=models.CASCADE, null=True) name = models.CharField(max_length=50) class CatSerializer(ModelSerializer): class Meta: model = Cat fields = '__all__' class HouseSerializer(WritableNestedModelSerializer): cats = CatSerializer(many=True) class Meta: model = House fields = '__all__' class HouseViewSet(viewsets.ModelViewSet): queryset = House.objects.all() serializer_class = HouseSerializer router = routers.DefaultRouter() router.register(r'houses', HouseViewSet) urlpatterns = [ path('', include(router.urls)), ] With this version of Python packages: $ pip freeze Django==2.1.4 django-rest-framework==0.1.0 djangorestframework==3.9.0 drf-writable-nested==0.5.1 pytz==2018.7 The HTML form doesn't support nested JSON serialization: And the Raw data form doesn't support sending binary files: -
Does the first instance of a model have an id of 0 or 1?
I'm wondering if the very first instance of a model has an id of 0 or 1? Thanks! -
bootstrap + django, wrapping cards
I have a quick question. I am going to loop through DB records and print one card for each record. The problem is, if I can't set a new row for each, I end up with this horrible squashed layout between the two rows of cards How can I loop through, make a card for each & still make it look nice? Thanks!! <div class="row"> <div class="col-4"> <div class="card" style="width: 18rem;"> <div class="card-body"> <h5 class="card-title">Card title</h5> <h6 class="card-subtitle mb-2 text-muted">Card subtitle</h6> <p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.</p> <a href="#" class="card-link">Card link</a> <a href="#" class="card-link">Another link</a> </div> </div> </div> <div class="col-4"> <div class="card" style="width: 18rem;"> <div class="card-body"> <h5 class="card-title">Card title</h5> <h6 class="card-subtitle mb-2 text-muted">Card subtitle</h6> <p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.</p> <a href="#" class="card-link">Card link</a> <a href="#" class="card-link">Another link</a> </div> </div> </div> <div class="col-4"> <div class="card" style="width: 18rem;"> <div class="card-body"> <h5 class="card-title">Card title</h5> <h6 class="card-subtitle mb-2 text-muted">Card subtitle</h6> <p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.</p> <a href="#" class="card-link">Card link</a> <a … -
How to solve err 'dict' object has no attribute 'save' when trying to make an update on DB
I'm getting a problem working with django and its model system. I'm new working with django and I'm stuck since I've probably making the things wrong. I'm trying to make an update to my DB and I get this error: "'dict' object has no attribute 'save'" I'm only trying to set a field to be active or inactive depending on a check input on my html. I'm sending the right value on the request. I'm getting a dictionary instead of a model object, but I don't really know how to change this, I think I followed the django docs. step by step. models.py: from django.db import models class Flags(models.Model): num = models.IntegerField(null=False) deliver= models.CharField(max_length=1, null=False) class Meta: db_table ="FLAGS" views.py: from django.http import HttpResponse from Logistic.models import Flags def updateDisponibilidad(request): flag = request.GET.get("flag") print(flag) disp = Flags.objects.using('default').values('num', 'deliver').get(num__exact=1) print(disp) disp['deliver'] = str(flag) disp.save() return HttpResponse(disponibilidad) Django docs. says I can acces to the values putting (in this case) disp.deliver, but when I do that, i get a different error: 'dict' object has no attribute 'deliver' It would be fantastic if anyone can help me so I be able to use this code: disp.deliver = flag disp.save() And work with that. -
How can I add an additional unique_together constraint to Django Guardian object level permissions?
Using the example from the docs, let's assume I have a Task model: class Task(models.Model): summary = models.CharField(max_length=32) content = models.TextField() reported_by = models.ForeignKey(User, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) class Meta: permissions = ( ('view_task', 'View task'), ) Let's say I have many users on my app, and I want to make sure of the following at the database level: No user has a duplicate task, i.e., a user can only have one task called "Sweep the floor." Users do not share tasks. For instance, if two users have a task "Sweep the floor.", there should be two tasks with the summary "Sweep the floor." on the backend, one for each of the two users I cannot add a user field on the Task model - I have to assign ownership of Task objects via permissions Out of the box, the django_guardian UserObjectPermission has this unique_together constraint: unique_together = ['user', 'permission', 'object_pk'] I think what I am looking for is a unique_together constraint that is more like this pseudo-code: unique_together = ['user', 'permission', 'object_pk', 'task__summary'] Or, is there another way to enforce this type of uniqueness at the database level using Django Guardian permissions? -
My view started to works with error after trying to make my template work on ajax
After remake my view to my post on my website, when i tryed to make my template working properly with ajax, there are some new problems appeared in my view. Here is my code of my view def post(request, slug): post_inst = get_object_or_404(InfoPost, slug=slug) q = QueryDict('', mutable=True) if request.method == 'POST': data = json.loads(request.body) q.update(data) comment_form = CommentsForm(q) print(comment_form.is_valid()) if comment_form.is_valid(): com = comment_form.save(commit=False) com.author = request.user com.post = post_inst parent_obj = None try: parent_id = int(data['parent_id']) except: parent_id = None if parent_id: parent_qs = PostComment.objects.filter(id=parent_id) if parent_qs.exists() and parent_qs.count() == 1: parent_obj = parent_qs.first() com.reply_to = parent_obj com.save() #return render(request, "MainPage/Post.html", {'comment_form': comment_form, 'post': post_inst}) return redirect('post', slug=post_inst.slug) else: comment_form = CommentsForm() return render(request, 'MainPage/Post.html', {'comment_form': comment_form, 'post': post_inst}) And here is a new error appeared: Traceback (most recent call last): File "E:\Env\Python\Python37-32\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "E:\Env\Python\Python37-32\lib\site-packages\django\core\handlers\base.py", line 126, in _get_response response = self.process_exception_by_middleware(e, request) File "E:\Env\Python\Python37-32\lib\site-packages\django\core\handlers\base.py", line 124, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\hell_\PyCharmProjects\django_site_2\MainPage\views.py", line 92, in post print(comment_form.is_valid()) File "E:\Env\Python\Python37-32\lib\site-packages\django\forms\forms.py", line 185, in is_valid return self.is_bound and not self.errors File "E:\Env\Python\Python37-32\lib\site-packages\django\forms\forms.py", line 180, in errors self.full_clean() File "E:\Env\Python\Python37-32\lib\site-packages\django\forms\forms.py", line 383, in full_clean self._post_clean() File "E:\Env\Python\Python37-32\lib\site-packages\django\forms\models.py", line 398, in … -
Prefetch_related failing against SQL Server
Using Django 2.X, and Pyodbc driver (installed from anaconda conda-forge django-pyodbc-azure) against MS Sql Server (not sure which version), I regularly have bugs using prefetch_related. An example looks simply like: for obj in MyORMType.objects.prefetch_related('otherormtype_set').all(): pass where OtherOrmType has a simple foreign key to MyOrmType, the error is: ... /opt/conda/lib/python3.6/site-packages/django/db/backends/utils.py in _execute(self, sql, params, *ignored_wrapper_args) 83 return self.cursor.execute(sql) 84 else: ---> 85 return self.cursor.execute(sql, params) 86 87 def _executemany(self, sql, param_list, *ignored_wrapper_args): /opt/conda/lib/python3.6/site-packages/sql_server/pyodbc/base.py in execute(self, sql, params) 544 self.last_params = params 545 try: --> 546 return self.cursor.execute(sql, params) 547 except Database.Error as e: 548 self.connection._on_error(e) ProgrammingError: ('The SQL contains -2098 parameter markers, but 128974 parameters were supplied', 'HY000') I can fall back to the dumb equivalent: for obj in MyORMType.objects.all(): other_objs = obj.otherormtype_set.all() but this is obviously quite slow. This bug occurs regularly for me under many different circumstances in this particular setup (always same Django version, driver, and DB), it's not a one-off annoyance. Is this my fault or an issue with SQL Server or Pyodbc (or Django)? Is there a way to work around the error without having to fetch each obj.otherormtype_set one at a time? -
Django - How do I check how post_save is being called?
I’m trying to create an instance of Listing so I can have user populate in the admin. I’m new to Django so I’ve been crashing but I’m starting to get the hang of it slowly. How do I check if this signal is being called on creation or on update? Thanks! Code Below: user_profile/models from django.db import models from django.urls import reverse from django.contrib.auth.models import AbstractUser, UserManager from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver from django.conf import settings from users.forms import CustomUserCreationForm, CustomUserChangeForm from users.models import CustomUser class Listing (models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.PROTECT, null=True) created = models.DateTimeField(auto_now_add=True, null=True) updated = models.DateTimeField(auto_now=True) name = models.CharField(max_length=100) address = models.CharField(max_length=100) zip_code = models.CharField(max_length=100) mobile_number = models.CharField(max_length=100) cc_number = models.CharField(max_length=100) cc_expiration = models.CharField(max_length=100) cc_cvv = models.CharField(max_length=100) def create_profile(sender, **kwargs): if kwargs['created']: user_profile = Listing.objects.create(user=kwargs['instance']) post_save.connect(create_profile, sender=User) user_profile/admin.py from django.contrib import admin from django.contrib.auth import get_user_model from django.contrib.auth.admin import UserAdmin from user_profile.forms import HomeForm from users.forms import CustomUserCreationForm, CustomUserChangeForm from user_profile.models import Listing from users.models import CustomUser # Register models here. class UserProfileAdmin(admin.ModelAdmin): list_display = ['name', 'address', 'zip_code', 'mobile_number', 'created', 'updated', 'user'] list_filter = ['name', 'zip_code', 'created', 'updated', 'user'] def __str__(self): return self.user.username admin.site.register(Listing, UserProfileAdmin) -
Why does heroku local produce a server error when debug is False?
I followed the getting started tutorial. Everything works fine until I set DEBUG=False (as advised for production). Then running heroku local to test the app produces a server error (500) when I visit /admin. I have not changed anything else. What's going on? -
How to continue a URL for a new view with already selected primary key (pk) in Django / Django Rest Framework
From my index view I list the available "clubs" in my database, when a user select a club it re-directs them to the club home page. I have included a player registration page but I have no idea how I can render this page based on what club the user selected previously in the index. So what I would like to do is output the url like so: http://127.0.0.1:8000/account/club_home/3/player_registration/ "3" being the primary key of the selected club. urls.py: url(r'^club_home/$', views.club_home, name='club_home'), url(r'^club_home/(?P<pk>\d+)/$', views.club_home, name='club_home_with_pk'), url(r'^club_home/player_registration/$', views.RegisterPlayer.as_view(), name='player_register'), views.py: class Index(TemplateView): template_name = 'index.html' def get(self, request): users = User.objects.all() clubs = ClubInfo.objects.all() args = {'users': users, 'clubs': clubs} return render(request, self.template_name, args) def club_home(request, pk=None): if pk: club = ClubInfo.objects.filter(pk=pk) user = request.user else: club = ClubInfo.objects.filter(user=request.user) user = request.user args = {'club': club, 'user': user } return render(request, 'club_home_page.html', args) class RegisterPlayer(APIView): renderer_classes = [TemplateHTMLRenderer] template_name = 'player_registration.html' def get(self, request): serializer = PlayerRegistrationSerializer() return Response({'serializer': serializer}) def post(self, request): serializer = PlayerRegistrationSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response({'serializer': serializer}) -
integrating daphne in docker-compose and adjusting nginx to work with webservices.
I have a working dummy webservice in django under my development that once a user clicks a button a "Hello World" message will appear with a random number. How did I do that? the index.html in the front_end <button onclick="myFunction()">Click me</button> <p id="this_id"></p> <script> function myFunction() { socket = new WebSocket("ws://" + window.location.host + "/personal/my_random_number/"); console.log("===>"+window.location.host) socket.onmessage = function(e) { <!-- alert(e.data); --> document.getElementById("this_id").innerHTML = e.data; } socket.onopen = function() { socket.send("hello world #"); } } the backend: setting.py CHANNEL_LAYERS = { "default": { "CONFIG": { 'hosts': [(REDIS_IP, 6379)], }, "BACKEND": "channels_redis.core.RedisChannelLayer", }, } ASGI_APPLICATION = 'CRM2.routing.application' routing: from django.urls import path from channels.http import AsgiHandler from channels.routing import ProtocolTypeRouter, URLRouter from channels.auth import AuthMiddlewareStack from .consumers import EchoConsumer application = ProtocolTypeRouter({ "websocket": AuthMiddlewareStack( URLRouter([ path("personal/my_random_number/", EchoConsumer), ]), ), }) Cunsomer (EchoConsumer.py) import random from channels.consumer import AsyncConsumer class EchoConsumer(AsyncConsumer): async def websocket_connect(self, event): print ("yes ------------------------ websocket connect") await self.send({ "type": "websocket.accept", }) async def websocket_receive(self, event): print ("HELLO HELLO WS") rand = random.randint(1,100) my_reply = event["text"]+" "+str(rand) await self.send({ "type": "websocket.send", "text": my_reply, }) The Problemwhen I move to production, this doesn't work! From what I understood (and I might be wrong) I need to: integrate daphne in … -
Cant find the right way to install mysqlclient
I've been trying to install mysqlclient for my python 3.7.2 for quite some time now. Currently using windows 10, python 3.7.2 and wamp server 2.1 I tried using the following 1) pip install mysqlclient 2) pip install c:\mysqlclient‑1.3.13‑cp36‑cp36m‑win_amd64.whl and everything along those lines Checked this link: Installing mysqlclient in Python 3.6 in windows 3)pip install "mysqlclient==1.3.12" 4) pip install --only-binary :all: mysqlclient 5)pip install mysql-connector-python I tried doing all of the above using cmd (as administrator) and that failed as well. Anyone with any sort of solution for this problem are welcome! Thank you in advance! -
Updating and fetching a Django model object atomically
I want a capability to update-and-read an object atomically. For example, something like a first() on top of update() below: obj = MyModel.objects.filter(pk=100).update(counter=F('counter') + 1).first() I know it is awkward construct. But just want to show my need. For the record I have used class method like: @classmethod def update_counter(cls, job_id): with transaction.atomic(): job = (cls.objects.select_for_update().get(pk=job_id)) job.counter += 1 job.save() return job where I would call as below and get my updated obj. my_obj = my_obj.update_counter() But the question is, is there any other django model technique given such read back are common and likely used by multiple threads to conclude something based on, say, the final count. -
Django Password Reset generating http link instead of https
I am using Django's inbuilt password reset mechanism. It sends an email with a link containing a token, which when clicked can be used to reset the password. However, the link being generated is using the template: {% trans "Please go to the following page and choose a new password:" %} {% block reset_link %} {{ protocol }}://{{ domain }}{% url 'password_reset_confirm' uidb64=uid token=token %} {% endblock %} Here, the {{ protocol }} is returning http instead of https. My nginx server would redirect any http requests to the https base link (the homepage). Hence, the password reset link does not work since the link generated is wrong. It simply goes to the homepage via nginx. How do I fix this? -
Can I block some dates in the django calender datepicker
I am trying to design a self-scheduling meeting page using Django. I am planning to use DateTime picker and show the available time slots to book. In datepicker how can I block the unavailable time slots? I have check DateFromToRangeFilter filter etc. Seems like these functionalities cannot satisfy my requirement. Can someone guide me how to block few dates in Django DateTime picker? Also, please find that I get the available slot's data from A third party in a form of excel and I dont have it in my Djnago database. Thanks in advance. -
Locking tables causes savepoint issues with django
I am trying to build a Directed-Acyclical-Graph (DAG) in a MySQL database within a Django application. Because this is acyclical, I need to verify that any added elements (vertexes/edges) do not create cycles within the graph. Many clients will attempt to add elements concurrently throughout the day, however these cycle checks need to be atomic, so I have reasoned that I need to use some lock when adding/updating elements. Django doesnt seem to provide anything like this, so I am trying to use a raw LOCK TABLES/UNLOCK TABLES query. Here is the code I use to do that... def lock_tables(): cursor = get_connection(DEFAULT_DB_ALIAS).cursor() tables = [ 'vertex', 'edge' ] lock_query = ', '.join( "{} {}".format(table, 'WRITE') for table in tables ) query = 'LOCK TABLES {}'.format(lock_query) cursor.execute(query) def unlock_tables(): cursor = get_connection(DEFAULT_DB_ALIAS).cursor() cursor.execute('UNLOCK TABLES') And then in my mode's save method... @transaction.atomic() def save(self, *args, **kwargs): print("---INSIDE MODEL SAVE") try: print("---LOCKING TABLES") lock_tables() print("---LOCKED TABLES") super().save(*args, **kwargs) # TODO: Add Cycle check here except Exception as ex: print("---EXCEPTION THROWN INSIDE SAVE: {}".format(ex)) raise finally: print("---UNLOCKING TABLES") unlock_tables() print("---UNLOCKED TABLES") However, something about locking and unlocking these tables is messing with savepoints created using django.db.transaction.atomic... At some point when Django tries … -
Using choices used in Models.py to route the page in Django
I started a project in Django where I am making a new restaurant site. What I thought initially is to make a Model like this: class Menu(models.Model): user = models.ForeignKey(User,default=1, on_delete=models.CASCADE) name = models.CharField("Name of the dish",max_length=30) category = models.CharField(max_length=20,choices=CATEGORY_CHOICES,default='SP') description = models.TextField(max_length=300) dish_image = models.ImageField(upload_to='uploads/') And I have CATEGORY_CHOICES as CATEGORY_CHOICES = [('L','Lunch'),.....] Now I have this button on the index page that routes to menu page. In Menu page, I am thinking of displaying the [n] number of tiles with the [name] ( n = number of elements in category choices and name = the full name of it ex:Lunch) After getting lots of error and figuring out each and every error, I have achieved this task. Now, after that, I want to open the menu of particular category when user clicks in it. Eg: If user clicks 'Lunch' tile, it should route to other page where all the list of the foods with that category are listed. My url pattern is like this: urlpatterns = [ path('', views.index, name="index"), path('menu/', views.menu, name="menu"), path('menu/<str:menu_category>/', views.menu_detail, name="menu_detail"), ] And I have this view : def menu_detail(request, menu_category): menu_list = get_list_or_404(Menu ,category=menu_category) menu_title = Menu.objects.get(category=menu_category) return render(request,'restaurant/menu_detail.html',{'menu_list':menu_list,'menu_title':menu_title}) In the Menu … -
How do I find the cause of duplicate key value violates unique constraint error while key doesn't exist in the DB?
In the table there is a column called previous_transaction_id defined in Django as follows: previous_transaction = models.OneToOneField( 'transactions.Transaction', verbose_name=_('Previous transaction'), on_delete=models.PROTECT, null=True, blank=True, related_name='next_transaction') Due to a bug some rows didn't have the correct value there. After fixing it I updated to the correct values. Now I'm trying to create a new entry and getting an error: IntegrityError: duplicate key value violates unique constraint "transactions_transaction_previous_transaction_id_b7df1bcd_uniq" DETAIL: Key (previous_transaction_id)=(*****) already exists. When I query the DB I don't see any rows that have this value in that column. What might be the problem? -
Multi Tenant Resources
I need some advice about where to find good resources for multi tenant database architecture. I have found this question on SO, but it's a bit specific for .net platform. This application is build with django and we need to expend the database and go towards multi tenant. For Posgresql I found out this question which explain how to start multi tenant approach, or at least it's a good starting point. But in general I didn't found good extensive recourse on the web for it, so any help would be great