Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Am trying to practice Django ORM on the google colab (colab.research.google.com), is there any way to do so
Am trying to practice Django ORM on the google colab (colab.research.google.com), is there any way to do so. 1.I want to create data base model[class entry (models.Model...)] 2.add the data in to the model table [>>> b = Blog(name='Beatles Blog', tagline='All the latest Beatles news.')>>> b.save()] 3.I want to practice queries in the colab env [eg:Entry.objects.all()] </p -
Validating list of data when many=True
Suppose the following model and serializer are given. class Human(models.Model): name = models.TextField(unique=True) class HumanSer(serializers.ModelSerializer): class Meta: model = Human fields = '__all__' I would like to validate that when a list of names is given, the names in that list do not repeat, without hitting the database (more on this below). data = [{'name': 'John}, {'name': 'John'}] ser = HumanSer(data=data, many=True) In a perfect world I would add validate_name method, access all previously validated entries, and raise `ValidationError. This doesn't seem possible at the moment, so the options I have found are: Access .initial_data and do the comparison. This seems not very reliable since I have to be careful, because I am working with the raw unvalidated data; pay attention to whether the data is a list or not, etc. Do nothing, in which case .is_valid() returns True, but .save() throws an exception. Is this case the REST call fails as a whole and I can't point to the user which name is the duplicate. -
Django Rest Framework returning 403 Forbidden when editing user, but works when not logged in as any user
I am trying to make a PUT request on my user model to edit username, bio etc. using Django Rest w/ React frontend. When I make the PUT request at the url via the django rest client it works no issues. From the frontend, when I am not logged into any django user I can send the PUT request via AXIOS with no issues. Once I am logged into any django user, even with superuser permissions, I get 403 Forbidden Error on my PUT request. Here is my views.py: class RetrieveUpdateDestroyUser(RetrieveUpdateDestroyAPIView): serializer_class = UserCreateUpdateSerializer queryset = CustomUser.objects.all() lookup_field = 'id' permission_classes = (AllowAny,) def update(self, request, *args, **kwargs): """ PUT and UPDATE requests handled by this method. """ return super().update(request, *args, **kwargs) In my frontend, this is how I make the PUT request (put request done with axios): export class UserProxy extends BackendProxy { updateUser(updatedUser, userID) { let parameters = `user/${userID}` return new Promise((resolve, reject) => { this.putRequest(updatedUser, parameters) .then(response => { resolve(response) }) .catch(error => { console.log(error) reject(error) }) }); } } Just very confused as to why I don't get the 403 Forbidden when I am not logged into a django user, but I do when I'm logged … -
import stripe web_1 | ModuleNotFoundError: No module named 'stripe' using docker for django
I am using django in docker container. I install stripe with this command docker-compose exec web pipenv install stripe==2.32.0 . This gave me successful message also. then I did docker down and rebuild. this is my view file # orders/views.py import stripe from django.conf import settings from django.views.generic.base import TemplateView from django.shortcuts import render stripe.api_key = settings.STRIPE_TEST_SECRET_KEY class OrdersPageView(TemplateView): template_name = 'orders/purchase.html' def get_context_data(self, **kwargs): # new context = super().get_context_data(**kwargs) context['stripe_key'] = settings.STRIPE_TEST_PUBLISHABLE_KEY return context def charge(request): if request.method == 'POST': charge = stripe.Charge.create( amount=3900, ncy='usd', description='Purchase all books', source=request.POST['stripeToken'] ) return render(request, 'orders/charge.html') The error I'am getting web_1 | File "<frozen importlib._bootstrap>", line 677, in _load_unlocked web_1 | File "<frozen importlib._bootstrap_external>", line 728, in exec_module web_1 | File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed web_1 | File "/code/orders/urls.py", line 4, in <module> web_1 | from .views import OrdersPageView web_1 | File "/code/orders/views.py", line 2, in <module> web_1 | import stripe web_1 | ModuleNotFoundError: No module named 'stripe' this is my pip file [[source]] name = "pypi" url = "https://pypi.org/simple" verify_ssl = true [dev-packages] [packages] django = "*" psycopg2-binary = "*" django-crispy-forms = "*" django-allauth = "*" pillow = "*" stripe = "==2.32.0" [requires] python_version = "3.7" I have no … -
Why example with "_set" from tutorial didnt work for me?
cat = Category.objects.filter(pk=2) prd = Product.objects.filter(pk=10) prd.category_set.set(cat) When I try run it I get error: object has no attribute "category_set". I want test using of argument "clear=False" from article (https://docs.djangoproject.com/en/3.1/ref/models/relations/) So I try this and it did not work too. prd.category_set(cat) What is wrong? 'Product' model have 'category' field (ManyToMany with related_name='category'). -
Web front end to coexist with a REST service built with Django
I have a web API service that has been built using Django and use Apache as its webserver. I have some new requirements to support some UI. Essentially each user of the service should see a landing page with some boxed content (say tweets or images) and they are provided with some simple options to sort, add or remove items. I have this second part built using React and Postgres, but to integrate this, could the React code somehow be plugged into Django? Any examples etc would be greatly appreciated. -
django tenant: public schema not accessing public_urls.py after adding new tenant
I have a bizarre problem that I cannot seem to be able to solve after banging my head off the wall for a few hours now. I am using django-tenant and after adding a new tenant, I cannot access my public schema. I get a 404 error because django is trying to find the URL outside of the public urls. I am getting somewhat confused about why this happens all of a sudden here is attached my public_urls: urlpatterns = [ path('i18n/', include('django.conf.urls.i18n')), path('register', registration), path('', login_view), path('accounts/', include('django.contrib.auth.urls')), path('admin/', admin.site.urls), #path('documentation', documentation), ] if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) and in my settings: PUBLIC_SCHEMA_URLCONF = 'inventory4.public_urls' ROOT_URLCONF = 'inventory4.urls' however when I access the url for my public schema, it seems to be now looking inside of ROOT_URLCONF Note: static files are served well and well there in the proper folders. I cant find out what is going, I am happy to add details to the post to better assist anyone who would have a clue on how to solve this -
every listing in for loop shows up twice
i have a a href menu where listing comes when you hover it but the problem is the forloop shows at the first hover every listing in that forloop twice after you hover it again the list s normal and shows every listing one time. Do you have any idea what the problem could be?? Thank you -
How to modified the __str__ method in django admin to print in two lines
MODEL class Linea_Invest(models.Model): nombre = models.CharField(max_length=50, blank=False, null=True, unique= True) carrera = models.ForeignKey( Carrera, on_delete=models.CASCADE, blank=False, null=True) class Meta: constraints = [ models.UniqueConstraint(fields=['nombre', 'carrera'], name='no repetir nombre carrera linea') ] def __str__(self): return f"Linea de investigación:{self.nombre}\nCarrera: {self.carrera}" This works in console, but when displaying in my template and in the admin I get something like this: DESIRED OUTPUT Línea de investigación: Ingeniería del Software Carrera: Ingeniería en Informática -
Detect inclination of lines in Python
Im creating a system that will be able to register people who will have written texts by hand, later I will have to analyze this image and detect if the writing is ascending, descending or straight. With graphology, I will be able to create the person's profile, but I have no ideas on how to analyze that image. System using Python and Django, i just need to read the image to make this analysis.Does anyone have a suggestion on how to do it? -
How to link url and view by a field of serializer in Django
I'm Beginner in Django. I need to link my view and url by a field. but i dont know how to handle that. The purpose is displayin a list of feedback for every CaseID. here is my code view: @login_required def FeedBack(request): id=request.GET.get("id", None) if id != None: result = [] for res in models.Fact_FeedBack.objects.filter(CaseID__id=id): result.append(models.Fact_FeedBack.serializer.__get__(res)) return render(request, 'CarIA/feedback.html', {'result': result}) url: url(r'^casedetail/(?P<case_id>[0-9]+)/feedbacks$', views.FeedBack, name='caria_ShowFeedback'), model: class Fact_FeedBack(models.Model): CaseID = models.ForeignKey('Fact_CarCase', related_name='Fact_FeedBack_CaseID', on_delete=models.CASCADE) FeedBackTitle = models.CharField(max_length=500) FeedBackDesc = models.CharField(max_length=4000, null=True) FeedBackCommand = models.CharField(max_length=4000, null=True) PublishDate = models.DateTimeField(blank=True, null=True) User = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='Fact_FeedBack_UserName', on_delete=models.CASCADE, null=True) slug = models.SlugField(max_length=100, null=True) def save(self, *args, **kwargs): self.slug = self.slug or slugify(self.CaseID) super().save(*args, **kwargs) def publish(self): self.PublishDate = timezone.now() self.save() def __str__(self): return self.FeedBackTitle @property def serializer(self): return { 'CaseID' : self.CaseID, 'FeedBackTitle':self.FeedBackTitle, 'FeedBackDesc':self.FeedBackDesc, 'FeedBackCommand':self.FeedBackCommand, 'PublishDate':self.PublishDate, 'User':self.User, } Error I recieve is: FeedBack() got an unexpected keyword argument 'case_id' Thanks for the tips -
How to refresh a div of a page to load the updated value from the database?
I am having a viewcount feature in my post of a small blog project which counts the number of times a particular blog has been viewed, but after viewing a particular blog, the value of the viewcount remains unchanged until the entire page is refreshed. So, I am trying to figure out a way to refresh only that portion of the div section which is containing the viewcount value. Here is my required portion of the html code:- <div class="media-body"> <h2><a class="article-title" href="{% url 'post-detail' post.slug %}" onclick="ViewCountRefresh()">{{ post.title }}</a></h2> <div class="article-metadata" id="viewcountrefresh"> <a class="mr-2" href="{% url 'blog-profile' name=post.author %}">{{ post.author }}</a> <div class="float-right"> <small class="text-muted">Category</small> <small class="text-muted">{{ post.date_posted }}</small> </div> <img style="height:19px; width:18px; float:right;" src="{% static "blog/viewicon.png" %}"><p style="float: right; display: inline !important;">{{post.view_count}}</p></img> </div> <p class="article-content">{{ post.content|truncatechars:200|safe }}</p> </div> I am trying to refresh the content of the div section containing the id viewcountrefresh so that when any blog is visited, and then I come back to my homepage I get the updated value of the viewcount from the database. Here is the js script:- function ViewCountRefresh(){ ... ... ... } I am a beginner in javascript & ajax, so having a hard time figuring out the code that … -
link serial number field from the list given in django
I wrote a Django app that has 3 classes in model.py: from django.db import models from multiselectfield import MultiSelectField from django.core.files.storage import FileSystemStorage fs = FileSystemStorage(location='~/Desktop/django_project/register/static/register/textfiles') class Product(models.Model): productId = models.AutoField(primary_key=True) product_name = models.CharField(max_length=20) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) price = models.CharField(max_length=30) serial = models.FileField(upload_to='uploads/%Y/%m/%d/',storage=fs,default="",blank=True,null=True) def __str__(self): return self.product_name class AllSerial(models.Model): serial_id = models.AutoField(primary_key=True) product_name_serial = models.ManyToManyField(Product) all_serial = models.IntegerField(default=0) used_serial = models.IntegerField(default=0) def __str__(self): return self.product_name_serial class Client(models.Model): clientId = models.AutoField(primary_key=True) name = models.CharField(max_length=50) city = models.CharField(max_length=50) phone_number = models.CharField(max_length=20) product_name = models.ManyToManyField(Product) DOWNLOADABLE = 'DL' SHIPINGPOST = 'POST' shippmentWayChoices = [ (DOWNLOADABLE, 'DOWNLOADI'), (SHIPINGPOST, 'POSTI'), ] shippmentWay = MultiSelectField( choices=shippmentWayChoices, default=DOWNLOADABLE, ) serialNumber = models.TextField() trackingItemPost = models.TextField() description = models.TextField() shoppingTime = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.name and here is my app look like: image one image two image tree but now in the product section, from the serial field, I want to add serial numbers (for example 1000000 serial). something like this: image four after that whenever I go to all_serials and then click on the product_name, I want to see all serials that previously added in the product section. like this: image five please help me even a single clue to … -
Docker Error: Service 'web' failed to build : The command '/bin/sh -c pip instal l-r requirements.txt'
Hi I prepaired an app and want to deploy it. As I learned Docker should be an easy tool to accomplish this but I spent so much time to create a Docker image. Tried many thing but still having "Service 'app' failed to build : The command '/bin/sh -c pip install -r /requirements.txt' returned a non-zero code: 1" error. Please someone help me what this is trying to tell me? Structure: project structure My Dockerfile: FROM python:3.8-alpine ENV PATH="/scripts:${PATH}" COPY ./requirements.txt /requirements.txt RUN apk add --update --no-cache --virtual .tmp gcc libc-dev linux-headers RUN pip install -r /requirements.txt RUN apk del .tmp RUN mkdir /app COPY ./MacroWebsite /app WORKDIR /app COPY ./scripts /scripts RUN chmod +x /scripts/* RUN mkdir -p /vol/web/media RUN mkdir -p /vol/web/static RUN adduser -D user RUN chown -R user:user /vol RUN chmod -R 755 /vol/web USER user CMD ["entrypoint.sh"] docker compose.yml file: services: app: build: context: . ports: - "8000:8000" volumes: - ./MacroWebsite:/app command: sh -c "python manage.py runserver 0.0.0.0:8000" environment: - DEBUG=1 -
Why when I analyse a field in django database in views.py it doesn't react?
I'm having a bit of a problem. I have a model for an Article: class Article(models.Model): title = models.CharField(max_length=25, null=True) status = models.CharField(max_length=20, null=True, default='edited') slug = models.BooleanField(null=False, default=False) content = models.CharField(max_length=250, null=True) category = models.CharField(max_length=25, null=True) tags = models.CharField(max_length=25, null=True) I wanted to make it work in a way that only one record can have the slug set to True. So I wrote this in my update view: def updateArticle(request, pk): articles = Article.objects.all() article = Article.objects.get(id=pk) form = ArticleForm(instance=article) if request.method == "POST": counter = 0 for i in articles: if i.slug: counter += 1 if counter > 1 and article.slug == True: for j in articles: j.slug = False form = ArticleForm(request.POST, instance=article) form.save() return redirect('/') return render(request, 'update_article.html', { 'article': article, 'form': form, }) But it doesn't work :(( I would be very thankful if you could help. -
Problem with a request call Post in django
I'm making a POST call for adding an event in the on_message() function at which step is a url to call the addEvent function (to add the event) and then a payload with values defined by me (inside the mqtt_iot file). The compiler does not enter into the addEvent function, it locks but does not make any errors (I'm using the terminal). I enclose the code. How could I fix it? In mqtt_Iot.py: def on_message(client, userdata, msg): #convert byte json to json object and then to python dict to extract urls parameters byte_payload = msg.payload string_payload = byte_payload.decode('utf-8') data_dict = json.loads(string_payload) group_id = data_dict['group_id'] calendar_id = data_dict['calendar_id'] #in base al topic su cui ho ricevuto il messaggio faccio un azione o l'altra if ( msg.topic == "event/update"): #invio l'evento più prossimo alla board client.publish(group_id,calendar_id) elif ( msg.topic == "event/new"): #il messaggio attiverà l'aggiunta di un evento facendo una post sul link adatto url = 'http://127.0.0.1:8000/homeProva1/%d/calendars/%d/events/new/' % (group_id,calendar_id) now= datet.datetime.now().time() end_time = datet.datetime.now() + datet.timedelta(hours=1) end_time = end_time.strftime("%H:%M:%S") now = now.strftime("%H:%M:%S") dt = datet.datetime.today() dt = dt.strftime("%Y-%m-%d") title = "Evento Node" description = "Evento prenotato in loco" payload = {"title": title, "day": dt, "start_time": now, "end_time": end_time, "notes":description} print("Payload") print(type(payload)) print(payload) … -
model? field related with specific field of other model?
I got a question. Assume I have a model. I would like to create a second one whic is related to a specific field of first one. Can we right something like this? models.ManytoManyField(Userprofile.whishlist class Userprofile(models.model): wishlist = models.ManyToManyField(Post, related_name='user_wishlist') ... class Rating(models.model): post = models.ManytoManyField(Userprofile.whishlist,...) -
FOREIGN KEY constraint failed Django 3.1.1
I have a API script that uploads my term dates. For Some reason I keep getting an error that I have a FOREIGN KEY constraint failed when the script runs. Appreciate any help on how to fix this. Attached is my models and my script. None of the data will save to the table. I appreciate any help you guys can give me. Thank you so much! models.py # School Information Stored class School(models.Model): school_name = models.CharField(max_length = 50, default = "") schoolpsid_id= models.CharField(default = "", max_length = 50, unique = True) school_number = models.CharField(primary_key = True,default = "", max_length = 50, unique = True) low_grade = models.CharField(default = "", max_length = 2 ) high_grade = models.CharField(default = "", max_length = 2 ) class Meta: verbose_name = "School" def __str__(self): return self.school_name # Term Information Stored class Term(models.Model): termpsid= models.CharField(default = "", max_length = 10, unique = True) schoolpsid = models.ForeignKey(School,on_delete = models.CASCADE, default = "" ,) start_year = models.CharField(max_length = 4, default = "") portion = models.CharField(max_length = 10, default = "") start_date = models.DateField(blank=True) end_date = models.DateField(blank= True) abbreviation = models.CharField(max_length = 50, default = "") name = models.CharField(max_length = 50, default = "") class Meta: verbose_name = … -
Getting a wiered warnig in console while using django in local machine
Hello I am using django 3.1 on my window 10 machine. While runnig starting the server it does not show any error or warning but while navigating it sometimes show this weird warning or we can say error. So what can be the reason of this error. Traceback (most recent call last): File "c:\python 3.8.2\Lib\socketserver.py", line 650, in process_request_thread self.finish_request(request, client_address) File "c:\python 3.8.2\Lib\socketserver.py", line 360, in finish_request self.RequestHandlerClass(request, client_address, self) File "c:\python 3.8.2\Lib\socketserver.py", line 720, in __init__ self.handle() File "C:\Users\NAMANT~1\Desktop\MIRROS~1\MIRROR~2\venv\lib\site-packages\django\core\servers\basehttp.py", line 174, in handle self.handle_one_request() File "C:\Users\NAMANT~1\Desktop\MIRROS~1\MIRROR~2\venv\lib\site-packages\django\core\servers\basehttp.py", line 182, in handle_one_request self.raw_requestline = self.rfile.readline(65537) File "c:\python 3.8.2\Lib\socket.py", line 669, in readinto return self._sock.recv_into(b) ConnectionAbortedError: [WinError 10053] An established connection was aborted by the software in your host machine``` -
Overriding admin save_model method
I use slugify to create slugs for my blog's posts urls. In order to accept in the slug also non english characters (greek), I overrode Post model's save() method, with one that includes a parameter allow_unicode=True. However that couldn't work in admin area. Whenever I tried to set a greek characters slug in admin area either by setting a new post with greek title, or by editing the english slug of an existing post, admin form wouldn't allow me to save. For that, as I found in other threads, I should override the save_model() method in admin.py file. So I did, but I get an error. Now the error I get points out that admin area requested the post whose slug is going to change with the old url (an id based one), instead of the slug-url I set in the urls.py. The error I get is either an AttribureError at /admin/blog/post/1 (when I'm editing the slug of an existing post), or an AttribureError at /admin/blog/post/add (when I'm adding a new post). And the exception value in both cases is 'WSGIRequest' object has no attribute 'save' How should I set admin-side save methods to request the urls using slug urls? … -
while i deploy my Django webapp to heroku pycharm can not detect Procfile
i am developing a web app using Pycharm.but when i try to open a Procfile within project root in pycharm it ask for extension.i konw Procfile does not have extension. Any solution?? -
Login/Logout View Django Rest
I want to create the login and logout endpoints for my api, when I try to go to my login endpoint, I don't find the fields in order to login, instead I find an empty page. I am using TokenAuthentication. What is wrong with my code? Here is my code for Login and Logout Login: UserModel = get_user_model() class UserLoginSerializer(serializers.Serializer): class Meta: model = UserModel fields = ('email', 'password',) extra_kwargs = {'password': {'write_only': True}} def validate(self, data): email = data.get('email', None) password = data.get('password', None) user = UserModel.objects.get(email= email) if(user): if(not user.check_password(data['password'])): raise serializers.ValidationError("Incorrect Password!") return data else: return Response("User Not Found!", status= status.HTTP_404_NOT_FOUND) views.py class UserLoginView(APIView): permission_classes = [AllowAny,] serializer_class = UserLoginSerializer def post(self, request): serializer = UserLoginSerializer(data= request.data) data = {} if(serializer.is_valid()): return Response(serializer.data, status= status.HTTP_200_OK) return Response(serializer.errors, status= status.HTTP_400_BAD_REQUEST) Logout: views.py class UserLogoutView(APIView): authentication_classes = [IsAuthenticated, ] permission_classes= [IsAuthenticated,] def get(self, request): #deleting the token in order to logout request.user.auth_token.delete() return Response("Successfully Logged Out!", status= status.HTTP_200_OK) Thanks. -
NoReverseMatch in django even I tried in all methods
I am just having this error saying Reverse for 'increament' not found. 'increament' is not a valid view function or pattern name. from . import views urlpatterns=[ path('increament/<follow>/',views.increament,name='increament'), ] HTML part {% for i in people %} <h2><a href="{% url 'increament' follow=i %}">{{i}}</a></h2> {% endfor %} views part def increament(request,follow): form1=FollowDetails(Userid=request.user.username,following=follow) form1.save() form2=FollowDetails(Userid=follow,follower=request.user.username) form2.save() return HttpResponse('Success') I tried Lot of way but still I cant rectifity it Could you help me to solve this -
How to print the kwargs of django signal?
I'm sending a signal from a model, the receiver does get the signal but I cannot use the kwargs in the signal. How do I see/print out what's sent in the signal? import django.dispatch timesheet_signal = django.dispatch.Signal() def send_timesheet_signal(self, employee, employee_id): timesheet_signal.send_robust(sender=self.__class__, employee=employee, employee_id=employee_id) @receiver(post_save, sender=Timesheet) def update_employee_info(sender, instance, created, **kwargs): instance = kwargs.get('instance') employee = instance.employee employee_id = instance.employee_id if created: ... I tried many shapes and forms, this is the current state of the receiver. How do I see/print out what's sent in the signal? -
How to use value from localStorage in Django template?
How can I use a value from a localStorage in a django template rendering? for example: <div class="one two {% if localStorage.hidden %}hidden{% endif %}">Some content</div>