Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
My CSS does not appear when I use "extend" and "block" in Django
I have spent half a day trying to figure this out. I ended up passing the CSS through the HTML style attribute. What do I have and tried: In settings.py I have included: django.contrib.staticfiles, `STATIC_URL = '/static/' In layout.html: {% load static %}, <link href="{% static 'auctions/styles.css' %}" rel="stylesheet"> The static files folders are orginized the following: MY_APP/static/auctions/styles.css And extending the layout and filling the body block, I have tried adding {% load static %} on top; I have put <link href="{% static 'auctions/styles.css' %}" rel="stylesheet"> afterwards and restarted the server, yet all this to no avail; -
Creating web card game for 4 players
I would like to make a web card game. Game should be for 4 players and it should wait for all players to connect and then start the game. Each player should see only his hand (not others hand), but all of them should see the same stack in the middle. My idea is that each player (when is on move) clicks on some card and that card will come to the middle where others will see it. There is specific order of players who is on a move. I would like to write this game in python and then use some JavaScript probably. I want to ask you what do you think is the easiest way to write this web app. I am struggling with the idea where should I write game's engine. Friend of mine has suggested me to use Django but I don't think this will solve my problem. As you probably noticed I am not very experienced in this stuff and that's why I am asking for an advice. Could you please give me an short advice how this all should be connected together and how should I continue? Thank you for your answers. -
How to add a plugin in a plugin Django CMS
I have create a plugin like http://docs.django-cms.org/en/latest/how_to/custom_plugins.html But i dont know how to add another plugin in this plugin . -
How do I add multiple authentications for a single user model in Django?
I have 3 user types (Customers, Vendors, Admins) which I have differentiated using their profiles. I want to have OTP based authentication for Customers from mobile (DRF) and Web app as well, user name and password based auth for Admins and Vendors from mobile (DRF) and Web app. How can I achieve this? Before downvoting, if the question is not clear, please comment below. -
How to get specific fields from a django model serializer which return all field(fields = '__all__' in serializer's meta)?
I have a serializer: class UsrSerializer(serializers.ModelSerializer): class Meta: model = Usr fields = '__all__' I don't want all fields but id, first_name, last_name and email here and don't want to modify serializer because I need all fields somewhere else: org = Organization.objects.get(pk=org_id) members = org.user_set.all() serializer = UsrSerializer(members, many=True) -
Live video stream problems with Django
I'm trying to stream live feed from my webcam into django. My code is very very similar to the code on this github page https://github.com/log0/video_streaming_with_flask_example (just using a StreamingHttpResponse instead of a response). I only added some keystroke features with pynput to control a cursor on the stream. The problem is my mac starts getting really slow after about 30-40 seconds or so to the point where I have to restart it. My main plan is to later transfer this system into a raspberry pi web server but my worry is that if it makes my mac freeze, whats its gonna do to the Pi? A solution I thought of was to maybe pause the stream or stop it but every time I try calling the VideoCamera.del() method the whole localhost server closes instead of the just the stream stopping. Some people were saying that it may be a memory problem but I mainly code in Python and I dont have much knowledge in terms of memory so if someone can help me out with that it would be great. I'm not sure if this is a problem with my computer or wifi or what. The raspberry pi is pretty … -
How to Keep Django Project Running After Putty Close?
i am new in django and i am uploading Django Project on digitalocean server first Time. My Upload is Successfull. i have Connected my digitalocean server Using Putty. when i run my Server ,it works Fine, but when i close Putty my Project Stopped Working .I have aplied following steps: sudo apt-get install screen Hit Ctrl + A and then Ctrl + D in immediate succession. You will see the message [detached] screen -r screen -D -r Howevver its not working. How to Keep running Djnago Project after closing Putty. i Can't find any valid Solution.How to do that? i Will be Thankful if any one can help me with this Issue. -
Using two submit buttons to save django inlineformset as draft
I have an inlineformset that works. I have attempted to add a second submit button, that when clicked will check that a particular field in each inline form has been filled out i.e. this field becomes a required filed only when the second submit button is clicked. The problem is that when I click this second submit button the validation errors don't appear and the form just seems to submit anyway. I think the issue is within my view, within form_valid. I'm not sure what I need to return when if form.is_valid() fails. I'm teaching myself to code, so any help or direction is much appreciated. Forms.py class response_form_draft(forms.ModelForm): class Meta: name = response exclude = ['id_question','order'] def __init__(self, *args, **kwargs): super(response_form_draft, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_show_labels = False class response_form_final(forms.ModelForm): class Meta: name = response exclude = ['id_question','order'] def __init__(self, *args, **kwargs): super(response_form_final, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_show_labels = False def clean(self): data = self.cleaned_data resp = data['response'] if resp == "": raise forms.ValidationError(('must not be blank')) checklist_formset_draft = inlineformset_factory(checklist, response, form = response_form_draft, extra=0, can_delete=False, widgets={'comments': forms.Textarea(attrs={'cols': 7, 'rows': 3, 'style':'resize:none'}) }) checklist_formset_final = inlineformset_factory(checklist, response, form = response_form_final, extra=0, can_delete=False, widgets={'comments': forms.Textarea(attrs={'cols': 7, 'rows': 3, … -
How to sort the list of query sets based on first name and last name using lambda in python?
Now I have the results based on the first name of the user using the below code : users.sort( key=lambda user:user.first_name) Here users is a list Ex: [<User: itnotify@awggases.com>, <User: aaron.debord@awggases.com>, <User: amy.sexton@awggases.com>, <User: andrew.funk@awggases.com>, <User: anthony.dieterle@amwelding.com>, <User: bill.neeley@amwelding.com>] I want a code which will sort users first name and last name using the same logic above -
Can not Upload Image from Form to Django Admin Model
I am trying to upload a Image from my Form (signup.html) and then i want that uploaded image name/url to be shown at Django admin models panel too. so i can access the image that user uploaded from the django admin panel. image upload feature is working in Django panel but when i upload it from my Form . my django admin is not saving it . it is also not saving any information like(email, bio,image). i already tried some solutions from stackoverflow but it didn't work. this is my views.py from django.shortcuts import render, redirect from .forms import CustomerForm from django.contrib import messages from django.contrib.auth.decorators import login_required from .models import Profile def register(request): if request.method == 'POST': form = CustomerForm(request.POST, request.FILES or None) if form.is_valid(): username = form.cleaned_data.get('username') email = form.cleaned_data.get('email') bio = form.cleaned_data.get('bio') image = request.FILES.get('image') form.save() messages.success(request, f'Account is created. ') return redirect('signin') else: form = CustomerForm() return render(request, 'Authentication/signup.html', {'form': form}) @login_required def UserAuth(request): return render(request, 'Authentication/profile.html') This is my forms.py below from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from .models import * class CustomerForm(UserCreationForm): first_name = forms.CharField(max_length=100, help_text='Preferred first Name') last_name = forms.CharField(max_length=100, help_text='Preferred Last Name') email = forms.EmailField() image … -
After creating virtual environment for installing Django
After creating virtual environment for installing Django, I have a non stopping blinking underscore with no feedback what I have is (my Environment)C:\Users\Smith\Desktop\djangoEnv>pip install Django blinking underscore "_ " on windows cmd -
AssertionError: Relational field must provide a `queryset` in Django Rest API even though one is provided
I'm trying to send my User -> Group foreign key to rest api to get the Group.name for display but when i use the serializer RelationalField(any of them) i get the following error: AssertionError: Relational field must provide a `queryset` argument, override `get_queryset`, or set read_only=`True`. even though I provided the queryset argument in my serializer class UserSerializer(serializers.ModelSerializer): group = serializers.SlugRelatedField(many=True, slug_field='name', queryset=Group.objects.all()) class Meta: model = User fields = ('pk', 'username', 'created_at', 'is_admin', 'group') I still get the error. Setting read_only='True' displayed the value but after that it wont let me change it. this is my GroupSerializer: class GroupSerializer(serializers.ModelSerializer): class Meta: model = Group fields = ('pk', 'name', 'description') these are the models I use: class Group(models.Model): name = models.CharField('Name', max_length=200,) description = models.CharField('Description', max_length=500) def __str__(self): return self.name class User(models.Model): username = models.CharField('Username', max_length=200) created_at = models.DateField('Created At', auto_now_add=True) is_admin = models.BooleanField('Is this user admin?', default=False) group = models.ForeignKey(Group, on_delete=models.CASCADE, null=True) def __str__(self): return self.username -
How to generate the json which looks like this using Django Rest Framework
I need to generate this below JSON Using Django. I need help in designing Models, Serializers and Views for generating this below JSON. I have no idea in doing this as this looks like nested JSON. { "ok": true, "members": [{ "id": "01FC991", "real_name": "John Anderson", "tz": "America/Los_Angeles", "activity_periods": [{ "start_time": "Feb 2 2020 1:33PM", "end_time": "Feb 2 2020 1:54PM" }, { "start_time": "Mar 2 2020 11:11AM", "end_time": "Mar 2 2020 2:00PM" }, { "start_time": "Mar 17 2020 5:33PM", "end_time": "Mar 17 2020 8:02PM" } ] }, { "id": "01FC992", "real_name": "James Anderson", "tz": "Asia/Kolkata", "activity_periods": [{ "start_time": "Feb 2 2020 1:33PM", "end_time": "Feb 2 2020 1:54PM" }, { "start_time": "Mar 2 2020 11:11AM", "end_time": "Mar 2 2020 2:00PM" }, { "start_time": "Mar 17 2020 5:33PM", "end_time": "Mar 17 2020 8:02PM" } ] } ] } -
Django filter related field using through model's custom manager
I have 2 models and a custom manager to filter out on active items: class List(models.Model): items = models.ManyToManyField("Item", through="ListItem") class ListItemManager(models.Manager): def get_queryset(self): return super(ListItemManager, self).get_queryset().filter(item__is_active=True) class ListItem(OrderedModel): item = models.ForeignKey("Item") objects = ListItemManager() Why does this not work as I would expect? active_list_items = List.objects.first().items # Contains items with `is_active=False` :( What is the correct way to filter out non active items through my through model? -
NoReverseMatch at / Reverse for 'create_order' not found. 'create_order' is not a valid view function or pattern name. Django question
**Dashboard file** <div class="col-md-7"> <h5>LAST 5 ORDERS</h5> <hr> <div class="card card-body"> <a class="btn btn-primary btn-sm btn-block" href="{% url 'create_order' %}">Create Order</a> <table class="table table-sm"> <tr> <th>Product</th> <th>Date Orderd</th> <th>Status</th> <th>Update</th> <th>Remove</th> order_form.html...I need an extra pair of eyes for this problem, cant find for hours what syntax mistake have I made this time or if django syntax rules changed after some update I dont konw about, from some reason, it just cannot find the create_order. Hope you guys can help and find it easily, it would help a ton {% extends 'accounts/main.html' %} {% load static %} {% block content %} <form action="" method="POST"> <input type="submit" name="Submit"> </form> {%endblock%} urls.py file from django.urls import path from . import views urlpatterns = [ path('', views.home, name="home"), path('customer/<str:pk>/', views.customer, name="customer"), path('products/', views.products, name="products"), path('create_order/', views.createOrder, name="create_order"), ] views.py file from django.shortcuts import render from django.http import HttpResponse from.models import * def home(request): customers=Customer.objects.all() orders=Order.objects.all() total_customers=customers.count() total_orders=orders.count() delivered=orders.filter(status="Delivered").count() pending=orders.filter(status="Pending").count() context={'orders':orders,'customers':customers, 'pending':pending, 'delivered':delivered,'total_orders':total_orders} return render(request, 'accounts/dashboard.html',context) def products(request): products = Product.objects.all() return render(request, 'accounts/products.html',{'products' :products}) def customer(request, pk): customer=Customer.objects.get(id=pk) orders=customer.order_set.all() order_count=orders.count() context={'customer': customer, 'orders': orders,'order_count':order_count} return render(request, 'accounts/customer.html', context) def createOrder(request): context={} return render(request, 'accounts/order_form.html',context) error by django NoReverseMatch at / Reverse for 'create_order' … -
why this problem appear when run this code to locate the position by use geoip2 in django?
I am working on a project to determine the location of the person using the IP using the 'geoip2' and 'geopy'. I have finished that and when I run this message appeared to him. The address 127.0.0.1 is not in the database. This is the code: -
I have recently faced this problem I am not able to solve this problem properly can some one please help me
Question: List some things that you could do to this function, to make it less verbose and more robust. I am quite new in django forms. I am woking on problem where in function name generate_outage_form passed two parameters name settings and segment Now I have to make function less verbose and more robust. def generate_outage_form(settings, segment=None): form = None datacenters = settings.get('datacenters') datacenters = get_and_sort(datacenters, 'abbreviation') departments = settings.get('departments') departments = get_and_sort(departments, 'name') outage_types = settings.get('outage_types', []) outage_causes = settings.get('outage_causes', []) outage_impacts = settings.get('outage_impacts', []) # Put a check to determine what form should be shown if not segment: if session.get('division'): dc_search = re.search(r'global dc', session.get('division'), re.I) ent_search = re.search(r'support', session.get('division'), re.I) if dc_search: form = forms.RecordDCOutage() segment = 'datacenter' if ent_search: form = forms.RecordSupportOutage() segment = 'support' if not form: form = forms.RecordDCOutage() segment = 'datacenter' else: form = forms.RecordSupportOutage() segment = 'support' else: if segment == 'datacenter': form = forms.RecordDCOutage() elif segment == 'support': form = forms.RecordSupportOutage() else: form = forms.RecordSupportOutage() segment = 'support' form.outage_type.choices = [ ( i_type.get('name'), i_type.get('name') ) for i_type in outage_types if ( i_type.get('active') and i_type.get(segment) ) ] form.outage_type.choices.insert(0, ('', '')) form.outage_cause.choices = [ ( cause.get('name'), cause.get('name') ) for cause in outage_causes if … -
Django admin - Filter foreignKey in an Inline
I have these models: class Country(models.Model): name = models.CharField(unique=True, max_length=50) class Person(models.Model): name = models.CharField(max_length=50, blank=True, null=True) country = models.ForeignKey(Country, models.DO_NOTHING, db_column='countries', blank=True, null=True) class Organization(models.Model): name = models.CharField(max_length=50, blank=True, null=True) class Membership(models.Model): person= models.ForeignKey(Person, models.DO_NOTHING, db_column='people', blank=True, null=True) organization= models.ForeignKey(Organization, models.DO_NOTHING, db_column='organizations', blank=True, null=True) There are a high number of people (over 1000) that can be members of several organizations. I have a view in the admin page as follows class MembershipInline(admin.StackedInline ): model = Membership extra = 1 class OrganizationAdmin(admin.ModelAdmin): inlines = [MembershipInline] admin.site.register(Organization,OrganizationAdmin) Therefore I can manage any organization and see the people that belongs to it. I can also add new people to the organization. The problem is that the number of people is too high and the list shows too many of them. Is there any way to filter this StackedInline? For example placing another field in the Inline where a country can be chosen to filter the people that can be added, or a search field to filter the person's name. Thanks in advance! -
Invalid email adress error when sending email via Django
I try to send email using send_mail but gt the error smtplib.SMTPSenderRefused: (501, b'5.1.7 Invalid address', '=?utf-8?q?django?=') I try in a shell but have the same error >>> from django.core.mail import send_mail >>> subject = 'subject' >>> message = 'message test' >>> email_from = 'django' >>> recipient_list = ['user@hotmail.fr'] ***-> I am sure my email adress is valid*** >>> send_mail(subject, message, email_from, recipient_list) -
Invalid Load Key '8' error while loading pickle
I am building a Machine Learning Model in which i have saved TfidfVectorizer to pickle.i am trying to use pickle dump but it is giving me error.It is working fine in Jupyter Notebook but when i am implement in Django api its give me error. final_tf_idf = TfidfVectorizer(max_features=5000) final_tf_idf.fit(reviews) with open("final_tf_idf.pkl", 'wb') as file: pickle.dump(final_tf_idf, file) with open("final_tf_idf.pkl", 'rb') as file: vectorizer = pickle.load(file) -
AssertionError: Relational field must provide a `queryset` in Django Rest API even though one is provided
I'm trying to send my User -> Group foreign key to rest api to get the Group.name for display but when i use the serializer RelationalField(any of them) i get the following error: AssertionError: Relational field must provide a `queryset` argument, override `get_queryset`, or set read_only=`True`. even though I provided the queryset argument in my serializer class UserSerializer(serializers.ModelSerializer): group = serializers.SlugRelatedField(many=True, slug_field='name', queryset=Group.objects.all()) class Meta: model = User fields = ('pk', 'username', 'created_at', 'is_admin', 'group') I still get the error. Setting read_only='True' displayed the value but after that it wont let me change it. -
Django Rest Framework enforce CSRF
I am trying to enforce CSRF for a Django Rest API which is open to anonymous users. For that matter, I've tried two different approaches: Extending the selected API views from one CSRFAPIView base view, which has an @ensure_csrf_cookie annotation on the dispatch method. Using a custom Authentication class based on SessionAuthentication, which applies enforce_csrf() regardless of whether the user is logged in or not. In both approache the CSRF check seems to work superficially. In case the CSRF token is missing from the cookie or in case the length of the token is incorrect, the endpoint returns a 403 - Forbidden. However, if I edit the value of the CSRF token in the cookie, the request is accepted without issue. So I can use a random value for CSRF, as long as it's the correct length. This behaviour seems to deviate from e.g. the regular Django login view, in which the contents of the CSRF do matter. I am testing in local setup with debug/test_environment flags on. What could be the reason my custom CSRF checks in DRF are not validated in-depth? -
Django model using hashmap
I have a question about how to properly model my data in Django (and later in graphene). I have a model exam which consists of date, subject, participants, results where subject,participants, results are references to other objects. I could of course have two lists of participants and results however it would be practical to have a map of type: pseudocode: results= map(participant,result) To be honest I do not know if this is even possible without introducing a additional model object participant_results Any insight very welcome. Benedict -
React native code is unable to send data to django admin
I am a beginner and I'm using Django in the backend of my react native app. I am unable to add data to the django admin panel from my app using fetch method. I am not getting any errors but my data is not getting posted to the backend.I have used the django api as the url in fetch method. Please let me know if any other code snippet is required to check. Would appreciate some help here. export class LoginScreen extends Component { constructor() { super(); this.state = { email: '', name: '', }; } updateValue(text, field) { if (field == 'email') { this.setState({ email: text, }); } else if (field == 'pwd') { this.setState({ pwd: text, }); } } submit() { let collection = {}; collection.email = this.state.email; collection.pwd = this.state.pwd; console.warn(collection); let url='http://10.0.0.2:8000/admin/mdlApp/mdlapp/add/' fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(collection), }) .then((response) => response.json()) .then((collection) => { console.log('Success:', collection); }) .catch((error) => { console.error('Error:', error); }); } render() { return ( <ImageBackground source={require('../images/bg4.png')} style={styles.bg}> <SafeAreaView style={styles.container}> <Logo /> <View style={styles.container1}> <TextInput style={styles.inputBox} name="email" placeholder="Enter Your Email" placeholderTextColor="#ffffff" onChangeText={(text) => this.updateValue(text, 'email')} /> <TextInput style={styles.inputBox} name="pwd" placeholder="Enter Your Password" secureTextEntry={true} placeholderTextColor="#ffffff" onChangeText={(text) => this.updateValue(text, … -
Convert vimeo link into an embed link in python
I am using Python and Flask, and I have some vimeo URLs I need to convert to their embed versions. For example, this: https://vimeo.com/76979871 has to be converted into this: https://player.vimeo.com/video/76979871 but Not converted My code is below: _vm = re.compile( r'/(?:https?:\/\/(?:www\.)?)?vimeo.com\/(?:channels\/|groups\/([^\/]*)\/videos\/|album\/(\d+)\/video\/|)(\d+)(?:$|\/|\?)/', re.I) _vm_format = 'https://player.vimeo.com/video/{0}' def replace(match): groups = match.groups() print(_vm_format) return _vm_format.format(groups[5]) return _vm.sub(replace, text)