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. I have read that social login can be implemented in Django with packages like all-auth. Which is best to implement this? Firebase Admin SDK or all-auth(any other packages, if any). -
Django .Reverse for 'doctor' with no arguments not found. 1 pattern (s) tried: ['doctor / (? P <pk> [^ /] +) / $']
Framework Django. I am trying to create a link to the profile of each user (doctor) by creating an automatic url by his id. an error appears: Reverse for 'doctor' with no arguments not found. 1 pattern (s) tried: ['doctor / (? P [^ /] +) / $'] I suppose I need to add a second parameter to the template link, but I can't figure out that "{% url 'doctor' ??%}" html ..."{% url 'doctor' %}"... view.py def doctor(request, pk): doctors = Doctor.objects.get(pk) return render(request, 'main/doctor.html', {'doctors': doctors}) urls path('doctor/<str:pk>/', views.doctor, name='doctor'), -
How to use django_seed to make manytomany field data
I'd like to make dummy db to check my backend. I used django_seed and faker to fill every single db column. but there is no way to fill manytomany field. How can I use django_seed to make manytomany field coulmn? -
Django Models - Establish a third relationship, between two models where one model reliant on foreign key of other?
John's Shop - Audiences: Audience A, Audience B, Audience C Nicole's Shop - Audiences: Audience D, Audience E for StoreDefaultAudience John's Shop should only be able to choose Audience A, Audience B, Audience C as a default audience for StoreDefaultAudience Nicole's Shop should only be able to choose Audience D, Audience E as a default audience only one StoreDefaultAudience should be allowed per Store stores.models.py class Store(models.Model): store_name = models.CharField(max_length=50) audiences.models.py class Audience(models.Model): audience_name = models.CharField(max_length=50) store = models.ForeignKey(Store, on_delete=models.CASCADE) third relationship that I want to create # only one StoreDefaultAudience should be allowed per Store # the default audiences should only be one of that store's audiences class StoreDefaultAudience(models.Model) default_audience = ? store = ? -
Django form DateTimeField
i created a form for input date and time for user, but this form got a strict format, such dont comfortable for input (000-00-00 00:00:00). Each symbol must writing user self.How i can change this form, so when inputing numbers , this symbols - - - : : : avtomaticaly appeared themselves class Appointment(models.Model): time_appointment = models.DateTimeField() patient = models.ForeignKey( Patient, related_name='patient_to_appointment', null=True, on_delete=models.SET_NULL) doctor = models.ForeignKey( Doctor, related_name='doctor_appointment', null=True, on_delete=models.SET_NULL) complaint = models.CharField(max_length=50, null=True, blank=True)`enter code here` html <form action="" method="POST"> {% csrf_token %} {{form}} <input type="submit" name="submit" /> </form> views.py def create_appointment(request): form = AppointmentForm(request.POST) if form.is_valid(): form.save() return redirect('/') return render(request, 'main/f_appointment.html', {'form': form}) -
Django how to reverse many to many objects sortedm2m
I am using sortedm2m library to keep many to many objects ordered. But how can I get a reversed list of objects, for example, something like gallery.photos.all().order_by("-m2m_table.id")? -
Django: how to show related model fields in template
I'm new in Django 3.0 and I'm lost in this easy question, please help me. I have 2 models: class Product(models.Model): fields... class ProductType(models.Model): product = models.ForeignKey(Product, related_name='product_types', on_delete=models.CASCADE) color = models.Charfield(...) In my template, I would like to show all the related product types and their fields to a specific product: ... {% for product in products %} {{ product.??? }} {% endfor %} Here is my view: class ProductsView(ListView): collection = None model = Product paginate_by = 6 template_name = 'shop/product/list.html' context_object_name = 'products' def get_queryset(self): products = Product.objects.filter(available=True) collection_name = self.kwargs['collection_name'] if 'collection_name' in self.kwargs else None if collection_name: collection = get_object_or_404(Collection, name=collection_name) products = products.filter(collection=collection) return products def get_context_data(self): context = super().get_context_data(**self.kwargs) context['notification'] = Notification.objects.all() if 'collection_name' in self.kwargs: context['collection'] = get_object_or_404(Collection, name=self.kwargs['collection_name']) context['collection_name'] = self.kwargs['collection_name'] context['collections'] = Collection.objects.all() return context Thank you -
Django. How to correctly save time & timezones
I have this code that behaves in a rather strange way and opens the question, how should I deal with timezones? So, first I have a datetime object I build from the info a user posts: time_zone = request.POST.get("time_zone") date_start = request.POST.get("date_start") time_day = request.POST.get("time_day") time_zone_obj = pytz.timezone("Etc/" + time_zone) # GMT + 2 in this example date_start = datetime.strptime(date_start, "%d/%m/%Y") date_start = date_start.replace(tzinfo=time_zone_obj) time_day = datetime.strptime(time_day, "%I:%M %p") date_start = date_start.replace(hour=time_day.hour, minute=time_day.minute) ... event.date_start = date_start event.save() print("event.date_start.hour:%s" % event.date_start.hour) return redirect("event_detail", event_id=event.id) This prints event.date_start.hour:6. Then, inmediatlty after saving the object and printing the hour, it redirects to the event_detail view, very simple: def event_detail(request, event_id): event = get_object_or_404(Event, id=event_id) print("event.date_start.hour:%s" % event.date_start.hour) ... And it prints event.date_start.hour:8. I don't understand why. Plz note that I printed the hour after I saved the object and then after I retrieved it in the other view. It has a difference of two hours that must have something to do with the timezone the user selected (GMT + 2). Why is this? Which is the best way to save this data? The user submits "6:00 AM" + "GMT+2" in the form and then later when I want to show the time … -
django-rest-framework get the timestamp since the object created through serialization
I need to get the time since a post object was created. While surfing the internet I have found the following implementation and it gives me the following error Adding @property to models post object class Post(models.Model): timestamp = models.DateTimeField(auto_now=False, auto_now_add=True) @property def timesince(self): return timesince.timesince(self.timestamp) I do not know how the django.utils timesince works, if you know - give me a hint class PostSerializer(serializers.ModelSerializer): timesince = serializers.DateTimeField() class Meta: model = Post fields('__all__') I get the following AttributeError Got AttributeError when attempting to get a value for field `timesince` on serializer `PostSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `Post` instance. Original exception text was: 'NoneType' object has no attribute 'year'. -
Importing and creating pages in Django / Wagtail
Although Wagtail and Django seem to be very efficient and sophisticated frameworks, they do not offer any simple way of importing (i.e bulk creating) pages. I have tried dozens of suggestions to do so (eg 1, eg 2, eg 3, eg 4, etc). I've also tried CodeRedCMS (which is based on Wagtail), but it offers a very rudimentary function which have so far not helped me. Gazmans solution in this post seemed very efficient but I could not figure out exactly how to go about solving the issue. So my question is simple: If I have a csv/json file with thousands of rows, where each row represents a post for a specific Page Model I've created in Wagtail, how do I import it to Wagtail? Any example with psuedo code would be immensely appreciated. The only solution that I did (almost) succeed with was by using DataGrip and directly import data into the table, but then Wagtail did not register the entries for some reason. -
Django foreign key not getting data
I have two tables defined in my models: class Products(models.Model): productsid = models.AutoField(primary_key=True) product_number = models.CharField(db_index=True, max_length=15) title = models.CharField(max_length=255, default=None, null=True, blank=True) date = models.DateField(db_index=True, default=datetime.date.today, null=True, blank=True) class ProductFlag(models.Model): product_number = models.CharField(db_index=True, max_length=15) company = models.ForeignKey(Company, db_index=True, on_delete=models.SET_NULL, null=True) productid = models.ForeignKey(Products, db_column='productsid', db_index=True, on_delete=models.SET_NULL, null=True) I want to get the the 'title' from Products when I query ProductFlag. In my views, I make this query: productflags = ProductFlag.objects.filter(company__companyid=self.kwargs.get('company_id')).order_by('product_number') I thought that I could then reference the title field in my template by looping through {% for product in productflags %} and grabbing {{ product_number.productid.title }}, but I get nothing at all. Looking at it in the Django shell, it seems that my productid is always "None" (and my database definitely had data in productsid). I have no issue with the company foreign key. What am I doing wrong? Thanks-- Al -
Trouble deploying django app to AWS lambda using zappa
I am trying to deploy my django app to AWS Lambda. I have viewed many tutorials on how to do so. However, whenever I run zappa deploy, I get the following error at the end: Deploying API Gateway.. Error: Warning! Status check on the deployed lambda failed. A GET request to '/' yielded a 502 response code. Running zappa tail gives me the following: [1604786373569] [DEBUG] 2020-11-07T21:59:33.569Z 1a7e8cd4-1bf2-4af4-b11b-2baa6c6691dc Read environment variables from: /var/task/my_cool_project/.env [1604786373570] [DEBUG] 2020-11-07T21:59:33.569Z 1a7e8cd4-1bf2-4af4-b11b-2baa6c6691dc get 'SECRET_KEY' casted as 'None' with default '<NoValue>' [1604786373582] [DEBUG] 2020-11-07T21:59:33.582Z 1a7e8cd4-1bf2-4af4-b11b-2baa6c6691dc get 'DB_ENGINE' casted as 'None' with default '<NoValue>' [1604786373582] [DEBUG] 2020-11-07T21:59:33.582Z 1a7e8cd4-1bf2-4af4-b11b-2baa6c6691dc get 'DB_NAME' casted as 'None' with default '<NoValue>' [1604786373582] [DEBUG] 2020-11-07T21:59:33.582Z 1a7e8cd4-1bf2-4af4-b11b-2baa6c6691dc get 'DB_USER' casted as 'None' with default '<NoValue>' [1604786373582] [DEBUG] 2020-11-07T21:59:33.582Z 1a7e8cd4-1bf2-4af4-b11b-2baa6c6691dc get 'DB_PASSWORD' casted as 'None' with default '<NoValue>' [1604786373582] [DEBUG] 2020-11-07T21:59:33.582Z 1a7e8cd4-1bf2-4af4-b11b-2baa6c6691dc get 'DB_HOST' casted as 'None' with default '<NoValue>' [1604786373582] [DEBUG] 2020-11-07T21:59:33.582Z 1a7e8cd4-1bf2-4af4-b11b-2baa6c6691dc get 'DB_PORT' casted as 'None' with default '<NoValue>' [1604786374005] [ERROR] NameError: name '_mysql' is not defined Traceback (most recent call last): File "/var/task/handler.py", line 609, in lambda_handler return LambdaHandler.lambda_handler(event, context) File "/var/task/handler.py", line 240, in lambda_handler handler = cls() File "/var/task/handler.py", line 146, in __init__ wsgi_app_function = get_django_wsgi(self.settings.DJANGO_SETTINGS) File "/var/task/zappa/ext/django_zappa.py", line … -
I have an error Dockerfile with Django . How to solve it?
Docker file doesn't work ! Dockerfile # Pull base image FROM python 3.8 # Set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # Set work directory WORKDIR /Django/bookstore/ #Install dependencies COPY Pipfile Pipfile.lock /Django/ RUN pip install pipenv && pipenv install --system #COPY project COPY . /Django/bookstore/ Docker-compose.yml version: '3.8' services: web: build: . command: python /Django/manage.py runserver 0.0.0.0:8000 volumes: - .:/Django ports: - 8000:8000 depends_on: - db db: image: postgres:11 volumes: - postgres_data:/var/lib/postgresql/data/ volumes: postgres_data: About Django My directory called /Django/bookstore/ Python version 3.8.5 When I am coding Docker on cmd I see an error docker-compose up -d --build Building web ERROR: Dockerfile parse error line 2: FROM requires either one or three arguments -
How to set a list of default serializer instances?
I have some serializers class FruitSerializer(serializers.Serializer): id = serialiser.IntegerField() name = serializers.CharField() class BucketSerialiser(serializers.Serializer): id = serialiser.IntegerField(required=False, default = 1) fruits = FruitSerializer(required=False, many=True) And i want to set default values in the BucketSerialiser.fruits if initially they were not set. For example bucket = BucketSerialiser(data={'id': 1}) ... buket.data -> // it should return the default fruits data. e.g {'id': 1, 'fruits': [{'id': 1, 'name': 'Apple'}, {'id': 2, 'name':'Orange'}]. I tried to do it like this class BucketSerialiser(serializers.Serializer): id = serialiser.IntegerField(required=False, default = 1) fruits = FruitSerializer(required=False, many=True, default = [ FruitSerializer(data={'id': 1, 'name': 'Apple'}), FruitSerializer(data={'id': 2, 'name': 'Orange'})] But it doesn't work. How to implement it correctly? -
assigning additional variables to form in Django
I have a simple application draft where I would like to have three functionalities : priority list for every production line with 3 part number assigned to it ( and number of pieces for each ) order where I can select production line when submitting new order via form I would like to check the priority list and assign the appropriate part number based on the quantity left in stock to the order form. Also I would like to subtract value of 1 from the number of pieces Now, I have the first two and I assume they are not perfect (maybe you can suggest some tweaks). But how can I add the third functionality ? views.py def priority(request): priority_form = PriorityForm() if request.method == 'POST': priority_form = PriorityForm(data=request.POST) if priority_form.is_valid(): priority_form.save() return redirect('priority') else: priority_form = PriorityForm() return render(request, 'dashboard/priority.html', {"form": priority_form}) def order(request): storage = PartNumber.objects.all() username = request.user.username if request.method == 'POST': order_form = OrderForm(username=username, data=request.POST) if order_form.is_valid(): order_form.save() return redirect('order') elif request.method == 'GET': order_form = OrderForm(username=username) return render(request, 'dashboard/order.html', {"form": order_form, "username": username}) forms.py class OrderForm(forms.ModelForm): class Meta: model = Order fields = ('end_user_id', 'production_line_id') def __init__(self, *args, **kwargs): username = kwargs.pop('username', None) super(OrderForm, self).__init__(*args, … -
Django approval model form: how to show both new and old values in admin panel?
I've a model and I want to let users suggest changes on its objects. My approach was to create a separate model and let the admin approve the changes. class SuggestedQuoteChanges(AbstractQuote): original_quote = models.ForeignKey(Quote, on_delete=models.CASCADE) user_email = models.EmailField() justification = models.TextField() def get_changes_fields(self): changes = tuple() # a bit of code... if original_value != new_value: changes += (field.name,) return changes In admin.py I want to show both values, but, at the moment, I only managed to show show the suggested values: class SuggestedQuoteChangesAdmin(admin.ModelAdmin): fieldsets = ( ( "Changes", { "classes": ("collapse",), "fields": (), }, ), (None, {"fields": ("justification", "user_email")}), ) readonly_fields = ("user_email", "justification") def get_fieldsets(self, request, obj=None): fieldsets = super().get_fieldsets(request, obj) fieldsets[0][1]["fields"] = obj.get_changes_fields() return fieldsets I've tried to use __getattr__ in the model to get something like obj.original_quote_field but was unsuccessful. First of all, creating a separate model is the best approach? If yes, how to show both original and suggested values in the admin panel? If no, what approach would you suggest? -
Type 'manage.py help <subcommand>' for help on a specific subcommand
On running python file python3 manage.py in ubuntu terminal i am getting this error. Type 'manage.py help <subcommand>' for help on a specific subcommand. Available subcommands: [auth] changepassword createsuperuser [contenttypes] remove_stale_contenttypes [django] check compilemessages createcachetable dbshell diffsettings dumpdata flush inspectdb loaddata makemessages makemigrations migrate sendtestemail shell showmigrations sqlflush sqlmigrate sqlsequencereset squashmigrations startapp startproject test testserver [sessions] clearsessions [staticfiles] collectstatic findstatic runserver This project contains the files of python, django, selenium and matplotlib. Project is based on COVID-19 data visualization. Please help me in solving it. -
While updating records in django check whether the newly entered data is already matching with the other records in database?
forms.py class RoleForm(forms.ModelForm): class Meta: model = Group fields = ['name'] def clean_name(self): name = self.cleaned_data['name'] if Group.objects.filter(name__iexact=name).exists(): raise forms.ValidationError("Role name already exists") return name views.py def updateroles(request, id): roles = Group.objects.all() instance = get_object_or_404(Group, pk=id) if request.method == "POST": fm = RoleForm(request.POST, instance = instance) if fm.is_valid(): fm.save() messages.success(request, 'Updated Successfully') return redirect('roles') else: fm = RoleForm(instance=instance) return render(request, 'crm/roles.html', {'form': fm, 'roles': roles}) While adding new records I want to check whether the records already exists in database.If it exist I need to raise a ValidationError which is working fine.But while updating records check whether the newly entered data is not matching with any other records,if it matches I need to raise a ValidationError like newly entered data matches with some other record.My current code is raising a validationerror even if I click on update without changing the existing data.Any help would be appreciated. -
python: can't open file '.manage.py': [Errno 2] No such file or directory
Im learning django and i get this error: python: can't open file '.manage.py': [Errno 2] No such file or directory when running python .\manage.py makemigrations I know im running the command in the same folder as my manage.py file, so what can be the issue? This is my directory tree: . ├── api │ ├── admin.py │ ├── apps.py │ ├── __init__.py │ ├── migrations │ │ └── __init__.py │ ├── models.py │ ├── tests.py │ ├── urls.py │ └── views.py ├── manage.py └── music_controller ├── asgi.py ├── __init__.py ├── settings.py ├── urls.py └── wsgi.py -
Creating a new user in a django project is not working properly
I am trying to have a user project where users can create a profile. After registration the user is created in the backend but it returns an error: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/accounts/profile/ The user is logged in but I don't know the reason and how to fix this error. Here is the models: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) def __str__(self): return f'{self.user.username} Profile' here is the views.py: def register(request): if request.method == 'POST': form = UserRegisterForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') messages.success(request, f'Your account has been created! You are now able to log in') return redirect('login') else: form = UserRegisterForm() return render(request, 'users/register.html', {'form': form}) @login_required def profile(request): if request.method == 'POST': u_form = UserUpdateForm(request.POST, instance=request.user) p_form = ProfileUpdateForm(request.POST, request.FILES, instance=request.user.profile) if u_form.is_valid() and p_form.is_valid(): u_form.save() p_form.save() messages.success(request, f'Your account has been updated!') return redirect('profile') else: u_form = UserUpdateForm(instance=request.user) p_form = ProfileUpdateForm(instance=request.user.profile) context = { 'u_form': u_form, 'p_form': p_form } return render(request, 'users/profile.html', context) Here is the urls.py in the main project: urlpatterns = [ path('admin/', admin.site.urls), path('', include('post.urls')), path('register/', user_views.register, name='register'), path('profile/', user_views.profile, name='profile'), path('login/', auth_views.LoginView.as_view(template_name='users/login.html'), name='login'), path('logout/', auth_views.LogoutView.as_view(template_name='users/logout.html'), name='logout'), path('password-reset............) ] What is the reason for directing to Request URL: … -
Execute a function when certain conditions are met
my django app have a function which is send_sms, I also want to have a automatic sms auto_sms function. when conditions are met on my data models. @views.py def send_sms(request): z = Rainfall.objects.latest('timestamp') numbers = Mobile.objects.all() message = ('Test Message') account_sid = '**************' auth_token = '**************' client = Client(account_sid, auth_token) for i in numbers: client.messages.create(to=i.mobile_number, from_='**************', body=message) return HttpResponseRedirect('/success/', 200) def auto_sms(request): responses = Rainfall.objects.filter( level='Torrential' or 'Intense', timestamp__gt=now() - timedelta(days=1), sms_sent=False, ) if responses.count() >= 10: send_sms(request) responses.update(sms_sent=True) @models.py class Rainfall(models.Model): level = models.CharField(max_length=10, blank=True, default='') amount = models.FloatField() timestamp = models.DateTimeField(auto_now_add=True) Now I'm testing it, that when auto_sms detects multiple(10) 'Torrential or Intense' entries into the database within a day. It must automatically execute send_sms but instead its returning an error: Cannot resolve keyword 'sms_sent' into field. Choices are: amount, id, level, timestamp what am I missing here? please help. Thanks! -
Serializer not passing complete information to API view
I created a serializer which the "user" below is from another Serializer which i imported, now the imported serializer(PubliceProfileSerializer) works fine on its own but it does not display the content of USER when i call it my browser from this serializer. Every other item shows except the user. Please help from rest_framework import serializers from users.api.serializers import PublicProfileSerializer from blog.models import Post class PostSerializer(serializers.ModelSerializer): user = PublicProfileSerializer(source='users.profile', read_only=True) category = serializers.SerializerMethodField() label = serializers.SerializerMethodField() class Meta: model = Post fields = '__all__' def get_category(self, obj): return obj.get_category_display() def get_label(self, obj): return obj.get_label_display() -
ManyToMany with Django Forms & Select2
I'm going to describe this issue to the best of my ability, I've been stuck trying to solve this for over 8 hours now and any insight is very much appreciated. My conclusion of the error is at the end of this post. Here are snippets of code pertaining to the issue: forms.py class AddActivityForm(ModelForm): class Meta: model = Activity fields = ['activity','tagsAssociated'] views.py def addactivity(request): if request.method == 'GET': return redirect(activitymanagement) else: form = AddActivityForm(request.POST) form = form.save(commit=False) #Checking if the activity exists activityExistsCheck = ActivityTbl.objects.filter(createdBy=request.user,activity=form.activity) if activityExistsCheck: print("Activity already exists!") else: form.createdBy = request.user form.save() print("Activity added") return redirect(activitymanagement) models.py class Activity(models.Model): activity = models.CharField(max_length=100) tagsAssociated = models.ManyToManyField(Tag) createdBy = models.ForeignKey(User, on_delete=models.CASCADE) createdOn = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.activity) form_template.html (aka activitymanagement.html) <script> //Script to POST Activity and Associated Tags function postActivityNTag(){ var activityName = document.getElementById("activityName").value; var tagsAssociated = $('#tagsAssociated').select2('data'); var actionForm = ("/activitymanagement/add"); document.getElementById('addNewActivityForm').action = actionForm; document.getElementById('addNewActivityForm').submit() }; </script> <form id="addNewActivityForm" action="{% url 'addactivity' %}" method="POST"> {% csrf_token %} <div class="input-group"> <input placeholder="Create a new activity" type="text" id="activityName" name="activityName" class="form-control" maxlength="100"/> &nbsp <select class="js-example-basic-multiple" id="tagsAssociated" name="tagsAssociated" multiple="multiple"> {% for tag in allTags %} <option value="{{ tag.id }}">{{ tag.tag }}</option> {% endfor %} </select> <button class="btn btn-success btn-sm" … -
Crispy Form (Other Languages) - DJANGO
We are building a platform with Django and used crispy forms which helped us a lot. But our customer does not speak English and we need everything to be in Turkish, tried googling but could not find a lot of answers. Any other tool I can use which could help? Thanks Onur -
Cannot assign "(<User: admin>,)": "Event.owner" must be a "User" instance
This is weird. I have this code: from django.contrib.auth import get_user event.owner = get_user(request), event.save() In the model, owner is a ForeignKey to the User model. At first, I tried assigning it directly to request.user (as I've done all the times). I am not sure why I get this error: Cannot assign "(<User: admin>,)": "Event.owner" must be a "User" instance.