Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django (Ngninx, Gunicorn) : manage dev, test and prod code of a given application
I have a Django application running with Nginx and Gunicorn on a remote server. We would like to get several versions of the same application: production, test and development, using URLs like: https//:www.domain.com (production) https//:www.domain.com/test/ (test version) https//:www.domain.com/dev/ (development version) I don't have a clue about the best strategy to adopt since people will only work on the application code and not at a higher level (project, server) My first idea was to simply duplicate the application within the same project: a copy for dev, and a copy for test, but according to the templates engine I was not able to execute the correct .html files Maybe, another way would maybe to deploy two new projects dedicated to dev and test? but I'm not sure how to proceed. The last way would be to create a fresh new django instance for each, but i'm lost about the way to setup my Nginx and Gunicorn settings accordingly to make everything working. May you please give me advices about the best way to proceed regarding your experience ? Thank you very much for your help !! :) Regards -
Font Awsome on a django project
Iḿ trying to put a icon on my website but it doesn't appear. Bellow is the html of the Icon that i got from fontawsome icons. <i class="fa-solid fa-chopsticks"></i> -
my problem was about rendering html document in django application [closed]
""" this is my view.py file in which i created in order to make view on my html document from urllib import response from django.shortcuts import render from django.http import HttpRequest def index(request): return response(request,'good/try.html') and also i create the path in urls.py file from django.urls import path from. import views urlpatterns = [ path('',views.index) ] My simple html document: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <p> many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like). </p> </body> </html> but when I try to render my html page it raise an error which was: TypeError at / 'module' object is not callable in the browser -
Django registered namespace, however, post request returns 404
I have such a structure in my project. *************** Directory Tree *************** dealerpanel/ ├── __init__.py ├── api/ │ ├── serializers/ │ │ ├── customer.py │ ├── urls.py │ └── views/ │ ├── payzee_redirect.py ├── apps.py ├── templates/ │ └── payzee-redirect.html ├── tests/ │ ├── api/ │ │ ├── test_payzee_redirect.py └── validators/ ├── utils.py └── validators.py The view I want to work with is payzee_redirect.py This view looks as follows: import time from django.db import transaction from rest_framework.parsers import FormParser from rest_framework.renderers import TemplateHTMLRenderer from rest_framework.request import Request from rest_framework.response import Response from rest_framework.views import APIView from apps.customer.models import PayzeeOrder from apps.dealerpanel.api.serializers.payzee import PayzeeSerializer from libs.settlement.constants import PaymentStatus class PayzeeRedirectView(APIView): authentication_classes = [] permission_classes = [] parser_classes = (FormParser,) renderer_classes = (TemplateHTMLRenderer,) template_name = "payzee-redirect.html" MAX_TRY = 4 def post(self, request: Request, *args, **kwargs) -> Response: return Response( {"is_error": False, "invoice_id": order.invoice.invoice_id}, template_name=self.template_name ) urls.py as follows: from django.urls import path from .views.payzee_redirect import PayzeeRedirectView app_name = "dealerpanel" urlpatterns = [ path("payzee/redirect/", PayzeeRedirectView.as_view(), name="payzee_redirect"), ] test_payzee_redirect.py class PayzeeRedirectiewTest(APITestCase): @classmethod def setUpTestData(cls): cls.host = TR.api_host baker.make("api.Eshop", scoring_category=baker.make("api.ScoringCategory")) invoice = baker.make("api.Invoice") baker.make("customer.PayzeeOrder", invoice = invoice) def test_payzee_order_does_not_exist(self): # Given data = { "OrderId": uuid4(), "ResponseCode": "00" } # When response = self.make_request(data) # … -
How to work with admin inline forms in Django crispy-forms
I ran into a problem when using crispy-forms. I have fields that I display through crispy layout. class OptionOfProductInline(admin.TabularInline): form = OptionOfProductInlineForm model = OptionOfProduct extra = 1 class ProductForm(forms.ModelForm): class Meta: model = Product fields = "__all__" def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_id = 'id-exampleForm' self.helper.form_class = 'blueForms' self.helper.form_method = 'post' self.helper.form_action = 'submit_survey' self.helper.form_tag = False self.helper.layout = Layout( TabHolder( Tab("Основні налаштування", HTML("<div class='tab_name'>Основні налаштування</div>"), Div( Div("article", "price", css_class='two_in_line'), Div(Div(HTML(_("<div>Availability</div>")), "availability", css_class="form-group"), "percent_sale", css_class='two_in_line'), Div("qty", "date_start_sale", css_class='two_in_line'), Div("unit_fk", "date_end_sale", css_class='two_in_line'), Div(Div(HTML(_("<div>Publish</div>")), "publish", css_class="form-group"), "order", css_class='two_in_line'), css_class="left_side"), Div( Div("image"), Div("qty_min_order"), Div("brand_fk"), Div("category_fk"), Div("show_in_categories"), css_class="right_side"), css_class="two_cols"), Tab("SEO", HTML("<div class='tab_name'>SEO</div>"), Div( Div(*name, css_class='column_fields'), Div(*slug, css_class='column_fields'), Div(*h1, css_class='two_in_line'), Div(*title, css_class='row_fields'), Div(*meta_description, css_class='field_description'), Div(*description, css_class='field_description'), css_class='name_slug'), css_class="center_side", ), ), ) @admin.register(Product) class ProductAdmin(TabbedTranslationAdmin): form = ProductForm add_form_template = "admin/my_form.html" change_form_template = "admin/my_form.html" The fields look like on this screenshot: https://i.imgur.com/lLL2G23.jpg. The "Inline" tab should contain formsets that look like this screenshot: https://i.imgur.com/nKOntVV.jpg and I want to output this formset through Layout. I tried to output like this, but it didn't work :( Tab("Inline", OptionOfProductInline, css_class="some_class",) OptionOfProduct and OptionOfProductInlineForm: class OptionOfProduct(models.Model): product_fk = models.ForeignKey(Product, on_delete=models.CASCADE, null=True, blank=True) option_value_mtm = models.ManyToManyField(OptionValue, null=True, blank=True) article = models.CharField(verbose_name=_('article'), null=True, blank=True, max_length=255) price = … -
How to fetch specific elements using dropdown list django
I am new to django and I am trying to show total employees and employees on each department in a table using a dropdown list. Dropdown code : <label>Depart</label> <select class="custom-select" style="width: 200px" id="depart"> <option value="Total">Total</option> {% for key,value in uv.items %} <option value="{{ value }}">{{ key }}</option> {% endfor %} </select> Table code : <table class="table table-striped"> <tr class="thead-dark "> <th>ID</th> <th>Nom et Prenom</th> <th>Lundi</th> <th>Mardi</th> <th>Mercredi</th> <th>Jeudi</th> <th>Vendredi</th> <th>Samedi</th> <th>Dimanche</th> </tr> {% for i in employe %} <tr> <td>{{ forloop.counter }}</td> <td>{{ i.name }} </td> <td>{{ i.monday }}</td> <td>{{ i.tuesday }}</td> <td>{{ i.wednesday }}</td> <td>{{ i.thursday }}</td> <td>{{ i.friday }}</td> <td>{{ i.saturday }}</td> <td>{{ i.sunday }}</td> </tr> {% endfor %} </table> -
How to deploy React and Django on OVH cloud
I have 0 idea how to do it, so I have an OVH VPS rented, from https://www.ovhcloud.com/en-au/ and I have the web app completed, I will buy a domain, however I have no idea how to deploy react with Django, or how to separate them on deployment if needed, can anyone give me a step by step with enough resources on how to do it? -
how to set and use a foreign key for single field in Django?
from djando.db import models class server(models.Model): server_IP = models.CharField(max_length=100) Server_name = models.CharField(max_length=100) class application(models.Model): ip_address= models.ForeignKey(server_IP,on_delete=models.CASCADE) ip = models.charField(max_length=100) application_name = models.ForeignKey(ip,on_delete=models.CASCADE) application_start_date = models.DateField() = models.DateField() here i want to use ip_address as a foreign key for server_IP ip as foreignkey for application name -
How to add background image in cms
Can any one explain How to add background image in django cms Im having a html file there is background image which comes from css HTML: <div class="container"> ... </div> CSS: .container { background: url(../images/sample.jpg); background-size: cover; background-repeat: no-repeat; height: 468px; } I need to change this to placeholder to make this content editable in django cms -
How can set environment for python when there are multiple django projects on one server?
I have a server which has this structure. Nginx -> uwsgi(port:8011) DjangoA -> uwsgi(port:8012) DjangoB I developed with pipenv in local. pipenv shell pipenv manage.py runserver Now I want to put this on server with At first I try this on capistrano task :bundle do on roles(:app) do #execute "/home/ubuntu/.pyenv/shims/pip install -r #{release_path}/requirements.txt" execute "/home/ubuntu/.pyenv/shims/pipenv install" end end task :migrate do on roles(:app) do execute "/home/ubuntu/.pyenv/shims/pipenv run python #{release_path}/manage.py makemigrations" execute "/home/ubuntu/.pyenv/shims/pipenv run python #{release_path}/manage.py migrate" end end task :assets do on roles(:app) do execute "yes yes | /home/ubuntu/.pyenv/shims/pipenv run python #{release_path}/manage.py collectstatic" end end However even after pipenv installing , there is no library appears. (or it is not correctly installed??) DEBUG [50051834] Command: /home/ubuntu/.pyenv/shims/pipenv install DEBUG [50051834] Installing dependencies from Pipfile.lock (db4242)... DEBUG [50051834] 🐍 ▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉ 0/0 — 00:00:00 DEBUG [50051834] DEBUG [50051834] To activate this project's virtualenv, run pipenv shell. Alternatively, run a command inside the virtualenv with pipenv run. INFO [50051834] Finished in 1.239 seconds with exit status 0 (successful). INFO [8a6402ea] Running /home/ubuntu/.pyenv/shims/pipenv run python /var/www/html/sokuapi/releases/20220901070724/manage.py makemigrations as ubuntu@koala.example.jp DEBUG [8a6402ea] Command: /home/ubuntu/.pyenv/shims/pipenv run python /var/www/html/sokuapi/releases/20220901070724/manage.py makemigrations DEBUG [8a6402ea] Traceback (most recent call last): File "/var/www/html/sokuapi/releases/20220901070724/manage.py", line 11, in main from django.core.management import execute_from_command_line ModuleNotFoundError: … -
Django unit testing - authenticated user check in model method
I am using Django 3.2 I am trying to test a model that checks if a user is authenticated. The model code looks something like this: class Foo(Model): def do_something(user, **kwargs): if user.is_authenticated(): do_one_thing(user, **kwargs) else: do_another_thing(**kwargs) My test code looks something like this: from model_bakery import baker from django.contrib.auth import authenticate, get_user_model User = get_user_model() class FooModelTest(TestCase): def setUp(self): self.user1 = baker.make(User, username='testuser_1', password='testexample1', email='user1@example.com', is_active = True, is_superuser=False) baker.make(User, username='testuser_2', password='testexample2', email='admin@example.com', is_active = True, is_superuser=True) self.unauthorised_user = authenticate(username='testuser_2', password='wrongone') def test_user(self): self.assertTrue(self.user1.is_validated) # why is this true? - I haven't "logged in" yet? self.assertFalse(self.unauthorised.is_validated) # Barfs here since authenticate returned a None So, How am I to mock an unauthenticated user, for testing purposes? - since it appears that the is_authenticated property is read only? -
KeyError: 'slider-graph.figure'
I'm trying to render a plotly dash app to django template but I'm having error it says that 'dispatch_with_args callback_info = self.callback_map[output] KeyError: 'slider-graph.figure''. I just started using plotly-dash, I'm familiarizing it. Here's my dash app analytics = pd.DataFrame({'country': ['USA', 'UK', 'France', 'Germany', ' China', 'Pakistan', 'India'], 'users': [1970, 950, 760, 810, 2800, 1780, 2250], 'page_views': [2500, 1210, 760, 890, 3200, 1910, 2930], 'avg_duration': [75, 60, 63, 79, 57, 61, 72], 'bounce_rate': [51, 65, 77, 43, 54, 57, 51]}) # ======================== Setting the margins layout = go.Layout( margin=go.layout.Margin( l=40, # left margin r=40, # right margin b=10, # bottom margin t=35 # top margin ) ) # ======================== Plotly Graphs def get_scatter_plot(): scatterPlot = dcc.Graph(figure=go.Figure(layout=layout).add_trace(go.Scatter(x=analytics['country'], y=analytics['avg_duration'], marker=dict( color='#351e15'), mode='markers')).update_layout( title='Average Duration', plot_bgcolor='rgba(0,0,0,0)'), style={'width': '50%', 'height': '40vh', 'display': 'inline-block'}) return scatterPlot def get_pie_chart(): pieChart = dcc.Graph( figure=go.Figure(layout=layout).add_trace(go.Pie( labels=analytics['country'], values=analytics['bounce_rate'], marker=dict(colors=['#120303', '#300f0f', '#381b1b', '#4f2f2f', '#573f3f', '#695a5a', '#8a7d7d'], line=dict(color='#ffffff', width=2)))).update_layout(title='Bounce Rate', plot_bgcolor='rgba(0,0,0,0)', showlegend=False), style={'width': '50%', 'height': '40vh', 'display': 'inline-block'}) return pieChart # ======================== Dash App app = DjangoDash('SimpleExample') # ======================== App Layout app.layout = html.Div([ html.H1('Website Analytics Dashboard', style={ 'text-align': 'center', 'background-color': '#ede9e8'}), get_scatter_plot(), get_pie_chart() ]) if 'SimpleExample' == '__main__': app.run_server() here is my html file {% load plotly_dash %} <div class="{% plotly_class … -
Please I'm new to python and I'm trying to do a recipe app using Django. I encountered an error which is "UnboundLocalError: local variable form
this is the picture of my views.py When I ran the code I saw an this error in the browser UnboundLocalError: local variable 'form' referenced before assignment -
function has no attribute all
i am getting this attribute error (function has no attribute all) when i clicked on a question in my browser after running my server. I have gone through the code many times but couldn't find the error. View.py class IndexView(generic.ListView): template_name ='pulls/index.html' context_object_name = 'latest_question_list' def get_queryset(self): """ Return the last five published questions (not including those set to be published in the future). """ return Question.objects.filter(pub_date__lte=timezone.now()).order_by('-pub_date')[:5] #Detail Function class DetailView(generic.DetailView): model = Question template_name ='pulls/detail.html' def queryset(self): """ Excludes any questions that aren't published yet. """ return Question.objects.filter(pub_date__lte=timezone.now()) -
Vue - Optimal way of receiving notifications from back-end
I'm adding backend-sent notifications to my Vue 3 app. My Django backend generates notifications and saves them to the user inbox; where they can be accessed and read at any time. I'm trying to decide which way is best for the front-end to receive such notifications. Basically, I'm torn between two options: use polling; something like a setInterval of 20 seconds that simply makes a REST call to get the most recent notifications for the user open a websocket; the server pushes a message each time there's a new notification I'm leaning a little more towards the websocket option; however, I am concerned with: complexity: having to manage re-connections and all the things that can go wrong with a WS performance: I am predicting peaks of 200-300 users at a time; is having that many open WS connection a possible concern? Weighing these factors, which one would be the better choice for my needs? And how would you mitigate the drawbacks of the chosen approach? -
why i am getting the error 'temp1app.CustomUser.user_pe rmissions' or 'auth.User.user_permissions'?
Hope you are doing well, i am beginner to the django and python, encountered the error while practicing projects from the github which is the user authentication project. i have posted a code below. feel free to ask if you have any questions. i have posted a question in this StackOverflow website to find the solution for the issue. please solve the issue. Thanks a lot for your help. Traceback error: python manage.py migrate SystemCheckError: System check identified some issues: ERRORS: auth.User.groups: (fields.E304) Reverse accessor for 'auth.User.groups' clashes with reverse accessor for 'temp1app.CustomUser.groups'. HINT: Add or change a related_name argument to the definition for 'auth.User.groups' or 'temp1 app.CustomUser.groups'. auth.User.user_permissions: (fields.E304) Reverse accessor for 'auth.User.user_permissions' clashes wi th reverse accessor for 'temp1app.CustomUser.user_permissions'. HINT: Add or change a related_name argument to the definition for 'auth.User.user_permissions' or 'temp1app.CustomUser.user_permissions'. temp1app.CustomUser.groups: (fields.E304) Reverse accessor for 'temp1app.CustomUser.groups' clashes wi th reverse accessor for 'auth.User.groups'. HINT: Add or change a related_name argument to the definition for 'temp1app.CustomUser.groups' or 'auth.User.groups'. temp1app.CustomUser.user_permissions: (fields.E304) Reverse accessor for 'temp1app.CustomUser.user_per missions' clashes with reverse accessor for 'auth.User.user_permissions'. HINT: Add or change a related_name argument to the definition for 'temp1app.CustomUser.user_pe rmissions' or 'auth.User.user_permissions'. temp1/settings.py from pathlib import Path import os # Build paths … -
in django how to link two fields of the same model with another model with the foreign key
I have a "ModelVoiture" model with a foreign key "type_carburant" field and I can access the "typeCarburant" field of the "Carburant" model. I need to access another field of the same model "Carburant", the field "prixCarburant" from the model "ModelVoiture" but if I add the line prixCarburant = models.ForeignKey(Carburant, on_delete=models.CASCADE) i have this error coutcarbur.ModelVoiture.prixCarburant: (fields.E304) Reverse accessor 'Carburant.modelvoiture_set' for 'coutcarbur.ModelVoiture.prixCarburant' clashes with reverse accessor for 'coutcarbur.ModelVoiture.typeCarburant'. HINT: Add or change a related_name argument to the definition for 'coutcarbur.ModelVoiture.prixCarburant' or 'coutcarbur.ModelVoiture.typeCarburant'. coutcarbur.ModelVoiture.typeCarburant: (fields.E304) Reverse accessor 'Carburant.modelvoiture_set' for 'coutcarbur.ModelVoiture.typeCarburant' clashes with reverse accessor for 'coutcarbur.ModelVoiture.prixCarburant'. HINT: Add or change a related_name argument to the definition for 'coutcarbur.ModelVoiture.typeCarburant' or 'coutcarbur.ModelVoiture.prixCarburant'. my code in coutcarbur/models.py class MarqueVoiture(models.Model): name = models.CharField(max_length=50) def __str__(self): return self.name class Carburant(models.Model): name = models.CharField(max_length=50) prixCarburant = models.DecimalField(max_digits=6, decimal_places=2) typeCarburant = models.CharField(max_length=50) def __str__(self): return self.name class ModelVoiture(models.Model): name = models.CharField(max_length=50) consolitre = models.DecimalField( max_digits=6, decimal_places=2) prixCarburant = models.ForeignKey(Carburant, on_delete=models.CASCADE) typeCarburant = models.ForeignKey(Carburant, on_delete=models.CASCADE) marque = models.ForeignKey(MarqueVoiture, on_delete=models.CASCADE) def __str__(self): return self.name how to implement related_name function in template to solve this problem. I must surely revise the diagram of my models? thanks for any help. -
Item update query produced by django is wrong
I am trying to update one item at a time using the Django ORM with TimescaleDB as my database. I have a timesacle hypertable defined by the following model: class RecordTimeSeries(models.Model): # NOTE: We have removed the primary key (unique constraint) manually, since we don't want an id column timestamp = models.DateTimeField(primary_key=True) location = PointField(srid=settings.SRID, null=True) station = models.ForeignKey(Station, on_delete=models.CASCADE) # This is a ForeignKey and not an OneToOneField because of [this](https://stackoverflow.com/questions/61205063/error-cannot-create-a-unique-index-without-the-column-date-time-used-in-part) record = models.ForeignKey(Record, null=True, on_delete=models.CASCADE) temperature_celsius = models.FloatField(null=True) class Meta: unique_together = ( "timestamp", "station", "record", ) When I update the item using save(): record_time_series = models.RecordTimeSeries.objects.get( record=record, timestamp=record.timestamp, station=record.station, ) record_time_series.location=record.location record_time_series.temperature_celsius=temperature_celsius record_time_series.save() I get the following error: psycopg2.errors.UniqueViolation: duplicate key value violates unique constraint "5_69_db_recordtimeseries_timestamp_station_id_rec_0c66b9ab_uniq" DETAIL: Key ("timestamp", station_id, record_id)=(2022-05-25 09:15:00+00, 2, 2) already exists. and I see that the query that django used is the following: {'sql': 'UPDATE "db_recordtimeseries" SET "location" = NULL, "station_id" = 2, "record_id" = 2, "temperature_celsius" = 26.0 WHERE "db_recordtimeseries"."timestamp" = \'2022-05-25T09:15:00\'::timestamp', 'time': '0.007'} On the other hand the update is successful with update(): record_time_series = models.RecordTimeSeries.objects.filter( record=record, timestamp=record.timestamp, station=record.station, ) record_time_series.update( location=record.location, temperature_celsius=temperature_celsius, ) and the sql used by django is: {'sql': 'UPDATE "db_recordtimeseries" SET "location" = NULL, "temperature_celsius" = … -
Django Channels: How can I run WSGI inside a Channels app?
I am going to write a Django chat apps using Channels. I haven't started yet, but I just want to know this: How can I run existing WSGI apps using Channels, which uses ASGI? I have Django 4.1 installed and Python 3.8 (i haven't installed Channels yet but i will) Thanks in advance :) -
return response number of count in django rest framework
I wanted to return the response number of the count of chiled_comments as in blew table. like for id no. 3 have 2(count) "parent_post_comment_id". and same as id no. 1 have only 1(count) "parent_post_comment_id". id is_post_comment parent_post_comment_id created_on description language_post_id 1 1 2022-08-30 09:06:07.078366 Comment Create 001!!! 2 2 1 2022-08-30 09:11:23.255055 Comment Create 002!!! 2 3 1 2022-08-30 09:16:45.394074 Comment Create 003!!! 2 4 0 3 (child of comment 3) 2022-08-30 12:26:48.076494 Comment Create 003-1!!! 2 5 0 3 (child of comment 3) 2022-08-30 12:27:10.384464 Comment Create 003-2!!! 2 6 0 2 (child of comment 2) 2022-08-30 12:27:27.306202 Comment Create 002-1!!! 2 7 0 2 (child of comment 2) 2022-08-30 12:27:37.405487 Comment Create 002-2!!! 2 8 0 1 (child of comment 1) 2022-08-30 12:27:53.771812 Comment Create 001-1!!! 2 models.py class Comments(models.Model): language_post = models.ForeignKey(PostInLanguages, null=False, related_name='comment_data', on_delete=models.CASCADE) is_post_comment = models.BooleanField(default=True) parent_post_comment_id = models.PositiveIntegerField(null=True) user = models.ForeignKey(User, on_delete=models.CASCADE) description = models.CharField(max_length=400, blank=False) created_on = models.DateTimeField(default=timezone.now) views.py class CommentGetView(viewsets.ViewSet): def retrieve(self, request, post_id=None, post_language_id=None, *args, **kwargs): try: post_in_lang = PostInLanguages.objects.get(id=post_language_id) post_in_lang_id = post_in_lang.id except PostInLanguages.DoesNotExist as e: return Response({"response": False, "return_code": "languages_post_not_exist", "result": "Comment_Get_Failed", "message": errors["postinlanguages_DoesNotExist"]}, status=status.HTTP_400_BAD_REQUEST) try: queryset = Comments.objects.filter(language_post_id=post_in_lang_id,is_post_comment=True) except Comments.DoesNotExist as e: return Response({"response": False, "return_code": "comments_not_exist", "result": … -
How to add header parameter to all url paths in drf_spectacular?
I'm using drf_spectacular to be able to use swagger and it's working fine. I define the required parameters for my API views (whether in the path or in the header) like this: @extend_schema( OpenApiParameter( name='accept-language', type=str, location=OpenApiParameter.HEADER, description="fa or en. The default value is en" ), ) but I don't want to add these lines of code to all of my API views. Is there an easy way to do this? (Something like defining these lines of code in SPECTACULAR_SETTINGS) I already found an APPEND_COMPONENTS option in drf_spectacular's documentation but I'm not familiar with it. -
Django Rest Framework admin styling messed up
I recently noticed my Django admin styling is messed up. The CSS seems to be working though and everything works, but once you click on a model, the next page is messed up. Does anyone know what causes this? I don't remember changing anything that would cause this. -
.Please try to help me. TypeError: UserManager.create_superuser() missing 1 required positional argument: 'username'
When I established a connection with MYSQL for the existing django data and trying to create a super user, above issue is raising. I cleared the db.sqlite3 database and it's migrations also models.py: from django.db import models from django.contrib.auth.models import AbstractUser class User(AbstractUser): name = models.CharField(max_length=20, null=True) email = models.EmailField(unique=True, null=True) bio = models.TextField(max_length=200, null=True) avatar = models.ImageField(null=True, default="avatar.svg") USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] forms.py: from django.forms import ModelForm from django.contrib.auth.forms import UserCreationForm from .models import Room, User class MyUserCreationForm(UserCreationForm): class Meta: model=User fields= ['name', 'username', 'email', 'password1', 'password2'] class UserForm(ModelForm): class Meta: model=User # assigning 'User' table or class from the models(db) fields = ['avatar', 'name', 'username', 'email', 'bio'] views.py: def loginPage(request): page = 'login' if request.user.is_authenticated: return redirect('home') if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') try: user = User.objects.get(username=username) except: messages.error(request, 'Incorrect Username') user=authenticate(request, username=username, password=password) #If cond to check the correct user or not if user is not None: login(request, user) return redirect('home') else: messages.error(request, 'Incorrect Username or password') context={'page':page} return render(request, 'base/login_register.html', context) def logoutUser(request): logout(request) return redirect('home') def registerPage(request): page = 'register' form = MyUserCreationForm() if request.method == 'POST': form = MyUserCreationForm(request.POST) if form.is_valid(): #commit is to get the instance from … -
Django pipedream through's exception: module 'pipedream' has no attribute 'steps'
I am using Twilio to send SMS in my Django application. and getting that message status from pipedream, but getting this error module 'pipedream' has no attribute 'steps'. In the pipedream website with this code, I get status but in my project, I am getting an error. Here is my code for a pipedream. status = pipedream.steps["trigger"]["event"]["body"]["SmsStatus"] I am attaching the screenshot of the pipedream. -
Django filter on Datetmefield
I have a model like below: class example(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=64) start_time = models.DateTimeField() end_time = models.DateTimeField() And I have below query: ohlcv_data = example.objects.filter( name='John', start_time__gte=datetime.datetime.strptime('2022-07-26 2019:30:00','%Y-%m-%d %H:%M:%S') end_time__lte=datetime.datetime.strptime('2022-07-26 2019:35:00','%Y-%m-%d %H:%M:%S')) For each minute i have a record so for top example i should give five record, but nothing returend.