Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django-Celery Scheduling Daily Tasks
I have to schedule a task to run every Monday through Saturday. I downloaded django-celery to accomplish the task. I followed the tutorial on the Celery site and I used and looked at a few stack overflow posts, for example: here & here I did a mix and match with the above posts and with this two great tutorials: Rhatore and Freitas I've been stuck for more than 8 hours and I think I've come along as far as I can on my own. Any help would be greatly appreciated. I downloaded RabbitMQ. Settings.py INSTALLED_APPS = [ 'apps.app1', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True CELERY_BROKER_URL = 'amqp://localhost' BROKER_URL = 'amqp://localhost' CELERY_RESULT_BACKEND = 'amqp://localhost' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' CELERY_TIMEZONE = 'UTC __init__.py from __future__ import absolute_import, unicode_literals from .celery import app as celery_app from .celery import app as celery_app __all__ = ('celery_app',) celery.py from __future__ import absolute_import, unicode_literals import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'Application.settings') app = Celery('Application') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) tasks.py - for simplicity sake I reduced the task to a simple print … -
Django model organization: food item locations in different grocery stores
I'm working on a cookbook app and I want to sort the ingredients of a recipe by their aisle in the grocery store. Since different grocery stores have different configurations, I want users to be able to sort the lists of ingredients by a selected store. I'm new to Django and am stuck on figuring out the models that I'll need for this. I think I want to have a many to many relationship between my Food model and a Store model. I think I want to use the through argument and have another intermediary Location model that connects the 'Food' and 'Store' and also contains which the aisle. If possible, I'd like to have the choices for aisle have a certain description that depends on the selection of the Store object class Food(models.Model): name = models.CharField(max_length=100) grocery_aisle = models.ManytoManyField(Store, through='Location') class Store(models.Model): name = models.CharField(max_length=100) aisles = { # Not really sure how to store this kind of information which would be different for each Store object. 0: 'Produce Section', 1: 'Aisle 1: bread and peanutbutter', 2: 'Frozen Desserts', 3: 'Pharmacy' } class Location(models.Model): food = models.ForeignKey(Food, on_delete=models.CASCADE) store = models.ForeignKey(Store, on_delete=models.CASCADE) aisle = models.SmallIntegerField(choices=MEASUREMENT_CHOICES) # option descriptions depend … -
__str__ returned non-string (type takimlar)
hi i couldn't solve this problem. I would appreciate if you help. class Musabaka(models.Model): kuno=models.ForeignKey(Club,on_delete=models.CASCADE,verbose_name="Kulüp") seno=models.ForeignKey(Sezon,on_delete=models.CASCADE,verbose_name="Sezon") rano=models.ForeignKey(takimlar,on_delete=models.CASCADE,verbose_name="Rakip Takım") katno=models.ForeignKey(Kategori,on_delete=models.CASCADE,verbose_name="Kategori") mtarih=models.DateTimeField(auto_now_add=False,verbose_name="Müsabaka Tarihi") def __str__(self): return self.rano how should I try a method class takimlar(models.Model): kno=models.ForeignKey(Club,on_delete=models.CASCADE) takim=models.CharField(max_length=50) created_date=models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.takim) -
A simple question about POST and GET request
I just started to learn Django (sorry if my english is bad :/ ) by following a sentdex tutorial. During the course, we added a User model into our database (please correct me if I'm wrong), and we created a function in our views.py file: def register(request): if request.method == "POST": form = UserCreationForm(request.POST) if form.is_valid():#si les champs sont OK : user = form.save() login(request, user) return redirect("main:homepage") else: for msg in form.error_messages: print(form.error_messages[msg]) But In this piece of code, I don't understand how Django knows if the request.method is True or False. Is it because I created a form with a Submit button in my template ? Thank you so much for your help :) Valentin -
Django Custom model manager and Modeladmin
I have an app called article. I want to hide articles with hidden = True. All hidden articles should not be findable except for admins. I'm using a custom manager and I'm using a custom Modeladmin. my custom modeladmin: class ArticleAdmin(admin.ModelAdmin): def get_queryset(self, request): qs = super().get_queryset(request) if request.user.is_superuser: return qs return qs.filter(hidden=False) my custom manager: class ArticleManager(models.Manager): def get_queryset(self): qs = super().get_queryset() return qs.filter(hidden=False) -
How to reload page with invalid form on user input error
I am using django to create a signup form for new users. I would like the page to reload with the invalid form and a custom error message if the user inputs are invalid. So basically I am trying to find a way to return the invalid form along with the page reload on the else statement. <div id="signupboxelementscontainer"> <form action="" method="post" name="signupform"> {% csrf_token%} <div id="namerow" class="row"> <input name="firstname"id="firstname" class="formelements" placeholder="First name" type="text"> <input name="lastname" id="lastname" class="formelements" placeholder="Last name" type="text"> </div> <input name="email" id="email" class="formelements" placeholder="Email address" type="email"> <br> <input name="storename" id="storename" class="formelements" placeholder="Your store name" type="text"> <input name="password" id="password" class="formelements" placeholder="Password" type="password"> <br> <input name="passwordagain" id="passwordagain" class="formelements" placeholder="Retype password" type="password"> <br> <div class="row"> </div> <button id="submitbutton" type="submit"> Submit</button> </div> <p>Already have an account? <a href="{% url 'login'%}">Sign in</a> </p> <p id="error">{{ error_message }}</p> </div> def signup(request): if request.method == "POST": signupform = signupform(request.POST) first_name = request.POST.get("firstname") last_name = request.POST.get("lastname") email = request.POST.get("email") storename = request.POST.get("storename") password = request.POST.get("password") passwordagain = request.POST.get("passwordagain") if password == passwordagain: user = User.objects.create_user(first_name=first_name,last_name=last_name,email = email, password = password, username=storename) else: error_message = "Your passwords do not match" return render(request,'main/signup.html', {"error_message": error_message,"signupform": signupform,}) return render(request, "main/signup.html",) -
Use credential of login django-allauth to send message with fbchat
I'm learning Django and I have been introduced with the social authentication provided by django-allauth that allows to login a user with his/her facebook account. Now, I would like to use fbchat to, .e.g, send a message. Is it possible to log in a client in fbchat with the django-allauth credentials? -
Django - FilterSet and Paginator
I would like to combine FilterSet and Paginator idea is to add a pagination to my FilterSet. I guess something is wrong with the request.GET but can't find it.. def articles_overview(request): f = ArticleFilter(request.GET, queryset=Article.objects.all()) paginator = Paginator(f.qs, 5) page = request.GET.get('page') art = paginator.get_page(page) return render(request, 'arti/overview.html', {'filter': art}) I don't see my list nor a pagination in the browser. When I eliminated everything linked to the pagination I have a good list on which I can filter.. -
How to migrate django auth to firebase auth with the Strangler Pattern in mind
I have the task to migrate the django auth part 1.8~1.11 to firebase auth, with the Strangler Pattern https://docs.microsoft.com/en-us/azure/architecture/patterns/strangler has the main rule, the first thing that I think is make a custom provider for allauth django plugin. but don’t know is this is the right path to go. Using the Strangler Pattern mean, that the User will login in the current app in production (django), but at the same time with firebase auth app in development, and vice versa. I have some advances, mostly in the firebase part. The To-Do that I have: [Done] Migrate the current users with the firebase-tools, Current users can login with the same password in firebase. https://github.com/firebase/firebase-tools/issues/1088 [ ] Login firebase and the same time in django and vice versa. I have the idea that the custom provider will link the local and social accounts on django with the firebase custom provider, this part is not clear yet to me. Basically I’m very noob with django and python. So I need some insights to get and define the right tasks for the next spring. -
Trying to use embedly with Django Rest Framework
I'm starting this project using Django Rest Framework as backend to build Rest Api. Whenever the user post a status I want to check if it has a link and then use Embedly to retrieve informations from the url. Here's my code my serializer class PostSerializer(serializers.ModelSerializer): user = UserPublicSerializer(read_only=True) url = serializers.SerializerMethodField() class Meta: model = Post fields =[ 'id', # ? 'user', 'content', 'code', 'url', ] read_only_fields = ['user', 'url'] def get_url(self, obj): request = self.context['request'] url = request.data.get('url') client = Embedly('174a6178b2894201a888b82e0f3c4c9a') url = client.oembed('http://instagram.com/p/BL7ti/') print(url) return url def validate(self, data): content = data.get("content", None) if content == "": raise serializers.ValidationError("Content or image is required.") return data my view class PostAPIView(mixins.CreateModelMixin, generics.ListAPIView): permission_classes = [permissions.AllowAny] serializer_class = PostSerializer queryset = Post.objects.all() def post(self, request, *args, **kwargs): return self.create(request, *args, **kwargs) def perform_create(self, serializer): serializer.save(user=self.request.user) Know the problem is when I want to access the url in the backend after using embedly it gives me this (the print(url) returns this) <Oembed http://instagram.com/p/BL7ti/> So I can't use it to retrieve informationsBut the response in the frontend returns a proper object with all the value needed (title, description, thumbnail etc..) I'm new to Django I don't understand why I need to access … -
Picture does't show in the django admin page
Hey guys so i have a field in my database that contains the url to a picture. So when i check a user, or when i wan't to modify one i get : enter image description here So the question is : how can i show the image instead of the whole thing . My code : models.py class Person(models.Model): nom = models.CharField(max_length=255) prenom = models.CharField(max_length=255) age = models.IntegerField() photo = models.ImageField(upload_to='static/media') def __str__(self): return str(self.id) def image_tag(self): return u'<img src="/media/%s" />' % self.photo #return mark_safe('<img src="/static/%s" width="150" height="150" />' % (self.image)) image_tag.short_description = 'Image' image_tag.allow_tags = True admin.py : class PersonAdmin(admin.ModelAdmin): list_display = ['id','nom','prenom','age','photo'] fields = ( 'nom','prenom','age','image_tag' ) readonly_fields = ('image_tag', ) Thanks in advance. -
Django-FormView and form validation issue
My problem is that even if I put 2 differents password the error message is not showing up, but if I put a password that is less than 6 character the error message appears class RegistrationForm(forms.Form): email = forms.EmailField() password = forms.CharField(min_length= 6, widget=forms.PasswordInput()) confirm_password = forms.CharField(min_length= 6, widget=forms.PasswordInput()) registration_date = forms.DateField() def clean(self): password = self.cleaned_data.get('password') confirm_password = self.cleaned_data.get('confirm_password') if password != confirm_password: raise ValidationError("Password error") Here is my view: class Registration(FormView): template_name = 'accounts/registration.html' form_class = RegistrationForm success_url = reverse_lazy('accounts:index') def form_valid(self, form): # my stuff... How can I force to have that sort of "popup" even when the 2 password are different and not only when a password is less than 6 character? -
Django file name changed on file upload
I am trying to upload a file using a form, save it to a directory, and save the file path to the database. So far, I can upload a file and save its path but the name of the file is changed to some random string like _i1qky6X or _f8d66HN rather than hello.py. Thanks. views.py class MapUploadView(FormView): form_class = MapUploadForm template_name = 'maps/upload_map.html' def form_valid(self, form): try: savePath = settings.BASE_DIR + '/documents/' filename = form.cleaned_data.get('file') default_storage.save(savePath, filename) map = Map() map.file = savePath + str(filename) map.floor_num = form.cleaned_data.get('floor_num') map.save() return HttpResponse("a new map was uploaded") except Exception as e: return HttpResponse(str(e)) models.py class Map(models.Model): file = models.FileField() floor_num = models.IntegerField('Floor', null=False, blank=False) def __str__(self): return self.file forms.py class MapUploadForm(forms.ModelForm): class Meta: model = Map fields = ('floor_num', 'file') -
How to upload image in cPanel in django?
OS == CentOS7 Python == 3.6.5 Django == 1.8 I have a "news" app in my Django project. And in the models of this app has ImageField. Trying to upload an image with .jpg format in django admin interface, it is in cPanel. But whenever uploading bar completes in 100%, it throws me to "Not Found" page, and says that The requested URL /admin/news/post/add/ was not found on this server. I thought it is server side problem, but when contacted with hosting provider's support team. They said it is code side problem not theirs. There is no permission to any apache nor nginx. OS Main urls.py # from django.urls import path from django.conf.urls import include, url from django.conf import settings from django.conf.urls.static import static from django.contrib.staticfiles.urls import staticfiles_urlpatterns from django.views.static import serve urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'^news/', include('news.urls')), url(r'^i18n/', include('django.conf.urls.i18n')), ] if settings.DEBUG is False: urlpatterns += [ url(r'^media/(?P<path>.*)$', serve, { 'document_root' : settings.MEDIA_ROOT,}), ] (news)app url, news/urls.py from . import views urlpatterns =[ url(r'^$', views.NewsView.as_view(), name='posts'), url(r'^i18n/', include('django.conf.urls.i18n')), url(r'^index', views.search, name="search"), url(r'^chaining/', include('smart_selects.urls')), url(r'^league/(?P<pk>[0-9]+)/$', views.league_detail, name='league_detail'), ] (news) app models.py NOTE! Error is in Post class'es ImageField: # from django.contrib.auth.models import User from django_userforeignkey.models.fields import UserForeignKey # import … -
Unable to create instance of Django model
I'm trying to create an instance of this Report model: class Report(models.Model): """ A model for storing credit reports pulled from Equifax. """ user = models.ForeignKey(to=CustomUserModel, on_delete=models.CASCADE, help_text='User report belongs to.') timestamp = models.DateTimeField(default=timezone.now) report = JSONField() However, whenever I try I get this error: Exception Type: TypeError at /internal/report Exception Value: 'report' is an invalid keyword argument for this function This happens whether I instantiate the instance using the Report().save() method, or the Report.object.create() method as follows: report_obj = Report.objects.create( user=user, report=report ) Does anyone have any clue what's going on? There is very clearly a "report" attribute for that class, so why the error? Thanks! -
Deactivation of the form field using bootstrapa 4
I am trying to deactivate the 'charfield' field for my forms, can I do it using the bootstrapa class? If so, how to correctly enter my 'form.compartment' field in html tags that provide it: html file <form action="." method="post"> {% csrf_token %} {{ time_edit_form.management_form }} {% for form in time_edit_form %} {{ form.id }} <ul> <li>{{ form.free_or_no|as_crispy_field }}</li> <li>{{ form.compartment|as_crispy_field }}</li> </ul> {% endfor %} <button type="submit" class="btn btn-block btn-primary"> Zapisz</button> </form> bootstrap 4 (deactivating the field) <div class="form-group"> <input type="text" class="form-control" placeholder="Disabled" disabled> </div> -
How do I adjust my Python regex to only include numbers?
I'm using Django and Python 3.7. I have text in a HTML element that looks like (2 votes) and I want to extract the number portion of that. I tried this m = re.match(r'\s*([-+])?\d+', elt_text) but this results in m.group() Out[24]: '(2' but I would like the match to only include the numbers, e.g. "2". How do I adjust my regex so that only the number portion is extracted in the m.group() ? -
how to fix not a callable attribute error in admin.py in custom user model in dajango?
i m just trying to get custom user model. server was running fine when i created User class in model.py and forms in forms.py. but after creating UserAdmin class in admin.py i m getting not a collable attribute error. even i do not have any attribute named as first_name or last_name nither i do have need of them. so how to get rid of that error?? //admin.py User=get_user_model() class UserAdmin(BaseUserAdmin): add_form=UserCreationForm list_dispalay=('username','email','is_admin',) list_filter=('is_admin',) fieldsets=( (None,{'fields':('username','email','password')}), ('permissions',{'fields':('is_admin',)}) ) search_fields=('username','email') ordering=('username','email') filter_horizontal=() admin.site.register(User,UserAdmin) admin.site.unregister(Group) //forms.py User=get_user_model() class UserCreationForm(forms.ModelForm): password1 = forms.CharField(label='Password', widget=forms.PasswordInput) password2 = forms.CharField(label='Password confirmation', widget=forms.PasswordInput) class Meta: model=User fields=['username','email'] def clean_password(self): # Check that the two password entries match password1 = self.cleaned_data.get("password1") password2 = self.cleaned_data.get("password2") if password1 and password2 and password1 != password2: raise forms.ValidationError("Passwords don't match") return password2 def save(self, commit=True): # Save the provided password in hashed format user = super(UserCreationForm, self).save(commit=False) user.set_password(self.cleaned_data["password1"]) if commit: user.save() return user class UserLoginForm(forms.Form): query=forms.CharField(label='Username/Email') password=forms.CharField(label='Password',widget=forms.PasswordInput) def clean(self,*args,**kwargs): query=self.cleaned_data.get('query') password=self.cleaned_data.get('password') user_qs_final=User.objects.filter( Q(username__iexact=query)| Q(email__iexact=query) ).distinct() if not user_qs_final.exists() and user_qs_final!=1: raise forms.ValidationError("Invalid credentials-user does not exits") user_obj=user_qs_final.first() if not user_obj.check_password(password): raise forms.ValidationError("credential are wrong") self.cleaned_data["user_obj"]=user_obj return super(UserLoginForm,self).clean(*args,**kwargs) //models.py class UserManager(BaseUserManager): use_in_migrations = True def create_user(self,username,email,password=None,is_admin=False,is_survilance=True,is_staff=False): #if not email: #raise ValueError('user must have email … -
Object has no attribute 'entry_set' error
I'm new to Python, trying to work through Python Crash Course and I've run into a problem that I can't figure out. Here's my error: 'Pizza' object has no attribute 'entry_set' In my model I have the foreign key defined to Pizza in Toppings and it works fine, but I apparently don't understand the entry_set definition. Here's my URL code: from django.urls import path from . import views app_name = 'pizzas' urlpatterns = [ # home path path('', views.index, name='index'), # show all pizza names path('names/', views.names, name='names'), # show all pizza toppings path('toppings/', views.toppings, name='toppings'), # show a pizza and it's toppings path('names/<int:name_id>/', views.pizza, name='pizza'), ] Here's my view code (as you can see, I have the entry_set): def pizza(request, name_id): """Show a single pizza and all it's toppings""" name = Pizza.objects.get(id=name_id) toppings = name.entry_set.order_by('topping') context = {'name': name, 'toppings': toppings} return render(request, 'pizzas/pizza.html', context) And lastly, my HTML code: {% extends 'pizzas/base.html' %} {% block content %} <p>{{ name }}</p> <p>Toppings:</p> <ul> {% for topping in toppings %} <li> <p>{{ topping|linebreaks }}</p> </li> </ul> {% endblock content %} Here's the models.py: from django.db import models class Pizza(models.Model): """Pizza names """ name = models.CharField(max_length=50) def __str__(self): """Return a string … -
Forbidden You don't have permission to access / on this server (apache2)
I am deploy my django app to Linode and i am using apache2 as server. When i first deploy my app it was doing fine running with the default django server, but when i configured apache2, i started getting the Forbidden You don't have permission to access / on this server. Apache/2.4.34 (Ubuntu) Server at 139.162.56.162 Port 80. I have research on stackoverflow and can't find any useful answer. Here is my code # The ServerName directive sets the request scheme, hostname and port that # the server uses to identify itself. This is used when creating # redirection URLs. In the context of virtual hosts, the ServerName # specifies what hostname must appear in the request's Host: header to # match this virtual host. For the default virtual host (this file) this # value is not decisive as it is used as a last resort host regardless. # However, you must set it for any further virtual host explicitly. #ServerName www.example.com ServerAdmin webmaster@localhost DocumentRoot /var/www/html # Available loglevels: trace8, ..., trace1, debug, info, notice, warn, # error, crit, alert, emerg. # It is also possible to configure the loglevel for particular # modules, e.g. #LogLevel info ssl:warn ErrorLog ${APACHE_LOG_DIR}/error.log … -
AWS ELB Health check path doesn't seem to access my health check path in Django
I'm using Django on my website. I made a health check url in my app by doing the following. views.py def health(request): return HttpResponse("OK") urls.py urlpatterns = [ path('health/', global_views.health, name='health'), ... ] It just shows OK text in the screen with 200 status which seems enough for health check as I looked it up. So, in my Elastic Beanstalk, I set "Health check path" to be /health under "Monitoring" in "Configurations". However it still shows the error message like www.example.com is currently unable to handle this request. (HTTP ERROR 503) -
Python subprocess.Popen() not working in a docker container - works fine locally
I have created a Django REST framework project that I want to deploy on a server. I do not have admin access to the server, and so, the only way I found to ensure that all the project dependencies (such as Anaconda distribution) will be available on the server, is to create a docker image for my project , then create a corresponding container on the server, then run it from there. In my project, I have a python script (mymain.py) that gets called using subprocess.Popen(). This works fine locally, and subprocess.Popen() does everything it is supposed to do. However, when I try to do it from the docker container, it seems as if the line subprocess.Popen() was completely skipped [mymain.py is not called]. For docker, I have created a docker-compose.yml file, and in command prompt I type: docker-compose up I do not see any error, and everything seem to be working fine, however subprocess.Popen() does not seem to be working. mymain.py first line is: print('Testing if subprocess called mymain.py!!!') This is how I am using subprocess.Popen (different file) in my code. I tried printing out the error, but unfortunately, both stdout and stderr return nothing. This is how I … -
How to Create a Django Model Instance That Contains a Required OneToOneField with DRF Serializers
The Question Let's say I have a model that contains a OneToOneField like so: models.py class Event(models.Model) # some basic fields... class EventDetail(models.Model): event = models.OneToOneField(Event, on_delete=models.CASCADE, related_name='event_detail') # other basic fields, all with default values... What is a proper way to implement a POST request that intends to create a new Event in the database that automatically creates a default EventDetail linked to it if it is None in the request header, using Django Rest Framework's Serializers? My Attempt test.py class EventTestCase(APITestCase): def test_post(self): # Need to provide an id, or else an error occurs about the OneToOneField event = Event(id=1) serializer = serializers.EventSerializer(event) res = self.api_client.post('/event/', serializer.data) views.py def post(self, request, format=None): serializer = EventSerializer( data=request.data) # ***This always returns false!*** if serializer.is_valid(): try: instance = serializer.save() except ValueError: return Response(status=status.HTTP_400_BAD_REQUEST) serializers.py class EventSerializer(serializers.ModelSerializer): serialization_title = "Event" event_detail = EventDetailSerializer() class Meta: model = Event exclude = ('id',) error_status_codes = { HTTP_400_BAD_REQUEST: 'Bad Request' } class EventDetailSerializer(serializers.ModelSerializer): serialization_title = "Event Detail" class Meta: model = models.EventDetail exclude = ('id',) error_status_codes = { HTTP_400_BAD_REQUEST: 'Bad Request' } As noted in a comment above, serializer.is_valid() always returns false with the error: {'event_detail': [u'This field may not be null.']} I understand … -
What's the model(or name) who calls shared method to save the reference?
I have a catalog to save all address from any "form" in django admin (called by models.ForeignKey), with street, number, city, that's Okay - but I want to save the name of field(or class, or filename, something ) that invoked this address method, to save together address information any reference about the source asked for class TraderClass(models.Model): trader_ID = models.AutoField(primary_key=True) caller #1 address_enterprise = models.ForeignKey(AddressClass, on_delete=models.CASCADE, default=None, verbose_name='Address') class EnterpriseClass(models.Model): enterprise_ID = models.AutoField(primary_key=True) caller #2 address_project = models.ForeignKey(AddressClass, on_delete=models.CASCADE, default=None, verbose_name='Address') The Address class AddressClass(models.Model): ID = models.AutoField(primary_key=True) address_source = models.CharField(max_length=32, default=__qualname__,verbose_name='Origin') __qualname__ only shows the same class "AddressClass" I need something like TraderClass/EnterpriseClass OR address_enterprise/address_project or anything I can save with the address -
Integrating view-flow with google-drive django api
My company is setting up a workflow aplication and they've chosen the viewflow library for designing it. I have little experience with django and have to integrate it with google drive but I wouldnt know hoy to modify the standard front end that comes with viewflow without starting it from scratch. How could I do this?