Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Multiple image in one queryset Django
How to add multiple images within one django queryset that will have a image field? It can be done through foreignkey but if i use different table for image then id's will be generated differently Can anyone help me on how exactly i can upload multiple images on one django queryset? Example: We can upload multiple images in one post Facebook -
How can I pass two queryset on the same page?? (django rest framework and react)
I want to show two queryset value in the same url. I have my homepage where I am passing all products list and after that section on the same page I am trying to show product based on category like this first recent products then next section all bikes(based on category). @api_view(['GET']) def getProducts(request): products = Product.objects.all() p = Product.objects.all().filter(category = 1) context = { "request": request, } first_serializer = ProductSerializer(products, many= True, context=context) second_serializer = ProductSerializer(p, many= True, context=context) response = first_serializer.data + second_serializer.data return Response(response) this is my react page Recent Products {loading ? <Loader /> : error ? <Message variant='danger'>{error}</Message> : <Row> {products.map(product => ( <Col key={product._id} sm={12} md={6} lg={4} xl={3}> <Product product={product} /> </Col> ))} </Row> } I want the same procedure like this <Row> {p.map((product) => ( <Col key={product._id} sm={12} md={6} lg={4} xl={3}> <Product product={product} /> </Col> ))} </Row> <Row> but I couldn't able to map the p object. what should I do now? I am using react with redux. -
Django Herkou deployment retuning Application Error
I'm stuck in a loop of problems with running my django app on heroku. I previously had an Internal Error message though i have fixed that. Now i'm facing with an Application Error and don't seem to understand why? I've included the heroku log below: `` 2021-08-22T05:06:17.059556+00:00 app[web.1]: self.load_wsgi() 2021-08-22T05:06:17.059556+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/workers/base.py", line 146, in load_wsgi 2021-08-22T05:06:17.059557+00:00 app[web.1]: self.wsgi = self.app.wsgi() 2021-08-22T05:06:17.059557+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/app/base.py", line 67, in wsgi 2021-08-22T05:06:17.059557+00:00 app[web.1]: self.callable = self.load() 2021-08-22T05:06:17.059557+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/app/wsgiapp.py", line 58, in load 2021-08-22T05:06:17.059558+00:00 app[web.1]: return self.load_wsgiapp() 2021-08-22T05:06:17.059558+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/app/wsgiapp.py", line 48, in load_wsgiapp 2021-08-22T05:06:17.059558+00:00 app[web.1]: return util.import_app(self.app_uri) 2021-08-22T05:06:17.059558+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/util.py", line 359, in import_app 2021-08-22T05:06:17.059559+00:00 app[web.1]: mod = importlib.import_module(module) 2021-08-22T05:06:17.059559+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/importlib/init.py", line 127, in import_module 2021-08-22T05:06:17.059559+00:00 app[web.1]: return _bootstrap._gcd_import(name[level:], package, level) 2021-08-22T05:06:17.059559+00:00 app[web.1]: File "", line 1030, in _gcd_import 2021-08-22T05:06:17.059560+00:00 app[web.1]: File "", line 1007, in _find_and_load 2021-08-22T05:06:17.059560+00:00 app[web.1]: File "", line 986, in _find_and_load_unlocked 2021-08-22T05:06:17.059560+00:00 app[web.1]: File "", line 680, in _load_unlocked 2021-08-22T05:06:17.059560+00:00 app[web.1]: File "", line 850, in exec_module 2021-08-22T05:06:17.059560+00:00 app[web.1]: File "", line 228, in _call_with_frames_removed 2021-08-22T05:06:17.059561+00:00 app[web.1]: File "/app/server/plur/wsgi.py", line 16, in 2021-08-22T05:06:17.059561+00:00 app[web.1]: application = get_wsgi_application() 2021-08-22T05:06:17.059561+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/django/core/wsgi.py", line 13, in get_wsgi_application 2021-08-22T05:06:17.059561+00:00 app[web.1]: return WSGIHandler() 2021-08-22T05:06:17.059573+00:00 app[web.1]: … -
Django - How to combine Authen middleware and my custom middleware?
I have an api that require Token in headers and users must have role is_staff to process. Here is my model.py to clarify about is_staff role class User(AbstractBaseUser, PermissionsMixin): """Custom user model that support using email instead of username""" email = models.EmailField(max_length=255, unique=True) name = models.CharField(max_length=255) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_employee = models.BooleanField(default=True) objects = UserManager() USERNAME_FIELD = 'email' Here is the api in my views.py class get_user_info_from_token(generics.GenericAPIView): permission_classes = (IsAuthenticated, ) def get(self, request): """ I put the below rows in middleware User = Token.objects.get(key = request.auth).user if User.is_staff: """ return HttpResponse("You are staff) Here is my middleware: class CustomMiddlware(object): ... def __call__(self, request): token = request.headers['Authorization'][6:] user = Token.objects.get(key=token).user if user.is_staff: response = self.get_response(request) else: return HttpResponseForbidden("You are not allowed") ... Well I have 2 questions: 1/ I want to put permission_classes = (IsAuthenticated, ) into my middlware to simplyfy my code. But I do not know how to do it. 2/ Moreover, in my middleware, I can not run User = Token.objects.get(key = request.auth).user since I got this error AttributeError: 'WSGIRequest' object has no attribute 'auth'. -
How to update models using model forms in django
I tried updating through model form but i am getting error this field required for all fields after submitting the form below is my update view enter code here def update_data(request, id): if request.method == 'POST': print("in post request form submitted") pi = User.objects.get(pk=id) frm = StudentRegistration(request.POST, instance=pi) print("going for form validation") if frm.is_valid(): print("form valid") frm.save() else: pi = User.objects.get(pk=id) frm = StudentRegistration(instance=pi) print("first request get") return render(request, 'enroll/updatestudent.html', {'form':frm} [output screen][1] above is my update view but my data is not updated im getting error field required after clicking submit please guide -
Can a Django ModelForm save multiple new models on a single submit?
I am learning Django and building a website to save and display cafeteria food offerings. I have a Model Meal and another FoodItem, where multiple FoodItems are children of a Meal. class Meal(models.Model): date = models.DateField(default=datetime.date.today) BFAST = 0 LUNCH = 1 DIN = 2 MEAL_TIME_CHOICES = [ (BFAST, 'Breakfast'), (LUNCH, 'Lunch'), (DIN, 'Dinner'), ] meal_time = models.IntegerField( choices = MEAL_TIME_CHOICES, default = MEAL_TIME_CHOICES[0] ) class FoodItem(models.Model): meal = models.ForeignKey(Meal, on_delete=models.CASCADE) name = models.CharField(max_length=80) I'd like to create a ModelForm that has multiple textinputs for FoodItems so that multiple foods can be saved and associated with the same meal on a single submission of the form. My attempt right now only allows me to submit a single food item at a time. class FoodItemForm(forms.ModelForm): class Meta: model = FoodItem fields = ('name',) Any assistance in doing this the correct way would be much appreciated! -
Can not switch from assigning permission_classes to use decorator @permission_classes
The below is an api that required authen. It works class some_random_api(generics.GenericAPIView): permission_classes = (IsAuthenticated, ) def get(self,request): return HttpResponse("Called successfully") However, I dont like declaring variable. After looking up this document, https://www.django-rest-framework.org/api-guide/permissions/ . I find an alternative way by using decorator. So I change my code into this. from rest_framework.decorators import permission_classes class some_random_api(generics.GenericAPIView): @permission_classes(IsAuthenticated) def get(self,request): return HttpResponse("You call random test api") Now this API does not check Authen -
should Stripe be integrated in frontend or backend ? (React+Django Rest )
just a bit confused as i found both solutions after a day of research. some suggest to use "pip install dj-stripe" and add keys and other options in "settings.py". Then the script in frontend to get redirect button and some suggest the use of "npm install --save @stripe/react-stripe-js @stripe/stripe-js", and add keys in "app.js" or a designated js file. i would like to know if it differs (security ,efficiency,.. wise), or is there a concrete way of doing it (best practice way), thank you. -
How to get a value from one method to another within a model observer
Here is an example from the filtering model observer: class MyConsumer(GenericAsyncAPIConsumer): ... @action() async def subscribe_to_comment_activity(self, user_pk, **kwargs): # We will check if the user is authenticated for subscribing. user = await database_sync_to_async(User.objects.get)(pk=user_pk) await self.comment_activity.subscribe(user=user) I want to do some filtering, but that is only possible for my case if I have the instance at hand to filter against. That means as I see it, I need the user=user value in the observer serializer method. @comment_activity.serializer def comment_activity(self, instance: Comment, action, **kwargs) -> CommentSerializer: '''This will return the comment serializer''' return CommentSerializer(instance) And here comes my question then, how can I get the user value in the model serializer method? -
django channels: updates to the data base deletes older data from the same session on the socket
So I'm building a tic tac toe game which you can play online, but I wanted to save the win / lose count of each user and I'm using django 3.2 ,channels 3 and channels_presence with python 3.9 I've built the socket and the client successfully and now you can play as much games as you would like... I think The problem is that the score I try to save get stored in the data base but after another game the score returns back to zero so if two users are playing in a room and user 1 won 2 games the score would get updated then if the other user won a game his score would be 1 and the user 1 score would be reset to zero My User model class CustomUser(AbstractUser): won_games = models.IntegerField(default=0) lost_games = models.IntegerField(default=0) draw_games = models.IntegerField(default=0) def win(self): self.won_games += 1 self.save() def lose(self): self.lost_games += 1 self.save() def draw(self): self.draw_games += 1 self.save() I've put this into the receive function in my consumers.py if text_data['type'] == 'completed': self_channel = Presence.objects.get(channel_name=self.channel_name) competitor = self_channel.room.presence_set.filter(~Q(channel_name=self_channel)).first().user competitor = CustomUser.objects.get(email=competitor.email) user = self.scope['user'] print(user.email, competitor.email) if competitor: competitor.win() if user.is_authenticated: user.lose() return **Note: **I'm relying on … -
How do disable redirecting when I clicking on a button? Django
I am trying to create a like button for my page. thats okey its working but when I click the button page is refreshing. When I click on the like button, I want the counter showing the number of likes to increase. I try used Ajax but I failed. here are my codes.. Views: def liked_post(request,pk): post =get_object_or_404(UserPosts, id=request.POST.get("userposts_id")) liked = False if post.like_post.filter(id = request.user.id).exists(): post.like_post.remove(request.user) liked = False else: post.like_post.add(request.user) liked = True return HttpResponseRedirect(reverse('detail', args=[str(pk)] )) def detail_post(request,_detail): postDetail = UserPosts.objects.get(pk = _detail) liked = False if postDetail.like_post.filter(id= request.user.id).exists(): liked = True context= { "detail":postDetail, "liked":liked } return render(request,"DetailPost.html",context) Javascript file: $(document).ready(function () { //like ajax call $('.like-form').submit(function (e) { e.preventDefault(); const userposts_id = $('.like-btn').val(); const token = $('input[name=csrfmiddlewaretoken]').val(); const url = $(this).attr('action') $.ajax({ method: "POST", url: url, headers: { 'X-CSRFToken': token }, data: { 'userposts_id': userposts_id } }) }) }) Template: <form class="btn-group mt-1 like-form" action="{% url 'like_post' detail.pk %}" method="POST"> {% csrf_token %} {% if request.user.is_authenticated %} {% if detail.username_id == request.user.id %} <button class="btn btn-primary btn-sm" disabled>Like</button> {% else %} {% if liked %} <button class="btn btn-danger btn-sm " type="submit" name="userposts_id" value="{{ detail.id }}">Unlike</button> {% else %} <button class="btn btn-primary btn-sm like-btn" type="submit" name="userposts_id" … -
Django: Update field in Model when condition is met
I have a Post Model that looks like the following. When the expired timestamp is less than the now timestamp I would like the status to change from Live to Expired however the code does not seem to update when the condition is met. How can I change this so it does update class Post(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=60) topic = models.CharField(choices=TOPIC_CHOICES, max_length=60) content = models.TextField(max_length=1500) likes = models.ManyToManyField(User, related_name="posts_likes", blank=True, through=PostLike) dislikes = models.ManyToManyField(User, related_name="post_dislikes", blank=True, through=PostDislike) # comments = models.CharField(max_length=240, null=True, blank=True) created_timestamp = models.DateTimeField(default=now, editable=False) expired_timestamp = models.DateTimeField(default=expiration_time, editable=False) status = models.CharField(max_length=60, default="Live") def save(self, *args, **kwargs): if now >= self.expired_timestamp: self.status = "Expired" super(Post, self).save(*args, **kwargs) -
Users can Create Models - Django - Python
I'm working on a Django website and for my next step, I am taking the Models that I have created in the code and allowing Users to create them. I have found no information on this and Im wondering if anyone else has. I need the ability for users to create their own fields and be able to add data to those fields. Essentially creating their own models. Thanks! -
Cropper JS lowers quality of image after cropping *Django Application*
I am having issues with the image quality of the cropped photos. Everything works and displays correctly, but the only issue is that the image quality diminishes after the image is cropped. The images look the same in the database as they do in the frontend (Low Quality). I know the question was answered Using Cropper js Image quality get reduced after cropping, but I still can't get it work. If anyone could help that would be much appreciated. base.html <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"> <link href= "{% static 'css/main.css' %}" rel="stylesheet"> <link href= "{% static 'css/profile.css' %}" rel="stylesheet"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script> ... <div class="container"> {% block content %} {% endblock %} </div> <script src="{% static 'js/jquery-3.1.1.min.js' %}"></script> <script src="{% static 'js/bootstrap.min.js' %}"></script> <script src="{% static 'js/cropper.min.js' %}"></script> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/cropperjs/1.5.12/cropper.css" integrity="sha512-+VDbDxc9zesADd49pfvz7CgsOl2xREI/7gnzcdyA9XjuTxLXrdpuz21VVIqc5HPfZji2CypSbxx1lgD7BgBK5g==" crossorigin="anonymous" referrerpolicy="no-referrer" /> profile_uploads.html <script> $(function () { /* SCRIPT TO OPEN THE MODAL WITH THE PREVIEW */ $("#id_file").change(function () { if (this.files && this.files[0]) { var reader = new FileReader(); reader.onload = function (e) { $("#image").attr("src", e.target.result); $("#modalCrop").modal("show"); } reader.readAsDataURL(this.files[0]); } }); /* SCRIPTS TO HANDLE THE CROPPER BOX */ var $image = $("#image"); var cropBoxData; var canvasData; $("#modalCrop").on("shown.bs.modal", function () { $image.cropper({ viewMode: … -
ImageFile doesn`t work, don`t know what the problem is in
I'm trying to upload a picture, but it doesn't work. No mistake returns, like if it is uploaded and self.validated_data['picture'] or serializer.self.validated_data['picture'] prints are not empty, but 'picture' in JSON stays null - it mustn`t. Nothing loads to media files, nothing is in DB Views @api_view(['GET', 'POST']) def api_pictures(request): if request.method == 'GET': pictures = Picture.objects.all() serializer = PictureSerializer(pictures, many=True) return JsonResponse(serializer.data, safe=False) if request.method == 'POST': serializer = PictureSerializer(data=request.data) if serializer.is_valid(): serializer.save() print(serializer.validated_data['picture']) return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) #Models class Picture(models.Model): pic_name = models.CharField(max_length=255, blank=True) picture =models.ImageField(upload_to='media_site/',blank=True, height_field='height', width_field='width') url = models.URLField(blank=True, null=True, max_length=500) height = models.IntegerField(blank=True, null=True) width = models.IntegerField(blank=True, null=True) #Urls urlpatterns = [ path("admin/", admin.site.urls), path("api/", include(router.urls)), path("api/images/", api_pictures), path("api/images/<int:pk>", detail_pictures), ] #Serializers.py class PictureSerializer(serializers.ModelSerializer): @staticmethod def name_parser(object_name): parser = re.search(r'[^/]*$', str(object_name)) return parser[0] def save(self): if 'picture' not in self.validated_data.keys(): url = self.validated_data['url'] result = urllib.request.urlopen(url=url) img = BytesIO(result.read()) converted_img = InMemoryUploadedFile(img, None, self.name_parser(url), 'image/jpeg', sys.getsizeof(img), None) print(converted_img) self.validated_data.update({'picture': converted_img}) else: self.validated_data.update({'picture': self.validated_data['picture']}) if 'pic_name' not in self.validated_data.keys(): name = self.name_parser(self.validated_data['picture']) self.validated_data.update({'pic_name': name}) class Meta: model = Picture fields = ('id', 'pic_name', 'picture', 'url', 'width', 'height', 'parent_picture') result But 'picture' mustn`t be null :(((( When i upload it self.validated_data['picture'] is not empty. Django returns … -
Why I'm unable to download my document with django? and how to do it?
I'm new to django and still learning, and I got here, in my own infinite loop, if I do how I sholud it be but i have an errors and it won't work, but if I do it like this there are no errors but it won't work. I want to user to be able to create excel template as he wish, this is simplified version that I want to work, just input few information and on base of that to be able to create excel template. This is views.py from django.http import HttpResponse from django.shortcuts import render import xlsxwriter from xlsxwriter import workbook from django.forms import Form, CharField, ChoiceField, IntegerField from django.core.validators import MaxValueValidator, MinValueValidator def home(request): return render(request, 'my_app/home.html') def create_template(request): return render(request, 'my_app/create_template.html') class TemplateForm(Form): doc_name = CharField(label='Document name') sheetnames = CharField(label='Sheetnames') choices = [] for year in range (1900, 2050): choices.append( (year, year) ) year1 = ChoiceField(label='Starting Year', initial=2021, choices=choices) year2 = ChoiceField(label='Ending Year', initial=2022, choices=choices) row_names = CharField(label='Column names') def create_template(request): if request.method == 'GET': form = TemplateForm() return render(request, 'my_app/create_template.html', {'form':form}) else: form = TemplateForm(request.POST) def create_form(doc_name, sheetnames, years, row_names): workbook = xlsxwriter.Workbook(doc_name + '_template.xlsx') worksheet_introduction = workbook.add_worksheet( "introduction" ) for i in sheetnames: … -
How to display a custom number of model records
In the database, I have 20 model objects, when I enter model page, I show all 10 records. I want to make a field defining how many records display, for example 10 entries. Then the remaining 10 entries will be on 2 page. -
Inner joins with timestamps in Django ORM
Django documentation states to check the ORM before writing raw SQL, but I am not aware of a resource that explains how to perform inner joins between tables without foreign keys. Many of the tables in my database need to be joined by time-related properties or intervals, which to my knowledge do not serve well as foreign keys. For example, in this basic example I need to first take a subset of change_events, and then join a different table ais_data on two separate columns: models.py class AisData(models.Model): navstatus = models.BigIntegerField(blank=True, null=True) start_ts = models.DateTimeField() end_ts = models.DateTimeField(blank=True, null=True) destination = models.TextField(blank=True, null=True) draught = models.FloatField(blank=True, null=True) geom = models.PointField(srid=4326) imo = models.BigIntegerField(primary_key=True) class Meta: managed = False db_table = 'ais_data' unique_together = (('imo', 'start_ts'),) class ChangeEvent(models.Model): event_id = models.BigIntegerField(blank=True, null=True) imo = models.BigIntegerField(blank=True, null=True) timestamp = models.DateTimeField(blank=True, null=True) class Meta: managed = False db_table = 'change_event' First I take a subset of change_events which returns a QuerySet object. Using the result of this query, I need to get all of the records in ais_data that match on imo and timestamp - so the raw SQL would look like this: SELECT ce.*, ad.geom FROM change_events ce JOIN ais_data ad WHERE ce.imo … -
Django Foreign Key chain object write?
i am working on management command that will write some data from json to database tables result is i would like to write objects that belong to table which is ForeignKey to another table and that table is also ForeignKey to its root table , so objects in table C(HostOsScanned) >> ForeignKey table B(HostScanned) wich is >> ForeignKey to table A(SiteAssest) Table from models is shown below i know how to write in case of A>B table but not with such scenario with chain of dependency's of foreign key like follow example below Please help Thanks ---example-- def handle(self, *args, **options): scan_name_id=SiteAssest.objects.get(scan_name=options['scan_name_id']) scan_iphost = HostScanned( host_ip_name=options['host_ip_name'], resolved_hostname=options['resolved_hostname'], resolve_type =options['resolve_type'], mac_address=options['mac_address'], mac_addr_type=options['mac_addr_type'], mac_vendor=options['mac_vendor'], host_state=options['host_state'], host_state_method=options['host_state_method'], host_state_ttl=options['host_state_ttl'], scan_name_id=int(scan_name_id.id), ) try: scan_iphost.save() self.stdout.write(self.style.SUCCESS('Success HostScanned write')) except Exception as e: print('id scanned',scan_name_id.id) self.stdout.write(self.style.ERROR(e)) --model--- class SiteAssest(models.Model): scan_name = models.CharField(max_length=250,blank=False) site_name = models.CharField(max_length=250,blank=False) location_name = models.CharField(max_length=250,blank=False) # Geo location lon = models.FloatField() lat = models.FloatField() site_ip_range1 = models.CharField(max_length=250,blank=True) site_ip_range2 = models.CharField(max_length=250,blank=True) site_ip_range3 = models.CharField(max_length=250,blank=True) #new entry scan_time_start = models.DateTimeField(default=datetime.date.today()) scan_timestr_start = models.CharField(max_length=250,blank=True) scan_time_end = models.DateTimeField(default=datetime.date.today()) scan_timestr_end = models.CharField(max_length=250,blank=True) scan_elapsed = models.IntegerField(blank=True, null=True) scan_exit_resault = models.CharField(max_length=50,blank=True) scan_args = models.CharField(max_length=250,blank=True) nmap_version = models.CharField(max_length=50,blank=True) # end new entry last_scaned = models.DateField(auto_now_add=False, null=True) TASK_STATUS_CHOICES = [ ('ID', 'IDLE'), ('RU', … -
ConnectionResetError while using fetch API to pass data to Django view which posts data to external api
I am trying to implement Opayo(Sagepay) with Django. From my template I am trying to send a card_identifier variable from my template to a view using fetch API. The view will then use the requests package to post this card_identifier along with other data to the an api to process the payment. The api should respond with a JsonResponse which I want to pass back to the template or use to perform a redirect to a payment success or failure page. async function processPayment() { var card_identifier = document.querySelector('[name="card-identifier"]').value var url = "{% url 'sagepay:processing_payment' %}" await fetch(url, { method: 'POST', headers: { 'content-type': 'application/json', 'X-CSRFToken': csrftoken, }, body: JSON.stringify({ merchantSessionKey: merchantSessionKeyContext, card_identifier: card_identifier, }) }) .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.log(error)) } In the view I am collecting this card_identifier variable and using it to make the payment via a post request to the sagepay api. def process_payment(request): body = json.loads(request.body) card_identifier = body["card_identifier"] merchantSessionKey = body["merchantSessionKey"] basket = Basket(request) total = str(basket.get_total_price()) total = total.replace(".", "") amount = int(total) headers = { "Authorization": "my key goes here", } data = { "transactionType": "Payment", "paymentMethod": {"card": {"merchantSessionKey": merchantSessionKey, "cardIdentifier": card_identifier}}, "vendorTxCode": "ggmachiSnesdaqjcjjjhqsbxjka", "amount": amount, "currency": "EUR", … -
Django Tool with Mariadb inside a Docker Container
I am kind of confused on what will be the right way to host my django application and make it independent to run on any machine. So basically, what my current plan is: I have a repository in GitLab of my Django Application. I will clone it via script at some location via ssh. Inside that repository I will perform python3 manage.py makemigrations python3 manage.py migrate docker build . -t $1 docker run -d -p 8000:8000 $1 Where $1 will be the parameter I will pass to name my docker image. My Dockerfile looks like : FROM python:3.6 RUN mkdir /Folder_Name WORKDIR /Folder_Name ADD . /Folder_Name RUN pip3 install -r requirements.txt EXPOSE 8000 CMD python3 manage.py runserver 0.0.0.0:8000 --noreload So this thing is working fine. But I feel that their is more legit way to perform this in one go. So this is about containerizing my Django Application. Before all this we also need a database. Right? Now the thing is, My database is MariaDB, which is again running on docker. For that I need to login to my docker container of MariaDB , and perform actions to Create Database (CREATE DATABASE DB_NAME CHARACTER SET UTF8;) Create User CREATE USER … -
delete and get the sessionid in react and javascript
I make an app in Django and react And I want to check with the server if the user is still authenticated if the user is not authenticated anymore I send 401 becks to the client so I have some questions how I can check if there is sessionid in cookies? I tried document.cookie but it did not work how to delete the sessionid?? Can someone help me please? and sorry for my English -
implementing a create function for a Serializer class containing foreignkey (Django Rest Framework)
So, this is how i have implemented the class: class VenueSerializer(serializers.ModelSerializer): city = serializers.StringRelatedField(many=True) class Meta: model = Venue fields = '__all__' def create(self, validated_data): venue = Team( name=validated_data['name'] #I know this is wrong but i just wanted to demonstrate what is it that i need to get done #city is the foreign key referencing to the model City city=validated_data['city'] ) venue.save() return venue So i have a model for venues, and each venue has to be associated with the model city. I am new to the REST Framework and i can't figure out a way to create an instance of the venue model while setting the value of the city field. Can someone please help me with this? Than you -
Django: Saving created object to user?
I have a model of uploads and i want to associate the uploaded images to the user so that later each user can only view his objects so so i m trying to save the created objects to the authenticated user, but it's not working and i keep getting owner =null on my model class Uploads(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) title=models.CharField(max_length=500,default='none') image=models.ImageField(upload_to='media',unique=True) created_at = models.DateTimeField(auto_now_add=True) associatedFile=models.ForeignKey(to=File, on_delete=models.CASCADE,null=True) owner=models.ForeignKey(User,related_name="uploads", on_delete=CASCADE,null=True) class IsOwnerFilterBackend(filters.BaseFilterBackend): def filter_queryset(self, request, queryset, view): queryset=Uploads.objects.all() return queryset.filter(owner=request.user) class UploadView(viewsets.ModelViewSet): queryset=Uploads.objects.all() serializer_class=UploadSerializer filter_backends = (IsOwnerFilterBackend,) @api_view(['GET', 'POST']) def methodes(self,request,*args,**kwargs): if request.method=='POST': serializer=UploadSerializer(data=request.data) if serializer.is_valid(): serializer.save(owner=self.request.user) return Response("test_token success", status=status.HTTP_200_OK) return HttpResponse({'message':'error'},status=400) elif request.method=='GET': images=Uploads.objects.filter(owner=self.request.user) serializers=UploadSerializer(images[0],many=False) return JsonResponse(serializers.data,safe=False) class UploadSerializer(serializers.ModelSerializer): image = Base64ImageField( max_length=None, use_url=True, ) owner=serializers.ReadOnlyField() class Meta: model = Uploads fields = '__all__' -
How to display for user that his wishlist is empty?
Question like in title. When i tried this views.py, error doesn't occur but site doesn't want to show, i can see only code. Any solutions? def wishlist(request): if request.user.is_authenticated: user = request.user.id if List.objects.filter(user=user).exists(): context = List.objects.filter(user=user) error = 'Your wishlist is empty' else: context = List.objects.filter(user=user) else: context = WishList(request) return render(request, 'wishlist/wishlist.html', {'wishlist': context}, {'error': error})