Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django.db.utils.ProgrammingError: there is no unique constraint matching given keys for referenced table
I am having a problem with Django 2.2.7 and postgresql 12 using the command "python manage.py migrate". When I execute it, the process fails with the following error: django.db.utils.ProgrammingError: there is no unique constraint matching given keys for referenced table "clients_clients" I understand that this error indicates that when a field is used as a foreing key in another table, this field must be unique. My model clients in Django is: class Clients(models.Model): name = models.CharField(max_length=60, unique=True) document_num = models.CharField(max_length=15) phone = models.CharField(max_length=15, blank=True) email = models.EmailField(max_length=30, blank=True) instagram = models.CharField(max_length=30, blank=True) address = models.TextField(max_length=100, blank=True) The model with the foreing key to the field "name" of clients_clients is: class Budgets(models.Model): date = models.DateField(error_messages={'null': "You must set a date"}) title = models.CharField(max_length=50, unique=True) client = models.ForeignKey(Clients, null=True, on_delete=models.SET_NULL, to_field='name') price = models.DecimalField(default=0, decimal_places=2, max_digits=10) observations = models.TextField(max_length=200, blank=True) As is shown above, the field "name" in model "Clients" is set as unique=True. But in spite of that, the error mentioned is shown. Anyone can help me to understand why? -
How to fix Error QuerySet value for an exact lookup must be limited to one result using slicing
I am trying to get/filter a specific piece of information and delete it from data bases. This data is a many to many relationship. Here is the model: class Log(models.Model): ................................... log_order = models.IntegerField(validators=[MinValueValidator(1)],blank=True, null=True) class LogForm(forms.Form): ............................. log_order = forms.IntegerField() class ActiveSession(models.Model): log = models.ManyToManyField(Log, related_name='savedlogs') .................................. Here is the views: if active_session.log: print(active_session.log.values()) log_order=1 specific_log=Log.objects.filter(log_order=log_order) print(specific_log) active_session = ActiveSession.objects.get(log=specific_log).latest() active_session.log.remove(specific_log) active_session.log.add(data) print(active_session.log.values()) How can I overcome this error by narrowing down the Log data to be delete from inside the ActiveSession model -
Django Rest Framework Authentication Credentials Were Not Provided/ Invalid Token
I am using DRF and Djoser. I am able to Login and set a token (verified this by looking in Django database after user logged in) but I get the following errors when: Trying to sign up: Invalid Token Trying to retrieve data from API: Authentication credentials were not provided Code is not the best, I am simply trying to get things functional before I work on better security. Any and all help is appreciated. Below is my code: settings.py ALLOWED_HOSTS = ['127.0.0.1', 'localhost'] CORS_ORIGIN_ALLOW_ALL = True REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.TokenAuthentication', ), 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), } # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'project', 'rest_framework', 'rest_framework.authtoken', 'corsheaders', 'djoser', 'django.contrib.postgres', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] serializers.py class ProjectsSerializer(serializers.ModelSerializer): class Meta: model = Project read_only_fields = ( 'created_by', 'created_at', 'updated_at', ), fields = ( 'project_title', 'project_description', 'interest_category', ) Views.py class ProjectViewSet(viewsets.ModelViewSet): serializer_class = ProjectsSerializer queryset = Project.objects.order_by('-created_at') permission_classes = (IsAuthenticated,) Urls.py from rest_framework.routers import DefaultRouter router = DefaultRouter() router.register("projects", ProjectViewSet, basename="projects") urlpatterns = [ path('api/v1/', include('djoser.urls')), path('api/v1/', include('djoser.urls.authtoken')), path('', include(router.urls)), ] -------------------------FRONTEND--------------------- createStore() state: { user: { username: '' }, isAuthenticated: false, token: '' }, mutations: … -
Form with default value when loading django page
I would like that when the page is loaded, a value or the default filter of the form is already triggered. In this case, I have a boolean filter that returns True or False and I wanted the True to be loaded by default because it filters items in HTMl Executado = django_filters.CharFilter(lookup_expr='exact').initial={'Executado':TRUE} -
Removing/Deleting Data in a Django Project
I have the following model with many to many relationship: class Log(models.Model): ................................... log_order = models.IntegerField(validators=[MinValueValidator(1)],blank=True, null=True) class LogForm(forms.Form): ............................. log_order = forms.IntegerField() class ActiveSession(models.Model): log = models.ManyToManyField(Log, related_name='savedlogs') .................................. For each ActiveSession I want to add different Log with different log_order. My desired outcome is to delete the Log in each ActiveSession if it is equal to data.log_order which means it already exists and I am trying to avoid duplication. Here is my trials that did not go through and got me different errors such as AttributeError: type object 'ActiveSession' has no attribute 'savedlogs' Here is the views.py if ActiveSession.savedlogs.values(): print("Outcome of active_session.log.values()",active_session.log.values()) # print(ActiveSession.objects.all()) if ActiveSession.Log.get(log_order=data.log_order): current_session=active_session.savedlogs.get(log_order=data.log_order) print('CurrentSession:', current_session) ------------required code to delete the Log inside the session------ else: active_session.log.add(data) print("Different Logs exists but not this log_order") else: active_session.log.add(data) print('Log added to Session') print(active_session.log.values()) To simplify and shorten unnecessary code the data.log_order is the outcome of a form which works perfectly fine. Please let me know if any clarification required. -
Making a decorator that does sum based on one field of a model in django, and also show images in template
I have encountered two challenges, one trying to do a sum with a decorator or in a generic view or in template, and other that i want to make sure images show in a browser, they were showing before but it stopped later: my model: class Accounts_revenue(models.Model): revenue_of = models.CharField(max_length=100, default='i.e: visa payment',null=False) revenue_by = models.ForeignKey(Profile, on_delete=models.CASCADE,null=True, blank=True ) amount = models.IntegerField( default='') day_on_which = models.DateField(auto_now=True, null=True, blank=True) evidence_document = models.ImageField(upload_to = 'uploads/', blank=True, default='') def __str__(self): return str(self.revenue_of) def get_absolute_url(self): return reverse('dashboard:revenue', kwargs= {'pk':self.pk} ) and my view class Accounts_revenues(ListView): template_name='dashboard/revenues.html' model= Accounts_revenue context_object_name = 'revenues' ordering = ['-day_on_which'] and in my template where i have both image and sum problem. {% for revenue in revenues %} <tbody> <tr> <td>{{ revenue.id }}</td> <td> <h2 class="table-avatar"> <a href="{{ revenue.get_absolute_url }}" class="avatar avatar-sm mr-2"><img class="avatar-img rounded-circle" src="{{ revenue.evidence_document.url }}" alt="User Image"></a> <a href="{{ revenue.get_absolute_url }}">{{ revenue.revenue_of }}</a> </h2> </td> <td>{{ revenue.expense_by }}</td> <td>{{ revenue.amount }}</td> <td>{{ revenue.day_on_which }}</td> <td class="text-right"> <div class="actions"> <a href="{% url 'dashboard:revenue_update' revenue.pk %}" class="btn btn-sm bg-success-light mr-2"> <i class="fas fa-pen"></i> </a> <a href="{% url 'dashboard:revenue_delete' revenue.pk %}" class="btn btn-sm bg-danger-light"> <i class="fas fa-trash"></i> </a> </div> </td> </tr> </tbody> {% endfor %} {% else %} <p>You seem … -
Python / Django render_to_string outpu rendered as text with html entities
I am porting a python / Django application from: Django==1.5.1 python version 2.6.6 to Django==3.2 python version 3.6.8 The issue that I am having is that I have a section of code that renders to string, a particular HTML template, and then adds that to list to output elsewhere. The actual code that produces this HTML is: class AccountAdmin(SmarterModelAdmin): list_display = ('username', 'files_url', 'teamMembers', 'roleMemberships', 'safetyLimit', 'admin_quota', 'manager', 'enabled', 'path') list_filter = ['enabled', 'manager', 'accountType'] search_fields = ['username'] inlines = [RolesInline] valid_lookups = ( 'members__member__username', 'teams__role__username', ) roles = Account.objects.filter(teams__member=account).order_by('username') roleList = [] for role in roles: link = '/admin/files/account/?teams__role__username=' + role.username # mylink = '<a href="{myurl}">'+role.username+'</a>' # linkText = format_html(mylink,myurl=link) linkText = render_to_string('common/contact.html', context={'URL': link, 'contact': role}) roleList.append(linkText) return ', '.join(roleList) roleMemberships.short_description='Roles' roleMemberships.allow_tags=True``` I have added in a logging.warn to validate what comes out of the render_to_string, and it is straight HTML. The commented out lines were something that I tried that fixed a similar issue. common/contact.html is: <a href="{{ URL }}" {% if not contact.enabled %} style="text-decoration:line-through;" {% endif %} >{{ contact.username }}</a> However, on the final render, It comes out like this: <a href="/admin/files/account/?teams__role__username=abaumann" >abaumann</a>, <a href="/admin/files/account/?teams__role__username=abaumann">abaumann</a> which when run through a browser looks like this: I … -
Stripe client_reference_id: null in checkout.session.completed
I have a stripe pricing table on my front end to render the options available to customers. On my backend I am using Django to handle account creation if the payment was successful. As below this was created following a tutorial on TestDriven.io btw. if event['type'] == 'checkout.session.completed': session = event['data']['object'] print(session) # # Fetch all the required data from session client_reference_id = session.get('client_reference_id') stripe_customer_id = session.get('customer') stripe_subscription_id = session.get('subscription') # Get the user and create a new StripeCustomer user = CustomUser.objects.get(id=client_reference_id) StripeCustomer.objects.create( user=user, stripeCustomerId=stripe_customer_id, stripeSubscriptionId=stripe_subscription_id, ) I am getting the following error raise self.model.DoesNotExist(apps.authentication.models.CustomUser.DoesNotExist: CustomUser matching query does not exist So after some digging I have found that Stripe is not returning the client_reference_id to my backend, below is a printout of the session variable "client_reference_id": null, I believe this is why the account is not being found by Django, but I can't seem to figure out why Stripe isn't sending this information over or how to attach it to the response to my Web hook? -
How to save mpesa transaction in my django app
I am currently working on a django app where I can be able to see and save all transaction made via my till number... No stk push just to be able to see and save all transaction done to that till number... Is there a way I can achieve that -
How to access(loop through) queryset passed from views to html template inside javascript block in django?
I want to loop through array/queryset passed from view to html template in django inside {% block js %} block, is it possible ? -
Weasyprint splits list marker from text on natural pagebreak
I have a styled ol item: <ol> <li>Communication requirements</li> </ol> CSS as follows: ol { list-style-type: none; counter-reset: item; margin: 0; padding: 0; } ol > li { counter-increment: item; font-weight: 700; display: table; margin-bottom: 10px; padding-top: 16px; } ol > li:before { content: counters(item, ".", decimal) ". "; display: table-cell; padding-right: 16px; } However when outputting to WeasyPrint there is a natural page break, the list marker is left behind: How do I prevent this? -
Custom Reset password templates forms doesn't show
I modified the first password reset page successfully. (Where the user insert his email address) Where it doesn't work it the Password Reset Confirm page (Where the users write his new password). When I click the link that I received by email to reset the password, it load my html template but it doesn't load my form. (Only load h1 tag and other things) html template {% load static %} <div class="box" align="center"> <h1>Write your new password</h1> <div class="small-line"></div> <form method="POST"> {% csrf_token %} {{ context.as_p }} <button type="submit" class="sendbut">Reset Password</button> </form> </div> forms.py class SetPasswordForm(forms.Form): def __init__(self, *args, **kwargs): super(SetPasswordForm, self).__init__(*args, **kwargs) # … new_password1 = forms.CharField( label=("New password"), widget=forms.PasswordInput(attrs={'autocomplete': 'new-password'}), strip=False, help_text=password_validation.password_validators_help_text_html(), ) new_password2 = forms.CharField( label=("New password confirmation"), strip=False, widget=forms.PasswordInput(attrs={'autocomplete': 'new-password'}), ) views.py @sensitive_post_parameters() @never_cache def PasswordResetConfirmView(request, uidb64=None, token=None, template_name='users/password_reset_confirm.html', token_generator=default_token_generator, set_password_form=SetPasswordForm, post_reset_redirect=None, current_app=None, extra_context=None): """ View that checks the hash in a password reset link and presents a form for entering a new password. """ UserModel = get_user_model() assert uidb64 is not None and token is not None # checked by URLconf if post_reset_redirect is None: post_reset_redirect = reverse('password_reset_complete') else: post_reset_redirect = resolve_url(post_reset_redirect) try: # urlsafe_base64_decode() decodes to bytestring on Python 3 uid = force_str(urlsafe_base64_decode(uidb64)) user … -
Django: TextChoices appearing in array as the __str__ representation and not as the value
I have the following field in my model: schedule = models.CharField( choices=WorkScheduleType.choices, max_length=255, unique=True, ) This behaves as expected when I do something like this: print(schedule) > DAILY But when I do something like this: print([schedule]) It renders like this: ["WorkScheduleType<DAILY>"] Why is this? Is the proper way to do this really in two lines instead? my_array = [] my_array.append(schedule) print(my_array) -
How do I use Javascript eventListeners in Django project
I am pretty much new to the Django framework and working on a small project that requires me to use static files (JavaScript) in it. I have a couple of buttons that I want to manipulate from the DOM but for some reason, I cannot have access to these buttons using DOM manipulations. Can someone please tell me why I can't print these buttons in my console? What I get an an output is an empty HTMLcollection[] const deleteButton = document.getElementsByClassName('delete-button'); console.log(deleteButton); ** Template ** <div class="my-2"> {% for todo in mytodos %} <div class="checkbox my-2"> <div class="checkbox-wrapper"> <input type="checkbox" id="cbox3" class="mr-2" value="third_checkbox"> <label for="cbox3"> {{ todo.todotext }} </label> </div> <div> <a href= {% url 'delete' %}> <button class="delete-button btn btn-outline-danger">Delete</button> </a> </div> </div> {% endfor %} </div> -
Django convert timestamp before performing a query?
I have a unique instance where my front-end timestamp is generated based off of a user specific setting. (User can choose their timezeone, 12/24 hour clock). I have a search feature in which a user can search based off of a timestamp. The issue that I have is that my timestamp in the database is a UTC timestamp, but the user will want to search based off of the visual timestamp that they see on the page. For example on the front-end of my application the timestamp shows... 2022-09-21 8:25:26 a.m. Yet on the postgres side that timestamp will show as... datetime.datetime(2022, 9, 21, 12, 25, 26, 959035, tzinfo=datetime.timezone.utc) When a user types in 09-21, as expected, zero results get returned. I am looking for a way to do convert time timestamp to the users timestamp before the query takes place, but not sure on the best solution, or right direction to to here. Any guidance would be greatly appreciated! -
Data upload server with user management and resumable uploads
I’m looking to build a web-based data upload server for a citizen science project and am wondering if there are out-of-the box solutions available or if there are some useful Python packages, libraries available to make the job easier? I don’t really want to reinvent the wheel and it seems that something like this should already exist. Maybe I’m just looking in the wrong place. The brief is that our volunteers make audio recordings to monitor threatened species, then upload their data for archiving and automated processing. I’d like a server that has the following: Simple web-based user interface - many of our participants have limited confidence with computers; No client-side software to install; User management: registration to approved email addresses only (or similar, maybe a manual admin approval process); Data files are 1 to 40MB in size but there are lots of them ~1000 files, and ~10 GB in total. If user loses network connection, uploads should be recoverable with the server capable of resuming an upload where it left off. That's quite important. live progress and status updates to the user. I have access to a web hosting server. Maybe a Django or Flask implementation already exists, or … -
Python Django M2M attribute via an intermediary model
I have a model with 2 M2M attributes: Connection is recursive and the ConnectionRequest uses an intermediary class. With Connection attribute, I am able to retrieve the connections of a user without problems (since I am using a native M2M field). But with ConnectionRequest is where I have challenges. I would like to retrieve the 'connection requests' for this user but struggling with this natively. I have implemented it however programmatically (through a query) - but its not clean. Basically, I would like to return the list of all connection requests. ie where the recipientAccount is the same as the parent class (Account) object. class Account(models.Model): firstName = models.CharField( 'First Name', max_length=100, blank=True, null=True) lastName = models.CharField( 'Last Name', max_length=100, blank=True, null=True) emailAddress = models.EmailField( 'Email Address', max_length=255, blank=True, null=True, unique=True) connections = models.ManyToManyField('self', blank=True) connection_requests = models.ManyToManyField( 'ConnectionRequest', blank=True, related_name='accounts') def __str__(self): return self.firstName + ' ' + self.lastName class ConnectionRequest(models.Model): senderAccount = models.ForeignKey( Account, related_name='sender_Account', on_delete=models.CASCADE) recipientAccount = models.ForeignKey( Account, related_name='recipient_Account', on_delete=models.CASCADE) def __str__(self): return str(self.senderAccount.id) + ' to ' + str(self.recipientAccount.id) I have an idea to try the below but suddenly realised that I am unable to access the Account object from the ConnectionRequest class (since its … -
How i can use nested include and block tag in django templates?
I want to show list of books in page. But below code does not do it. base.html <!DOCTYPE html> <html lang="en"> <head> </head> <body> {% include 'core/main.html' %} </body> </html> main.html <main class="container"> <div class="wrapper"> {% block main %} {% endblock %} </div> </main> books.html {% extends 'core/base.html' %} {% block main %} Books {% endblock %} -
Two different forms on one $(document).ready(function) submit
I have two different forms which basically do the same thing so just for an ease of use and less coding is there any way I can assign both of them on one $(document).ready(function()). My original $(document).ready looks like this : $(document).ready(function() { $("#transaction_form_new").on('submit', (function(e) { e.preventDefault(); var formData = new FormData(this); formData.append('farm', {{farm.id}}); $.ajax({ ... }) This one is for creating a new form and i want to add the 'edit_form' also. I tried it like this but with no result: $(document).ready(function() { $("#transaction_form_new"),$("#transaction_form_edit").on('submit', (function(e) { -
Group records in queryset
I have the following models in an django app. class Person(models.Model): name = models.CharField(max_length=50) class Product(models.Model): owner = models.ForeignKey(Person, on_delete=models.CASCADE) class Order(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) buyer = models.ForeignKey(Person, on_delete=models.CASCADE) I would like to get a list of orders placed by a buyer grouped according to the owner of the product in the order. Something like this orders placed by buyer 1 order__product__owner 1 order 1 order 2 order 3 order__product__owner 2 order 4 order 5 order 6 -
how to dynamically populate choices field from another model containing the values to be used - Django
I have a model that has some choices that the admin chooses while entering some data in the admin pannel. I am using the general way of making a choice field as below CATEGORY= ( ('arbitration', 'arbitration'), ('binding precedent', 'binding precedent'), ('contempt', 'contempt'), ('execution of decree', 'executuon of decree'), ('limitations', 'limitations'), ('negative equality', 'negative equality'), ('od/ss/rd', 'Obitor Dicta / Sub Silenso-Ratio/ Decidendi'), ('review', 'review'), ('special relief', 'special relief'), ) ) class Civil(models.Model): law_category= models.CharField(max_length=60, choices=CATEGORY ,null=True, help_text="required") Here the choices are hard coded. Now I want the admin to have control over what choices he can have inside CATEGORY. So what I thought would work is to create another model where he can enter the the values for CATEGORY and that would in return create some dynamic choices for the field law_category= models.CharField(max_length=60, choices=CATEGORY ,null=True, help_text="required") The way I approached the problem was as below class CivilChoices(models.Model): key=models.CharField() value = models.CharField() Here I thought of entering the key and values. But now I do not know how to get these values inside the Civil model for CATEGORY to use, or even if it is the right way to do it. Please suggest me a way to create dynamic choices for … -
Django LEFT JOIN or INNER JOIN the same query set together multiple times
It's been a minute since I've used SQL so I'm not 100% sure LEFT or INNER join is the correct term, as I googled this and in most cases, people just wanted to concatenate the results, wich is not SQL JOIN's. I have 3 models. Dumbed down they are as follows: class Stakeholders(models.Model): firstname = models.CharField(max_length=50) lastname = models.CharField(max_length=50) email = models.EmailField(max_length=254) class Policy(models.Model): name = models.CharField(max_length=50) description = models.CharField(max_length=150) class StakeholderPolicyResp(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) stakeholder = models.ForeignKey(Stakeholders, on_delete=models.CASCADE) policy = models.ForeignKey(Policy, on_delete=models.CASCADE) response = models.IntegerField(default=0) I want to create a table that has a unique stakeholder with the response for up to 4 policies. In simple example: Stakeholder ------------------- 1 John Doe jd@email.com Policy ------------------- 1 Policy 1 2 Policy 2 3 Policy 3 StakeholderPolicyResp ------------------- UID1 1 1 0 UID2 1 2 4 UID3 1 3 3 What I want out is a table that can have varying amount of columns, but something like this: MyTable ------------------ Stakeholder data - Policy x Resp - Policy y Resp - Policy z Resp ================== John | Doe | 0 | 4 | 3 Here we have the stakeholder with the responses for policy 1, policy 2 and policy … -
How to make a filter in a model (Django/ORM) respecting the place of the fields in the query?
I have a model Student with this fields: id, first_name, last_name. I added a compose index with first_name and last_name. The problem is when i filter. I use Student.objects.filter(last_name='Caicedo', first_name='Pedro') but the internal ORM select is: SELECT `students`.`id`, `students`.`first_name`, `students`.`last_name` FROM `students` WHERE (`students`.`first_name` = 'Pedro' AND `students`.`last_name` = 'Caicedo'); args=('Pedro', 'Caicedo'); It does not respect the order, and I need to respect it by optimizing the query. -
Django Admin and object ID = 0
Using django admin to manage records from a pre-existing external database, I face issues with objects having 0 as value for the model's id fields. Each time i edit this object django creates a new one. I understand that having 0 for an id is like having a null value and that django considers the object as a new one to be inserted in the model table. is there a way to specify that 0 is a good id (even if not a good idea ...) ? -
How to override create action of django rest framework ModelViewSet to create bulk records?
Demo model class Item(models.Model): name = models.CharField(max_length=20) Demo view class ItemViewSet(viewset.ModelViewSet): queryset = Item.objects.all() serializer_class = ItemSerializer Demo input passing using API post request [ {name: 'Book'}, {name: 'PC'}, {name: 'Phone'} ] How to create multiple table records with single post request?