Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How am I supposed to add a field to a signup form in django-allauth? Docs vs Stackoverflow vs Blog posts
It appears that there are multiple ways to add a simple field to a django-allauth signup form. From @danielfeldroy I see what's quoted below. # SpyBookSignupForm inherits from django-allauth's SignupForm class SpyBookSignupForm(SignupForm): # Specify a choice field that matches the choice field on our user model type = d_forms.ChoiceField(choices=[("SPY", "Spy"), ("DRIVER", "Driver")]) # Override the init method def __init__(self, *args, **kwargs): # Call the init of the parent class super().__init__(*args, **kwargs) # Remove autofocus because it is in the wrong place del self.fields["username"].widget.attrs["autofocus"] # Put in custom signup logic def custom_signup(self, request, user): # Set the user's type from the form reponse user.type = self.cleaned_data["type"] # Save the user's type to their database record user.save() But then, in the response to a ticket from https://github.com/pennersr/django-allauth/issues/826 pennersr (django-allauth's founder) states that all we have to do is: class SignupForm(forms.Form): first_name = forms.CharField(max_length=30, label='Voornaam') last_name = forms.CharField(max_length=30, label='Achternaam') def signup(self, request, user): user.first_name = self.cleaned_data['first_name'] user.last_name = self.cleaned_data['last_name'] user.save() And then add ACCOUNT_SIGNUP_FORM_CLASS = 'yourproject.yourapp.forms.SignupForm' to my settings. See: How to customize user profile when using django-allauth But then in the docs we have this: https://django-allauth.readthedocs.io/en/latest/forms.html#signup-allauth-account-forms-signupform Where we do this: from allauth.account.forms import SignupForm class MyCustomSignupForm(SignupForm): def save(self, request): # Ensure you … -
django model is getting Alter Field alert on every migrations
i am getting alter filed alert every time when i run the command python manage.py makemigrations i also delete my database old migration files but the alert is still there can anybody know how can i solve this issue? Migrations for 'assignment': assignment/migrations/0012_auto_20201016_0754.py - Alter field city on assignment - Alter field status on assignment class Assignment(models.Model): CITY_SELECT = { ('i', 'Islamabad'), ('l', 'Lahore'), ('m', 'Multan'), ('k', 'Karachi'), ('q', 'Queta'), ('p', 'Pashawar') } STATUS_SELECT = { ('p', 'Pendding'), ('d', 'Done'), ('i', 'In field'), ('c', 'Cancel') } place = models.CharField(max_length=100) desc = models.CharField(max_length=500) reporter = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) created_on = models.DateTimeField(auto_now_add=True) assign_time = models.DateTimeField(auto_now=False, null=True) city = models.CharField(choices=CITY_SELECT, max_length=9) status = models.CharField(choices=STATUS_SELECT, max_length=8) -
No such file or directory when i load image
When loading an image from a form, an error is triggered: "[Errno 2] No such file or directory: '... \ pictures \ foto.jpg'", but if i load from database then everything works well file views.py: elif "ProfileUpdateForm" in request.POST: form=ProfileUpdateForm(request.POST,request.FILES) if form.is_valid(): profile=Profile.objects.get(user=self.request.user) profile.avtor=form.cleaned_data.get('avtor') profile.save() obj=Profile.objects.get(user__username=self.request.user) return HttpResponseRedirect(reverse_lazy('profile',kwargs={'slug': obj.slug},)) file forms.py: class ProfileUpdateForm(forms.ModelForm): class Meta: model=Profile fields=('avtor',) widgets={'avtor': forms.FileInput(),} file models.py: class Profile(models.Model): user=models.OneToOneField(User,verbose_name="Пользователь",on_delete=models.CASCADE) avtor=models.ImageField(verbose_name="Аватарка",default='user_images/default.jpg', upload_to='user_images',blank=True) def save(self, *args, **kwards): image = Image.open(self.avtor.path) if image.height > 256 or image.width > 256: resize = (256, 256) image.thumbnail(resize) image.save(self.avtor.path) return super(Profile, self).save(*args, **kwards) file profile.html: <form action="" method="POST" enctype="multipart/form-data"> {% csrf_token %} {{ ProfileUpdateForm.as_p }} <input name="ProfileUpdateForm" class="input-button" type="submit" value="Save" /> </form> -
How to Retrieve Post by Each Category in a Blog and Place them on postlist html page in django
Am creating a blog and a news website in django which have a specific category displayed on its hompage. That is the specific category for news, Politics and education are beeing displayed on my post_list.html. I get a no exception provided when i try to retrieve it by Post.objects.filter(category__name__in=["news"]) This is the model for my category class Category(models.Model): name = models.CharField(max_length=250) slug = models.SlugField(max_length=250, unique=True) This is the model for my Post class Post(models.Model): image = models.ImageField(upload_to="images/") title = models.CharField(max_length=150) summary = models.CharField(max_length=250) category = models.ForeignKey(Category, on_delete=models.CASCADE) *This is the view for my postlist class PostListView(ListView): model = Post template_name = blog/post_list.html context_object_name = "posts" ordering = ["date_posted" paginate_by = 5 def get_queryset(self): posts = get_object_or_404(Post) return Post.objects.filter().order_by( "-date_posted") def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['posts'] = Post.objects.filter()[0:4] context['new_cat'] =Post.objects.filter(category__name__in=[" news"])[0.5] context['new_politics'] = Post.objects.filter(category__name__in=["politics"])[0.5] return context *** This is my pos_tlist.html code for retrieving post by category in news <div> <h1>News</h1> <div/> {% for post in new_cat%} div class="mt-2" <a href="{{ post.get_absolute_url }}"><img class="object-cover w-full rounded-lg" src="{{ post.image.url }}" alt="{{ post.title }} cover"> </a></div> <div class="py-2 flex flex-row items-center justify-between"> <a href="{{ post.get_absolute_url }}"><h1 class="hover:text-blue-600 text-gray-900 font-bold text-xl mb-2 py-2">{{ post.title }}</h1></a></div> ''' I get a no exception provided for … -
Field 'id' expected a number but got <Listing: Ps4 Pro>
It's my first time creating a Django website with models, and in my first attempt to insert data into my table I'm getting this error. My models are as follows: class User(AbstractUser): pass #https://docs.djangoproject.com/en/3.1/topics/auth/default/ class Listing(models.Model): listingID = models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name="listID") created_by = models.ForeignKey(User, on_delete=models.SET_NULL, related_name="myListing", null=True) watchers = models.ManyToManyField(User, blank=True, related_name="watchlist") title = models.CharField(max_length=30) description = models.TextField() creation_date = models.DateField(auto_now=True) img_url = models.URLField() active = models.BooleanField(default=True) def __str__(self): return f"{self.title}" class Bid(models.Model): listing = models.ForeignKey(Listing, on_delete=models.SET_NULL, related_name="bidsMadeOnMe", null=True, blank=True) user = models.ForeignKey(User, on_delete=models.SET_NULL, related_name="myBids", null=True) price = models.FloatField() creation_date = models.DateField(auto_now=True, null=True) def __str__(self): return f"Bid={self.price}" and the view that handles the form submission is this one: @login_required def create_listing(request): if request.method == "POST": user = User.objects.get(username=request.user.username) l = Listing(created_by=user, title=request.POST["title"], description=request.POST["desc"], # https://stackoverflow.com/questions/12176585/handling-dates-over-request-get creation_date=models.DateTimeField(auto_now_add=True), img_url=request.POST["image_url"] ) l.save() b = Bid(l, user, request.POST["initial_bid"], models.DateTimeField(auto_now_add=True) ) b.save() return render(request, "auctions/index.html") I know the problem is the way I'm adding the data but I can't fix it. Can someone give me some light? -
Stop a running function in Django
I am uploading a CSV file then adding the rows in the database and I want to able to pause, resume or terminate the function that handles the upload so the user can pause or terminate while the file is still uploading the file to the server or when the server is adding the content of the CSV file into the database I tried to use threading but i couldn't do it that way and then i tried to time.sleep() but it just runs and it does not pause the show function and when i try to stop the pause function it does not stop views.py is_paused = False def show(request): content = {} if not is_paused: if request.method =='POST': uploaded_file = request.FILES['file'] print(uploaded_file.name) print(uploaded_file.size) fs = FileSystemStorage() fs.save(uploaded_file.name,uploaded_file) upload = Upload() upload.title = uploaded_file.name upload.file = uploaded_file upload.save() filecontent = file_content() path = '/home/ahmed/Desktop/atlan/atlan/media/'+uploaded_file.name with open(path) as csv_file: csv_reader = csv.reader(csv_file, delimiter=',') next(csv_reader) for row in csv_reader: filecontent.seq = row[0] filecontent.First_name =row[1] filecontent.Last_name = row[2] filecontent.age = row[3] filecontent.street = row[4] filecontent.city = row[5] filecontent.state = row[6] filecontent.zipcode = row[7] filecontent.dollar = row[8] filecontent.color = row[9] filecontent.date = row[10] file_content.CSV_ID = upload.ID filecontent.save() else: time.sleep(2) return render(request,'upload/upload.html', content) def … -
How to achive SUM aggregate() + distinct(fields) in Django ORM
I have a model: class A(models.Model): name = models.CharField() price = models.IntegerField() I need to aggregate Sum of all records in db but before it I want to remove duplicates by name (distinct) So i try use A.objects.all().distinct('name').aggregate(total=Sum('price') But I got error NotImplementedError: aggregate() + distinct(fields) not implemented. So, How can I achieve same result in django orm? -
Django if statement not working inside of a for loop in templates
So I want to display all the posts from the user, in their profile while logged in, but can't seem to figure out how to do it. This is my template: {% for post in posts %} {% if user.username == post.author %} <div class="container col-lg-8 ml-lg-5"> <div class="box"> <a href="#"><img class="rounded-circle account-image" src="{{ post.author.profile.image.url }}" alt="" ></a> <a href="#"><h4 style="float: left;">{{post.author}}</h4></a> <small>{{post.date_posted}}</small> <hr width="82%" align="right"> <br> <div class=""> <p>{{post.content}}</p></div> </div> <br> </div> {% endif %} {% endfor %} And this is my model: class Post(models.Model): content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) It doesn't show me any errors, it just doesn't work. When I try removing the if statement, it works, but shows me every post by every user -
Different models order in main.django_content_type table during unittesting
I'm using django 3.1 with SQLite DB. I'm using my django project as API, so django rest framework is installed as well. During my unittest (with pycharm) I've observed that in table main.django_content_type some models in my dev DB and test DB are ordered differently and have different IDs. For example defaultcategory and customcategory: dev DB: admin logentry auth permission auth group contenttypes contenttype sessions session core customuser core historicalcustomuser authtoken token authtoken historicaltoken finances fixtransaction finances historicaldefaultcategory finances historicaltransfer finances historicaltransaction finances transaction finances fixtransfer finances historicalfixtransfer finances historicalcostaccount finances historicalfixtransaction finances transfer finances costaccount finances historicalcustomcategory finances defaultcategory finances customcategory test DB: admin | log entry auth | permission auth | group contenttypes | content type sessions | session core | custom user core | historical custom user finances | cost account finances | transfer finances | transaction finances | historical transfer finances | historical transaction finances | historical fix transfer finances | historical fix transaction finances | historical default category finances | historical custom category finances | historical cost account finances | fix transfer finances | fix transaction finances | default category finances | custom category authtoken | Token authtoken | historical Token Is there any way … -
Django- Query Multiple models with many to many and one to one relationships
Reposted from an earlier question - but made simpler: 3 Models: Actor(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4) type = models.Charfield(max_length=20) Organisation(models.Model): id = id = models.UUIDField(primary_key=True, default=uuid.uuid4) name = models.Charfield(max_length=20) actor = models.OneToOneField(Actor, on_delete=Models.CASCADE) parent_organisation = models.ForeignKey(Actor, on_delete=models.CASCADE) CustomUser(AbstractBaseUser,PermissionsMixin): id = models.UUIDField(primary_key=True, default=uuid.uuid4) name = models.Charfield(max_length=20) member_of = models.ManyToManyField(Actor, on_delete=models.CASCADE) actor = actor = models.OneToOneField(Actor, on_delete=Models.CASCADE) Note: I have left out fields which are not important. In the Views.py - I wish to find all users within an organisation - Such that given an organisation id, I get the users for the whole organisation. I wish to find all the users with a department - Such that given an organisation id, I get the users for the department (NB: departments are linked on the same organisation model but by the parent -FK) I have tried many different combinations over the last 3 days including: Chaining by : current_organisation = Actor.objects.get_actor(request.session['organisation']).first() This works and I get the Organisation that a user belongs to; The next step: organisation_departments = Actor.objects.filter(parent__actor_id__in =current_organisation) gives me an error of 'Actor' object is not iterable I have looked through the Docs and a similar example here. am I right in suggesting that there should be method using … -
Django static files suddenly disappeared 404 error
I have weird question, but can anyone know what happened? I have made Django app and everything worked fine, and then restarted server and start again Django with command: And then static files do not loaded (CSS, images ...)... I get 404 error. What happened??? Please help... Maybe I have to run it on the other way? I really do not know what happened, because everything worked fine, and then after I started that again everything go wrong.. nohup python manage.py runserver 0.0.0.0:8000 & This is the command that I used to start django (server) again.. -
Django: window.localstorage to store a CSS animation
I'm trying to make a facebook inspired ajax like button with Jquery and Django. The AJAX call is working. The button has a counter, the users' names who have liked the post along with a CSS animation just like facebook's (where on clicking the button, it turns blue and when clicking it again, the button goes back to normal). The problem is on reload, my CSS animation on the button is gone and I'm not able to update the counter and the user's name on the list while on an AJAX call (Althought they work on page reload, not the CSS animation though). For CSS animation I tried to use Javascript's localStorage method but it just toggles the CSS animation and doesn't store it locally. A little help would be appreciated. Here's my code: #Like-Button-Form(i is iterating through my post model object): <form id="like_form" method="get"> <!-- {% csrf_token %} --> <div class="like"> <button type="button" name="post_id" id="like{{ i.id }}" data-catid="{{ i.id }}" class="like_ajax_btn" value="{{ i.id }}"> <i class="fad fa-heart"></i> Like </button> {% if i.like %} <div class="show_likes"> {{ i.total_likes }} Like{{ i.total_likes|pluralize }} <div class="username_liked"> {% for p in i.like.all %} <div><a class="username_likes_post" href="{% url 'userprofile' p.id %}">{{ p.username }}</a></div> {% … -
DJANGO - USER'S NOTIFICATION
I'm working on a django project. It manages designers projects. Each project has a worker (who is working on the project) and a responsible (who assigns the project to a worker). The worker can modify some attributes of the project through an Update Form (and one of the project's attributes is 'complete', that is a boolean). When the worker goes to the update form and checks the 'complete' checkbox, I'd like to implement the feature of sending a notification to the projects' responsable to let him know that the project has been finished. So I'd like to sent the notification not every time that the worker modifies the projects, but just when he checks the 'complete' checkbox. How should I do that? Each project has an image field for the final result of the project, and I'd like to know if it is possible to attach it to the notification that it is sent when the workers marks that the project has been completed. Also, as well as the notification, I'd like to send the responsible an email always with the image attached. To do that do I need to use celery or there is a simpler way that doesn't … -
how to make an Q%A section in Python without using the django or other additional tools, just need the basic
Using Q&A Forum for posting questions and displaying them how to make an Q%A section in Python without using the django or other additional tools, just need the basic. -
How to create like system without reloading page with django?
Well I have made like system with django but that is not perfect because when i click on like button it does like but refresh the current open page. I want to toggle like button without refreshing the current open page. If you how to do that than please share with me. It will be great help if you tell me how that is possible. this is how i am handling post like toggle button in view. view.py class PostLikeToggle(RedirectView): def get_redirect_url(self, *args, **kwargs): slug=self.kwargs.get('slug') print(slug,'slug') pk=self.kwargs.get('pk') print(pk,'pk') obj =get_object_or_404(Post,pk=pk,slug=slug) print(obj,'post') user=self.request.user if user.is_authenticated: if user in obj.likes.all(): obj.likes.remove(user) else: obj.likes.add(user) return f'/posts/{pk}/{slug} ' -
ImportError: cannot import name 'Profile' from 'profiles.models'
This is kind of strange import error as I am 95% sure I didn't make any spelling mistake. I made two app one named products and other is profiles. I imported Profile class from profiles.models inside products model and made foreignkey. No problem in here. everything was running smoothly until I imported Product class from products.models inside profiles.models. I got this error File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/home/sddhruvo/Desktop/django/ECOM_ONE/Ecommerce/profiles/models.py", line 12, in <module> from products.models import Product File "/home/sddhruvo/Desktop/django/ECOM_ONE/Ecommerce/products/models.py", line 8, in <module> from profiles.models import Profile ImportError: cannot import name 'Profile' from 'profiles.models' (/home/sddhruvo/Desktop/django/ECOM_ONE/Ecommerce/profiles/models.py) It saying ImportError: cannot import name 'Profile' from 'profiles.models' here is my profiles.models import uuid from django.conf import settings from django.contrib.auth.models import AbstractUser from django.db import models from django.urls import reverse from django.utils.translation import gettext_lazy as _ from django.template.defaultfilters import slugify from django.db.models.signals import post_save from django.dispatch import receiver #from products.models import Product class CustomUser(AbstractUser): """Default user for stalker_project.""" #: First and last name do not cover name … -
Django save metadata -[Errno 2] No such file or directory:
I got a question. I got an issue with the path: [Errno 2] No such file or directory: I've tried with: url = self.image.url image_meta = image.open(url) then in adding the the first part of URL "https://...." + self.image.url I still got the same issue do you have any idea class Picture(models.Model): catego = models.ForeignKey(Catego,on_delete=models.CASCADE,related_name="catego_pictures") user = models.ForeignKey(User, blank=True, null=True,on_delete=models.CASCADE,related_name='user_pictures') image = models.ImageField(upload_to='nutriscore/') latitude = models.DecimalField(max_digits=9, decimal_places=6, blank=True, default='0') longitude = models.DecimalField(max_digits=9, decimal_places=6, blank=True, default='0') date = models.CharField(max_length=100, blank=True) software = models.CharField(max_length=100, blank=True) artist = models.CharField(max_length=100, blank=True) metadata = models.TextField(max_length=1000, blank=True) pictureoption = models.CharField(max_length=20,choices=Pictureoption.choices,default=Pictureoption.HOME,) publishing_date = models.DateField(auto_now_add=True) def save(self, *args, **kwargs): super().save(*args, **kwargs) url = self.image.url full_path = os.listdir(url) image_meta = image.open(full_path) exif = {} for tag, value in image_meta.get_exif().items(): if tag in TAGS: exif[TAGS[tag]] = value if 'DateTime' in exif: self.date = DateTime if 'Software' in exif: self.software = Software if 'Artist' in exif: self.artist = Artist ... self.metadata = exif super().save(*args, **kwargs) def __str__(self): return self.catego.name -
django not uploading files to aws s3 when using javascript
i have a view where the user can upload multiple images and view them before saving using javascript and im using aws s3 to store my static files the view use to work fine when it was only pure python i only had this problem after adding some js functionality to the template this is my model.py: class Image(models.Model): lesson = models.ForeignKey(Lesson, default=None, on_delete=models.CASCADE) title = models.CharField(max_length=200) image = models.FileField(validators=[validate_image_extension]) views = models.IntegerField(null=True,blank=True,default=0) def __str__(self): return self.title this is my add image view.py def add_lesson_image(request,lesson_id): if request.method == 'POST': lesson = Lesson.objects.get(id=lesson_id) title = request.POST.get('title') images = request.FILES.getlist("file[]") allowed = ['.jpg','.png','jpeg'] #list of the allowed images formats valid = [] for img in images: if Path(str(img)).suffix in allowed: #filtering the images by valid formats valid.append(img) else: messages.warning(request, f"l'extension de fichier '{img}' et n'est pas autorisée") for img in valid: #saving images one by one fs = FileSystemStorage() file_path=fs.save(img.name,img) image=Image(lesson=lesson,title=title,image=file_path) image.save() if len(valid) > 0: #checking if the user input has valid images messages.success(request, "Les images a été enregistrées.") else: messages.warning(request, "aucune image ajoutée") return redirect('edit_lesson',lesson_id) return render (request,'lesson/add_lesson_image.html') this the js added to the template to send multiple images in the request and to view, and preview the images and … -
Annotate sum of vote scores to an item in Django
I have a situation, need to count sum of vote scores and annotate that to an item queryset. model: class Vote(models.Model): item = models.ForeignKey( Item, on_delete=models.CASCADE, related_name="votes") user = models.ForeignKey( User, on_delete=models.CASCADE, related_name="votes") score = models.IntegerField() I tried different variations of this but keep failing: all_votes = Vote.objects.filter(item=OuterRef('pk')) Item.objects.annotate(total_score=Sum(Subquery(all_votes.values("score")))) I get this back all the time: ProgrammingError: more than one row returned by a subquery used as an expression -
Django/Gunicorn/Nginx: wrong JS files seems to be served
My project works locally I have deployed my project with Django/Gunicorn/Supervisor in a remote server I have a select button (id = id_patient) with list of options. When user select an option, informations related to this option are displayed using ajax request. But in remote server, informations are not displayed. When I look with my web browser debug tool (see image), it looks like it is not the good js files that is served But in my static folder on server, it is the good js files... // affichage des informations sur le patient sélectionné pour la ré-allocation $("#id_patient").on("click", function (event) { var csrftoken = getCookie('csrftoken'); if ($(this).val() != "") { $.ajax({ type: "POST", url: $("#form_reallocation").data("patient-url"), data: { csrfmiddlewaretoken: csrftoken, 'patient': $(this).val(), }, dataType: 'html', success: function (data) { $("#information_patient").html(data); } }); } else { $("#information_patient").children().remove(); } }); enter image description here to collect the new static files, I have run python manage.py collectstatic and files are collected but I have a warning message that indicate possible duplicate in static files : Found another file with the destination path 'randomization/js/script.js'. It will be ignored since only the first encountered file is collected. If this is not what you want, make … -
DRF POST giving NOT NULL constraint failed
In a simple API with Python 3.9, Django 3.1.2 and DRF 3.12.1, got the following models class Movie(models.Model): movieNumber=models.CharField(max_length=10) movieCategory=models.CharField(max_length=20) class MovieWatcher(models.Model): firstName = models.CharField(max_length=20) lastName = models.CharField(max_length=20) middleName = models.CharField(max_length=20) email = models.CharField(max_length=20) phone = models.CharField(max_length=10) class Reservation(models.Model): # This model has the relation with the other two. movie = models.ForeignKey(Movie,on_delete=models.CASCADE) # CASCADE means that when a Movie is deleted, this reservation must also be deleted. movieWatcher = models.OneToOneField(MovieWatcher,on_delete=models.CASCADE) and the following FBV @api_view(['POST']) def save_reservation(request): movie=Movie.objects.get(id=request.data['movieId']) movie_watcher=MovieWatcher() movie_watcher.firstName=request.data['firstName'] movie_watcher.lastName=request.data['lastName'] movie_watcher.middleName=request.data['middleName'] movie_watcher.email=request.data['email'] movie_watcher.phone=request.data['phone'] movie_watcher.save() reservation=Reservation() reservation.movie = movie reservation.movie_watcher = movie_watcher reservation.save() return Response(status=status.HTTP_201_CREATED) To test that endpoint, I created a POST request to http://localhost:8000/saveReservation/ After, clicked in Body. Inside Body, x-www-form-urlencoded. Here I used as keys: movieId, firstName, lastName, middleName, email and phone. As value for the movieId I add an existing movieId created previously and the user does not exist. All things considered, I was hoping to get the Status 201 Created. Yet, I get a Status 500 Internal Server Error and the following error IntegrityError at /saveReservation/ NOT NULL constraint failed: movieApp_reservation.movieWatcher_id in the terminal it's possible to see this Internal Server Error: /saveReservation/ Traceback (most recent call last): File "C:\Users\tiago\Desktop\beyond\venv\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return … -
Django + Mongodb : Subsetting data in the backend/frontend(template)
My django app pulls raw facebook data from a mongodb database (via djongo/pymongo) and run its through a series of internal data pipelines. At my dashboard.html page, I'm displaying some metrics(posts count, likes count etc..) for the past 7days. Everything works fine up to this point. Now I would like to let the user select from a dropdown menu list whether "past 7 days" or "past 14 days" should be displayed. Obs: It seems that I can't simply use QuerySet because the data being displayed needs to be processed in different pipelienes in the backend before rendering. Obs2: As of now I have some duplicated code in my view in order to get "7 days data" and "14 days data". I would like to simplify that. Obs3: Perhaps Ajax could be a way to go (avoid caching delay/page refresh) but I can't figure out a way to implement that. Thank you in advance!! my views.py: @login_required def dashboard(request): # Mongodb connection this_db = DatabaseFb( 'xxxxMyMongodbConnectionxxx', 'mydbname') collection_posts = this_db.collections('fb_posts') collection_comments = this_db.collections('fb_comments') # ####### Past 7 days FB data ################# this_puller_7d = DataPullerFB(collection_posts, collection_comments, past7days) posts_7d = this_puller_7d.posts_data_puller() comments_7d = this_puller_7d.comments_data_puller() this_dataprep_posts = DataPrepPosts(posts_7d) df_posts_7d = this_dataprep_posts.to_timeseries() this_dataprep_comments = DataPrepComments(comments_7d) … -
Azure App Services: Stopping site MYSITE because it failed during startup
I had my Django web app running on the Azure App Services using a single docker container instances. However, I plan to add one more container to run the celery service. Before going to try the compose with celery and Django web app, I first tried using their docker-compose option to run the Django web app before including the compose with celery service. Following is my docker-compose configuration for Azure App Service version: '3.3' services: web: image: azureecr.azurecr.io/image_name:15102020155932 command: gunicorn DjangoProj.wsgi:application --workers=4 --bind 0.0.0.0:8000 --log-level=DEBUG ports: - 8000:8000 However, the only thing that I see in my App Service logs is: 2020-10-16T07:02:31.653Z INFO - Stopping site MYSITE because it failed during startup. 2020-10-16T13:26:20.047Z INFO - Stopping site MYSITE because it failed during startup. 2020-10-16T14:51:07.482Z INFO - Stopping site MYSITE because it failed during startup. 2020-10-16T16:40:49.109Z INFO - Stopping site MYSITE because it failed during startup. 2020-10-16T16:43:05.980Z INFO - Stopping site MYSITE because it failed during startup. I tried the combination of celery and Django app using docker-compose and it seems to be working as expected. Following is the docker-compose file that I am using to run it on local: version: '3' services: web: image: azureecr.azurecr.io/image_name:15102020155932 build: . command: gunicorn DjangoProj.wsgi:application … -
Python Django project - What to include in code repository?
I'd like to know whether I should add below files to the code repository: manage.py requirements.txt Also created the very core of the application that includes settings.py. Should that be added to the repo? And the last one. After creating a project, a whole .idea/ folder was created. It was not included in the .gitignore file template, so how about that? -
Run QuerySet Django without for
I have a query in Django, and I want to apply a match in each register. whatever = Whatever.objects.all() for w in whatever: contador+=getMycoincidenceswhatever(w) getMycoincidenceswhatever is a function where I search some coincidences with other table. def getMycoincidenceswhatever(w) coincidences=Notificationwhatever.objects.filter (Q(field_whatever__in=w.field)).count() return coincidences Is there some way to do it without use bucle for? The problem is that this query is is slowing down my server, because this bucle.