Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to add data to manytomanyfield in drf
enter image description here enter image description here enter image description here So I have a 2 models with a manytomany field. A book might be created without a publisher. When a publisher is added, I want to add it to the Books model with respect to its id any help is much appreciated -
Django `UniqueConstraint` exception handled the same as 'unique=True'
When UniqueConstraint of a model is violated, an exception is raised. How can I make it to behave the same as violation of a field with unique=True? identifier = models.CharField("id", max_length=30, unique=True, blank=True, null=True, validators=[validate_id]) class Meta: constraints = [ models.UniqueConstraint( Lower("identifier"), name="id_case_insensitive_constraint" ) ] Here I want a form's form_invalid called with the same field errors and all that, whether the input is exactly the same as another one or its only difference is case distinction. -
How to access a field through a sub table Django
I Have a table Product and a table Variation, I want to access the field Price inside the table Variation trough calling my Product Object How im trying to call the field in my HTML page: {{item.variation.price_set.first}} Note: {{item}} is my product object my models: class Product(models.Model): //JUST NORMAL FIELD STUFF class Variation(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) price = models.FloatField() -
Get queryset objects grouped by an annotation value range
I need to filter my objects in a way to get them grouped by range (range is fixed, for this case let's say we have these 3 ranges [0.0, 33.0] [33.01, 66.0] [66.01, 100.0] here is my model class Item(models.Model): name = models.CharField( help_text="Itemname", max_length=256 ) price = models.DecimalField(max_digits=6, decimal_places=2) I am trying to get a result that looks like this { "0.0-33.0": { name: x, }, "33.01-66.0": { name: y, name: z, }, } I tried something like this: item_by_range = Item.objects.filter(price__lte=100.0).annotate( price_group=Case( When(price__range=[0.0, 33.0], then=Value('0-33')), When(price__range=[33.01, 66.0], then=Value('33-66')), When(price__range=[66.01, 100.0], then=Value('66-100')), default=Value('No group'), output_field=CharField(), ) ).values('name', 'price_group').order_by('price_group') but this only works if I pass only price_group in values but this way I lose the name of the item thanks. -
Can you use session authentication with token authentication? Django Rest Framework
I’m using Django token based auth for my mobile app (react native) and I’m able to log in successfully. I’m also using the Spotify api which I have to open the browser (safari) to log in then it’ll redirect me back to a url in my backend Django-Rest then redirect me back to my react frontend. My issue is that I have to set a redirect uri for Spotify but can’t attach my auth token to it. So after I log into Spotify in the browser and it redirects to the url, I get a 401 error bc it won’t recognize the current user. Is there a way to store the token/current user in cookies/session so the browser will remember who the user is? Do I use session authentication?? Can I/Do I use both token and session authentication? Appreciate any help! Can provide more info if it’ll help -
Given that both the functions are asynchronous, how to ensure that the second function executes after the first function has completely executed
I am learning django and I am stuck with this problem. I wrote a code that uses a function two times. Here is the code snippet. rjl = run(["gnome-terminal", "--", "sh", "-c", f"ffmpeg -i {video_name}_audio_stripped.mp4 -i {audio_name} -c:v copy -c:a aac {final_tutorial}"], cwd="media/") while True: print("frgd") if(rjl.check_returncode()==None): print("wdcv") #for i in range(1000000000): # continue run(["gnome-terminal", "--", "sh", "-c", f"ffmpeg -i {final_tutorial} -vcodec libx265 -crf 28 reduce_{final_tutorial}"], cwd="media/") break else: print("ygbhb") So, the function is run(). Please note that run is subprocess.run. The second run() uses the output generated by the first run function as input. Since run() is asynchronous the second run() executes before the first run() has produced the desired output. In this case, the first run() produces a .mp4 file in the media folder. I made some changes in the code as you can see to solve this problem but still the problem remains. Can someone please suggest me what should I do? I am a newbie and some help will be appreciated. -
Refreshing context variable with ajax
getting null instead of the refreshed value when the event is triggered in the template, getting the correct value in both terminal and console for example success 6 and 6 respectively. How do I get the real value to render out instead of null, feel free to improve this question if you see anything wrong. Cheer! This is my code: path('ajax_update/', views.ajax_update, name="ajax_update"), view def ajax_update(request): stuff = bagstuff(request) bag = stuff['bag'] if is_ajax and request.method == "GET": if bag: print("success", bag) data_attribute = request.GET.get(bag) return JsonResponse(data_attribute, safe=False, status=200) else: print("failed") context = {"bag": bag} return render(request, template, context) template: <script> var number= "{{bag}}"; var update_bag_url = "{% url 'main:ajax_update' %}"; </script> javascript: function update_bag() { // optional: don't cache ajax to force the content to be fresh $.ajaxSetup ({ cache: false }); // specify loading spinner var spinner = "<img alt='loading..' />"; $("#lil-icon-two").html(spinner).load(update_bag_url); console.log(number); } -
in django filter argument kay not define error
my model is first_name=models.CharField(max_length=100, null=False) last_name=models.CharField(max_length=100) dept = models.ForeignKey(Department,on_delete=models.CASCADE) salary = models.IntegerField(default=0) bonus = models.IntegerField(default=0) role = models.ForeignKey(Role, on_delete=models.CASCADE) phone = models.IntegerField(default=0,max_length=12) hire_date = models.DateField(default=datetime.now() and my view is as if request.method == "POST": # print("post received") # print(request.POST) name = request.POST['first_name'] d = request.POST['department'] role = request.POST['role'] emps = Employee.objects.all() if name: emps = emps.filter(Q(first_name__icontains== name) | Q(last_name__icontains == d)) if d: pass if role: pass return render(request, 'fil_emp.html') but at this time i received error like ** "first_name__icontains" is not defined ** -
Getting Image through HTML and using Python Code
I am trying to make a website that gets the user image and uses facelandmark code(python) to tell the user about user's face shape and etc. How can I get the imange through html and use the image file in python code and show the result to the user again? Is using django the only way? I have tried to study django in many ways and most of the stuffs I found were not directly helping on my planning website. Thank you for reading -
Django creating post for foreign key has error 'Direct assignment to the reverse side of a related set is prohibited'
I have a Protein model that is linked to the Domain model through the proteins foreign key in the Domain model. class Protein(models.Model): protein_id = models.CharField(max_length=256, null=False, blank=False) sequence = models.CharField(max_length=256, null=True, blank=True) length = models.IntegerField(null=False, blank=False) taxonomy = models.ForeignKey(Organism, blank=True, null=True, on_delete=models.DO_NOTHING) def __str__(self): return self.protein_id class Domain(models.Model): domain_id = models.CharField(max_length=256, null=False, blank=False) description = models.CharField(max_length=256, null=False, blank=False) start = models.IntegerField(null=False, blank=False) stop = models.IntegerField(null=False, blank=False) proteins = models.ForeignKey(Protein, blank=True, null=True, related_name="domains", on_delete=models.DO_NOTHING) def __str__(self): return self.domain_id I want to post a new protein record using the Protein serializer. The Protein serializer displays the data from the Domain under the domains field. class ProteinSerializer(serializers.ModelSerializer): domains = DomainSerializer(many=True) taxonomy = OrganismSerializer() class Meta: model = Protein fields = [ 'protein_id', 'sequence', 'taxonomy', 'length', 'domains', ] I made the create function in the Protein serializer to create the two foreign keys when posting a new record. However, when creating the foreign key for domains, I get the error TypeError: Direct assignment to the reverse side of a related set is prohibited. Use domains.set() instead. I have tried using domains.set() for my domains list but it still gives me the same error? def create(self, validated_data): taxonomy_data = self.initial_data.get('taxonomy') domains_data = self.initial_data.get('domains') domains_list … -
Django forms not saving posts to database
i am trying to create a course from my frontend using django form, everything seems fine but when i hit the create button it just refreshes the page without saving to database or throwing back any error, and that is not what i am expecting. create-course.html def create_course(request): if request.method == "POST": form = CreateCourse(request.POST, request.FILES) if form.is_valid(): new_form = form.save(commit=False) new_form.slug = slugify(new_form.course_title) new_form.course_creator = request.user new_form.save() messages.success(request, f'Your Course Was Successfully Created, Now in Review') return redirect('dashboard:dashboard') else: form = CreateCourse() context = { 'form': form } return render(request, 'dashboard/create_course.html', context) models.py class Course(models.Model): course_title = models.CharField(max_length=10000) slug = models.SlugField(unique=True) course_thumbnail = models.ImageField(upload_to=user_directory_path) short_description = models.CharField(max_length=10000) course_description = models.TextField() price = models.IntegerField(default=0) discount = models.IntegerField(default=0) requirements = models.CharField(max_length=10000) course_level = models.CharField(max_length=10000, choices=COURSE_LEVEL) # course_rating = models.CharField(max_length=10000, choices=COURSE_RATING) # course_rating = models.ForeignKey(CourseRating, on_delete=models.SET_NULL, null=True, blank=True) course_language = models.CharField(max_length=10000, choices=COURSE_LANGUAGE) # course_category = models.CharField(max_length=10000, choices=COURSE_CATEGORY) course_category = models.ForeignKey(Category, on_delete=models.DO_NOTHING) course_tag = models.ManyToManyField(Tag) course_cost_status = models.CharField(max_length=10000, choices=COURSE_COST_STATUS, default="Free") course_intro_video = models.FileField(upload_to=user_directory_path) course_intro_video_url = models.URLField(default="https://") course_intro_video_embedded = models.URLField(default="https://") course_creator = models.ForeignKey(User, on_delete=models.CASCADE) date_created = models.DateTimeField(auto_now_add=True, null=True) course_duration = models.IntegerField(default=0) course_publish_status = models.CharField(max_length=10000, choices=COURSE_PUBLISH_STATUS) views = models.IntegerField(default=0) likes = models.IntegerField(default=0) featured = models.BooleanField(default=False) digital = models.BooleanField(default=True) best_seller = models.BooleanField(default=False) forms.py from course.models import … -
Django - how to update elements within a list in a single pUT request
Could use some help with the following please. I am looking to update the objects in a list as one PUT request, how would I go about doing it? I've made some progress but I can't seem to figure it out. The list to PUT to perform updates could be some of the objects in the table, or all of them. But I am aiming to, in one request, submit a list of share elements, and have all the elements that match those in the table be updated with the new values, if any, of the elements within the list of this one PUT request. Models.py class Share(models.Model): ShareName = models.CharField(max_length=100, unique=True, default="N/A") ISINCode = models.CharField(max_length=100, primary_key=True, default="N/A") Price = models.DecimalField(decimal_places=6, max_digits=9, default=0.000000) Serializers.py class ShareSerializer(serializers.ModelSerializer): """ Serializer for Share """ class Meta: model = Share fields = ('ShareName', 'ISINCode', 'Price') Views.py class ShareViewSet(ModelViewSet): authentication_classes = [] permission_classes = [] queryset = Share.objects.all().order_by('ISINCode') # serializer_class = ShareSerializer paginator = None def get_serializer(self, *args, **kwargs): if "data" in kwargs: data = kwargs["data"] # enable list posting if isinstance(data, list): kwargs["many"] = True return super(ShareViewSet, self).get_serializer(*args, **kwargs) I've read through the docs here https://www.django-rest-framework.org/api-guide/serializers/#listserializer and also figured out one way to probably … -
Custom Mixin is not showing up
I'm not getting any errors but the carousel not showing up in my content/views.py class IndexView(CarouselObjectMixin, ListView): model = Post template_name = 'index.html' cats = Category.objects.all() ordering = ['-post_date'] ordering = ['-id'] def get_context_data(self, *args, **kwargs): cat_menu = Category.objects.all() context = super(IndexView, self).get_context_data(*args, **kwargs) context["cat_menu"] = cat_menu return context maybe their is something wrong with my custom mixin itself, I'm not sure if I build it correctly. slideshow/views.py class SlideShowView(ListView): model = Carousel context_object_name = 'carousel' template_name = 'showcase.html' Custom Mixin class CarouselObjectMixin(object): model = Carousel context_object_name = 'carousel' template_name = 'showcase.html' slideshow/templates/showcase.html {% extends 'base.html' %} {% load static %} {% block content %} <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1" /> <!-- Showcase --> <body> <section class="bg-transparent text-dark text-center"> <div id="carouselExampleControls" class="carousel slide" data-bs-ride="carousel"> <div class="carousel-inner"> {% for object in carousel %} <div class="carousel-item {% if forloop.counter0 == 0 %} active {% endif %}"> <img src="{{object.image.url}}" class="d-block w-100" alt="..."> </div> {% endfor %} </div> <button class="carousel-control-prev" type="button" data-bs-target="#carouselExampleControls" data-bs-slide="prev"> <span class="carousel-control-prev-icon" aria-hidden="true"></span> <span class="visually-hidden">Previous</span> </button> <button class="carousel-control-next" type="button" data-bs-target="#carouselExampleControls" data-bs-slide="next"> <span class="carousel-control-next-icon" aria-hidden="true"></span> <span class="visually-hidden">Next</span> </button> </div> </section> <!-- Post --> </body> {% endblock %} slideshow/models.py class Carousel(models.Model): title = models.CharField(max_length=255, blank=True) description = models.TextField(max_length=255, blank=True) image = models.ImageField(upload_to="showcase/%y/%m/%d/", … -
Can i use flask with Django? [duplicate]
I am currently learning Django want to flask. I need some guidance for flask and Django. I want to create two apps. 1st application is a api service. I am thinking of using flask for this. 2nd application is creating blog for this api service. I want these two apps never interact with each other;never share some information with each and be independent. Is it possible? Sorry for asking that much dumb question i am still learning django. Thank you. -
DEBUG: Crawled (403) - INFO: Crawled 0 pages
Here's my spider class ProductoSpiderTres(CrawlSpider): name = 'linio' item_count = 0 allowed_domain = ['www.linio.com.co'] p = "portatil lg" start_urls = ["https://www.linio.com.co/search?scroll=&q="+p] handle_httpstatus_list = [403] def __init__(self, **kwargs): super().__init__(**kwargs) rules = { Rule(LinkExtractor(allow = (), restrict_xpaths = ('//a[@class="page-link page-link-icon"]'))), Rule(LinkExtractor(allow = (), restrict_xpaths = ('//a[@class="col-12 pl-0 pr-0"]')), callback = "parse_item", follow = False), } def parse_item(self, response): global outputResponse lista = {} lista['titulo'] = response.xpath('//span[@class="product-name"]/text()').extract_first() lista['urlImagen'] = response.xpath('//img[@class="image-modal"]/@src').extract_first() lista['precio'] = response.xpath('//span[@class="price-main-md"]/text()').extract_first() lista['conyven'] = response.xpath('nn').extract_first() #ignore this lista['estrellas'] = response.xpath('nn').extract_first() #And this lista['url'] = response.request.url outputResponse.append(lista) self.item_count += 1 if self.item_count > 3: raise CloseSpider('item_exceeded') yield lista And... here's where I execute it def executetres(peticion): url = ['https://www.linio.com.co/search?scroll=&q='+peticion] process = CrawlerProcess({ 'USER_AGENT': "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.120 Safari/537.36" }) process.crawl(ProductoSpiderTres, start_urls=url) process.start() return outputResponse print (executetres("computador portatil")) And then... I got this: 2022-04-30 21:16:31 [scrapy.utils.log] INFO: Scrapy 2.5.1 started (bot: scrapybot) 2022-04-30 21:16:31 [scrapy.utils.log] INFO: Versions: lxml 4.7.1.0, libxml2 2.9.12, cssselect 1.1.0, parsel 1.6.0, w3lib 1.22.0, Twisted 21.7.0, Python 3.9.5 (tags/v3.9.5:0a7dcbd, May 3 2021, 17:27:52) [MSC v.1928 64 bit (AMD64)], pyOpenSSL 22.0.0 (OpenSSL 1.1.1m 14 Dec 2021), cryptography 36.0.1, Platform Windows-10-10.0.19044-SP0 2022-04-30 21:16:31 [scrapy.utils.log] DEBUG: Using reactor: twisted.internet.selectreactor.SelectReactor 2022-04-30 21:16:31 [scrapy.crawler] INFO: Overridden settings: {'USER_AGENT': … -
Trying to create a Custom Mixin for Class Based Views
I am trying to make a custom mixin for my Carousel but I am getting this error File "/src/content/urls.py", line 3, in from . import views File "/src/content/views.py", line 34, in class IndexView(CarouselObjectMixin, ListView): NameError: name 'CarouselObjectMixin' is not defined the mixin that I made was added to my content app class IndexView(CarouselObjectMixin, ListView): model = Post template_name = 'index.html' cats = Category.objects.all() ordering = ['-post_date'] ordering = ['-id'] def get_context_data(self, *args, **kwargs): cat_menu = Category.objects.all() context = super(IndexView, self).get_context_data(*args, **kwargs) context["cat_menu"] = cat_menu return context but the custom mixin is in my slideshow app. Function Based View views.py def SlideShowView(request): carousel = Carousel.objects.all() context = { 'carousel' : carousel, } return render(request, "showcase.html", context) Converted to Class Based View views.py class SlideShowView(ListView): model = Carousel context_object_name = 'carousel' template_name = 'showcase.html' Custom Mixin views.py class CarouselObjectMixin(object): model = Carousel context_object_name = 'carousel' template_name = 'showcase.html' -
serializer increases the query in django rest framwrork
I have an API that returns the data including ManyToMany relation's data as well, but when I see queries in Django Debug Toolbar so it's more than 100 queries at the backend which I think is not a good approach, even if the records increases so the queries also get increases. I just want fewer queries so the API can respond faster, is there any way to achieve it? models.py class Package(models.Model): name = models.CharField(max_length=255, default='') description = models.CharField(max_length=255, null=True, blank=True) project = models.ForeignKey(Project, on_delete=models.CASCADE, null=True) is_active = models.IntegerField(default=1, null=True) tags = models.ManyToManyField(Tag, related_name='packageroom') members = models.ManyToManyField(User,related_name='packages') account = models.ForeignKey(User, on_delete=models.CASCADE, null=True) class Meta: db_table = 'packages' serializers.py class PackageSerializer(serializers.ModelSerializer): tags = TagSerializer(read_only=True, many=True) # added to fetch tags details team_members = UserDetailSerializer(read_only=True, many=True) # added to fetch team members details class Meta: model = Package fields = ['id', 'name', 'description', 'project', 'tags', 'team_members'] views.py query = Package.objects.filter(project=project_id, is_active=1).prefetch_related('tags', 'team_members').select_related('project', 'account') packages = PackageSerializer(query, many=True).data return Response(packages) I just want fewer queries so the API can respond faster, is there any way to achieve it? -
Django - How to update the status of one model in the save method of another model
I have two models ''' class JobPosition(models.Model): ... position_status = models.CharField(choices=POSITION_STATUS) class Outreach(models.Model): ... outreach_status = models.CharField(choices=OUTREACH_STATUS, max_length=20) position = models.ForeignKey('action.JobPosition', on_delete=models.CASCADE, related_name='feelers') ''' I want the position_status of jobposition to be, at any time, the highest of the outreach_status of the outreaches that are related to it (feelers). Where "highest" is set by an arbitrary rule of mine that we can ignore. My thinking is to override the save method of the outreach model and make it so that when the status of the outreach changes, I trigger an update status in the jobposition model to update the status of the position. However, I am realizing that within the safe method, the status of the outreach is still not updated in the DB so if I trigger something on the jobposition model, it would not work. Any other idea? I can do everything in the outreach method but it would have to be an ugle function and I was hoping there was a better way within the jobposition model. -
Como sumar la columna de valores de los registros de una tabla clasificandolos por sus categorías que vienen heredadas de otro model django
Tengo un programa de contabilidad que recibe inputs (transacciones) del usuario, entre otros datos que tiene la tabla de transacciones llamada "Ingreso" está la columna de "Bolsillo_Afectado" y lo que quiero hacer es mostrarle al usuario sus bolsillos (o cuentas para que me entiendan mejor) y el total de dinero que tiene cada uno). Cabe recalcar que la columna de "Bolsillo_Afectado" está heredada de otra clase como ForeingKey, Aquí el codigo, espero puedan ayudarme, he batallado mucho con ello :´) models.py ------------------------------------------------------------- class Bolsillo(models.Model): Nombre = models.CharField(max_length=25, verbose_name='Nombre bolsillo', unique=TRUE) class Meta: #este va a ser la manera en la que se ordenen los datos al llamarlos desde el admin o desde las vistas ordering = ['id'] def __str__(self): #Esto será lo que devuelva el modelo al momento de mostrarse desde el administrador, se pueden poner varios campos return self.Nombre class Ingreso(models.Model): timestamp = models.DateField( default=timezone.now) Valor = models.DecimalField(null=FALSE, blank= FALSE,decimal_places=0, max_digits=10 ) Categoría = models.ForeignKey(Categoría_Ingresos, on_delete=models.PROTECT) #El tipo de relación many to many field permite u Bolsillo_Afectado = models.ForeignKey(Bolsillo, on_delete=models.PROTECT) #la propiedad PROTECT indica que no se puede borrar un registro de bolsillo si otra tabla lo está usando Nombre = models.CharField(max_length=30, blank=FALSE, null=FALSE) Usuario = models.ForeignKey(User, on_delete=models.CASCADE, related_name='form_ing' … -
consoling out django context in console
why am I getting output in console as {{request.num}} without the actual number? This is my code: def test(request): number = 4 context = {"num": number} javascript var number = "{{request.num}}"; console.log(number) -
Django get max length value from same model with Coalesce
I'm trying to write the following raw query with the ORM. I'm not sure is it possible or not. select first_name, middle_name, COALESCE(middle_name, ( select middle_name from contacts c2 where c2.first_name = c1.first_name and c2.last_name = c1.last_name and c2.middle_name is not null order by length(c2.middle_name) desc limit 1 ) ) expected, last_name from contacts c1 The expected result is like the following, if middle_name is null, get the middle name from another record that has the same first_name and last_name. id| first_name | middle_name | expected | last_name 1 | ahmet | <NULL> | burak | ozyurt 2 | ahmet | burak | burak | ozyurt DB: Postgres Django Version: 3.12 -
docker-compose django unable to connect to postgres
I'm trying to dockerize an existing django application. I've followed the example docker-compose and docker files on https://docs.docker.com/samples/django/ I've added the links and networks suggestion as see on other posts, to no avail. I've brought up the db by itself with docker-compose up db and run docker ps and confirmed it's up, accepting connections, and has the name db. I'm not sure what else to try. My docker-compose: version: '3' services: #octoprint: # image: octoprint/octoprint # restart: unless-stopped # ports: # - 16766:16766 # volumes: # - ./octoprint:/octoprint # logging: # driver: none db: image: postgres volumes: - ./data/db:/var/lib/postgresql/data environment: - POSTGRES_DB=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres container_name: db networks: harpnetwork: harp: build: context: . dockerfile: docker/harp/Dockerfile volumes: - ./harp:/harp environment: - POSTGRES_DB=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres ports: - 16765:16765 depends_on: - db networks: harpnetwork: links: - db:db networks: harpnetwork: My django db config: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': os.environ.get('POSTGRES_NAME'), 'USER': os.environ.get('POSTGRES_USER'), 'PASSWORD': os.environ.get('POSTGRES_PASSWORD'), 'HOST': 'db', 'PORT': 5432, } } and my Dockerfile to build the django project From python:3.10 COPY ./harp harp WORKDIR /harp RUN pip install -r requirements.txt RUN python manage.py migrate CMD ["python", "manage.py", "runserver", "0.0.0.0:16765"] -
How do I input an image that is already displayed on html?
I'm working with a webcam application and I am trying to integrate it into Django framework. This is the function that takes a photo(it's javascript in static folder): // play sound effect shutter.play(); // take snapshot and get image data Webcam.snap( function(data_uri) { // display results in page document.getElementById('results').innerHTML = '<img id="imageprev" src="'+data_uri+'"/>'; } ); document.getElementById("camera").outerHTML = ""; Webcam.reset(); } This is a fraction from my template: <div id="camera"></div> <button onclick="takeSnapShot()" type="button" id="button1" class="button-1">Take Picture</button> <form action="" enctype="multipart/form-data" method="POST"> {% csrf_token %} <div name="results" id="results"></div> <div class="button-2"> <button type="submit" href="/">Pateikti</button> </div> </form> So after picture taken, it displays an image inside < div > tag which id is "results" And now I want to save taken photograph. So I tried POST method, but when I do that, the template reloads, and the image gets lost. So I believe that's why I'm getting this error window. Also usually POST method used when you want to save files in your server which client uploads, so I'm not sure if this is the best way to do this So my question is: Is there a method to save an image to your server from a template? Or am I using POST method wrong? … -
How to permit only users with a particular domain to login? Django google authentication
I'm trying to limit the access to a page only to logged users. I used the google authentication, but it let every account to log in; instead i want to avoid every domains different from 'fermi.mo.it'. A google account like luca@gmail.com shouldn't be able to login, while an account like luca@fermi.mo.it should be able to. I noticed this code to make it, but it doesnt work. It says: "No module named 'social_core'" but i installed it. AUTHENTICATION_BACKENDS = ( 'social_core.backends.google.GoogleOAuth2', 'django.contrib.auth.backends.ModelBackend', ) SOCIAL_AUTH_GOOGLE_OAUTH2_WHITELISTED_DOMAINS = ['fermi.mo.it'] These are all the modules that i installed: -
How Can I Create Array Form Input in Django
I have the following form input in my template that displays questions from the database. <input type="text" name="qus[{{ question.id }}]" id="qus" value="{{ question.quest }}" /> I created my Django form with: class QuestionForm(forms.Form): qus = SimpleArrayField(forms.CharField(max_length = 50)) Each time I submit the form, it does'nt work. It seems the form is not valid MyQuestionForm = QuestionForm(request.POST) if request.method == "POST" and MyQuestionForm.is_valid(): How can I create the form properly and loop through request.POST['qus'] to retrieve all the values when I submit the form? Please help.