Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to solve django and angular cors errors
I'm developing application and got this error: Access to XMLHttpRequest at 'https://subdomain.domain.org/api/parks/?page_size=6&page_number=1' from origin ''https://subdomain.domain.org' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Django Config setting.py: INSTALLED_APPS = [ ... 'corsheaders', ... ] MIDDLEWARE = [ ... 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', ... ] ALLOWED_HOSTS = ['app_name-backend.herokuapp.com'] CORS_ALLOWED_ORIGINS = [ 'https://app_name-frontend.herokuapp.com', 'https://subdomain.domain.org', ] CORS_ALLOW_ALL_ORIGINS = False Angular Requests service.ts: getParks(filters: any=null, parameters:any=null): Observable<any> { ... var httpHeaders = new HttpHeaders(); httpHeaders.set('Content-Type', 'application/json'); httpHeaders.set('Access-Control-Allow-Origin', '*'); var requestUrl = this.baseServiceUrl + this.serviceUrl; return this.httpClient.get<any>(requestUrl, { params: httpParams, headers: this.httpHeaders }) .pipe( ... ), catchError(this.handleError<Park[]>('Park getParks', [])) ); } The front and back are hosted on heroku Any idea how to fix it ? Thanks in advance. -
Cann't install django with error 'Non-zero exit code (2)'
When i create new django project in pycharm i have error enter image description here Help me please -
how do I update cart with AJAX
I'm trying to use ajax to update the {{cartItems}} on nav when someone hits the add-to-cart button on shop.html without reloading the page, so far this is what I was able to work on. So how do I make this work? also if u have any other suggestion please lemme knw! would really appreciate your help, thx!! rest of the important code is here: https://gist.github.com/StackingUser/34b682b6da9f918c29b85d6b09216352 urls.py path('ajax_update/', views.ajax_update, name="ajax_update"), nav.html <span class="bag-icon"> {% url 'store:cart' as url %} <a id="icons-account" href="{% url 'store:cart' %}"><i class="fas fa-shopping-bag {% if request.path == url %}change{% endif %}"></i><a id="lil-icon-two">{{cartItems}}</a></a> </span> cart.js var updateBtns = document.getElementsByClassName('update-cart') for(var i=0; i < updateBtns.length; i++){ updateBtns[i].addEventListener('click', function(){ var productId = this.dataset.product var action = this.dataset.action console.log('productId:', productId, 'action:', action) console.log('USER:', user) if(user === 'AnonymousUser'){ addCookieItem(productId, action) }else{ updateUserOrder(productId, action) } }) } function addCookieItem(productId, action){ console.log('User is not authenticated') if (action == 'add'){ if (cart[productId] == undefined){ cart[productId] = {'quantity':1} }else{ cart[productId]['quantity'] += 1 } } if (action == 'remove'){ cart[productId]['quantity'] -= 1 if (cart[productId]['quantity'] <= 0){ console.log('Item should be deleted') delete cart[productId]; } } console.log('CART:', cart) document.cookie ='cart=' + JSON.stringify(cart) + ";domain=;path=/" /*replacing location.reload() with ajax*/ function updating_cart_ajax(){ $.ajax({ url: 'ajax_update/', success: function (result) { $('.shop').reload(result) }, … -
Is it okay to use WordPress HTML for Django?
I have a client asking me to build a static HTML website. He wants to integrate it with Django for backend. The first initial design was not very good and he wants me to build another one with specific feature. I was looking to build the site using WordPress and then convert the WordPress site into a static HTML website using a plugin called Simply Static. My only concern is will it be okay if I use such method to build a static site? I've never use Django, so I don't really know whether it would a problem to integrate their backend or not. The reason why I'm using WordPress is because I think it would be a lot faster for me to do the job. I already generate one Wordpress page into a static HTML and it runs okay without any problem. But, as I said, I don't know if it's gonna be a problem for backend team to integrate Django. Thank you -
react.js & django, useParams unable to navigate to the page
I am current building a react app with django, I am trying to navigate from the HomePage to the DataPage with corrsponding id. However, it return Page not found error. I am using react-router-dom v6. Using the URLconf defined in robot.urls, Django tried these URL patterns, in this order: admin/ api/ api-auth/ homepage homepage/data The current path, homepage/data/54, didn’t match any of these. Here is my App.js export default class App extends Component { constructor(props) { super(props); } renderHomePage() { return ( <HomePage /> ); } render() { return ( <BrowserRouter> <Routes> <Route exact path='homepage/' element={this.renderHomePage()} /> <Route path='homepage/data/:id' element={<DataPage />} /> </Routes> </BrowserRouter> ) } } const appDiv = document.getElementById("app"); render(<App />, appDiv); And I want to navigate to the DataPage below: const EmtpyGrid = theme => ({ Grid: { ... } }); function DataPage(props) { const { classes } = props; const { id } = useParams(); return ( <div> ... some material ui components ... <div/> ) }; DataPage.propTypes = { classes: PropTypes.object.isRequired, }; export default withStyles(EmtpyGrid)(DataPage); I was thinking whether I need configure my url.py in frontend as well, and I need to define a designated value for {id} returned from the materialui component first. Perhaps … -
How to list the given data in ascending order. The columns "Account name " and " Account status"
enter image description here views.py `def listEngagements(request): active=Engagement.objects.filter(status="Active") completed=Engagement.objects.filter(status="Completed") datas_list=active|completed query = request.GET.get('q') if query: datas_list = Engagement.objects.filter(engagementName__contains=query) paginator = Paginator(datas_list, 20) # 6 datas per page page = request.GET.get('page',1) try: datas = paginator.page(page) except PageNotAnInteger: datas = paginator.page(1) except EmptyPage: datas = paginator.page(paginator.num_pages) return render(request,'engagement.html',{'datas':datas,'username':username}) models `class Engagement(models.Model): engagementName = models.CharField(default=" ",max_length=100,null=True,blank=True) engagementValue=models.IntegerField(default=0) email = models.EmailField(null=True,blank=True) status = models.CharField(max_length=50,null=True) class Meta: ordering =['engagementName'] def __str__(self): return str(self.engagementName)` html code <table class="table table-stripped table-hover"> <thead> <tr> <th>Account Name</th> <th>Account Value</th> <th>Email</th> <th>Account Status</th> <th></th> </tr> </thead> <tbody> {% for i in datas %} <tr> <td>{{i.engagementName}}</td> <td>{{i.engagementValue}}</td> <td>{{i.email}}</td> <td>{{i.status}}</td> <td> <a href="#editEmployeeModal" class="edit" data-toggle="modal" onclick="editengagementDetails( name = '{{i.engagementName}}', engagement_id = '{{ i.id }}', email = '{{i.email}}', status ='{{i.status}}' );" ><i class="fa fa-edit" data-toggle="tooltip" title="Edit"></i></a> <!-- <a href="{% url 'deleteclient' i.id %}" class="delete" ><i class="fa fa-trash" data-toggle="tooltip" title="Delete"></i></a> --> </td> </tr> {% endfor %} </tbody> ` -
migrate fails due to auth.User
I'm trying to use rest_framework.authtoken I'm following this instructions https://www.django-rest-framework.org/api-guide/authentication/#tokenauthentication but whenever i try to do python manage.py migrate authtoken.Token.user: (fields.E300) Field defines a relation with model 'auth.User', which is either not installed, or is abstract. authtoken.Token.user: (fields.E307) The field authtoken.Token.user was declared with a lazy reference to 'auth.user', but app 'auth' isn't installed. this error happens I red error message and thought that I need to install "auth" so I pip install django-rest-auth but it didn't work and this is my part of my settins.py INSTALLED_APPS = [ 'rest_auth', 'rest_framework.authtoken', ] REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.SessionAuthentication', 'rest_framework.authentication.TokenAuthentication', ], 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.AllowAny', ] } it is views.py (i'm working on it so itis not completed) @api_view(http_method_names=['POST']) @permission_classes([AllowAny]) @psa() def exchange_token(request, backend): serializer = UserSerializer(data=request.data) if serializer.is_valid(raise_exception=True): user = request.backend.do_auth(serializer.validated_data['access_token']) if user:#drf built in token authentication?? token, _ = Token.objects.get_or_create(user=user) # drf token authentication return Response({'token':token.key}) else: return Response( {'errors':{'token':'Invalid token'}}, status = status.HTTP_400_BAD_REQUEST, ) I'm trying to do this to use that "Token.objects~~" there is no migration file i can fix.. documents just told me to do python manage.py migrate anyone please inform me what is wrong.. -
How to use tooltip in django dropdownlist form
I have a django dropdown list in the django form in forms.py Fruits= [ ('orange', 'Oranges'), ('cantaloupe', 'Cantaloupes'), ('mango', 'Mangoes'), ('honeydew', 'Honeydews'), ] fruits = forms.CharField(label='Fruits', widget=forms.Select(choices=Fruits)) i want to make it such that whenever I hover to any of the list it needs to show a description of that particular fruit. For instance: For orange: it is orange, for apple: it is apple and so on. How would I accomplish that? Any help would be appreciated. Thank you! The option tag has only 'value' attribute, but I would need 'data-toggle: tooltip' and the title attribute. -
My pagination is not working properly django and bootstrap
First image before clicking on the next button second image is after clicking on the next button -
How to use multiple models in one ListView Class
I want to create pege which previews auhors profile and posts with Django. I created UserPostListView Class, then I want to search on Profile model by author's name and get profile. How can I do this? All code here models.py class Profile(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE) image = models.ImageField(default='default.jpg',upload_to='profile_pics') def __str__(self): return f'{self.user.username} Profile' def save(self): super().save() img = Image.open(self.image.path) output_size = (300,300) img.thumbnail(output_size) img.save(self.image.path) views.py(UserPostListView Class) class UserPostListView(ListView): model = Post template_name = 'blog/user_posts.html' context_object_name = 'posts' paginate_by = 5 def get_queryset(self): user = get_object_or_404(User, username=self.kwargs.get('username')) return Post.objects.filter(author=user).order_by('-date_posted') def get_context_data(self, **kwargs): context = super(UserPostListView, self).get_context_data(**kwargs) context['profiles'] = Profile.objects.all() return context -
Import Deep Learning Models into Django
Background I was building a demo search engine and met a problem of loading my DL models into django. My code is basically structured like this: models/ DPR.py # save model defination utils/ manager.py # save model hyperparameter settings backend/ SearchApp/ view.py # where I want to use my model To clarify, my model should be initialized this way: from utils.manager import Manager from models.DPR import DPR manager = Manager() model = DPR(manager) Problems I want to load the model once after the django app run. I failed to load the model in backend/SearchEngine/app.py as suggested in here because I cannot import DPR and Manager into this file. So any idea? Thanks in advance. -
How do i update manytomanyfield in django?
I want to assign a job to an artisan who clicks 'Accept' but i cant get to assign or update the model to indicate that someone has accepted it.Below is my codes: I want to assign a job to an artisan who clicks 'Accept' but i cant get to assign or update the model to indicate that someone has accepted it.Below is my codes: #model here is the model **class OrderItem(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) ordered = models.BooleanField(default=False) product = models.ForeignKey(Product, on_delete=models.CASCADE) quantity = models.IntegerField(default =1) img = CloudinaryField(blank=True,null=True) status = models.CharField(max_length=200, null=True, blank=True, default='Pending') description=models.TextField(max_length=100,null=True,blank=True) #location = models.ForeignKey('artsans.Area' ,on_delete =models.CASCADE ,null=True,blank=True) address = models.CharField(max_length=300, null=True,blank=True) artisan_assigned = models.ManyToManyField('artisan.Artisan' ,blank=True) date_created = models.DateField(auto_now_add = True, null=True, blank=True) #date_accepted = models.DateField(auto_now_add = True, null=True, blank=True) #payment_id class Meta: verbose_name_plural='Orderitem' ordering = ['-date_created'] #2nd model 2nd model class Artisan(models.Model): user = models.OneToOneField(User,null=True,blank=True, on_delete= models.SET_NULL,related_name='artisan') nin = models.CharField(max_length=20, null=True, unique = True) location = models.ForeignKey(Area ,on_delete =models.CASCADE ,null=True,blank=True) address = models.CharField(max_length=200, null=True) phone = models.CharField(max_length=15, null=True,unique=True) profession_name = models.CharField(max_length=200, null=True, unique = False) profile_img = CloudinaryField(blank=True,null=True) #date_created = models.DateTimeField(auto_now_add=True, null=True) date_created = models.DateField(auto_now_add = True, null=True, blank=True) def __str__(self): return str(self.user.username) # view file #view.py def jobAccepted(request,id): artisan = [Artisan.objects.filter(user=request.user)] if OrderItem.objects.get(id=id, ordered=True,status='Paid'): … -
Django is hashing my passwords different when creating a User vs trying to authenticate a user
I'm having trouble getting authentication to work and I found that the problem is my when I create a user their password is hashed in a different style than PBKDF2. Instead the passwords are always in a format like this: !iak7ijJTzsXRgsbwqtQBtXCZeU3Ccd96k2PpOCRa . However, when I'm working in my views make_password and check_password are using PBKDF2. Model: class UserManager(BaseUserManager): def create_user(self, email, password): if not email: raise ValueError("User must have an email address") user = self.model( email = self.normalize_email(email), ) user.set_password(password) user.save() return user def create_super_user(self, email, password=None): if not email: raise ValueError("User must have an email address") user = self.model( email = self.normalize_email(email), ) user.is_admin = True user.save() return user class User(AbstractBaseUser): id = models.UUIDField(primary_key=True, default=uuid4, editable=False) email=models.EmailField( verbose_name='Email', max_length=255, unique=True ) password=models.CharField( max_length=255, verbose_name='password' ) username = None first_name = None last_name = None is_active = models.BooleanField(default=True) EMAIL_FIELD = 'email' USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = UserManager() def __str__(self): return self.email I suspect the issue is coming from my custom Model, but it's identical to one I wrote for another app that had no issues. Register View: class CreateUser(APIView): serializer_class = CreateUserSerializer def post(self, request, format='json'): serializer = self.serializer_class(data=request.data) if serializer.is_valid(): email = serializer.data.get('email') password = serializer.data.get('password') … -
Django Class based view filtering queryset but not?
I have a bit of a challenge with the way a date filter is working: Django Class based view, starting here https://github.com/varlenthegray/wcadmin/blob/master/customer/views.py#L61 class CustomersCustomReport(generic.ListView): model = Customer template_name = 'customer/reports/custom_report.html' def get_queryset(self): from_date = self.request.GET.get('fromDate') to_date = self.request.GET.get('toDate') self.queryset = Customer.objects.filter(is_active=True) if from_date: from_date = datetime.strptime(from_date, '%m-%d-%Y').strftime('%Y-%m-%d') print("Checking date from " + from_date) self.queryset.filter(next_service__gte=from_date) if to_date: to_date = datetime.strptime(to_date, '%m-%d-%Y').strftime('%Y-%m-%d') print("Checking date to " + to_date) self.queryset.filter(next_service__lte=to_date) return self.queryset I'm expecting this to return a filtered query based on the date that is a form field. https://wcadmin.innovated.tech/customer/report/custom_report?fromDate=04-01-2022&toDate=04-30-2022 I know this data isn't filtered because the entire customer list is 521 entries of mock data that are active. I was following information from this question: How Can I Filter By Date Range Using Djangos Built in ListView? I know it's getting data from the database, I know it's getting the date range I want from the URL due to the print, and the model is set to DateField for next_service, so I'm not quite sure what's going wrong here? -
Django ManyToMany through field with JSON:API and Swagger
I created a serializer that has a field called products_list, which is Nested. My problem is that I'm using Swagger autogenerated documentation with drf-yasg, and that field does not appear in the expected body for the endpoint. I installed and copied the SWAGGER_SETTINGS on https://github.com/glowka/drf-yasg-json-api My documentation schema code looks like this: from drf_yasg import openapi from drf_yasg.generators import OpenAPISchemaGenerator from drf_yasg.views import get_schema_view class BothHttpAndHttpsSchemaGenerator(OpenAPISchemaGenerator): def get_schema(self, request=None, public=False): schema = super().get_schema(request, public) schema.schemes = ["http", "https"] return schema schema_view = get_schema_view( openapi.Info( title="Mobile quoter API", default_version='1.0.0', description="API managing quoting app", terms_of_service="https://www.google.com/policies/terms/", ), generator_class=BothHttpAndHttpsSchemaGenerator, public=True, ) These are my Serializers: class QuoteSerializer(serializers.ModelSerializer): """Serializer for Quotes""" products_list = QuoteProductsSerializer(many=True, write_only=True, required=True) extra_info = serializers.CharField(required=False) class Meta: model = Quote fields = ( 'client', 'extra_info', 'products_list', 'generated_by', 'closed_at', 'created_at', 'cost', ) extra_kwargs = { 'quoteproducts_set': {'write_only': True}, 'generated_by': {'read_only': True}, 'closed_at': {'read_only': True}, 'created_at': {'read_only': True}, 'cost': {'read_only': True}, } My models: class Quote(SafeModel): client = models.ForeignKey(Client, on_delete=models.PROTECT) generated_by = models.ForeignKey(User, on_delete=models.PROTECT) closed_at = models.DateTimeField(blank=True, null=True) extra_info = models.TextField(blank=True) cost = models.DecimalField(max_digits=9, decimal_places=2) products = models.ManyToManyField(Product, through='QuoteProducts') # Quote model does not have a created_at field because SafeModel has one class QuoteProducts(Model): product = models.ForeignKey(Product, on_delete=models.PROTECT) quote = models.ForeignKey(Quote, on_delete=models.PROTECT) quantity … -
how do I update the cart with AJAX and django
I'm trying to use ajax to update the {{cartItems}} on nav when someone hits the add-to-cart button on shop.html without reloading the page, so far this is what I was able to work on. So how do I make this work? would really appreciate your help, thx!! rest of the important code is here: https://gist.github.com/StackingUser/34b682b6da9f918c29b85d6b09216352 urls.py path('ajax_update/', views.ajax_update, name="ajax_update"), nav.html <span class="bag-icon"> {% url 'store:cart' as url %} <a id="icons-account" href="{% url 'store:cart' %}"><i class="fas fa-shopping-bag {% if request.path == url %}change{% endif %}"></i><a id="lil-icon-two">{{cartItems}}</a></a> </span> cart.js var updateBtns = document.getElementsByClassName('update-cart') for(var i=0; i < updateBtns.length; i++){ updateBtns[i].addEventListener('click', function(){ var productId = this.dataset.product var action = this.dataset.action console.log('productId:', productId, 'action:', action) console.log('USER:', user) if(user === 'AnonymousUser'){ addCookieItem(productId, action) }else{ updateUserOrder(productId, action) } }) } function addCookieItem(productId, action){ console.log('User is not authenticated') if (action == 'add'){ if (cart[productId] == undefined){ cart[productId] = {'quantity':1} }else{ cart[productId]['quantity'] += 1 } } if (action == 'remove'){ cart[productId]['quantity'] -= 1 if (cart[productId]['quantity'] <= 0){ console.log('Item should be deleted') delete cart[productId]; } } console.log('CART:', cart) document.cookie ='cart=' + JSON.stringify(cart) + ";domain=;path=/" /*replacing location.reload() with ajax*/ function updating_cart_ajax(){ $.ajax({ url: 'ajax_update/', success: function (result) { $('.shop').reload(result) }, }); } } function updateUserOrder(productId, action){ console.log('User is logged in, … -
Can you order QuerySets in Django using a custom function?
I'm fairly new to Django and was following a tutorial. A little ways through, I decided to make my own ordering for a model, but this involves a custom function. This section of the program involves taking all the rooms and ordering them vertically on the page. Since the model is quite simple, I hope you can deduce the basic gist of the Room model as I am not very good at explaining (the entire model isn't shown but I think the relevant parts are). I want to order the rooms by the number of participants in the room. The function get_participants() defined at the bottom of the model does the work of getting the number of participants, however I cannot figure out how to apply this. class Room(models.Model): host = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) name = models.CharField(max_length=200) participants = models.ManyToManyField( User, related_name='participants', blank=True) def get_participants(self): return len(self.participants.all()) Here is one of the view functions where I have attempted to implement this function for sorting. I read somewhere that you can use the built-in python sorted() method on QuerySets, though I'm not sure this is the case. def home(request): q = request.GET.get('q') if request.GET.get('q') != None else '' rooms = sorted(Room.objects.filter( … -
Pass arguments from get_context_data() to a form
I have the following CBV: class UserSupplementTransporterView(TemplateView): model = Supplement template_name = 'tool/transporter-detail.html' context_object_name = "tarifs" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) slug = self.kwargs['slug'] context['supplement'] = get_object_or_404(Supplement, slug=slug) print(context['supplement'].header_row) return context I want to extract the value of context['supplement'].header_row and pass it to my forms.py: class CompareFormTransporteur(forms.ModelForm): file = forms.FileField(label="Fichier CSV", required=True) header_row = forms.IntegerField(label="Header row", required=True) class Meta: model = CheckFile fields = ['file',] def __init__(self, request, *args, **kwargs): super().__init__(*args, **kwargs) self.request = request if self.instance: self.initial['header_row'] = 2 #To be filled dynamically def clean(self): super().clean() extension = os.path.splitext(self.request.FILES['file'].name)[1] integer = self['header_row'].value() print(integer) if extension in ['.xlsx', '.xls']: uploaded = parse_excel(self.request.FILES['file'], rowheader=integer) elif extension == ".csv": uploaded = parse_csv(self.request.FILES['file']) elif extension == ".xml": uploaded = parse_xml(self.request.FILES['file']) self.request.session['uploaded'] = uploaded self.request.session['profile'] = self.cleaned_data.get('profile') print(self.cleaned_data.get('profile')) If needed, here are my models: class CheckFile(models.Model): name = models.CharField(max_length=200, blank=True) month = models.DateField(blank=True, null=True) timestamp = models.DateTimeField(blank=True, null=True) profile = models.CharField('Choix du profil', blank=False, choices=PROFILE_CHOICES, max_length=100, default="Client") file = models.FileField(blank=True, null=True, upload_to="uploads/", validators=[validate_file_extension]) def __str__(self): return self.name class Meta: verbose_name = "file" verbose_name_plural = "files" class Supplement(models.Model): transporter = models.ForeignKey(Transporter, on_delete=DO_NOTHING, blank=True, null=True) company = models.ForeignKey(Company, on_delete=DO_NOTHING, blank=True, null=True) brand = models.ForeignKey(Brand, on_delete=DO_NOTHING, blank=True, null=True) header_row = models.IntegerField(blank=True) supplement_annonce_incomplete = models.DecimalField('Supplément annonce incomplète', … -
Pipenv ModuleNotFoundError
Searching for solution: pipenv install django pipenv shell django-admin startproject test . python manage.py runserver Result: ModuleNotFoundError: No module named 'django' It is working with: pipenv run python manage.py runserver But it worked before without pipenv run What's the case? Already reinstalled pipenv, cleared --lock, removed virtualenvs from .local folder, still same error when running python manage.py runserver inside project. -
Django: simplejwt isn't working with @api_view
I am trying to apply JWT token authentication to my Django app. I am following this tutorial https://simpleisbetterthancomplex.com/tutorial/2018/12/19/how-to-use-jwt-authentication-with-django-rest-framework.html I added these settings # settings.py REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework_simplejwt.authentication.JWTAuthentication', ], } Then I added authentication check to api_view # views.py @api_view(['GET', 'POST']) @authentication_classes([authentication.TokenAuthentication]) @permission_classes([permissions.IsAuthenticated]) def task(request): if request.method == 'POST': if "type" in request.data: category_name = request.data["type"] task = create_task.delay(category_name) return Response({"message": "Create task", "task_id": task.id, "data": request.data}) else: return Response({"message": "Error, not found 'type' in POST request"}) Then I have an error: "Authentication credentials were not provided." for the following request: How can I fix the error? -
How to send data from two forms to two tables in Django database using one view?
I would like to send data from two forms to two tables in the Django database but I am getting the error "FOREIGN KEY constraint failed" error. How can I include two forms in the view to send data to the database tables? My models are the User model and class Account(models.Model): def create_new_ref_number(): not_unique = True while not_unique: unique_ref = random.randint(1000000000, 9999999999) if not Account.objects.filter(account_number=unique_ref): not_unique = False return str(unique_ref) user = models.ForeignKey(User, related_name='+', on_delete=models.CASCADE, default='0') DOB = models.DateField('DOB', max_length=20) address = models.CharField('Address', max_length=120) contact_number = models.CharField('Contact Number', max_length=120) ... account_number = models.CharField('Account Number', unique=True, max_length=20, null=False, editable=True, default=create_new_ref_number) ... current_balance = models.IntegerField('Balance', default=0, null=True) # transaction atomic allows to group changes in DB # if save operation will fail transaction creation will be also restored @transaction.atomic def apply_deposit(self, amount: int): # create new deposit transaction Trans.objects.create( user=self.user, amount=amount, account_number=self.account_number ) # update balance self.current_balance += amount self.save() def __str__(self): return str(self.name) My forms are class NewForm(ModelForm): class Meta: model = Account fields = ('DOB', 'address', 'contact_number', 'account_number') exclude = ['user', 'account_number'] labels = { 'DOB': '', 'address': '', 'contact_number': '', } widgets = { 'DOB': forms.DateInput(attrs={'class':'form-control','placeholder':'Date of Birth: dd/mm/yyyy'}, format='%m/%d/%y'), 'address': forms.TextInput(attrs={'class':'form-control','placeholder':'Address'}), 'contact_number': forms.TextInput(attrs={'class':'form-control','placeholder':'Contact Number'}) } and class … -
Count and Sum objects from different models - Django
I'm working on my Django project and I'm triying to order my posts by the sum of 2 related models. So this query should take the attendance count from the Post model and the attendant count from the Attending model and get the total sum. These are the models: class Post(models.Model): title = models.CharField(max_length=100) attendance = models.ManyToManyField(User, related_name='user_event_attendance') class Attending(models.Model): attendant = models.ForeignKey(User, related_name='events_attending', on_delete=models.CASCADE, null=True) post = models.ForeignKey('Post', on_delete=models.CASCADE, null=True) By now I have the 'attendance' count of the post model and ordered by the count: views.py new_query = Post.objects.filter( Q(status='NOT STARTED', post_options='PUBLIC') | Q(status='IN PROGRESS',post_options='PUBLIC')).distinct().annotate(total=Count('attendance')).order_by(-total') -
Problem with "extra_context" in a login view
I'm looking at login views rn but have troubles trying to redirect using the "next" variable that I'm trying to assign a value to inside of "extra_context" dictionary. Overriding "extra_context" in a custom view that inherits from "LoginView" also doesn't work. Redirecting with "next_page" or when hardcoding a value for GET's "next" field works fine. Here's my code. HTML <form class="" action="{%url 'luecken:login'%}" method="post"> {% csrf_token %} <table> <tr> <td>Username: </td> <td>{{form.username}}</td> </tr> <tr> <td>Password: </td> <td>{{form.password}}</td> </tr> </table> <button type="submit" name="logInBtn">Log in</button> <input type="hidden" name="next" value="{{next}}/"> </form> urls.py from django.urls import path, include from . import views from django.contrib.auth.views import LoginView # Custom urls app_name = 'luecken' urlpatterns = [ path('', views.homepage, name = 'homepage'), path('login', LoginView.as_view(extra_context={'next':'/some_url/'}), name='login') -
Django upload excel file
I'm trying to load my old excel format file (xls). But I got error with empty row. How can I break loop from empty row? def isNaN(num): return num != num wb = pd.ExcelFile(file) first_sheet = wb.sheet_names[0] ws = wb.parse(first_sheet, header=5) for row in ws.itertuples(): if isNaN(row[11]): break Error: AttributeError: 'dict' object has no attribute 'headers' -
Django List View get_queryset not rendering all objects
I have the following ListView which I want to use also for filtering the results class Membresias(ListView): model = Cliente template_name = 'main/membresias.html' def get_queryset(self): nombre = self.request.GET.get('nombre') if nombre is None: return Cliente.objects.all() else: return Cliente.objects.filter(nombre = nombre).values() when the 'nombre' variable is not None it show the results, PROBLEM: but when I leave it blank or is None, it does not show any records at all and according to the validation the queryset should retrieve all the records. Here is part of the html for the table <div class = "container"> <div class="table-responsive"> <table class="table"> <thead> <tr> <th scope="col">#</th> <th scope="col">Nombre</th> <th scope="col">Email</th> <th scope="col">Teléfono</th> <th scope="col">Activo</th> </tr> </thead> <tbody> {% for cliente in object_list %} <tr> <th scope="row"><a href="{{ cliente.get_absolute_url }}">{{cliente.id}}</a></th> <td>{{cliente.nombre}}</td> <td>{{cliente.email}}</td> <td>{{cliente.telefono}}</td> {% if cliente.activo == False %} <td><input type="checkbox" readonly class="form-check-input mt-1" id="Estatus" disabled value={{cliente.activo}}></td> {% else %} <td><input type="checkbox" readonly class="form-check-input mt-1" checked id="staticEmail" disabled value={{cliente.activo}}></td> {% endif %} </tr> {% endfor %} </tbody> </table> </div>