Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Should graphene classes be repetitive like this?
I have the following mutation classes to for CRUDing a model. However, I have another model that I need to do the exact same classes on it. Should I create the exact same classes again with other names like class CreateComment, class UpdateComment and class DeleteComment or there is a way to make reusable classes with graphene? class CreatePost(graphene.Mutation): class Arguments: description = graphene.String(required=True) post = graphene.Field(schema.Posts) @classmethod def mutate(cls, root, info, description): post = models.Post(description=description,added_by=info.context.user) post.save() return CreatePost(post=post) class UpdatePost(graphene.Mutation): # owner(added_by)+admin can update and delete class Arguments: id = graphene.Int(required=True) description = graphene.String() post = graphene.Field(schema.Posts) @classmethod def mutate(cls, root, info, id, description): post = models.Post.objects.get(id=id) if (info.context.user == post.added_by): post.description = description post.save() return CreatePost(post=post) else: "Only the owner of the post and the admin(website's wonr) can edit and delet this post" class DeletePost(graphene.Mutation): # owner(added_by)+admin can update and delete class Arguments: id = graphene.Int(required=True) post = graphene.Field(schema.Posts) @classmethod def mutate(cls, root, info, id): post = models.Post.objects.get(id=id) if (info.context.user == post.added_by): post.delete() return f"{'ID':ID}" else: return {'partial': True} -
Filter only normal users not staff or superusers in Django
I want get only normal users not staff or superusers, how can i add option to this code users = User.objects.filter() thanks for helping me -
Puzzled with datetime.datetime axis data on chartjs with Django app in views.py
I'm currently using MQTT to transfer temperature data from an ESP32 using a broker to a Django app. I have a view retrieving data from a Table with id,date,message,topic. I can create the chartjs line graph with the ('id') as x axis but the datetime.datetime('createdat) row doesn't work. **models.py** class Mqtt(models.Model): createdat = models.DateTimeField(db_column='createdAt') topic = models.CharField(max_length=255) message = models.CharField(max_length=255, blank=True, null=True) qos = models.IntegerField() class Meta: managed = False db_table = 'mqtt' **views.py** def chart_red(request): labels = [] data = [] chart_red_obj = Mqtt.objects.order_by('createdat')[:2] for mqtt in chart_red_obj: labels.append(mqtt.createdat) data.append(mqtt.message) return render(request, "chart_red.html", { 'labels':labels, 'data':data, }) }) **html and js** <canvas id="myChart"></canvas> <script> var temp = { type: 'line', data: { datasets: [{ data: {{ data|safe }}, label: 'Trend' }], labels:{{ labels|safe }}, }, options: { responsive: true } }; window.onload = function() { var ctx = document.getElementById('myChart').getContext('2d'); window.myLine = new Chart(ctx, temp); }; ** the output is as below with no Chartjs chart created. before coming here I've tried momentjs, datetime.parse and datetime.strptime python solutions but my skills are lacking and have not unlocked the answer as yet. ** </script> var config = { type: 'line', data: { datasets: [{ data: ['65.3', '65.3'], label: 'Trend' }], **labels:[datetime.datetime(2021, … -
Ajax is not saving data in DataBase
I am building a BlogApp and I am stuck on a Problem. What i am trying to do I am trying to access user's location via JavaScriptand saving in the Model's instance in DataBase. Accessing location is working fine. BUT saving is not working The Problem Location's city is not saving in DataBase. When i refresh the page then it doesn't save in DataBase. models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE,default='',unique=True) full_name = models.CharField(max_length=100,default='') city = models.CharField(max_length=30,default='') views.py def func(request): city = request.GET.get('city') city.save() message = 'Updated' return HttpResponse(message) template (.html) # Getting city name ( first javascript code ) through IP is working. <script> $.ajax({ url: "https://geolocation-db.com/jsonp", jsonpCallback: "callback", dataType: "jsonp", success: function(location) { $('#city').html(location.city); } }); </script> #This code is for send data to Django. <script> $("city").change(function)(){ const city = 'city'; $.ajax({ url ="{% url 'mains:func' %}", data = { 'city':city, } , success.function(data){ console.log("Update"); } }); }; </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> <div>City: <span id="city"></span></div> I don't know where is the Problem. Any help would be Appreciated. Thank You in Advance. -
get values from checkboxes in django
I have several checkboxes from bootstrap and I need to get their vaules in my django app. I've tried to read them by using request.GET.get_list but all it does is returning an empy list. POST doesn't work either. Any suggestions? persl.html: {% for l in pl %} <tr> <td><div class="form-check"> <input class="form-check-input" type="checkbox" name="checks" value="value" id="fs"> <label class="form-check-label" for="checks"> </label> </div> </div> </td> <td><a href="pupdate/{{l.pk}}"><i class="bi bi-pencil-square"></i></a></td> <td><a href="pdelete/{{l.pk}}"><i class="bi bi-trash"></i></a></td> <td>{{l.pk}}</td> <td><a href="detail/{{l.padress.pk}}">{{l.fname}}</a></td> <td>{{l.lname}}</td> <td>{{l.mobil}}</td> <td>{{l.mail}}</td> <td>{{l.padress}}</td> </tr> {% endfor %} views.py: class PDelete(DeleteView): template_name='kammem/delete.html' model=Person success_url=reverse_lazy('personer') def get_queryset(self): if self.request.method == 'GET': v=self.request.GET.getlist('checks') return v -
Unable to get user.id from into django form
I'm unable to get user.school.id into the form shown below. I have not been able to know the reason as to why this is happening. Below is my forms.py class StudentsForm(forms.ModelForm): class Meta: model = StudentsModel fields = ("school","adm","name","kcpe","form","stream","gender","notes") widgets = { 'school':forms.TextInput(attrs={"class":'form-control','value':'','id':'identifier','type':'hidden'}), "adm":forms.TextInput(attrs={"class":'form-control'}), "name":forms.TextInput(attrs={"class":'form-control'}), "form":forms.Select(choices=class_forms,attrs={"class":'form-control'}), "stream":forms.Select(choices=streams,attrs={"class":'form-control'}), "gender":forms.Select(choices=gender, attrs={"class":'form-control'}), } Below is the script from the template where the id is to reflect. <script> document.getElementById('identifier').value = '{{ user.school.id }}'; </script> And this is the Students model class StudentsModel(models.Model): school = models.ForeignKey(School,on_delete=models.CASCADE) adm = models.CharField(max_length=200) name = models.CharField(max_length=200) form = models.ForeignKey(FormModel, on_delete=models.CASCADE) stream = models.ForeignKey(StreamModel,on_delete=models.CASCADE) gender = models.ForeignKey(GenderModel,on_delete=models.CASCADE) def __str__(self): return "%s | %s" % (self.name,self.adm) Please help me out. If there's anything else I need to add let me know. class School(models.Model): name = models.CharField(max_length=100,default='default') def __str__(self): return str(self.name) class User(AbstractUser): school = models.ForeignKey(School, on_delete=models.DO_NOTHING, null=True, blank=True,default=1) #role = models.CharField(max_length=10, choices=ROLES, blank=False, null=False) is_student = models.BooleanField(default=False) is_teacher = models.BooleanField(default=False) is_admin = models.BooleanField(default=False) def __str__(self): return (str(self.school) + ' | ' + self.username) The view class AddStudentView(LoginRequiredMixin,CreateView): model = StudentsModel form_class = StudentsForm template_name = 'students.html' success_url = reverse_lazy('students') def get_context_data(self, *args, **kwargs): streams = StreamModel.objects.filter(school=self.request.user.school) students = StudentsModel.objects.filter(school=self.request.user.school) forms = FormModel.objects.filter(school=self.request.user.school) context = super(AddStudentView,self).get_context_data(*args, **kwargs) context["streams"] = streams context["students"] = … -
Same Question for all users at a particular time
I want to create a quiz website with Django where all users get the same question at a particular time and after the timer ends all users get the next question. As I am new to this I just wanted to know is this possible, and if yes what do I search for on the internet -
Table doesn't exist, when in reality it does
So, I have created a database called build1, the name of the project is building_access. I have created tabled in the database(build1) called product +----------------------------+ | Tables_in_build1 | +----------------------------+ | auth_group | | auth_group_permissions | | auth_permission | | auth_user | | auth_user_groups | | auth_user_user_permissions | | building_access_contact | | contact | | django_admin_log | | django_content_type | | django_migrations | | django_session | | order | | product | | review | +----------------------------+ 15 rows in set (0.00 sec) I did python manage.py makemigrations I did python manage.py migrate sessions I did python migrate --run-syncdb, which said that table building_access_contact already exists, which I know, which is suppose to synchronize not create a new one. Anyways, when i go to main page it says this (1146, "Table 'build1.building_access_product' doesn't exist") So my reaction would be to go to admin and make a product. And so I did, but it gave me the same error. So i went over to database to check if IT DOESN'T EXISTS, and as you can see from show tables;. It does exists.. So, any ideas? -
fixtures Pytest in django module scope vs function scope
class TestShowOrderApi: @pytest.fixture(scope="module") def order(self, django_db_setup, django_db_blocker): with django_db_blocker.unblock(): return Order.objects.create() @pytest.fixture() def setup(self, order): self.url = "%s://%s/v1/management/order/%s" % (PROTOCOL, settings.API_HOST, order.number) self.headers = {'X-API-KEY': 'secret'} return self @pytest.mark.django_db(transaction=False) def test_it_should_return_200_when_merchant_show_his_order_via_api_v1(self, setup, order): order_json = OrderSchema().dump(order) response = requests.get(self.url, headers=self.headers) assert order_json == response.json()["payload"]['order'] this test is pass once the order fixture scope is module , when i change it to function scope the response return 404 of non finding the order object why is that ? -
OSError at /account/reset_password/ and also OSError at /student/register/ [Errno 99] Cannot assign requested address
The problem The error occurs when a user resets a password or when the user registers an account. The user gets the error during registration after setting email.send(fail_silently=False) This error occurs only in production environment, the project is working well in development environment Password Reset Error details myapp/urls.py from django.urls import path from django.contrib.auth import views as auth_views urlpatterns = [ path('reset_password/', auth_views.PasswordResetView.as_view( template_name="accounts/password_reset.html"), name="reset_password"), path('reset_password_sent/', auth_views.PasswordResetDoneView.as_view( template_name="accounts/password_reset_sent.html"), name="password_reset_done"), path('reset/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view( template_name="accounts/password_reset_form.html"), name="password_reset_confirm"), path('reset_password_complete/', auth_views.PasswordResetCompleteView.as_view( template_name="accounts/password_reset_done.html"), name="password_reset_complete"), ] settings.py ... other settings EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = 'my email address' EMAIL_HOST_PASSWORD = 'my email password' -
My React app is repeating the same error when using socket.io
I'm putting together a React web-app that uses Django for the backend server, coded in Python. At the moment, I'm attempting to change the data on a page when a new user joins. This is everything I have on the frontend to get this working: import io from 'socket.io-client'; let socket = io('http://127.0.0.1:8000'); class Room extends Component { constructor(props) { super(props); this.state = { chat: [{message:'Hello everyone'}] }; } componentDidMount() { socket.on('receive', data => { console.log(data); this.setState({chat:[...this.state.chat,data]}); }) } msgthreads = () => { return this.state.chat.map((msg, index)=>{ return <div key={index}> <p>{msg.message}</p> </div> }); } sendmessage =()=> { console.log(this.textInput.value); socket.emit('send',{message:this.textInput.value}); } some irrelevant code... render(){ return ( <div> {this.msgthreads()} </div> <div> <input type="text" className="form-control" ref={(input) => { this.textInput = input; }}/> <button onClick={this.sendmessage}>testbutton</button> </div> } export default Room; But this is the error that I'm getting: GET http://127.0.0.1:8000/socket.io/?EIO=4&transport=polling&t=NWlvd71 404 (Not Found) The error just keeps happening every few seconds, even when I'm doing anything. Is there something I have to do on the backend to get this working or is this a problem with the code above? -
Bootstrap 'row's not working but 'col's do
As the title says, I am pretty sure I set up bootstrap correctly and everything but running this page it shows me all the correct divs and and sized columns, however all the 'row' tags are ignored. they are just thrown all over the place. Shouldnt they be stacked one ontop of the other? I really dont want to hard code positions, i want this to be responsive. I have some CSS attatched to this but its the bootstrap giving me issues. <body> {% block body %} <div class='row banner'></div> <div class='row header'> <div class='col-4 image'></div> <div class='col-8 bio'></div> </div> <div class='row profile'> <div class='col-3' style='justify-content: center; align-items:flex-start;'></div> Followers <div class='followers'></div> <div class='col-6'></div> <div class='feed'></div> <div class='col-3' style='justify-content: center; align-items:flex-start;'> Following <div class='following'></div> </div> {% endblock %} </body> -
send Data from react to django rest api
after a lot of searching i keep finding how to send Data from react to django api using classes not functions so how would i convert this for exmaple to a functional component (this is not my code, just an example) export default class CreateRoomPage extends Component { constructor(props) { super(props); this.state = { guestCanPause: this.props.guestCanPause, votesToSkip: this.props.votesToSkip, errorMsg: "", successMsg: "", }; this.handleRoomButtonPressed = this.handleRoomButtonPressed.bind(this); this.handleVotesChange = this.handleVotesChange.bind(this); } handleGuestCanPauseChange(e) { this.setState({ guestCanPause: e.target.value === "true" ? true : false, }); } handleRoomButtonPressed() { const requestOptions = { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ votes_to_skip: this.state.votesToSkip, guest_can_pause: this.state.guestCanPause, }), }; fetch("/api/create-room", requestOptions) .then((response) => response.json()) .then((data) => this.props.history.push("/room/" + data.code)); } renderCreateButtons() { return ( <Grid container spacing={1}> <Grid item xs={12} align="center"> <Button color="primary" variant="contained" onClick={this.handleRoomButtonPressed} > Create A Room </Button> </Grid> </Grid> ); } } -
I try to run localhost Django for Webdevelopment but this error happen How can I solve it
You have 17 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions. Run 'python manage.py migrate' to apply them. March 14, 2021 - 13:57:58 Django version 3.0, using settings 'firstweb.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. Error: [WinError 10013] An attempt was made to access a socket in a way forbidden by its access permissions -
object has no attribute 'get' in django views
I am using the django version 3.0.11. I am going to make rest api using rest_framework. I think there is no problem url router and other parts. class DemoAPI( mixins.ListModelMixin, mixins.CreateModelMixin, mixins.UpdateModelMixin, mixins.DestroyModelMixin ): model = Demo serializer_class = DemoSerializer def __init__(self, obj, **kwargs): obj = super().__init__(**kwargs) self.bUseDefaultGetParam = False return obj def list(self, request, *args, **kwargs): queryset = self.get_queryset() if self.request is dict: query = self.request.GET.get('q', None) if query: condition = Q(demo_name__icontains=query) | Q(api_number__icontains=query) queryset = self.model.objects.filter(condition) else: queryset = self.model.objects.all() serializer = DemoSerializer(queryset, many=True) context = super().get_context_data(**kwargs) null_api = "0000000000" null_apis = Demo.objects.filter(api_number=null_api) demos = Demo.objects.exclude(api_number=null_api) context["null_apis"] = null_apis context["mapbox_access_token"] = os.getenv('MAPBOX_ACCESS_TOKEN') context["well_markers"] = [] for demo in demos: if not demo.surface_hole_longitude or not demo.surface_hole_latitude: continue context["well_markers"].append( { 'name': demo.demo_name, 'location': [ float(demo.surface_hole_longitude), float(demo.surface_hole_latitude), ] } ) context['data'] = serializer.data print("demos: ", serializer.data) return Response(context) When I tried to call this api, an error is occured. AttributeError at /api/demos/ 'DemoAPI' object has no attribute 'get' Request Method: GET Request URL: http://localhost:8000/api/demos/ Django Version: 3.0.11 Exception Type: AttributeError Exception Value: 'DemoAPI' object has no attribute 'get' Exception Location: /usr/local/lib/python3.7/dist-packages/livereload/middleware.py in process_response, line 22 Python Executable: /usr/bin/python3 Python Version: 3.7.3 Python Path: ['/app', '/usr/lib/python37.zip', '/usr/lib/python3.7', '/usr/lib/python3.7/lib-dynload', '/usr/local/lib/python3.7/dist-packages', '/usr/lib/python3/dist-packages'] Server time: … -
Django. Group by. Annotating queryset with pre-modification one of the columns
I have two simple models: transaction and category. Each transaction has category and amount (money) Categories have hierarchical structure (each category has parent category, except for one root category) In Django model view I have: class Transaction: category = models.ForeignKey(Category, on_delete=models.PROTECT, null=True) amount = models.DecimalField('amount', decimal_places=2, max_digits=10) class Category: name = models.CharField('name', max_length=200, null=True) parent_category = models.ForeignKey('self', on_delete=models.CASCADE, null=True) I have category hierarchy like: Root -> Food -> Pizza -> Apple -> Transport -> Taxi -> Bus I need to collect spending statistics by categories for particular month, sum all amounts for each category under Root (including sub categories) To group by all categories I did: Transaction.objects.filter(date__month=date.today().month) .values('category_id') .annotate(total_amount=Sum('amount')) I got stats like: Pizza = 100; Apple = 20; Taxi = 50; Bus = 10; And I need: Food = 120; Transport = 60; Mb I can calculate parent categories for Pizza/Taxi inplace by queryset methods before grouping -
Django TypeError: argument of type 'datetime.datetime' is not iterable
When I try to add a new field or modify my model in any way I get the following error when I try to migrate to the database: File "C:\Users\uddin\Envs\web\lib\site-packages\django\db\models\fields\__init__.py", line 1913, in get_prep_value if value and ':' in value: TypeError: argument of type 'datetime.datetime' is not iterable This is what my model.py file looks like from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django.urls import reverse from PIL import Image class Post(models.Model): title = models.CharField(max_length=100) title2 = models.CharField( max_length=100) content = models.TextField() content2 = models.TextField(default=None) post_image = models.ImageField(upload_to='post_pics') post_image2 = models.ImageField(upload_to='post2_pics') date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail', kwargs={'pk': self.pk}) Any help would be appreciated -
Accessing User Location ( Only City Name ) ( NOT Map )
I am building a BlogApp and I am stuck on a Problem. What i am trying to do I am trying to access user location like :- City or State. I don't want to access in Map. I just want to access the city name of users. What have i tried I try through JavaScript and Google Apis to access location , It showed the location perfectly. BUT i didn't find any way to save the location of User in Database from FrontEnd to BackEnd. So i dropped down that method. The Below ↓ code is showing the FrontEnd Code of JavaScript. <script> let thisElement = $(this) $.ajax({ url: "https://geolocation-db.com/jsonp","/update_counter/", jsonpCallback: "callback", dataType: "jsonp", success: function(location) { $('#country').html(location.country_name); console.log('success') thisElement.parent().parent().fadeOut(); } }); </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> <div>Country: <span id="country"></span></div> Then i tried MaxMind's GeoIP it also didn't work for me. Then i tried THIS BUT they are not connected to any model, so it may be difficult to save user location in DataBase. I don't know what to do. Any help would be appreciated. Thank You in Advance. -
NOT NULL constraint failed: api_student.author_id
I have 10 admin users, and each of them posts 20 posts. There will be 200+ posts in the Student API. I want to show admin only his own 20 posts. When I want to add a student I got IntegrityError. Exception Type: IntegrityError Exception Value: NOT NULL constraint failed: api_student.author_id Terminal ::: django.db.utils.IntegrityError: NOT NULL constraint failed: api_student.author_id Models.py Code = models.CharField(max_length=20, unique = True) fullName = models.CharField(max_length=200, blank = False) banglaName = models.CharField(max_length=200, blank = True) photo = models.ImageField(upload_to='facultyImages/', blank = True) author = models.ForeignKey(User, on_delete= models.CASCADE, default=None, null=True, editable=False) email= models.CharField(max_length=200, blank = True) Admin.py class StudentAdmin(admin.ModelAdmin): def get_queryset(self, request): qs = super(FacultyAdmin, self).get_queryset(request) return qs.filter(author=request.user) admin.site.register(Student, StudentAdmin) -
Django EMAIL ADDREAS field not in human readable form
I'm submitting a form and this is what appears to me on the admin page in the Email Address field: self.__class__.objects.normalize_email(self.email) How can I fix that I`m improving my English, be patient :D -
Realize a group by from a model having multiple foreign keys to the the same column of another table
following situation ModelA(django.db.models.Model): abc = ForeignKey('modelB', related_name="from abc") def = ForeignKey('modelB', related_name="from def") modelB(django.db.models.Model): Is there a way to achieve a GROUP_BY via ModelA.objects.values('some_magic_link_to_Model_B').annotate() instead of ModelA.objects.values('abc', 'def').annotate() (with the consequence to manually construct the result list because its results in grouped results of two keys) or do i have to consider adding a intermedia M2M transition? -
how to change the datetime format in admin panel?
I have an answer model with str method as defined below: class Answer(models.Model): created_at = models.DateTimeField(auto_now_add=True, null=True) def __str__(self): return "(" + str(self.created_at) + ")" I would like to show in this format Feb. 27, 2021, 6:55 p.m in the admin panel but it shows like this in admin panel How can i achieve the above format? Thanks for the help! -
Error while try to go forward or skip the videos in Django
I don't know if the problem is common or anyone faces this problem because I searched but I didn't find any solution for this problem, my problem is when I try to skip or go forward in any video it's didn't work or return me to the 0 s, so I tried a different video player to solve this problem but didn't work so the problem seems to come from Django, I tried to use a different database like Postgres from SQLite and it's didn't also work -
Show thumbnail in __str__ method in admin
I have an Image model where I have typically shown the filename in the __str__ method. I'd like to instead show a thumbnail of the image instead. Here's my model: class Image(models.Model): image = models.ImageField(upload_to='images/') def filename(self): return basename(self.image.name) def __str__(self): return self.filename() -
Initialize Model Class Global Variable At Runtime
I am trying to import student data from xlsx. I have to select column_name of StudentMasterResource class dynamically which is present in xlsx file. I got all column name in constants module has one dictionary which name column_name. When I do it for the first time, it works, then it fails resource.py from common_account import constants def getClassName(key): if key in constants.column_name: return constants.column_name[key] return key class StudentMasterResource(resources.ModelResource): organisation_id = fields.Field(column_name= getClassName('organisation_id'),attribute='organisation_id', widget = widgets.ForeignKeyWidget(OrganisationMaster, 'organisation_name'), saves_null_values=True) name = fields.Field(column_name= getClassName('Name'), attribute='name', saves_null_values=True, widget=widgets.CharWidget()) date_of_birth = fields.Field(column_name= getClassName('date'), attribute='date_of_birth', saves_null_values=True, widget=widgets.DateWidget())