Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
reverse the value of form field in Django
I have a model named Ticket class Ticket(models.Model): ... color = models.ForeignKey(Color, on_delete=models.PROTECT) When I using Createview to create the ticket, how can I reverse the order of 'color' field? like the newest color is on the top. thanks -
How to convert csv file so it can be JSON serializable and vice versa?
I need to pass a csv file uploaded from a web page in celery task to call an api for each row of csv. But I get an error that is not JSON serializable I thought to convert file into json using following: json.dumps(unicode(self.get_form_kwargs().get('files')['uploaded_file'])) But it is also not working In views.py: class FileUploadView(FormView): template_name = 'addFile.html' form_class = FileUploadForm @method_decorator(sales_spear_login_required) def dispatch(self, *args, **kwargs): return super(FileUploadView, self).dispatch(*args, **kwargs) def form_valid(self, form): file_det = self.get_form_kwargs().get('files')['uploaded_file'] create_dialer_report_async(self.request.user.email, file_det, list_name, campaign_name) return render(self.request, self.template_name, {'form': form, 'report_generated': True}) In services.py: def create_dialer_report_async(logged_user_email, file_det, list_name, campaign_name): create_dialer_report.apply_async((logged_user_email, file_det, list_name, campaign_name)) def create_dialer_report(user_emails, file_det, list_name, campaign_name): reader = csv.DictReader(file_det) for row in reader: # calling api from each row It should be available as csv file object in services.py. However i believe this is string here. -
django rest JSONWebTokenAPIView serializer-class object has no attribute 'object'
i am extending JSONWebTokenAPIView from rest_framework_jwt to my custom view : class UserLogin(JSONWebTokenAPIView): serializer_class = serializers.AdabaziUserLoginJWT and here is my custom serializer class: class AdabaziUserLoginJWT(serializers.Serializer): username = serializers.CharField() password = serializers.CharField(style = {'input-type':'password'}) status = serializers.SerializerMethodField(method_name='show_status') #token = serializers.CharField(read_only=True) class Meta(): model = Adabazi_user fields = ('status') def show_status(self,obj): return obj.status def validate(self,attrs): credentials={ 'username' : attrs.get('username'), 'password' : attrs.get('password') } user = authenticate(**credentials) if user : if user.is_active: ada_user = Adabazi_user.objects.get(user=user) if ada_user.status ==1: ada_user.status = 2 #user is logged in right now ada_user.updated_at = timezone.now() user.last_login = timezone.now() payload = jwt_payload_handler(user) token = jwt_encode_handler(payload) return { 'token':token, 'user':user, 'adabazi_user' : ada_user} else: raise serializers.ValidationError('User is already logged in.') else: raise serializers.ValidationError('Account is deactivated.') else: raise serializers.ValidationError('User credentials failed.') def create(self,validated_data): user = validated_data['user'] adabazi_user = validated_data['adabazi_user'] user.save() ada_user.save() return ada_user but when i want to POST username and password to localhost/api/user/login/ which this url is connected to my view ; this error occured : in this line of code post method which is in JSONWebTokenAPIView makes error user = serializer.object.get('user') or request.user Exception Value: 'AdabaziUserLoginJWT' object has no attribute 'object' how can i access serializer instance object attribute ? is there any object attribute for serializers at all? -
how to add one form for two models Django
i had read about InlineModelAdmin objects and tried to implement it. Basically i have two models Respectively contracts and contractDetails. class contracts(models.Model): productDetailID=models.ForeignKey(productDetails,on_delete=models.CASCADE,verbose_name='Select Product') supplierID=models.ForeignKey(suppliers,on_delete=models.CASCADE,verbose_name='Select Supplier') totalUnits=models.IntegerField(verbose_name='Total Units',editable=False) ratePerUnit=models.IntegerField(verbose_name='Rate Per Unit',editable=False) saleTax=models.IntegerField(verbose_name='Sale Tax') incomeTax=models.IntegerField(verbose_name='Income Tax') saleTaxwithHeld=models.IntegerField(verbose_name='Sale Tax with Held') startDate=models.DateField(verbose_name='Start Date') endDate=models.DateField(verbose_name='End Date') manulContractNumber=models.IntegerField(verbose_name='Manul Contract Number') paymentDays=models.IntegerField(verbose_name='Payment Days') remarks=models.CharField(verbose_name='Remarks',max_length=100,default=None) dateOfEntry=models.DateField(editable=False,default=datetime.now()) class contractDetails(models.Model): contractID=models.ForeignKey(contracts,on_delete=models.CASCADE,verbose_name='Select Contract') weightPerBag=models.IntegerField(verbose_name='Weight Per Bag') conesPerBag=models.IntegerField(verbose_name='Cones Per Bag') weightPerCone=models.IntegerField(verbose_name='Weight Per Cone') noOfBags=models.IntegerField(verbose_name='No of Bags') noOfAdditional=models.IntegerField(verbose_name='No of Additional Cones') ContractDetails have contractID as foregnkey. Now i had tried create one form from these two model using InlineModelAdmin. from django.contrib import admin from Purchase.models import suppliers,Contacts,contracts,contractDetails class contractsInline(admin.TabularInline): model = contracts class contractsdetailsInline(admin.TabularInline): model = contractDetails class contractsAdmin(admin.ModelAdmin): inlines = [ contractsInline, contractsdetailsInline ] # Register your models here. admin.site.register(suppliers) admin.site.register(Contacts) admin.site.register(contracts,contractDetails) admin.site.register(contractsAdmin) But it always return me Error when i tried to migrate it TypeError: 'MediaDefiningClass' object is not iterable -
How to add tag urls to sitemap.xml?
I'm working on sitemap.xml generation for Django + Wagtail project. I already have xml generation for articles, It was implemented by overriding get_sitemap_urls method, but Wagtail sitemap generator doesn't see the blog tags urls. ... from taggit.models import TaggedItemBase class BlogPageTag(TaggedItemBase): content_object = ParentalKey( 'BlogInnerPage', related_name='tagged_items', on_delete=models.CASCADE, ) class BlogInnerPage(Page): icon = models.ForeignKey( 'wagtailimages.Image', null=True, blank=False, on_delete=models.SET_NULL, related_name='+' ) ... post_date = models.DateTimeField(auto_now_add=True, null=True) tags = ClusterTaggableManager(through=BlogPageTag, blank=False) @property def sidebar_tags(self): blogs = BlogInnerPage.objects.live().all() tags = {} for post in blogs: for tag in post.tags.all(): if tag.slug in tags: tags[tag.slug]['count'] += 1 else: tags[tag.slug] = { 'name': tag.name, 'count': 1 } return sorted(tags.items()) ... def get_sitemap_urls(self): return [ { 'location': self.full_url, 'lastmod': self.last_published_at, 'changefreq': 'weekly', 'priority': .8 } ] I'm expecting to see the following result for tags: <url> <loc>https://blog.example.com/?tag=design</loc> <lastmod>2019-01-31T12:24:01+00:00</lastmod> <priority>0.80</priority> </url> Here is what I've got for articles <url> <loc> http://blog.exposit.com/trends-booming-todays-it-industry/ </loc> <lastmod>2018-10-04</lastmod> <changefreq>weekly</changefreq> <priority>0.8</priority> </url> -
Django JSONField not receiving cleaned data
I have a very simple model which contains a JSONField: class Thing(models.Model): title = models.CharField(max_length=1024) text = JSONField(default=dict) I've created a custom widget that allows for the input of key-value pairs: class JsonWidget(forms.widgets.Widget): template_name = 'json_widget.html' def get_context(self, name, value, attrs): context = super().get_context(name, value, attrs) data = json.loads(value) if not data: data = JSON_DEFAULT context['data'] = data.items() return context def value_from_datadict(self, data, files, name): keys = data.getlist('json-key') values = data.getlist('json-value') json_data = {k: v for k, v in zip(keys, values)} return json_data I coerce the dict returned by the widget into a string in the field's clean function on the form: class ThingForm(forms.ModelForm): class Meta: model = Thing fields = ['title', 'text'] widgets = { 'text': JsonWidget(), } def clean_text(self): text = self.cleaned_data.get('text') return json.dumps(text) I've inspected the output of JsonWidget.value_from_datadict (dict) and ThingForm.clean_text (str) are the expected types. But when the object goes to save it throws an exception: TypeError: the JSON object must be str, bytes or bytearray, not 'dict' This is my first time building a custom widget for Django, is there something obvious I've missed here? Thanks! -
i am creating a simple website using django with 2 html pages i am kind of new on django
i am working on Django and making a simple web page with 2 html files first html page will have a button which will take us to the next page where we will signup our details but my button is not working it is showing me errors.i don't know the right way of making it -
Query Multiple in Same Field Django
functionalities.filter(acl_controller='Employee') I want to query functionalities model where acl_controller='Employee' and acl_controller='Manager' and acl_controller='Admin'. I know i can use multiple filters - functionalities.filter(acl_controller='Employee').filter(acl_controller='Manager').filter(acl_controller='Admin') But i want to know is there any better approach to filter out. -
How to write test for django inbuilt login form by using assertFormError
I have to write unit tests for user login in my app. I have used django.contrib.auth.views for login. And i have to use assertFormError for testing error message in form. Since assertFormError accepts form instance as a second argument. I am not able to import the login form in test.py.How to instance Login form in test.py Here is my urls.py from django.contrib.auth import views as auth_views from django.urls import path from users import views as user_view urlpatterns = [ path('', user_view.register, name="register"), path('register/', user_view.register, name="register"), path('home/', user_view.home, name="home"), path('login/', auth_views.LoginView.as_view(template_name='users/login.html'), name="login"), path('logout/', auth_views.LogoutView.as_view(template_name='users/logout.html'), name="logout"), ] -
Server Error (500) Timeout after changing Database in Django
So after finishing my Django Project everything works fine on the test database server with following settings: DATABASES = { 'default': { 'ENGINE':'sql_server.pyodbc', 'NAME':'xxx', 'USER':'xxx', 'PASSWORD':'xxx', 'HOST':'192.168.10.40', 'OPTIONS': { 'driver': 'ODBC Driver 13 for SQL Server', }, }, '200000': { 'ENGINE':'sql_server.pyodbc', 'NAME':'xxx', 'USER':'xxx', 'PASSWORD':'xxx', 'HOST':'192.168.10.40', 'OPTIONS': { 'driver': 'ODBC Driver 13 for SQL Server', }, }, } but after trying to change it to the new database server like: DATABASES = { 'default': { 'ENGINE':'sql_server.pyodbc', 'NAME':'xxx', 'USER':'xxx', 'PASSWORD':'xxx', 'HOST':'192.168.10.36/ATS', 'OPTIONS': { 'driver': 'ODBC Driver 13 for SQL Server', }, }, '200000': { 'ENGINE':'sql_server.pyodbc', 'NAME':'xxx', 'USER':'xxx', 'PASSWORD':'xxx', 'HOST':'192.168.10.36\ATS', 'OPTIONS': { 'driver': 'ODBC Driver 13 for SQL Server', }, }, } i get a server error 500 after like 2minutes when i change the database server back to the old one it works again what problems can cause this error? can it be that i got an instance on the server and the /ATS is causing the problem? -
How to save records and get records on behalf of another user
I'm working on a Django 1.5 Project. The application contains the user hierarchy of Owner Admin Viewer Owner owns all the data in the database. Admin users are created by the owner and have different login credentials. Can add/edit/delete data under Owner. Viewer users are created by the owner and have different login credentials. Can view data created under the Owner. Users model have a field is_shared (boolean) to identify main user and shared user and access_level is mapped in another model MultiUser. I have thought of to implement it in the way Update all viewsets and put check in get_queryset. where first check will be made if user has is_shared=True then check in MultiUser model, get the user from MultiUser and then filter records on behalf of the user. But this will require changes throughout the application viewsets. Is there a way to do this without making changes to the whole application. May be middleware. -
Cant see SQL queries with multiple database landscape
Django 2.1.7, MySQL. DATABASES config is like: DATABASES = { 'default': {}, 'auth_db': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'auth', ... }, 'db1': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'db1', ... }, 'db2': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'd2', ... } } I have various issues with viewing raw SQL queries: 1) Cant print the query of particular queriset: qs = Model.objects.using("db2").filter(...) print(qs.query) This code drops ImproperlyConfigured because it doesnt respect the .using("db2") and somewhy check the default db which is empty (Empty default_db is quite okay as said in django docs) 2) When in runtime i open a shell to monitor queries: from django.db import connections print(connections["db1"].queries) i just see this: [{'sql': 'None', 'time': '0.001'}, {'sql': 'None', 'time': '0.000'}, {'sql': 'None', 'time': '0.008'}] debug=True is set like said in docs. Anyone has an experience with this kind of issues woth multiple db? -
What does choice mean in "for choice in question.choice_set.all" from the Django poll tutorial?
I'm new to Django and am working through the first poll tutorial. I'm having trouble understanding the use of the word "choice" in a for loop within the tutorial. I've read other questions related to this part of the tutorial, but most dealt with choice_set.all {% for choice in question.choice_set.all %} <li>{{ choice.choice_text }}</li> {% endfor %} My question is related to the initial use of the word choice in the for statement... for "choice" in. It appears to be referencing the whole Choice model which I don't quite understand. It seems like it would make more sense to say "for choice.choice_text in" while looping through checking for choice_text matches against values in question.choice_set.all. The Choice model contains choice_text, question, and votes at this point of the tutorial. Can someone help me understand what the first mention of choice refers to in the for loop? -
Site local works correct,but deploy to the heroku ,it show teamplatesdoesnotexist
Thanks in advance.my english is poor. Django project works locally but not when deployed to Heroku. i am following the . but the strange part is it only fails on Heroku and not locally. ... TemplateDoesNotExist at /users/register/ learning_logs/base.html Request Method: GET Request URL: https://lit-dusk-37283.herokuapp.com/users/register/ Django Version: 2.1.5 Exception Type: TemplateDoesNotExist Exception Value: learning_logs/base.html Exception Location: /app/.heroku/python/lib/python3.6/site-packages/django/template/backends/django.py in reraise, line 84 Python Executable: /app/.heroku/python/bin/python Python Version: 3.6.5 Python Path: ['/app/.heroku/python/bin', '/app', '/app/.heroku/python/lib/python36.zip', '/app/.heroku/python/lib/python3.6', '/app/.heroku/python/lib/python3.6/lib-dynload', '/app/.heroku/python/lib/python3.6/site-packages'] Server time: Tue, 12 Feb 2019 05:08:49 +0000 Template-loader postmortem Django tried loading these templates, in this order: Using engine django: django.template.loaders.app_directories.Loader: /app/.heroku/python/lib/python3.6/site-packages/django/contrib/admin/templates/learning_logs/base.html (Source does not exist) django.template.loaders.app_directories.Loader: /app/.heroku/python/lib/python3.6/site-packages/django/contrib/auth/templates/learning_logs/base.html (Source does not exist) django.template.loaders.app_directories.Loader: /app/.heroku/python/lib/python3.6/site-packages/bootstrap3/templates/learning_logs/base.html (Source does not exist) django.template.loaders.app_directories.Loader: /app/learning_logs/templates/learning_logs/base.html (Source does not exist) django.template.loaders.app_directories.Loader: /app/users/templates/learning_logs/base.html (Source does not exist) my_setting.py import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['localhost'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'bootstrap3', #my app 'learning_logs', 'users', ] MIDDLEWARE … -
Domain-based identification frontend django-tenant-schemas
I had built a multi-tenant application in Django using django-tenant-schemas. Procedure Migrate with public schema and have PUBLIC_SCHEMA_URLCONF <company-name>.com (website) is used for tenant registration and to show pricing, terms and condition Migrate for client1 client1.<company-name>.com Migrate for client2 client2.<company-name>.com and so on. Followed docs https://django-tenant-schemas.readthedocs.io/en/latest/ Everything is working perfectly. Problem Have separate frontend (built in vuejs) I want to associate frontend and perform Domain-based identification Setup axios to request unique client Example, client1.<company-name>.com/v1/api <--- backend client1.<company-name>.com <--- frontend also, client2.<company-name>.com/v1/api <--- backend client2.<company-name>.com <--- frontend Conclusion setup vuejs project in django rather than a separate project -
nginx host not found in upstream in dockerized nginx
I have a set up and running nginx container and django app container on my server. I wanted to bulid another container that holds another django app but on another python version. So I did. But then when I tried to configure proxy_pass to my new container nginx keeps restartings with error [emerg] host not found in upstream "zen_bhaskara" in /etc/nginx/nginx.conf:91 Thing is I already had the same problem when I was setting up first and now running django app. I solved it by creating new network and adding two containers in it and then nginx could resolve container name. But same trick didn't work with this new container and I spend hours already without any success of sovling it. Here's a config for my first app: server { server_name some.server.name; listen 80; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $remote_addr; auth_basic "Restricted"; auth_basic_user_file /etc/nginx/conf.d/pass.htpasswd; location / { client_max_body_size 500m; proxy_pass http://django_app_1; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $remote_addr; proxy_set_header Host $host; } Then I tried to do the same for new app: server { listen 80; resolver 127.0.0.11; server_name another.server.name; location / { proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_pass http://djangoapp2:80; } } And here's my Dockerfile for a new app: FROM … -
jQuery not loading in Django admin homepage/dashboard, login and logout pages
I need to load a js file throught all django admin pages. Hence I copied the base.html file located in django/contrib/admin/templates/admin/ and added it to my templates folder under templates/admin/base.html. Added the js file under app_static/admin/js/ (location to my static files). Next, I included the <script> tags inside the base.html under the {% block extrahead %} tags. When I open the change_list and change_form pages, the js fires correctly. It does not fire in the homepage/dashboard, login and logout pages. Returns an error stating Uncaught ReferenceError: django is not defined. An error usually thrown when jQuery has not been initialized. session_expiry.js (function($){ $(function() { console.log('js has been called'); }); })(django.jQuery); Could anyone point out what I might be missing. -
Different URLs doing similar functions in Django: "Error detail": "Method \"GET\"
There are my models below: class Grade(models.Model): grade = models.CharField(max_length=255, primary_key=True) class Student(models.Model): name = models.CharField(max_length=255) grade = models.ForeignKey(grade, on_delete=models.CASCADE) rollno = models.BigIntegerField() class Third(models.Model): grade = models.OneToOneField(grade, on_delete=models.CASCADE, primary_key=True) stds = models.TextField() The views.py is follow: class RegisterStudent(generics.ListAPIView): ''' GET stu/ POST stu/ ''' queryset = Student.objects.all() serializer_class = StudentSerializer def post(self, request, *args, **kwargs): grade, created = Grade.objects.get_or_create( grade=request.data["grade"], ) a_site = Student.objects.create( name=request.data["name"], grade = grade, rollno=request.data["rollno"], ) print(type(a_site.grade)) return Response( data=DeviceSerializer(a_site).data, status class StudentinGrade(generics.UpdateAPIView): print('You should be the one wrking') ''' GET grade/{grade}/stu/ POST grade/{grade}/stu/ ''' queryset = Student.objects.all() serializer_class = StudentSerializer def post(self, request, *args, **kwargs): grade, created = Grade.objects.get_or_create( grade=request.data(kwargs["pk"]), ) a_site = Student.objects.create( name=request.data["name"], grade = grade, rollno=request.data["rollno"], ) return Response( data=DeviceSerializer(a_site).data, status=status.HTTP_201_CREATED ) There are Other classes to post data for grades and combine the two classes which I haven't posted here. What I am trying to do with first class is just get the data for students, which works with the urls below: urlpatterns = [ path('grade/<str:pk>/stu', StudentinGrade.as_view(), name = "grade-stu"), path('grade/<str:pk>/', CombiView.as_view(), name = "get-grade"), # To combine both the classes path('stu/', RegisterStudent.as_view(), name = "new-stu"), path('stu/<str:pk>/', ViewStudent.as_view(), name = "get-stu"), # To view registered students ] For the second … -
Django-excel won't import a file. Says does not match any given model
Getting my head around Django-excel. Following the official documentation on how to use it. Am on this section: http://django.pyexcel.org/en/latest/#handle-data-import For some reason after submitting the excel file, I get this error: Sheet: Sheet1 does not match any given models.Please be aware of case sensitivity. The import_data function that handles the request looks like this: def import_data(request): if request.method == "POST": form = UploadFileForm(request.POST, request.FILES) def choice_func(row): q = Question.objects.filter(slug=row[0])[0] row[0] = q return row if form.is_valid(): request.FILES['file'].save_book_to_database( models=[Question, Choice], initializers=[None, choice_func], mapdicts=[ ['question_text', 'pub_date', 'slug'], ['question', 'choice_text', 'votes']] ) return redirect('handson_view') else: return HttpResponseBadRequest() else: form = UploadFileForm() return render( request, 'upload_form.html', { 'form': form, 'title': 'Import excel data into database example', 'header': 'Please upload sample-data.xls:' }) I don't see any errors here but I don't know where else to look for. -
How to get linkify to take you to a detail view from a django table?
I'm trying to create link from a django-tables2 column to a 'detail view' of the object. For instance, I have a column of health providers and I want a user to be able to click on it and see specific information for the health provider from a django table of search results. Currently, it's not working. I can get the table to show up, but cannot get it where they can click to the detail page. Please, help. There is a problem with my urls and my views, so I'm going to include the tables.py, the views.py and the urls.py. The link I'm trying to linkify is the foreign key for Hospital model in the Price Model. This is the urls.py. This is the under url_patterns. path('hospital_detail/(?P<pk>\d+)/$', views.HospitalDetailView.as_view(), name='hospital-detail') This is the views.py. from django.template import RequestContext, get_object_or_404, render from django.views.generic.detail import DetailView from catalog.models import Price, Hospital, Service from django_tables2 import RequestConfig from catalog.tables import PriceTable class HospitalDetailView(generic.DetailView): model = Hospital def hospital_detail_view(request, primary_key): hop = get_object_or_404(Hospital, pk=primary_key) return render(request, 'hospital_detail.html', {'hospital': hop}) def results(request): if request.method == "GET": Q=() out_words = request.GET.get('s') context = RequestContext(request) table = PriceTable(Price.objects.filter(service__desc_us__icontains = out_words)) RequestConfig(request).configure(table) else: table = PriceTable(Price.objects.all()) RequestConfig(request).configure(table) return render(request, … -
Authenticating the username and password returns user as none during logn
While i am authenticating the login form using authenticate function i am getting user as none eventhough getting the username and password. settings.py: --------- AUTHENTICATION_BACKENDS = ("django.contrib.auth.backends.ModelBackend",) forms.py: ---------- class login_form(forms.Form): username = forms.CharField() password1 = forms.CharField(widget=forms.PasswordInput) views.py: -------- form = login_form(request.POST or None) if form.is_valid(): username = form.cleaned_data.get("username") password = form.cleaned_data.get("password1") print (username,password) user = authenticate(username=username, password=password) print('user is', user) In database side the login credentials are saved.I dont know what is going wrong here. -
How I can Install misaka
Can't install misaka and getting error: command 'gcc' failed with exit status 1 I am getting this error of gcc when installing misaka by using comand pip install misaka Running setup.py clean for misaka Failed to build misaka Installing collected packages: misaka Running setup.py install for misaka ... error Complete output from command /home/avanish/anaconda3 running install running build running build_py creating build creating build/lib.linux-x86_64-3.7 creating build/lib.linux-x86_64-3.7/misaka copying misaka/callbacks.py -> build/lib.linux-x86_64-3.7/misaka copying misaka/constants.py -> build/lib.linux-x86_64-3.7/misaka copying misaka/utils.py -> build/lib.linux-x86_64-3.7/misaka copying misaka/api.py -> build/lib.linux-x86_64-3.7/misaka copying misaka/__init__.py -> build/lib.linux-x86_64-3.7/misaka running build_ext generating cffi module 'build/temp.linux-x86_64-3.7 / creating build/temp.linux-x86_64-3.7 building 'misaka._hoedown' extension creating build/temp.linux-x86_64-3.7/build creating build/temp.linux-x86_64-3.7/build/temp.linux-x86_64-3.7 creating build/temp.linux-x86_64-3.7/misaka creating build/temp.linux-x86_64-3.7/misaka/hoedown gcc -pthread -B /home/avanish/anaconda3/envs/myDjangoEnv unable to execute 'gcc': No such file or directory error: command 'gcc' failed with exit status 1 --------------------------------------- -
CreateView + get_absolute_url
I'm trying to use CreateView, here is some problem and I'm stacking it. enter code here First of all, i'm trying to create a post and dynamically fill user field who create post. It save the post but don't save the user: image from admin #views.py class PostCreateView(CreateView): model = Post template_name = 'blog/post_create.html' fields = ('title', 'slug', 'body',) def form_valid(self, form): form.instance.blog__user = self.request.user return super(PostCreateView,self).form_valid(form) #models.py The second one, i think main problem, i don't use get_absolute_url correctly and i get this problem: No URL to redirect to. But it good works for post_detail. class Blog(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) slug = models.SlugField(max_length=50) def __str__(self): return self.user.username def create_blog(sender, **kwargs): if kwargs['created']: user_blog = Blog.objects.create(user=kwargs['instance'], slug=kwargs['instance']) post_save.connect(create_blog, sender=User) class Post(models.Model): blog = models.ForeignKey(Blog, on_delete=models.CASCADE) slug = models.SlugField(max_length=50, db_index=True) title = models.CharField(max_length=120, db_index=True) body = models.TextField(blank=True, db_index=True) pub_date = models.DateTimeField(auto_now_add=True) def get_absolute_url(self): return reverse('post_detail_url', kwargs={'slug': self.slug, 'username': self.blog}) #urls.py urlpatterns = [ path('<username>/create/', PostCreateView.as_view(), name='post_create'), path('<username>/<str:slug>/', PostDetailView.as_view(), name='post_detail_url'), path('<username>/', PostListView.as_view(), name='post_list_url'), path('<username>/<str:slug>/update/', PostUpdateView.as_view(), name='post_update'), ] I'm tried to define get_success_url and i get this: NoReverseMatch Please help i'm really lost in the clouds! -
A clear step by step process for running a periodic task in a django application
I have been trying a long for creating a periodic task in Django but there are lot of version constraints and not a clear explanation. -
django-rest-auth with Google: How to post access token properly
I'm really new to using retrofit2. I'm trying to send access token to the backend from mobile app and authenticate the user via Google but I can not do it properly. The backend returns 400. My code is like this. views.py from allauth.socialaccount.providers.google.views import GoogleOAuth2Adapter from rest_auth.registration.views import SocialLoginView class GoogleLogin(SocialLoginView): adapter_class = GoogleOAuth2Adapter urls.py path('rest-auth/google/', GoogleLogin.as_view(), name='google_login'), And my Java code (I'm using retrofit2) public interface ApiService { // login @POST("/rest-auth/google/") Call<Account> login(@Header("access_token") String accessToken); MainActivity.java private void login() { ApiService service = ApiClient.getService(); service.login(mAuthToken).enqueue(new Callback<Account>() { @Override public void onResponse(Call<Account> call, Response<Account> response) { if (!response.isSuccessful()) { Toast.makeText(MainActivity.this, "Code:" + response.code(), Toast.LENGTH_LONG).show(); return; } Toast.makeText(MainActivity.this, "Success!", Toast.LENGTH_LONG).show(); } @Override public void onFailure(Call<Account> call, Throwable t) { mTextViewResult.setText(t.getMessage()); } }); } mAuthToken is access token. I think I'm wrong with the way to pass the access token to backend. What am I wrong with this?