Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django activation field does not change
I've succeeded to send email for activation. However, when user click on the link, the signup_confirmation field does not change. Here's my model: class UserProfile(models.Model): GENDER = ( ('Male', 'Male'), ('Female', 'Female'), ('Other', 'Other'), ) user = models.OneToOneField(User, on_delete=models.CASCADE) phone = models.CharField(blank=True, max_length=20) address = models.CharField(blank=True, max_length=150) city = models.CharField(blank=True, max_length=20) country = models.CharField(blank=True, max_length=20) image = models.ImageField(blank=True,storage = PrivateMediaStorage()) language = models.CharField(blank=True, max_length=20) gender = models.CharField(max_length=10, choices=GENDER,default="Other") signup_confirmation = models.BooleanField(default=False) def __str__(self): return self.user.username def user_name(self): return self.user.first_name + ' ' + self.user.last_name + ' [' + self.user.username + '] ' Here's my activated field: def activate(request, uidb64, token): try: uid = force_text(urlsafe_base64_decode(uidb64)) user = User.objects.get(pk=uid) except (TypeError, ValueError, OverflowError, User.DoesNotExist): user = None # checking if the user exists, if the token is valid. if user is not None and account_activation_token.check_token(user, token): # if valid set active true user.is_active = True # set signup_confirmation true user.userprofile.signup_confirmation = True user.save() login(request, user) return redirect('activated') else: return render(request, 'user/activation_invalid.html') Somehow the code user.userprofile.signup_confirmation = True does not work. Please have a look -
Django clean method() raises 'Bid' object has no attribute 'kwargs'
I'm trying to restrict a bidder that bids on certain project via a form from bidding neither less than the minimum budget that the project publisher has specifies neither greater than the maximum budget. After checking similar problems i found that overriding the clean method is the most suitable, but i'm facing " 'Bid' object has no attribute 'kwargs' " error This is the clean method: def clean(self): if Project.objects.get(pk=self.kwargs['pk']).budget_min >= self.bid_amount or self.bid_amount >= Project.objects.get(pk=self.kwargs['pk']).budget_max: raise ValidationError('the bid amount should be between the minimum and maximum project budget') This is my models.py # projects/models.py from django.contrib.auth import get_user_model from django.core.exceptions import ValidationError from django.db import models from django.urls import reverse from django.core.validators import MaxValueValidator, MinLengthValidator, MinValueValidator from upload_validator import FileTypeValidator from .validators import user_directory_path, validate_file_size from multiselectfield import MultiSelectField class Project(models.Model): title = models.CharField( 'Choose a title for your project', max_length=255, validators=[ MinLengthValidator( 15, 'Title must be descriptive and greater than 15 characters') ] ) body = models.TextField('Tell us more about your project', max_length=3000, validators=[ MinLengthValidator( 10, 'Must be descriptive and greater than 10 characters') ] ) upload_file = models.FileField( upload_to=user_directory_path, verbose_name="upload file:(Max file size: 2.5 MB)", validators=[ validate_file_size, FileTypeValidator( allowed_types=[ 'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'application/pdf', 'application/vnd.ms-powerpoint', 'application/vnd.openxmlformats-officedocument.presentationml.presentation', 'application/vnd.ms-excel', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'image/tiff', … -
CSRF validation works from Postman but not React/Axios
It's honestly a catastrophic blow to the ego I haven't already figured this out--spent 6 hours so far... I have a React app running off a Django Rest Framework backend. For the password reset functionality I am using Django's builtin view (auth_views.PasswordResetView). I have a form in React that accepts an email and sends a post request to reset the users password. The way I send the data in postman is: Url: http://192.168.0.85:8000/reset_password Body: {'email': 'blabla@bla.com'} Headers: {'X-CSRFToken': OGH9iUEtGPqntMYifQ5kiin2ufV9tK39tbp9Wmh6tLST0DXCXSkY8mOvyq5AjjnZ} ...and it works like a charm! Until I try to replicate the same exact call using axios in React: axios.defaults.xsrfCookieName = 'csrftoken'; axios.defaults.xsrfHeaderName = 'X-CSRFToken'; axios.post('http://192.168.0.85:8000/reset_password',{'email': 'blabla@bla.com'},{headers})) ...this results in a 403 error with this message from the backend: WARNING:django.security.csrf:Forbidden (CSRF cookie not set.): /reset_password I've spent 6 hours googling and experimenting and can't figure out for the life of me why the Axios request would be any different than the Postman one. This problem is particularly infuriating because @csrf_exempt won't work on the django builtin views. -
CropperJS : Images stored in server (Django)
How to crop Images stored in server? I'm not using a form since I'm not uploading the image. How can this be done? Django View from .models import Image def main_view(request): obj = Image.objects.get(pk=1) context = {'obj':obj} return render(request, 'main.html',context) HTML + CROPPERJS <div> <img src="{{obj.file.url}}" id="image" width="400px" > <button id="button">Crop</button> </div> <script> const image = document.getElementById('image'); const cropper = new Cropper(image, { aspectRatio: NaN, crop(event) { console.log(event.detail.x); console.log(event.detail.y); console.log(event.detail.width); console.log(event.detail.height); console.log(event.detail.rotate); console.log(event.detail.scaleX); console.log(event.detail.scaleY); }, }); (Ajax logic to send the cropped image to the server) -
what makes FormView a better fit/choice than Createview?
just in general, i usually use and see people use "CreateView" that saves automatically to the data base, while the save "FormView" needs to be triggered in form_valid function, But, beside that i was wondering: is there other uses of "FormView"? better uses of form_valid? does both "CreateView", and "FormView" do the same job (in general)? what are the mean differences/cases? thanks for the explanations. -
How to submit create view with ManytoMany model
so I am trying to do a CreateView class which saves recipe entered by user, however instead of using a textfield, I am trying to capture each measurement of each ingredient. My models: I am not sure if the problem lies here class IngredientList(models.Model): ... class Recipe(models.Model): cuis = [ ('Italian', 'It'), ('French', 'Fr'), ] title = models.CharField(max_length=100) ingredients = models.ManyToManyField( IngredientList, through='ShoppingList') instructions = models.TextField(max_length=3000) serving_size = models.IntegerField(default=0) cuisine_type = models.CharField( max_length=100, choices=cuis, blank=True, null=True) image = models.ImageField(default='recipe.jpg', blank=True, null=True) duration = models.IntegerField(blank=True, default=0) def __str__(self): return self.name def get_absolute_url(self): return reverse('recipe-detail', kwargs={'pk': self.pk}) class RecipeList(models.Model): recipe = models.ForeignKey(Recipe, on_delete=models.CASCADE) ingredients = models.ForeignKey(IngredientList, on_delete=models.CASCADE) measurement = models.FloatField(default=1) def __str__(self): return self.recipe.title My form: class RecipeForm(forms.Form): name = forms.CharField() ingredient = forms.ModelMultipleChoiceField( IngredientList.objects.all(), widget=forms.CheckboxSelectMultiple) measurement = forms.IntegerField() instructions = forms.CharField(widget=forms.Textarea) serving_size = forms.IntegerField() cuisine_type = forms.ChoiceField(choices=RecipeList.cuis) duration = forms.IntegerField() And the views : class RecipeCreateView(FormView): template_name = "recipe/recipeList_form.html" form_class = RecipeForm success_url = reverse_lazy('recipes') def form_valid(self, form): self.name = form.cleaned_data['name'] self.ingredient = form.cleaned_data['ingredient'] self.measurement = form.cleaned_data['measurement'] self.instructions = form.cleaned_data['instructions'] self.serving_size = form.cleaned_data['serving_size'] self.cuisine_type = form.cleaned_data['cuisine_type'] self.duration = form.cleaned_data['duration'] recipe = Recipe(name=self.name, instructions=self.instructions, serving_size=self.serving_size, cuisine=self.cuisine_type, duration=self.duration) recipe.save() ingredient_list = IngredientList.objects.filter(pk__in=self.ingredient) for i in ingredient_list: recipe.ingredients.add(i) return super(RecipeCreateView, self).form_valid(form) The problem is, … -
Implement Django Channels On Many Domains Using Same Server Using Apache
I have a server that was getting the API large traffic and causing so i switched to the web socket , they are working well in my PC but I don't know how to deploy them to the server because my server has multiple domains. So how will all work for multiple domain that's all my question. And also the developer told me that I can use same socket for multiple websites so i also wanted to know how to do that? -
Why django mail app not working on cpanel
I hosted a django app on cPanel Trying to use Gmail to send an email but I keep getting Server Error (500) EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' DEFAULT_FROM_EMAIL = 'email' SERVER_EMAIL = 'email' EMAIL_USE_TLS = True EMAIL_USE_SSL = False EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_HOST_USER = 'email' EMAIL_HOST_PASSWORD = 'password' I hosted it on pythonanywhere and its working fine -
How do i pass data from a django function to another function
I have this signup django app and its more like a signup page for a website. I have an issue now, i made a one to one database relationship between the users data and their web profile from django.db import models import datetime from django.utils import timezone class UserDetail(models.Model): SEX = ( ('M', 'Male'), ('F', 'Female'), ) first_name = models.CharField(max_length=60) middle_name = models.CharField(max_length=60) last_name = models.CharField(max_length=60) gender = models.CharField(max_length=1, choices=SEX) email = models.EmailField() def __str__(self): return '%s %s' % (self.first_name, self.last_name) class WebDetail(models.Model): user = models.OneToOneField(UserDetail, on_delete=models.CASCADE) username = models.CharField(max_length=60) password = models.CharField(max_length=60) # TODO: i need to search how to do auto_now_add function # time_created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.username and here is my views.py from django.shortcuts import render from django.http import HttpResponse from .forms import UserDetailForm, WebDetailForm from .models import UserDetail, WebDetail from django.shortcuts import redirect, reverse def index(requests): form = UserDetailForm() if requests.method == "POST": form = UserDetailForm(requests.POST) if form.is_valid(): UserDetail.objects.create(**form.cleaned_data) # print(requests.POST['first_name']) # return HttpResponse('<h1>Hello</h1>') # return redirect('signup:web_detail_create') context = {'form': form} return render(requests, 'signup/index.html', context) def web_detail_create(requests): form = WebDetailForm() if requests.method == "POST": form = UserDetailForm(requests.POST) if form.is_valid(): # TODO: i need the function above to go with the users data and that … -
what is difference between success_url and get_success_url
class CustomLoginView(LoginView): template_name = 'task/login.html' fields = '__all__' redirect_authenticated_user = True success_url = reverse_lazy('tasks') # def get_success_url(self): # return reverse_lazy('tasks') In this case, I think success_url will work with no error, but there is error It worked well using get_success_url method but i don't know what is difference between them. Furthermore, I'd like to know how works method and attribute in Class. Thanks -
Where to store uploaded files in DRF
I have a simple (for now) full stack web application with DRF on the backend and React as frontend. I have various pages, one of them is user's profile. Any user can change their avatar, this is also handled on the backend. I do it by calling the backend API with a path to a file, it gets uploaded to a media directory and served from backend, so frontend can access it (apps work separately on 2 different ports). That's how it looks in most tutorials/articles on the internet. I actually made this feature just now and while I was happy and wanted to commit my changes I noticed that I have an additional change which is the uploaded avatar. Now the problem is, what do I do with that? Obviously, I cannot just add it to my repo, that would be stupid, right? And if I gitignore it, then the path like avatars/foo.jpg stays in my DB but I won't be able to serve it, because there will be no file. I wanted to ask what's the general solution (or in DRF) to this problem. First thing that comes to mind is storing the images in a separate database … -
Kubernetes share temporary storage to upload file async
Following this post and this, here's my situation: Users upload images to my backend, setup like so: LB -> Nginx Ingress Controller -> Django (Uwsgi). The image eventually will be uploaded to Object Storage. Therefore, Django will temporarily write the image to the disk, then delegate the upload task to a async service (DjangoQ), since the upload to Object Storage can be time consuming. Here's the catch: since my Django replicas and DjangoQ replicas are all separate pods, the file is not available in the DjangoQ pod. Like usual, the task queue is managed by a redis broker and any random DjangoQ pod may consume that task. I need a way to share the disk file created by Django with DjangoQ. The above mentioned post basically mention two solutions: -solution 1: NFS to mount the disk on all pods. It kind of seems like an overkill since the shared volume only stores the file for a few seconds until upload to Object Storage. -solution 2: the Django service should make the file available via an API, which DjangoQ would use to access the file from another pod. This seems nice but I have no idea how to proceed... should I … -
Django password reset token doesn't work after upgrade to v3.1?
I'm scratching my head on this one all day. I have a Wagtail site that was previously running on Django 2.2 that I'm in the process of upgrading to Django 3.1. I'm using the Django internal password reset token functions to generate unsubscribe links for marketing email being sent through Django. Since six was deprecated in 3.x versions of Django I've had to re-write my repurposing of the one-time login links a bit, and despite mimicking the behavior of Django internally the view simply doesn't work, despite working manually in the shell. The last bit is the kicker, if I input the values manually and step through my code in the shell, it seems to work. from django.shortcuts import render from django.contrib.auth import ( REDIRECT_FIELD_NAME, get_user_model, login as auth_login, logout as auth_logout, update_session_auth_hash, ) from django.utils.decorators import method_decorator from django.utils.http import urlsafe_base64_decode from django.core.exceptions import ValidationError from django.contrib.auth.tokens import default_token_generator from wagtailcache.cache import nocache_page UserModel = get_user_model() @nocache_page def unsubscribe(request, uidb64, token): breakpoint() INTERNAL_RESET_SESSION_TOKEN = '_password_reset_token' try: uid = urlsafe_base64_decode(uidb64).decode() user = UserModel.objects.get(email=uid) except (TypeError, ValueError, OverflowError, UserModel.DoesNotExist, ValidationError): user = None if user is not None: session_token = request.session.get(INTERNAL_RESET_SESSION_TOKEN) token_generator = default_token_generator if token_generator.check_token(user, token): # If valid token, … -
Problem with getting data from database django
I am facing a big problem . I am using this query in order to get data from database : try : user = UserModel.objects.get(subject_dn=subject_dn,issuer_dn=issuer_dn) except Exception : raise exceptions.NotFound(' User corresponding to the entred Certificate is not found in the System') logger.info('this is the found user %s' %user) The problem that even i have the user in the database :I'm getting all the time user not found ... Can someone explain to me why this could happen ? Thank you -
django-simple-jwt auth on page reload
I'm using django simplejwt for auth for my react django app. I have it all set up but I'm trying to figure out how to authenticate the user on reload. So when they reload the page, I can check local storage for the refresh and access token, but I can't figure out how to make sure these tokens are valid. It seems that the only way is to make an actual api call to the backend (I'm not currently making an api call on page load). I can't seem to find a function in that library that checks that the tokens are valid. So I could just make a dummy endpoint that I hit on page load that will force an authentication, but I was wondering if there's a more proper way to do it. As of now, one could reload the page and access it if they have local storage variables with the correct keys but incorrect values (but obviously not access any data because no api calls have been made yet). -
The code does not work until after restarting the server
I have a problem with the form file I wrote a code, but it does not work properly until after restarting the server def PAYMENT_CHOICES(): check_pay=payment.objects.first() if check_pay.payment == '1': return (('COD', 'Cash on delivery'),) elif check_pay.payment == '2': return (('CARD', 'Credit card'),) elif check_pay.payment == '3': return (('COD', 'Cash on delivery'), ('CARD', 'Credit card')) class paymentForm(forms.Form): payment_option = forms.ChoiceField( widget=forms.RadioSelect, choices=PAYMENT_CHOICES()) and in template <div class="col-lg-12 col-md-12"> {% for value, name in form.fields.payment_option.choices %} <div class="agree-label"> <input type="radio" name="payment_option" id="{{ name }}" value="{{ value }}" required> <label for="{{ name }}"> {{ name }} </label> </div> {% endfor %} </div> -
Type object 'Model' has no attribute 'objects' - when it's clearly there..?
I'm getting this error when I try to create a new object via Book.objects.create(): AttributeError: type object 'Book' has no attribute 'objects' For this code: # models.py class BookManager(models.Manager): def get_queryset(self): return super(BookManager, self).get_queryset().filter(type="book") def create(self, **kwargs): return super(BookManager, self).create(**kwargs) class ChapterManager(models.Manager): def get_queryset(self): return super(ChapterManager, self).get_queryset().filter(type="chapter") def create(self, **kwargs): return super(ChapterManager, self).create(**kwargs) class Text(models.Model): type = models.CharField(max_length=255, blank=False) # for STI def __init__(self, *args, **kwargs): super(Text, self).__init__(*args, **kwargs) # If we don't have a subclass at all, then we need the type attribute to match # our current class. if not self.__class__.__subclasses__(): self.type = self.__class__.__name__.lower() else: subclass = [ x for x in self.__class__.__subclasses__() if x.__name__.lower() == self.type ] if subclass: self.__class__ = subclass[0] else: self.type = self.__class__.__name__.lower() class Chapter(Text): objects = ChapterManager() class Meta: proxy = True class Book(Text): objects = BookManager() class Meta: proxy = True Where you can see the Chapter and Book objects clearly have an objects field pointing to the custom manager... For some more context, I'm using single table inheritance for my models. This exact same code works fine for another project I have so I have no clue what's happening. -
cant redirect to success page in django paypal
i have a Django Store Website which use Paypal for payment but in my views.py,Django do everything except go to the directed page that i choose this is my views.py def capture(request,id): do some stuff return redirect(reverse("shop:success")) <script type="text/javascript"> function completeOrder(){ var url = "{% url 'shop:paypal' id=orders.id %}" fetch(url, { method:'POST', headers:{ 'Content-type':'application/json', 'X-CSRFToken':csrftoken, }, body:JSON.stringify("{{orders.id}}") }) } // Render the PayPal button into #paypal-button-container paypal.Buttons({ style: { layout: 'horizontal', color:"blue", label:"checkout", tagline:"false", shape:"pill", size:"small", }, // Set up the transaction createOrder: function(data, actions) { return actions.order.create({ purchase_units: [{ amount: { value: '{{orders.converter}}' } }] }); }, // Finalize the transaction onApprove: function(data, actions) { return actions.order.capture().then(function(details) { // Show a success message to the buyer completeOrder() alert('Transaction completed by ' + details.payer.name.given_name + '!'); }); } }).render('#paypal-button-container'); -
my PostgreSQL docker image database doesn't exist on Django
I am doing a django API with docker and postgresql, i set up a docker compose file to use a db network which is a postgresql image and an app network which is my django app. I don't know what is happening (i followed a tutorial) but my configuration isn't working, it give me an error on django that the database doesn't exist. Here is the files: docker-compose.yml version: "3" services: app: build: context: . ports: - "8000:8000" volumes: # Any change made on the project will be reflected on the container - ./app:/app command: > sh -c "python manage.py wait_for_db && python manage.py migrate && python manage.py runserver 0.0.0.0:8000" environment: - DB_HOST=db - DB_NAME=recipe - DB_USER=postgres - DB_PASS=supersecretpassword depends_on: - db db: image: postgres:10-alpine environment: - POSTGRES_DB=recipe - POSTGRES_USER=postgres - POSTGRES_PASSWORD=supersecretpassword Dockerfile FROM python:3.7-alpine LABEL maintainer="trolliama" # Recommended - Don't Allow the python buffer the outputs ENV PYTHONUNBUFFERED 1 COPY ./requirements.txt /requirements.txt # Dependencies to run postgresql # apk it's the packege install of alpine like: apt # apk add == apt install RUN apk add --update --no-cache postgresql-client RUN apk add --update --no-cache --virtual .tmp-build-deps \ gcc libc-dev linux-headers postgresql-dev RUN pip install -r /requirements.txt RUN apk del … -
Getting data from Django models to Google Charts
I'm trying to displays charts of the most sold items in the store. So I would need to take information from the database and into the html. The charts don't seem to load. When I tried static data (the examples from Google), it works fine. However, I cannot seem to do it with dynamic data. I converted the array into a json and did the |safe in the html for escaping. Yet still it doesn't appear. If anyone has an tips on how to fix it, please help! Below is my views.py where I call the html file that has the script of charts. def charts(request): data_arr = [] for item in Item.objects.all(): data_arr.append([item.ItemName, item.quantity_sold]) return render(request,'coffeeapp/charts.html',{'item':json.dumps(data_arr)}) Here is my code in the charts.html file <script src="https://www.gstatic.com/charts/loader.js"></script> <script> google.charts.load('current', { packages: ['corechart'] }); google.charts.setOnLoadCallback(drawChart); function drawChart() { // Define the chart to be drawn. var data = google.visualization.arrayToDataTable( ['Item', 'Quantity Sold'], [{{item|safe}}] ); // Instantiate and draw the chart. var chart = new google.visualization.PieChart(document.getElementById('myPieChart')); chart.draw(data, null); } </script> <!--Div that will hold the pie chart--> <div id="myPieChart"/> -
Whenever I use send_mail in django it sends me emails from myself rather than the address I'm providing
So I've been working on this blog website and I wanted to add a form so that users can contact the blog admin. However when they fill out the form and send email.. The email I receive is from myself and not from the user. Someone Please help me to fix it. The form is working correctly and message-email does return the email that they enter. e.g. lets say in my form I add a user email as example1@example.com but when I recieve an email it's not coming from example1@example.com but from my host email myemail@gmail.com. views.py: def contact(request): if request.method == 'POST': message_name = request.POST['message-name'] message_email = request.POST['message-email'] message = request.POST['message'] #send mail send_mail( 'message from ' + message_name + ' their email ' + message_email , message, message_email, ['myemail@gmail.com'], ) return render(request, 'blog/contact.html', {'message_name':message_name}) settings.py: EMAIL_HOST = 'smtp.gmail.com' EMAIL_POST = 587 EMAIL_HOST_USER = 'myemail@gmail.com' EMAIL_HOST_PASSWORD = '******' EMAIL_USE_TLS = True -
Couldn't trace back NoReverseMatch Error: Reverse for 'update' with arguments '('',)' not found
I am once again facing an error that is related to NoReverseMatch. Still, I couldn't find the source. Here is my code: urls.py from django.urls import path from . import views urlpatterns = [ path("", views.index, name="index"), path("<int:aufgabenzettel_id>", views.details, name="details"), path("add/", views.add, name="add"), path("delete/<int:aufgabenzettel_id>", views.delete, name="delete"), path("edit/<int:aufgabenzettel_id>", views.edit, name="edit"), path("update/<int:aufgabenzettel_id>", views.update, name="update") ] models.py from django.db import models # Create your models here. class Aufgabenzettel(models.Model): Aufgabeselbst = models.CharField(max_length=64) def __str__(self): return f"{self.Aufgabeselbst}" views.py from django.http.response import HttpResponseRedirect from django.shortcuts import render from django.urls import reverse from .models import Aufgabenzettel # Create your views here. def index(request): return render(request, "aufgabenzettel/index.html", { "Aufgabenliste":Aufgabenzettel.objects.all() }) def details(request, aufgabenzettel_id): aufgabenzettel = Aufgabenzettel.objects.get(pk=aufgabenzettel_id) return render(request, "aufgabenzettel/details.html", { "details":aufgabenzettel }) def add(request): if request.method == "POST": Aufgabe = request.POST["Hinzufügen"] Aufgabenzettel.objects.create(Aufgabeselbst=Aufgabe) return HttpResponseRedirect(reverse("index")) return render(request, "aufgabenzettel/add.html") def delete(request, aufgabenzettel_id): aufgabenzettel = Aufgabenzettel.objects.get(pk=aufgabenzettel_id) aufgabenzettel.delete() return HttpResponseRedirect(reverse("index")) def edit(request, aufgabenzettel_id): aufgabenzettel = Aufgabenzettel.objects.get(pk=aufgabenzettel_id) return render(request, "aufgabenzettel/edit.html", { "details":aufgabenzettel }) def update(request): if request.method == "post": Aufgabejetzt = request.POST["Bearbeiten"] Aufgabejetzt.save() return HttpResponseRedirect(reverse("index")) return render(request, "aufgabenzettel/edit.html") index.html {% extends "aufgabenzettel/layout.html" %} {% block body %} <h1>Meine Aufgaben</h1> <ol> {% for Aufgabeselbst in Aufgabenliste %} <li> <a href="{% url 'details' Aufgabeselbst.id %}"> {{ Aufgabeselbst }} </a> <form action="{% url 'delete' Aufgabeselbst.id %}" … -
How can I debug get()keywords must e strings?
Based on this, I have a django-import-export resource that I use to upload books into my model. I am not able to upload when I set import-id_fields = ('id',). However, when I set it to import-id_fields = ('reg_no,), it works. My aim is to be able to upload a number of books whose details are similar in most cases, reg_no may be the same.... What I realized before was that when I uploaded with import-id_fields = ('reg_no",), all the books of reg_no same for a particular user were visible in the other users profile,which should not be the case. class Books(models.Model): school = models.ForeignKey(School, on_delete=models.CASCADE) reg_no = models.CharField(max_length=100) book_name = models.CharField(max_length=200) The resource class ImportBooksResource(resources.ModelResource): def __init__(self, school_id,*args,**kwargs): super().__init__() self.school_id = school_id self.fields["id"] = fields.Field(widget=ForeignKeyWidget(Books,'id')) self.fields['department'] = fields.Field(widget=ForeignKeyWidget(Departments, 'name')) def before_save_instance(self, instance, using_transactions, dry_run): instance.school_id = self.school_id def before_import_row(self, row, **kwargs): row['department'] = row['department'].lower() class Meta: model = Books fields = ('reg_no','book_name','book_detail','department') import_id_fields = ('id',) import_order = ('reg_no','book_name','book_detail','department') The view. class uploadBooks(LoginRequiredMixin,View): context = {} def get(self,request): form = UploadBooksForm() self.context['form'] = form return render(request,'libman/upload_books.html',self.context) def post(self, request): school_id = request.user.school.id#Gets the currently logged in user form = UploadBooksForm(request.POST , request.FILES) data_set = Dataset(school = request.user.school) if form.is_valid(): file = … -
How to use OR condition for icontains in multiple fields with graphene-django
I have the following model in Django: class JobPost(models.Model): company = models.CharField(blank=True, max_length=30, null=True) job = models.CharField(blank=True, max_length=30, null=True) category = models.CharField(blank=True, max_length=30, null=True) description = models.TextField(blank=True, max_length=500, null=True) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.job And I have the following schema with graphene: class JobPostNode(DjangoObjectType): class Meta: # Assume you have an Animal model defined with the following fields model = JobPost filter_fields = { 'company': ['exact', 'icontains', 'istartswith'], 'job': ['exact', 'icontains', 'istartswith'], 'category': ['exact', 'icontains', 'istartswith'], "description": ['exact', 'icontains', 'istartswith'], } interfaces = (relay.Node,) class Query(graphene.ObjectType): job = relay.Node.Field(JobPostNode) all_jobs = DjangoFilterConnectionField(JobPostNode) schema = graphene.Schema(query=Query) I want to use icontains whereas I will get data based on an OR not on AND; for example the following query: { allJobs(job_Icontains: "t", company_Icontains: "v") { edges { node { company job } } } } Should return data that has the letter "t" in job OR the letter "v" in company, not the letter "t" in job AND the letter "v" in company. How can I do that? -
ValueError: Unable to configure handler 'django_file'
I found a Django project and failed to get it running in Docker container in the following way: git clone git clone https://github.com/NAL-i5K/django-blast.git $ cat requirements.txt in this files the below dependencies had to be updated: psycopg2==2.8.6 I have the following Dockerfile: FROM python:2 ENV PYTHONUNBUFFERED=1 RUN apt-get update && apt-get install -y postgresql-client WORKDIR /code COPY requirements.txt /code/ RUN pip install -r requirements.txt COPY . /code/ For docker-compose.yml I use: version: "3" services: dbik: image: postgres volumes: - ./data/dbik:/var/lib/postgresql/data - ./scripts/install-extensions.sql:/docker-entrypoint-initdb.d/install-extensions.sql environment: - POSTGRES_DB=django_i5k - POSTGRES_USER=django - POSTGRES_PASSWORD=postgres ports: - 5432:5432 web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" depends_on: - dbik links: - dbik $ cat scripts/install-extensions.sql CREATE EXTENSION hstore; I had to change: $ vim i5k/settings_prod.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'postgres', 'USER': 'postgres', 'PASSWORD': 'postgres', 'HOST': 'db', 'PORT': '5432', } } Next, I ran docker-compose up --build Starting djangoblast_dbik_1 ... Starting djangoblast_dbik_1 ... done Recreating djangoblast_web_1 ... Recreating djangoblast_web_1 ... done Attaching to djangoblast_dbik_1, djangoblast_web_1 dbik_1 | dbik_1 | PostgreSQL Database directory appears to contain a database; Skipping initialization dbik_1 | dbik_1 | 2021-05-21 21:05:18.976 UTC [1] LOG: starting PostgreSQL 13.3 (Debian 13.3-1.pgdg100+1) on x86_64-pc-linux-gnu, compiled by …