Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to implement Google, Facebook and Email login functionality in Django using firebase?
I am developing a mobile app that allows the user to login via Google, Facebook, and email. I am trying to implement it using firebase and firebase admin SDK. What is the proper way to implement this? I need to know more about the implementation login and need clarity about the following questions. How to create the user. Create the user directly from the app by using functions like signInWithCredential() and createUserWithEmailAndPassword() or user create the user with create_user() in the server using Django and firebase-admin SDK. Do we need to keep the uid in any tables in the Django database? Do we need to create the default User model provided by Django for authentication. -
How to save the social token with Django allauth?
I managed to login with Discord, everything works fine, but to do api calls for retrieving more informations (in my case the connections, also edited the scopes for it), I need the oauth2 social token. In the database there is a table called socialaccount_socialtoken, so i think allauth is able to ask for it automatically. The documentation doesn't write anything about it. Do I have to make a custom callback view which retrieves the social token and saves it to the database? -
Ecommerce books for Django junior developer
I like to follow written tutorials and learning by doing alongside with reading online documentation to get the context. I am now passionate "junior Django web developer" and i would like to build some dropshipping eshop in Django bcs it is platform that i trust and like to learn. Nevertheles i would like to know your recommendation for the books in terms of SEO, eshop UI and maybe even Django itself eventhough after bunch of online videos and books i fell in love of series of William Vincets books: "Django for Beginners" and "Django for Professionals". For SEO i heard good review for "The Art of SEO" so maybe that could be good pick. Also thinking about the dropshiping. Since i dont own any product and i want to learn how to build eshop and test it by market, i dont even know what dropshiping products could be good or not. Or what commision in % should be for me. Is there any good practical book about dropshipping too? In short i need books for like: Comprehensive guide for eshop SEO Modern UI designbook for variety of eshops Comprehensive guide for dropshipping Any recommendation please? Thank you -
django admin overriding delete_model not working with bulk delete
I want to disable deleting for a specific model instance I overrided delete_model in the ModelAdmin as follows : def delete_model(self, request, client): if client.schema_name == 'public': messages.set_level(request, messages.ERROR) messages.error(request, 'Suppression interdite pour la racine') else: super().delete_model(request, client) It works when I click the delete button on change view But not with bulk delete as the instance is deleted without preventing How can I fix this ? I also realized that delete_model is not called with bulk delete which makes a bit weird. -
Get foreign serialized ReadOnlyField on Django Rest Framework
Currently I have a model like so: class BotSerializer(serializers.ModelSerializer): class Meta: model = Bot fields = ['id', 'bot_name', 'comment', 'bot_activities'] depth = 1 class BotActivitySerializer(serializers.ModelSerializer): bot_name = serializers.ReadOnlyField(source='bot.bot_name', read_only=True) started_date_activity = serializers.DateTimeField(source='started_at', format="%m/%d/%Y %H:%M:%S", required=False, read_only=True) finished_date_activity = serializers.DateTimeField(source='finished_at', format="%m/%d/%Y %H:%M:%S", required=False, read_only=True) class Meta: model = BotActivity fields = ['started_at', 'started_date_activity', 'finished_at', 'finished_date_activity', 'bot', 'bot_name', 'bot_activity_status'] When I call the Bot seriliazer I get: { "id": 1, "bot_name": "HTTP header checker", "comment": "testtest", "bot_activities": [ { "id": 1, "started_at": "2020-11-04T15:47:26.168212Z", "finished_at": null, "bot_activity_status": "In Progress", "bot": 1 } ] } But I need to also get the started_date_activity and finished_date_activity fields. What to do to get their value too? -
DocuSign Integration. Is it possible to get auth token without users consent. I want to send docusign envolope email internally using my credentials
I have an application that sends DocuSign emails to users when clicking on a button from the frontend. So If I go by Auth code grand or implicit grant, my user has to sign in to their account. For JWT they will be redirected to consent.That means all my users need to have docusign account for sending. Is there any way to send mail from the system? -
Django constance and dajngo modeltranslations
I used Django Constance on my Django site how can I translate these things with Django model translation -
Migrations failed : error no changes detected migration django
when i run 'py manage.py makemigrations' it shows no changes detected even if i have added main as an app in settings.py And when i run 'py manage.py makemigration main' it shows no installed app with label 'main' Can someone please help ? -
Docker Compose up, Does Not Mount Named Volume When Images Are Updated
I have a docker-compose containing a Django and postgres service. I define a volume inside the docker-compose. But, when I issue docker-compose down and docker-compose up, all my data are lost. According to the docker docs: regarding docker-compose down By default, the only things removed are: Containers for services defined in the Compose file Networks defined in the networks section of the Compose file The default network, if one is used Networks and volumes defined as external are never removed. Anonymous volumes are not removed by default. However, as they don’t have a stable name, they will not be automatically mounted by a subsequent up. For data that needs to persist between updates, use host or named volumes. So, I tried using named volumes by creating a volume: docker volume create --name=postgres_db Then, in my docker-compose, I referenced this volume and emphasized external=true. Here's my docker-compose: version: '3' services: db_host: image: postgres networks: - backend-tier environment: POSTGRES_PASSWORD: ${POSTGRES_PASSWORD} volumes: - postgres_db:/var/lib/postgres/data web: image: web_image:latest command: bash -c "python3 manage.py makemigrations && python3 manage.py migrate && python3 manage.py runserver 0.0.0.0:8585" # executes after running container container_name: prack_dock # name for the container volumes: - .:/src/django-docker ports: - "8888:8585" networks: - backend-tier … -
Model Formset and regular ModelForm in same template?
I got two models: Project: class Project(Model): name = CharField(max_length=50) members = ManyToManyField("accounts.User", through='ProjectUser') organization = ForeignKey(Organization, related_name="projects", on_delete=CASCADE) def __str__(self): return self.name and Task: class Task(Model): task = CharField(max_length=100) project = ForeignKey(Project, on_delete=CASCADE) class Meta: db_table = 'task' I got a UpdateView class: class ProjectUpdateView(UpdateView): form_class = ProjectUpdateForm template_name = 'projects/project_edit.html' success_url = reverse_lazy('projects:list') How can I allow a user to add tasks (through an inline formset) on the same page as where they'd edit a Project instance? E.g one consolidated form where the user can edit the Project name, and add / remove Task instances, all in one place -
Is there a way to automated a function on Django?
I have this function on my views.py, I want to automatically run it when I started python manage.py runserver. is it possible? Thanks! def auto_sms(request): responses = Rainfall.objects.filter( level='Torrential' or 'Intense', timestamp__gt=now() - timedelta(days=1), ) if responses.count() >= 5: send_sms(request) return HttpResponse(200) -
how to reflect changes in postgres database to django model?
I created a new field in the database using pgadmin, I did not use django to create the field, how can I reflect the new field I created in pgadmin to django? I tried already to run python manage.py makemigration and migrate. and i receive this error. django.db.utils.ProgrammingError: column "discount_price_formula" of relation "customAdmin_product" already exists -
Displaying models in the Django admin
please help me figure out the following: firstly, we are talking about the task on the side of the standard django admin panel. let's say there are three models: class M1(models.Model): title = ... class M2(models.Model): m1 = ForeignKey(m1) name = ... class M3(models.Model): f1 = ForeignKey(m1) f2 = ManyToManyField(M2) add all 3 models to the admin panel. go from the admin panel to the 3rd model in order to create a record, select f1 (ForeignKey to M1); can this interactive be done in the standard django admin panel ?? -
Query Postgres via GraphQL in Django without models?
Is there a python library to run graphql query on Postgres database and return results. I want to be able to do the following: Client sends a graphql query Authenticate the request using django Pass the graphql query to some library or tool "which fetches required data from postgres and returns it" Return the query results to client Now how to do step 3,4? //After authenticating the user def graphql_handle(graphql_query): //run graphql_query on postgresql tables using some library or something else WITHOUT USING DJANGO MODELS. //return the details fetched in above step Is there any such tool available? After authenticating the user,I should be able to " pass the query to some graphql tool which gets required data from postgres and returns it ". Is there such a tool? -
DRF 'create' method deletes fields from 'validated_data'
I want to realize POST method to create Article object. I have to provide this body: { "title": "Sample title", "link": "https://www.sample.com/" } And get Article object with auto assigned ID, author_name(current user) and creation_date. But i got an problem - "create" methor deletes one field - author_name. (See code below) Finally i get next error msg: IntegrityError at /api/articles/ Error: Null value in column "author_name_id" with NOT NULL DETAIL: Error row contains (32, Sample title, https://www.sample.com/, 2020-11-08, null). How do i solve my problem? models.py class Article(models.Model): title = models.CharField( name='title', max_length=120, null=False, ) link = models.URLField( name='link', unique=True, null=False, ) creation_date = models.DateField( name='creation_date', default=date.today, null=False, ) author_name = models.ForeignKey( User, on_delete=models.CASCADE, related_name='articles', null=False, ) def __str__(self): return self.title views.py class ArticleView(APIView): def post(request): if request.user.is_authenticated: data = {"author_name": request.user} data.update(request.data) print(request.data) serializer = ArticleSerializer(data=data) if serializer.is_valid(raise_exception=True): serializer.save() return Response(status=201) return Response(status=403) request.data >>> {'title': 'Sample title', 'link': 'https://www.sample.com/', 'author_name': <SimpleLazyObject: <User: admin>>} serializers.py class ArticleSerializer(serializers.ModelSerializer): author_name = serializers.StringRelatedField() class Meta: model = Article fields = "__all__" def create(self, validated_data): print(validated_data) return Article.objects.create(**validated_data) validated_data >>> {'title': 'Sample title', 'link': 'https://www.sample.com/'} -
Django added foreign key migrate legacy objects
I have extended a Django model: class PNotification(models.Model): boolean fields with default=False def get_notifications(): noti = PNotification.objects.create() return noti class Product(models.Model): notification_object = models.ForeignKey(PNotification, on_delete=models.CASCADE, default=get_notifications) Product was extended with a ForeignKey to PNotification. Now I thought with the default attribute Django would create for all legacy Product objects in the Databse a new PNotification object. Unfortunately, all legacy Product objects do not have a ForeignKey to PNotification. How can I give each legacy Product object an initial PNotification object via the ForeignKey field? -
Django with Docker stuck on "Watching for file changes with StatReloader"
I'm trying to use Django with Docker. My Dockerfile: FROM alpine # Environment setup ... # Python3 installation RUN apk add --no cache build-base RUN apk add --no cache python3 python3-dev py-pip RUN apk add --no cache git RUN apk add --no cache libxml2-dev libxslt-dev openldap-dev RUN pip3 install --requirement ${_PROJECT_DIR}/requirement.txt --target ${_VENDOR_DIR} ENV PYTHONPATH ${_PROJECT_DIR}:${_VENDOR_DIR} CMD ["python3", "management/manage.py", "runserver", "0.0.0.0:8000"] I ran: sudo docker build -t django_app . sudo docker run -d django_app sudo docker logs -f <container> And it was stuck on: Watching for file changes with StatReloader I also tried to run sudo docker run -d -p 8000:8000 django_app but got the same result. Some points: There are already exist some topics that describe this problem but all of them use docker-compose (which I don't use). I prefer to use alpine (instead of using python alpine or ubuntu alpine) because I'm limited with space. Should I run sudo docker run -d -p 8000:8000 django_app or without the ports? In the Django's settings.py file, I have: ALLOWED_HOSTS ['*']. Also, without Docker, my application works so I guess it has something to do with Docker's environment and not the Django application. How could I resolve this issue? -
How do I filter media by include and excluded tags using the Django ORM
I have the following models... class Media(models.Model): name = models.CharField(max_length=255) tags = models.ManyToManyField('Tag', blank=True) class Tag(models.Model): name = models.CharField(max_length=255) class Filter(models.Model): name = models.CharField(max_length=255) tags_included = models.ManyToManyField('Tag', blank=True, related_name='included_tags') tags_excluded = models.ManyToManyField('Tag', blank=True, related_name='excluded_tags') def get_media(self): return """ return all media that has any tags_included set and remove all media that has tags_excluded set """ And I am looking for a method of getting a media selection based on a filter of tags that must be included and tags that must not be included. So I guess it must use __in, filter and exclude some how but cant seem to get anything to run. Any help with this would be appreciated, Thanks. -
Django: Queryset aggregating ManyToMany values
I have MyUser model with ForeignKey and ManyToMany related fields city and skills: accounts/models.py class MyUser(AbstractBaseUser): email = models.EmailField() city = models.ForeignKey('jobs.City') skills = models.ManyToManyField('jobs.Skill') jobs/models.py class Skill(models.Model): name = models.CharField() class City(models.Model): name = models.CharField() I need to make a queryset that would return data in this format: {'email': 'some@email.com', 'city': 'London', 'skills': ['Python', 'Java']}, {'email': 'another@email.com', 'city': 'Berlin', 'skills': ['JavaScript', 'C#', 'Python']}, ... MyUser.objects.values('email', 'city__name', 'skills__name') returns all data I need but ManytoMany values returned separately duplicating other entries: {'email': 'some@email.com', 'city': 'London', 'skills': 'Python'}, {'email': 'some@email.com', 'city': 'London', 'skills': 'Java'}, {'email': 'another@email.com', 'city': 'Berlin', 'skills': 'JavaScript'}, {'email': 'another@email.com', 'city': 'Berlin', 'skills': 'C#'}, {'email': 'another@email.com', 'city': 'Berlin', 'skills': 'Python'}, ... So how can I make a queryset aggregating ManyToMany values into one set? -
Why I get error after using 'from django.contrib import admin'
this is my first post asking you for help. I know that I am doing something wrong but I would be very keen on you helping me in solving this problem. I am starting first project in Django That is why I've installed the latest version. I've created django directory. I've created virtualenv. I've installed django. ...and I've got a problem with importing modules from django as below my directories -
Populate empty fields with value from different field
I have a problem with making migrations after changing my model. I changed already exisitnig DateField (lectures_begginning) from null=true to null=false. Now I have to populate old entries. Fortunately I have existing DateField (semester_begginning) which was always set to null=false. Usually these two differ by 4-5 days so I can just copy the semester_beggining. class Semester(models.Model): lectures_beginning = models.DateField( null=False, verbose_name='Class start day') semester_beginning = models.DateField( null=False, verbose_name='Semester start day') How can I change migration so it copies value of semester_beginning to lectures_beginning only if latter is NULL? from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('courses', '0034_auto_20201106_2039'), ] operations = [ migrations.AlterField( model_name='semester', name='lectures_beginning', field=models.DateField(verbose_name='Dzień rozpoczęcia zajęć'), ), ] -
Why am getting empty array in fetiching data using axios in react js and in urls?
I Created a view for article model and I have the data in my database but when I go on url then it's showing empty array my below code view.py class ArticleView(RetrieveAPIView, RetrieveUpdateAPIView, RetrieveDestroyAPIView): serializer_class = ArticleSerializer permission_classes = [AllowAny] pagination_class = ArticleSizeLimitPagination def get_queryset(self): return Article.objects.filter().order_by('-updated_on') def get_object(self): try: return Article.objects.get(id=self.request.data['id'], is_deleted=False) except Exception: return None def perform_create(self, serializer): return serializer.save(user=self.request.user) def destroy(self, request, *args, **kwargs): try: instance = self.get_object() instance.is_deleted = True instance.save() return Response(data='delete success') except Http404: return Response(status=status.HTTP_204_NO_CONTENT) urls.py urlpatterns = [ path('', ArticleView.as_view()), path('<uuid:pk>/', ArticleView.as_view()), ] When I run the url then HTTP 200 OK Allow: GET, PUT, PATCH, DELETE, HEAD, OPTIONS Content-Type: application/json Vary: Accept { "sub_title": "", "upvote": null, "title": "" } Where did I do wrong? Is there issue in def function for RetrieveAPIView? -
only one button calling ajax in django
So I have a Product Model which I simply use to render the products data into the homepage. I also have ajax code which is called when one of the add to cart buttonat the bottom of each product is pressed it sends the id of the product to a view to add the product to the cart database and it works fine but the problem is it works fine with the first product only. only the first product calls ajax all of the other 7 buttons do not call it. I think it is probably a frontend problem maybe since the front end except for the ajax code isn't mine. Models.py : class ProductModel(models.Model): STATUS_CHOICES = ( ('In stock', 'In stock'), ('Out of stock', 'Out of stock'), ) image = models.ImageField(null=True) lens_image = models.ImageField(null=True) name = models.CharField(max_length=200) small_description = models.CharField(max_length=200, null=True) description = models.TextField() price = models.DecimalField(max_digits=6, decimal_places=2, null=True) status = models.CharField(max_length=12, choices=STATUS_CHOICES, default='In stock') date_created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.name class CartModel(models.Model): customer = models.ForeignKey(User, on_delete= models.CASCADE, related_name="cart") products = models.ManyToManyField(ProductModel) views.py : def home(request): products = ProductModel.objects.all() ctx = {'products': products} return render(request, 'homepage/index.html', ctx) def cart_add(request): try : if request.is_ajax() and request.method == 'POST': print("IT … -
Django inline formset - sort it based on a related model or display forms conditionally?
I have a model Tour which has a foreign key to a model Driver, and another foreign key to a model Timetable. The inline formset in django is created based on Driver and Tour form. I'd like to filter the formset according to the fields in Timetable form (order after group day and time) - the foreign key to this form is supposed to be static and never change, therefore it's not shown in the form. I cannot access the data in Timetable form through a form - is that possible? MODELS class Timetable(models.Model): route = models.AutoField(primary_key=True) group = models.CharField(max_length=1, default='') day = models.DateField(auto_now=False, auto_now_add=False) time = models.TimeField(auto_now=False, auto_now_add=False) class Tour(models.Model): #FK driver = models.ForeignKey(User, default=None, on_delete=models.CASCADE) route = models.ForeignKey(Timetable, default=None, on_delete=models.CASCADE departed = models.DateTimeField(auto_now_add=False) arrived = models.DateTimeField(auto_now_add=False) VIEWS @login_required(login_url="/accounts/login/") def display_all(request): driver = User.objects.get(username = request.user) TourFormSet = inlineformset_factory(User, Tour, fields=('departed', 'arrived'), can_delete =False, extra = 0) if request.method == 'POST': formset = TourFormSet(request.POST, request.FILES, instance=driver) if formset.is_valid(): formset.save() return redirect('app:final') else: formset = TourFormSet(instance=driver) return render(request, 'app/displayall.html', { 'formset':formset }) Alternatively, I tried to display a sorted Timetable table in a template and conditionally show correct forms from the formset. It displays correctly right after, but the formset … -
Django Rest - Create and Action method returns error 403 forbidden
Apologize if this is a newbie question or for using inaccurate terminology. coz I am a newbie. I built a simple Django/React app that allows users to post short texts that can be liked and unliked. In the console I get, POST http://localhost:8000/api/posts/create/ 403 (Forbidden) and POST http://localhost:8000/api/posts/create/ 403 (Forbidden). The REST Framework Renderer gives me, GET /api/posts/create/ HTTP 405 Method Not Allowed Allow: POST, OPTIONS Content-Type: application/json Vary: Accept { "detail": "Method "GET" not allowed." } and, GET /api/posts/action/ HTTP 405 Method Not Allowed Allow: OPTIONS, POST Content-Type: application/json Vary: Accept { "detail": "Method "GET" not allowed." } The console gives me, xhr.send(jsonData) in the components as error. At first I thought it was a simple authentication error but I tried signing in to admin on different browsers to no success. What am I missing here? Any assistance is greatly appreciated. webapp/webapp-web/src/lookup/components.js function getCookie(name) { var cookieValue = null; if (document.cookie && document.cookie !== '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = cookies[i].trim(); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + …