Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django SQLITE3 BASE_DIR not working when moving machines
So I have the following code which specifies the path of where my db file is located on my system. It works flawlessly on the computer which I have created my django project in. However, when I move the project to a different machine, it does not find the db.sqlite3 file and instead creates a new one in the root directory of that machine, so I have to create a DB_DIR and manually specify the path and cannot use BASE_DIR for the database connection. BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } Does anyone have any suggestions? -
(Djoser) Weird activation email when I update the user fields
Every time when I try to update my user with the PATCH method to the /users/me/ endpoint, an activation email is always sent. The user is already active in the system... so I don't know what is happening. SEND_ACTIVATION_EMAIL is True, but I understand that the email will be sent only after: creating an account or updating their email (I'm not updating the email) DJOSER = { .... 'ACTIVATION_URL': 'auth/users/activation/{uid}/{token}', 'SEND_ACTIVATION_EMAIL': True, .... } -
TemplateDoesNotExist at /account/password_reset_confirm/MQ/set-password/ registrationpassword_reset_confirm.html
I`m using the Django authentication system to reset the user password. I create an app named account, in which I add the following codes in the urls.py modules: from django.urls import path, include from django.contrib.auth import views as auth_views from . import views urlpatterns=[ path('password_reset/', auth_views.PasswordResetView.as_view(), name='password_reset'), path('password_reset/done/', auth_views.PasswordResetDoneView.as_view(), name='password_reset_done'), path('password_reset_confirm/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view( template_name='registration/password_reset_confirm.html'), name='password_reset_confirm'), path('reset/done/', auth_views.PasswordResetCompleteView.as_view(), name='password_reset_complete'), ] I create all the templated needed in the app`s template/registration repository: password_reset_form.html, password_reset_done.html, password_reset_confirm.html, password_reset_complete.html, And I also add the email setting to my project: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = '********' EMAIL_HOST_PASSWORD = '**********' EMAIL_PORT = 587 EMAIL_USE_TLS = True I run the server, on the password reset page I enter the email that the user is verified, after that, I received the password reset link in my inbox, but When I click it then the TemplateDoesNotExist exception occurs. -
How to get react components in a separate static js file read by Django? What is the least to be installed to make it work?
What are the modifications needed to be done ? And/or what is the least needed to be installed for this to work? First, in a static reactclasses.js file the file only contains this. (Is there anything else needed to be added?) class Login extends React.Component { render() { return ( <div id="login"> <form action="/login" method="POST"> <input type="text" name="username" placeholder="Username" required/> <input type="password" name="password" placeholder="Password" required/> <input type="submit" value="Submit"/> </form> </div> ); } } In an html file <!--- in the head tag ---> <script src="https://unpkg.com/react@16/umd/react.development.js" crossorigin></script> <script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js" crossorigin></script> <script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script> <script src="{% static 'reactclasses.js' %}" type="text/babel"></script> <!--- in a script tag with type=text/babel in the body tag --> ReactDOM.render(<login />, document.querySelector("thediv")); the console errors image -
Send related image to Django Rest Framework
Hello everyone reading this post. I got such issue. So, first of all I have such models layout class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile') description = models.TextField(max_length=4000, null=True) liked_profiles = models.ManyToManyField('self', related_name='likes') disliked_profiles = models.ManyToManyField('self', related_name='dislikes') class Image(models.Model): profile = models.ForeignKey(Profile, on_delete=models.CASCADE, related_name='images', max_length=6) path = models.ImageField(upload_to='profile_images') So, I want to create a drf endpoint that will receive some kind of image, create it, and link to the profile model. But I really not sure how to implement this(I want to make it with django viewsets). The main goal is not to provide another viewset class (like ImageViewSet), but to make it part of ProfileViewSet. So now I have such viewset (contains a method to update the description) class ProfileViewSet(viewsets.ModelViewSet): queryset = Profile.objects.all() permission_classes = (IsAuthenticated, ) @action(detail=True, methods=['PUT']) def set_description(self, request, pk=None): profile = self.get_object() serializer = DescriptionSerializer(data=request.data) if serializer.is_valid(): profile.description = request.data['description'] profile.save() else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) I want to add something like "add_image" method to it. How can I implement it and is it actually possible(otherwise you can help me to implement it with another viewset)? I will be extremely grateful for your help -
ArrayReferenceField(ManyToManyField) in django-admin, Djongo/MongoDB
I catch error while saving Diary document in django-admin Here Diary model -
django test client: Django Restframework does not have PUT data from test client
Trying to write django unit tests for APIs with djangorestframeworks. But the api cannot get data from PUT method(request.data). The api works just fine with form data from javascript and html but just cannot work with unit tests. And the api works fine with POST method. ps: request.body has correct data tests.py: from django.test import TestCase, Client class TestAPI(TestCase): def setUp(self): '''all Set wtih Client(self.client) and User(self.user) ........''' def test_method(self): put_res = self.client.put('test_api/', data={'x': 3}, content_type="multipart/form-data") post_res = self.client.post('test_api/', data = {'x': 3}, content_type="multipart/form-data") views.py from rest_framework.views import APIView class Test(APIView): def put(self, request): print(request.data) # request.data is empty, but request.body is not. return Response('wrong') def post(self, request): print(request.data) # got {'x': 3} correctly return Response('Good') -
Django migrating from SQLITE to PGSSQL
I am looking to migrate my Django application from Sqlite to Postgres. I used the following code for the first step : P:\webapp>python manage.py dumpdata > datadump.json Which returned the following error: System check identified some issues: WARNINGS: ?: (urls.W005) URL namespace 'admin' isn't unique. You may not be able to reverse all URLs in this namespace CommandError: Unable to serialize database: 'cp950' codec can't encode character '\ufffd' in position 310: illegal multibyte sequence Exception ignored in: <generator object cursor_iter at 0x00000000171CC1C8> Traceback (most recent call last): File "C:\Users\franky.doul\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\sql\compiler.py", line 1609, in cursor_iter cursor.close() sqlite3.ProgrammingError: Cannot operate on a closed database. I am still fairly new to Django, could someone help me understand the above error message please ? -
Change serializer class for single method in Django Rest Framework
If I want to override a method in my viewset to change the serializer_class for only a single method, how can I do that. I tried passing serializer_class=CustomSerializer but it doesn't have any effect. class VoteViewset(viewsets.ModelViewSet): queryset = Vote.objects.all() # Use normal serializer for other methods serializer_class = VoteSerializer def list(self, request, *args, **kwargs): # Use custom serializer for list method return viewsets.ModelViewSet.list(self, request, serializer_class=VoteWebSerializer, *args, **kwargs) Basically do the same list method as the inherited viewset, but use a different serializer to parse the data. The main reason for this is because javascript does not handle 64 bit integers, so I need to return the BigInteger fields as a string instead of integer. -
django: queryset doesnt show the right result
I'm not sure how to write the queryset since I have a list of categories, my try is below, however, I'm not getting the wanted result. Any help is appreciated! model: category= (('sell', 'sell'),('rent','rent')) categories= models.CharField(max_length = 10, choices= category, null = True) html: <select name="type" class="form-control " style = "width:250px;"> <option selected="true" disabled="disabled" selected>Type</option> <option value="sell" class = 'numbers'>sell</option> <option value="rent" class = 'numbers'>rent</option> </select> views>query> # type if 'types' in request.GET: types= request.GET['types'] if types: queryset_list = queryset_list.filter(category__in = ['sell','rent']) -
DataBase Error when saving a list of strings in django with MongoDB on the server side
I am trying to add a list of strings to DB, so i made a for loop to iterate over the list to save each string to the deadline_date field inside the BsfEvents class in models.py. Only the first item was saved, and after that all i am getting is DatabaseError() for unknown reasons. I tried to use try and except to catch the error as e, when i am trying to print it, it print empty line, so i used repr to print the Traceback, but i did not understand where is the problem. This is a side project, and i should note that i am not experienced so much in django with mongoDB. Here is my code inside the views.py: class BsfEventsViewSet(viewsets.ModelViewSet): queryset = BsfEvents.objects.all() permission_classes = [ permissions.AllowAny ] serializer_class = BsfEventsSerializer @action(detail=False, methods=['POST']) def add_bsfevent_to_db(self, request): BsfEvents.objects.all().delete() deadline = get_events_deadline() # deadline is a list of strings event_details = get_events_details() # event_details is a list of strings try: for item in deadline: date = BsfEvents(deadline_date=item) date.save() for item in event_details: detail = BsfEvents(description=item) detail.save() response = {'success': 'Events added successfully.'} except Exception as e: print(repr(e)) traceback.print_exc() response = {'error': 'Error while adding events to DB'} return … -
How can I change the default select options?
I set a selection model form at models.py and form.py. But I want the default options to change dynamically. For example, if it has a data [user:test, status:wishlist, gameSlug:test-1] found in the database. I hope when I using this "test" account open "test-1" page, the selection will show "wishlist" as default. here is my code: models.py: class UsersMarksTags(models.Model): STATUS = [ ('booked', 'Booked'), ('wishlist', 'Add to Wishlist'), ('Not interested', 'Not intersted'), ] user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE); status = models.CharField(max_length = 200, null = False, choices = STATUS, default = 'booked'); gameSlug = models.CharField(max_length = 200, null = False); form.py: class statusForm(forms.ModelForm): class Meta: model = UsersMarksTags; fields = ['status']; views.py: class showGameInformation(FormView): template_name = "showList/gameDetail.html"; form_class = statusForm; def form_valid(self, form): ....... test.html: <form method = 'POST'> {% csrf_token %} {{ form.as_p }} <input type='submit' value='Submit' /> </form> -
Postgres paste table to Local not working
I'm new in Postgres and currently having a trouble on how can I copy past the table through creating new connection in Navicat from a friend. So I just want to paste those table into my local but the problem is I have been encountered this error. I'm been using navicat version 15 and postgres version 11. It is possible that the problem is comes from the table restricted from my friend? Thanks in advance Image 1 Image 2 auth_group_id_seq does not exist -
Django giving error when null and blank both True
I have a field in my model: message = models.BigIntegerField('Vote Message', null=True, blank=True) Yet when I try to POST to this view (rendered from a rest_framework.viewsets.ModelViewSet), I get an error message: "This field may not be null." Why is it giving me that if I have it specifically to allow a null value? -
Django: Using a For Loop in a DetailView class page
Using Django, is it possible to have a For Loop in a page from a DetailView Class page? I have detail pages of things pulled from my database, but I was hoping I could have a For Loop inside that page that runs through a list of names in that table to link to each other (if that makes sense). urls.py: from django.urls import path, include from .views import payplan_emails_view urlpatterns = [ path('normal-payplan-emails/<int:pk>', payplan_emails_view.as_view(), name="normal-payplan-emails"), ] views.py: from django.shortcuts import render, redirect from .models import knowledgebase_instruction from django.views.generic import DetailView class payplan_emails_view(DetailView): model = knowledgebase_instruction template_name = "instructions/payplans_base.html" payplans_base.html: {% block content %} <h4>{{knowledgebase_instruction.name}}</h4> <p>{{knowledgebase_instruction.instructions|safe}}</p> <ul> <!-- I would love to loop through items in the table here --> <li><a href="#">List Item 1</a></li> </ul> {% endblock%} -
Django models: Choose a FK from two options (Just one)
This is the models.py from a Subscription app. Some fields have been omitted, to simplify the code. # PLAN class Plan(BaseVersionPlusModel): code = models.CharField(max_length=17, primary_key=True) description = models.CharField(max_length=255) price = models.FloatField() services = models.ManyToManyField(Service, through='subscriptions.PlanService', blank=True) products = models.ManyToManyField(Product, through='subscriptions.PlanProduct', blank=True) class PlanService(BaseVersionPlusModel): service = models.ForeignKey(Service, on_delete=models.CASCADE) plan = models.ForeignKey(Plan, related_name='plan_services', on_delete=models.CASCADE) limit = models.FloatField(default=9999) class PlanProduct(BaseVersionPlusModel): product = models.ForeignKey(Product, on_delete=models.CASCADE) plan = models.ForeignKey(Plan, related_name='plan_products', on_delete=models.CASCADE) limit = models.FloatField(default=9999) # SUBSCRIPTION class Subscription(BaseVersionPlusModel): client = models.ForeignKey(Client, on_delete=models.PROTECT, blank=True) plan = models.ForeignKey(Plan, on_delete=models.PROTECT, blank=True, null=True) # CONSUME class ServiceConsume(BaseVersionPlusModel): subscription = models.ForeignKey(Subscription, on_delete=models.CASCADE) service = models.ForeignKey(Service, on_delete=models.CASCADE) class ProductConsume(BaseVersionPlusModel): subscription = models.ForeignKey(Subscription, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) I would like to get the Consume model in just one table instead of ServiceConsume and ProductConsume. Someting like this: Class Consume(BaseVersionPlusModel): subscription = models.ForeignKey(Subscription, on_delete=models.CASCADE) **service/product = FK(Service/Product) #But choosing only one** Is this possible in Django? -
Django Parsing Mailchimp webhooks
I'm writing a webhook handler to receive data from Mailchimp in a Django application. The Mailchimp documentation lists the code for Flask: @app.route('/', methods=['POST']) def index(): reqType= itemgetter('type')(request.get_json()) reqData= itemgetter('data')(request.get_json()) I tried the following in Django, however I received an error that 'byte indices must be integers or slices, not str': @csrf_exempt def mailchimp_handler(request): reqtype = request.body["type"] reqdata = request.body["data"] Setting the following didn't work: reqtype = request.body[0] and reqdata = request.body[1] I also tried the following, without success: def mailchimp_handler(request): data = json.loads(request.body) reqtype= data["type"] reqdata= data["data"] -
Django REST Knox Authentication Issues
I've completed the development work on a Django REST API using Knox-Rest. It works great in my development environment but after moving it to the Prod environment, it authenticates and I receive my token back. Then using Postman, to test my API, I do a get using that token to validate the user and I get a 401 error, Credentials Not Provided. Looking at the in the "knox_authtoken" table I see separate rows for each login I tried. On the same table in development, I just see one row per user. I think the answer to why it's not working is related to what I'm seeing on the table but I'm not sure what it's telling me. All of the code is identical so it's likely in the setup but I can't seem to track it down. So anyone with some experience with the Django Knox-REST API that might have some ideas, I'd really appreciate it. -
How to include python django's starting message in logging
In test, I found out that Python Django application's staring message may contain important warnings, etc, and see the screenshot below for an example. However, the log file didn't include these message. I'm wondering if there's any setting to include it in logging? Any hints will be highly appreciated. Example screen output: (venv3.7) [user@vnl1916 APPLICATION]$ python manage.py runserver 0.0.0.0:8000 Performing system checks... System check identified some issues: WARNINGS: eav.Value.value_bool: (fields.W903) NullBooleanField is deprecated. Support for it (except in historical migrations) will be removed in Django 4.0. HINT: Use BooleanField(null=True) instead. System check identified 1 issue (0 silenced). You have 13 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, authtoken, ebackendapp, sites. Run 'python manage.py migrate' to apply them. February 08, 2021 - 12:31:55 Django version 3.1.4, using settings 'ebackendproject.settings' Starting development server at http://0.0.0.0:8000/ Quit the server with CONTROL-C. ^C(venv3.7) [user@vnl1916 APPLICATION]$ -
Why is this not in the Dockerfile?
I've been messing with Docker and Django lately and rather than clutter up my system, I decided to make a dev container for Django. I've got it working but I want to know the "why" of this situation. I followed this tutorial on the Docker website and finally got everything working. I don't get why we do docker-compose run web django-admin startproject composeexample and not put the django-admin startproject composeexample inside the Dockerfile or the compose file? I've tried to do both but it wont work, it builds the image but without a django project being created. I get a manage.py not found error. I feel like the project should be inside the image and not have to be run at the end of the docker-compose run command. So why do we do this and why doesn't putting it inside the Dockerfile work? -
How to skip any strings values from an excel column Pandas
I have a pandas dataframe in which a column must accept only decimal fields, what can I do to skip or delete all of the rows that values in this columns are strings? -
Django FileField 'SyntaxError: positional argument follows keyword argument'
I am trying to remove a discontinued package from a django project which is requiring me to replace a field that was in the package from many migration files. I switched to models.FileField however I'm getting errors that suggest issues with the order of my parameters. I tried switching around the parameters but I couldn't seem to get the error to resolve. Here's the error: models.FileField(upload_to='producer/closing/', blank=True, verbose_name='File'), ^ SyntaxError: positional argument follows keyword argument Any suggestions as to what is happening? -
I have a ValueError at /accounts/register/ in registration form
class UserFormView(View): form_class = UserForm template_name = 'registration/register.html' # display blank form def get(self, request): form = self.form_class(None) return render(request, self.template_name, {'form': form}) # process form data def post(self, request): form = self.form_class(request.POST) if form.is_valid(): user = form.save(commit=True) # cleaned (normalized) data email = form.cleaned_data['email'] first_name = form.cleaned_data['first_name'] last_name = form.cleaned_data['last_name'] date_of_birth = form.cleaned_data['date_of_birth'] phone_number = form.cleaned_data['phone_number'] address = form.cleaned_data['address'] password = form.cleaned_data['password'] user.set_password(password) user.save() # returns user objects if credentials are correct user = authenticate(email=email, password=password) if user is not None: if user.is_active: login(request, user) return redirect('accounts:home') return render(request, self.template_name, {'form': form.as_p}) this is a views.py which check a validation of registration form, but when I register a form in a server I find a ValueError at /accounts/register/ -
Django url routing 404
I am a beginner in Full stack Machine Learning and I have decided to use Django to develop myself further. I created a simple ML - prediction and deployed it in the server of my company. By default, the server always gives the project name as the prefix. example: https://companyserver.net/projectname/. in my local system the code is working well, however if i deploy it to the company server, when i try to open another page from 'home' page, Django throws a 404 error. the URL pattern (should) looks like following: https://companyserver.net/predict/? but that is wrong, as it should contain the projectname after the .net, so it should be like this: https://companyserver.net/projectname/predict/? If I add the project in the middle of the URL just like above, the page opens correctly. What is the best practice to solve this problem? I searched somewhere online that I can use constant FORCE_SCRIPT_NAME under settings.py. Trying this, but it makes even more trouble in my local system. Appreciate your help very much. -
How can I make a line disabled (readonly) in Django?
For example, I have a table (List View) of events that will happen over a period of time. When any event is over I would like to click on a "Cancel" button that does not delete the event from the database and that keeps it appearing in the table but in a way that I cannot edit or undo the cancellation. How can I do that? The examples I saw here did not help me because none of them had any button that could disable stuff.